kiki-agent-lite 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs/en/configuration/config-files.md +32 -19
- package/dist/docs/en/configuration/data-locations.md +23 -1
- package/dist/docs/en/configuration/env-vars.md +6 -8
- package/dist/docs/en/configuration/overrides.md +19 -8
- package/dist/docs/en/configuration/providers.md +75 -4
- package/dist/docs/en/customization/agents-and-subagents.md +6 -2
- package/dist/docs/en/customization/personas.md +36 -2
- package/dist/docs/en/customization/plugins.md +41 -1
- package/dist/docs/en/customization/prompt-fields.md +4 -0
- package/dist/docs/en/features/agent-workflows.md +8 -8
- package/dist/docs/en/features/browser-and-computer.md +40 -0
- package/dist/docs/en/features/daily.md +10 -10
- package/dist/docs/en/features/ecosystem.md +5 -5
- package/dist/docs/en/features/extend.md +9 -8
- package/dist/docs/en/features/freedom.md +8 -8
- package/dist/docs/en/features/index.md +44 -28
- package/dist/docs/en/features/long-work.md +9 -9
- package/dist/docs/en/features/look.md +5 -5
- package/dist/docs/en/features/people.md +6 -6
- package/dist/docs/en/features/phone.md +5 -3
- package/dist/docs/en/features/spaces.md +7 -7
- package/dist/docs/en/features/workbench.md +8 -8
- package/dist/docs/en/guides/interface.md +16 -4
- package/dist/docs/en/guides/sessions.md +6 -2
- package/dist/docs/en/guides/settings.md +15 -2
- package/dist/docs/en/reference/command.md +58 -1
- package/dist/docs/en/reference/tools.md +25 -5
- package/dist/docs/en/server/acp.md +3 -1
- package/dist/docs/en/server/mcp.md +5 -1
- package/dist/docs/en/server/rest-api.md +115 -4
- package/dist/docs/zh/configuration/config-files.md +32 -19
- package/dist/docs/zh/configuration/data-locations.md +23 -1
- package/dist/docs/zh/configuration/env-vars.md +6 -8
- package/dist/docs/zh/configuration/overrides.md +19 -8
- package/dist/docs/zh/configuration/providers.md +75 -4
- package/dist/docs/zh/customization/agents-and-subagents.md +6 -2
- package/dist/docs/zh/customization/personas.md +36 -2
- package/dist/docs/zh/customization/plugins.md +41 -1
- package/dist/docs/zh/customization/prompt-fields.md +4 -0
- package/dist/docs/zh/features/agent-workflows.md +10 -10
- package/dist/docs/zh/features/browser-and-computer.md +40 -0
- package/dist/docs/zh/features/daily.md +10 -10
- package/dist/docs/zh/features/ecosystem.md +5 -5
- package/dist/docs/zh/features/extend.md +8 -7
- package/dist/docs/zh/features/freedom.md +8 -8
- package/dist/docs/zh/features/index.md +44 -28
- package/dist/docs/zh/features/long-work.md +8 -8
- package/dist/docs/zh/features/look.md +5 -5
- package/dist/docs/zh/features/people.md +5 -5
- package/dist/docs/zh/features/phone.md +5 -3
- package/dist/docs/zh/features/spaces.md +7 -7
- package/dist/docs/zh/features/workbench.md +8 -8
- package/dist/docs/zh/guides/interface.md +16 -4
- package/dist/docs/zh/guides/sessions.md +6 -2
- package/dist/docs/zh/guides/settings.md +15 -2
- package/dist/docs/zh/reference/command.md +58 -1
- package/dist/docs/zh/reference/tools.md +25 -5
- package/dist/docs/zh/server/acp.md +3 -1
- package/dist/docs/zh/server/mcp.md +5 -1
- package/dist/docs/zh/server/rest-api.md +114 -3
- package/dist/hostRunner.mjs +92 -1
- package/dist/mailbox-worker.mjs +297 -0
- package/dist/main.mjs +2 -2
- package/dist/native/windows-process-helper.exe +0 -0
- package/dist/query-store-worker.mjs +446 -0
- package/dist/sqlite-indexer.mjs +223 -401
- package/dist/sqlite-query-worker.mjs +226 -249
- package/dist/usage-parser-worker.mjs +24 -5
- package/dist/web/assets/AppErrorBoundary-BN6IDdP1.js +1 -0
- package/dist/web/assets/{LifeMark-CL6-HWDu.js → LifeMark-UBMVaTWr.js} +1 -1
- package/dist/web/assets/{NavScopeBoundary-CFCnvZR0.js → NavScopeBoundary-BCryw-UG.js} +1 -1
- package/dist/web/assets/{arc-DYDCMlOS.js → arc-C7IAvCCJ.js} +1 -1
- package/dist/web/assets/{architectureDiagram-3BPJPVTR-C9Y7T0O2.js → architectureDiagram-3BPJPVTR-CbwFBxn7.js} +1 -1
- package/dist/web/assets/{blockDiagram-GPEHLZMM-CdUrp-tD.js → blockDiagram-GPEHLZMM-B20N4t8r.js} +1 -1
- package/dist/web/assets/{c4Diagram-AAUBKEIU-PrwvB9IJ.js → c4Diagram-AAUBKEIU-3BYtlcP-.js} +1 -1
- package/dist/web/assets/channel-BJs5vJuh.js +1 -0
- package/dist/web/assets/{chunk-2J33WTMH-BL56g_Es.js → chunk-2J33WTMH-CpjgczxM.js} +1 -1
- package/dist/web/assets/{chunk-4BX2VUAB-DvJD5M9M.js → chunk-4BX2VUAB-BScxUF5G.js} +1 -1
- package/dist/web/assets/{chunk-55IACEB6-C8f-nzvx.js → chunk-55IACEB6-CrcLYJXd.js} +1 -1
- package/dist/web/assets/{chunk-727SXJPM-DOGkWKkV.js → chunk-727SXJPM-BwlyIOjw.js} +1 -1
- package/dist/web/assets/{chunk-AQP2D5EJ-fFOuz7g6.js → chunk-AQP2D5EJ-DKKIRkRv.js} +1 -1
- package/dist/web/assets/{chunk-FMBD7UC4-BpeXZ9LM.js → chunk-FMBD7UC4-CVDMj2kX.js} +1 -1
- package/dist/web/assets/{chunk-ND2GUHAM-CRUh76fb.js → chunk-ND2GUHAM-CL-PM6r8.js} +1 -1
- package/dist/web/assets/{chunk-QZHKN3VN-uNfxaPk0.js → chunk-QZHKN3VN-DPV2KbKZ.js} +1 -1
- package/dist/web/assets/classDiagram-4FO5ZUOK-BookeACB.js +1 -0
- package/dist/web/assets/classDiagram-v2-Q7XG4LA2-BookeACB.js +1 -0
- package/dist/web/assets/client-CXcrCawx.js +3 -0
- package/dist/web/assets/connection-C8nwzwXB.js +1 -0
- package/dist/web/assets/{cose-bilkent-S5V4N54A-BNkxG-qX.js → cose-bilkent-S5V4N54A-D1CEiQM6.js} +1 -1
- package/dist/web/assets/{dagre-BM42HDAG-BerioUei.js → dagre-BM42HDAG-BlFV941E.js} +1 -1
- package/dist/web/assets/{diagram-2AECGRRQ-Czv2SR07.js → diagram-2AECGRRQ-BC0ldkFY.js} +1 -1
- package/dist/web/assets/{diagram-5GNKFQAL-Uzi1weGK.js → diagram-5GNKFQAL-B22Iej6G.js} +1 -1
- package/dist/web/assets/{diagram-KO2AKTUF-W36h_ff3.js → diagram-KO2AKTUF-B75UNw6D.js} +1 -1
- package/dist/web/assets/{diagram-LMA3HP47-FG4dDk52.js → diagram-LMA3HP47-CypI7IJM.js} +1 -1
- package/dist/web/assets/{diagram-OG6HWLK6-CQoEjIAY.js → diagram-OG6HWLK6-OsXumvcD.js} +1 -1
- package/dist/web/assets/{erDiagram-TEJ5UH35-Ck06KVyZ.js → erDiagram-TEJ5UH35-3756GOvS.js} +1 -1
- package/dist/web/assets/{export-T_izwEkQ.js → export-Bn8PqPg4.js} +1 -1
- package/dist/web/assets/{flowDiagram-I6XJVG4X-C5hgxdFZ.js → flowDiagram-I6XJVG4X-DB6Y_UDg.js} +1 -1
- package/dist/web/assets/{ganttDiagram-6RSMTGT7-BS52Pw5_.js → ganttDiagram-6RSMTGT7-CHJeuoAY.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-PVQCEYII-DLlQKZHs.js → gitGraphDiagram-PVQCEYII-Dj85554Y.js} +1 -1
- package/dist/web/assets/{highlighted-body-OFNGDK62-Btm6MuZ4.js → highlighted-body-OFNGDK62-DMgPHetp.js} +1 -1
- package/dist/web/assets/{index-CZX3qUe2.js → index-0tHq8zh2.js} +1 -1
- package/dist/web/assets/index-7ySDqvaN.css +1 -0
- package/dist/web/assets/index-B0KPRi1U.js +166 -0
- package/dist/web/assets/{index-CRDDqofN.js → index-B599VnpP.js} +1 -1
- package/dist/web/assets/{index-Cd62y0wD.js → index-BFK-GypQ.js} +1 -1
- package/dist/web/assets/{index-BMWid2q9.js → index-BPX8gmpB.js} +1 -1
- package/dist/web/assets/{index-5_yzg61S.js → index-BSGYc1tb.js} +1 -1
- package/dist/web/assets/{index-CJ92kLtO.js → index-BTt9Q5iv.js} +1 -1
- package/dist/web/assets/{index-B4iu4SJW.js → index-BWzUsoY_.js} +1 -1
- package/dist/web/assets/{index-CgcJPsK6.js → index-BYlSV3FO.js} +1 -1
- package/dist/web/assets/{index-BkPV0psm.js → index-BpXQ1q-u.js} +1 -1
- package/dist/web/assets/{index-Dceu0bqY.js → index-BqPxpGUh.js} +1 -1
- package/dist/web/assets/{index-CM-nNfuV.js → index-C6qeLCPw.js} +4 -4
- package/dist/web/assets/{index-ByiwExpV.js → index-C7mOS2T4.js} +1 -1
- package/dist/web/assets/{index-CG8uIlD7.js → index-C8OFfbEs.js} +1 -1
- package/dist/web/assets/{index-B-6LiYTY.js → index-CI7yuMGZ.js} +1 -1
- package/dist/web/assets/{index-B2Pu0Iuu.js → index-CJqIcuAl.js} +1 -1
- package/dist/web/assets/{index-BECSk4If.js → index-CTRJmDep.js} +1 -1
- package/dist/web/assets/{index-Bezli3SF.js → index-CXGCKoId.js} +1 -1
- package/dist/web/assets/{index-hG2s2Spn.js → index-CsY571EL.js} +1 -1
- package/dist/web/assets/{index-BFcyN2Zw.js → index-CwQG_9rB.js} +1 -1
- package/dist/web/assets/{index-BLU8_Um7.js → index-D--cw39y.js} +1 -1
- package/dist/web/assets/{index-B9MlqF7J.js → index-D260jsUJ.js} +1 -1
- package/dist/web/assets/{index-D_oPSlBL.js → index-DJjmEXx4.js} +1 -1
- package/dist/web/assets/{index-BNch_a4L.js → index-DRMjjql1.js} +1 -1
- package/dist/web/assets/{index-BeMvPEXs.js → index-DUxOVxHS.js} +1 -1
- package/dist/web/assets/{index-Ca607_hK.js → index-DZMkZKhW.js} +1 -1
- package/dist/web/assets/{index-BwcG86o3.js → index-DqK8MfQN.js} +1 -1
- package/dist/web/assets/{index-DKIysLbI.js → index-DxUmR9aV.js} +1 -1
- package/dist/web/assets/{index-Cy8C_eFR.js → index-GK8aa9pT.js} +1 -1
- package/dist/web/assets/{index-Bg99yVX_.js → index-bYtKyBMB.js} +1 -1
- package/dist/web/assets/{index-eUyF-8Sq.js → index-wxHFHTgD.js} +1 -1
- package/dist/web/assets/{infoDiagram-5YYISTIA-CD4XJGFm.js → infoDiagram-5YYISTIA-DeDPIdEH.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-YF4QCWOH-fu5E3_CT.js → ishikawaDiagram-YF4QCWOH-ButuBiBW.js} +1 -1
- package/dist/web/assets/{journeyDiagram-JHISSGLW-CXcnKBfJ.js → journeyDiagram-JHISSGLW-Dlbmqm-j.js} +1 -1
- package/dist/web/assets/{kanban-definition-UN3LZRKU-BawKH6Pl.js → kanban-definition-UN3LZRKU-tlQK1cOz.js} +1 -1
- package/dist/web/assets/{linear-BplJuXph.js → linear-iXuNfUWp.js} +1 -1
- package/dist/web/assets/mermaid-GHXKKRXX-sDJax95P.js +624 -0
- package/dist/web/assets/{mindmap-definition-RKZ34NQL-DA1SE2uy.js → mindmap-definition-RKZ34NQL-2qPv-mwT.js} +1 -1
- package/dist/web/assets/{pieDiagram-4H26LBE5-6i021QeX.js → pieDiagram-4H26LBE5-CrLe1C-O.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-W4KKPZXB-CcKSZDMT.js → quadrantDiagram-W4KKPZXB-DfeIFxc0.js} +1 -1
- package/dist/web/assets/{requirementDiagram-4Y6WPE33-lYVuWRuD.js → requirementDiagram-4Y6WPE33-BWtjdxie.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-5OEKKPKP-4Zfb4_h4.js → sankeyDiagram-5OEKKPKP-B5TxJ6mb.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-3UESZ5HK-DqltKmlY.js → sequenceDiagram-3UESZ5HK-Cf92ZCl1.js} +1 -1
- package/dist/web/assets/{spaces-CjuXbmxF.js → spaces-DqMTtCXX.js} +1 -1
- package/dist/web/assets/{stateDiagram-AJRCARHV-HFdhqxzx.js → stateDiagram-AJRCARHV-NR9I-Q4d.js} +1 -1
- package/dist/web/assets/stateDiagram-v2-BHNVJYJU-BiegFWxE.js +1 -0
- package/dist/web/assets/{theme-beWE_6f8.js → theme-6OL1RXgY.js} +1 -1
- package/dist/web/assets/{timeline-definition-PNZ67QCA-HNRxaB3t.js → timeline-definition-PNZ67QCA-CBAOVMfm.js} +1 -1
- package/dist/web/assets/{vennDiagram-CIIHVFJN-DwsCTyaD.js → vennDiagram-CIIHVFJN-C68x6TdS.js} +1 -1
- package/dist/web/assets/{wardley-L42UT6IY-BWW2wtVO.js → wardley-L42UT6IY-DuZZr5jm.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-YWT4CUSO-C-ktKm7v.js → wardleyDiagram-YWT4CUSO-D6dVGtHd.js} +1 -1
- package/dist/web/assets/{xychartDiagram-2RQKCTM6-48AxNW9k.js → xychartDiagram-2RQKCTM6-DYLUhZX4.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 +2 -2
- package/dist/search-worker.mjs +0 -14177
- package/dist/web/assets/AppErrorBoundary-DiGMUg4r.js +0 -1
- package/dist/web/assets/channel-Bj_gZ_Lv.js +0 -1
- package/dist/web/assets/classDiagram-4FO5ZUOK-ssCwe2R4.js +0 -1
- package/dist/web/assets/classDiagram-v2-Q7XG4LA2-ssCwe2R4.js +0 -1
- package/dist/web/assets/client-DGj93bGT.js +0 -3
- package/dist/web/assets/connection-Bpf-EjrL.js +0 -1
- package/dist/web/assets/index-BIebkSEI.css +0 -1
- package/dist/web/assets/index-D8z7lcQn.js +0 -166
- package/dist/web/assets/mermaid-GHXKKRXX-BO9hkP3Z.js +0 -621
- package/dist/web/assets/stateDiagram-v2-BHNVJYJU-Dx28QuZF.js +0 -1
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{as as s,at as g,au as h,av as K,aw as O,ax as b,ay as u,az as S,aA as c,aB as q,aC as d,aD as Vs,aE as Hs,aF as k,aG as It,aH as ae,aI as Ws,aJ as R,aK as nn,aL as zs,aM as Ce,aN as Ks,aO as Qs,aP as Ys,aQ as Xs,aR as Js,aS as Zs,aT as ei,aU as io,aV as ti,aW as ro,aX as oi,aY as ni,aZ as si,a_ as ii,a$ as ri,b0 as ai,b1 as ci,b2 as rt,b3 as at,b4 as sn,b5 as di,b6 as li,b7 as ui,b8 as pi,b9 as mi,ba as hi,bb as gi,bc as vi,bd as ge,be as Si,bf as fi,bg as yi,bh as bi,bi as ao,bj as _i,bk as Ii,bl as Ti,bm as wi,bn as Ei,bo as ki,bp as ct,bq as dt,br as Ae,bs as Ci,bt as Ri,bu as Pi,bv as Oi,bw as Ai,bx as co,by as Mi,bz as xi,bA as Ui,bB as Di,bC as Ni,bD as We,bE as ji,bF as Li,bG as Me,bH as lo,bI as qi,bJ as lt,bK as $i,bL as Gi,bM as Fi,bN as ut,bO as Bi,bP as B,bQ as Vi,bR as Hi,bS as Wi,bT as zi,bU as Ki,bV as Qi,bW as Yi,bX as Xi,bY as z,bZ as Ji,b_ as Zi,b$ as er,c0 as tr,c1 as or,c2 as pt,c3 as nr,c4 as sr,c5 as jt,c6 as ir,c7 as rr,c8 as ar,c9 as cr,ca as dr,cb as lr,cc as ur,cd as pr,ce as mr,cf as rn,cg as hr,ch as gr,ci as vr,cj as Sr,ck as fr,cl as yr,cm as an,cn as br,co as _r,cp as Ir,cq as Re,cr as cn,cs as Tr,ct as wr,cu as Ye,cv as Er,cw as kr,cx as Cr,cy as Rr,cz as Pr,cA as Or,cB as Ar,cC as Mr,cD as xr,cE as Ur,cF as Dr,cG as Nr,cH as jr,cI as Lr,cJ as qr,cK as uo,cL as po,cM as $r,cN as Gr,cO as Fr,cP as Br,cQ as Vr,cR as Hr,cS as Wr,cT as zr,cU as Kr,cV as Qr,cW as dn,cX as ln,cY as un,cZ as Yr,c_ as pn,c$ as mn,d0 as Xr,d1 as Jr,d2 as mo,d3 as Zr,d4 as mt,d5 as ea,d6 as xe,d7 as ta,d8 as oa,d9 as ve,da as na,db as X,dc as ho,dd as sa,de as ht,df as ia,dg as gt,dh as ra,di as aa,dj as vt,dk as ca,dl as da,dm as la,dn as ua,dp as go,dq as pa,dr as ma,ds as vo,dt as ha,du as ga,dv as va,a as Sa,B as So,dw as fa,dx as ya,dy as ba,dz as fo,dA as _a,dB as Ia,dC as Ta,dD as wa,dE as St,dF as Ea,dG as ka,dH as Ca}from"./index-D8z7lcQn.js";const Lt="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ze=32,hn=16,qt=10,yo=0xffffffffffff;var se;(function(o){o.Base32IncorrectEncoding="B32_ENC_INVALID",o.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",o.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",o.EncodeTimeNegative="ENC_TIME_NEG",o.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",o.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",o.PRNGDetectFailure="PRNG_DETECT",o.ULIDInvalid="ULID_INVALID",o.Unexpected="UNEXPECTED",o.UUIDInvalid="UUID_INVALID"})(se||(se={}));class Ie extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e}}function Ra(o){const e=Math.floor(o()*ze)%ze;return Lt.charAt(e)}function Pa(o){const e=Oa(),t=e&&(e.crypto||e.msCrypto)||null;if(typeof t?.getRandomValues=="function")return()=>{const n=new Uint8Array(1);return t.getRandomValues(n),n[0]/256};if(typeof t?.randomBytes=="function")return()=>t.randomBytes(1).readUInt8()/256;throw new Ie(se.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Oa(){return xa()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Aa(o,e){let t="";for(;o>0;o--)t=Ra(e)+t;return t}function Ma(o,e=qt){if(isNaN(o))throw new Ie(se.EncodeTimeValueMalformed,`Time must be a number: ${o}`);if(o>yo)throw new Ie(se.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${yo}: ${o}`);if(o<0)throw new Ie(se.EncodeTimeNegative,`Time must be positive: ${o}`);if(Number.isInteger(o)===!1)throw new Ie(se.EncodeTimeValueMalformed,`Time must be an integer: ${o}`);let t,n="";for(let i=e;i>0;i--)t=o%ze,n=Lt.charAt(t)+n,o=(o-t)/ze;return n}function xa(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function bo(o){return typeof o=="string"&&o.length===qt+hn&&o.toUpperCase().split("").every(e=>Lt.indexOf(e)!==-1)}function Ua(o,e){const t=Pa(),n=Date.now();return Ma(n,qt)+Aa(hn,t)}const _o={off:0,turn:1,block:2,delta:3};function Io(o,e){return o?o[e]??o["*"]??"off":"off"}function Da(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 To=512*1024,Na={meta:["GET","/meta"],spaceSummary:["GET","/space-summary"],sessions:["GET","/sessions"],sessionQuery:["GET","/sessions/query"],ephemeralSessions:["GET","/sessions/ephemeral"],sessionCreate:["POST","/sessions"],session:["GET","/sessions/{sessionId}"],sessionUpdate:["PATCH","/sessions/{sessionId}"],sessionArchive:["POST","/sessions/{sessionId}:archive"],sessionRestore:["POST","/sessions/{sessionId}:restore"],sessionFork:["POST","/sessions/{sessionId}:fork"],saveEphemeral:["POST","/sessions/{sessionId}/ephemeral/save"],endEphemeral:["POST","/sessions/{sessionId}/ephemeral/end"],compact:["POST","/sessions/{sessionId}:compact"],undo:["POST","/sessions/{sessionId}:undo"],autoCompact:["GET","/sessions/{sessionId}/agents/{agentId}/auto-compact"],autoCompactUpdate:["PATCH","/sessions/{sessionId}/agents/{agentId}/auto-compact"],agentHooks:["GET","/sessions/{sessionId}/agents/{agentId}/hooks"],sessionProfile:["POST","/sessions/{sessionId}/profile"],personaSettings:["GET","/sessions/{sessionId}/persona-settings"],personaSettingsApply:["POST","/sessions/{sessionId}/persona-settings"],goal:["GET","/sessions/{sessionId}/goal"],messages:["GET","/sessions/{sessionId}/messages"],snapshot:["GET","/klient/session-view/{sessionId}/snapshot"],transcript:["GET","/klient/session-view/{sessionId}/transcript"],content:["POST","/klient/session-view/{sessionId}/transcript/content"],catchUp:["GET","/klient/session-view/{sessionId}/transcript/catch-up"],transcriptPage:["GET","/sessions/{sessionId}/transcript"],transcriptDetail:["GET","/sessions/{sessionId}/transcript/detail"],transcriptDetails:["GET","/sessions/{sessionId}/transcript/details"],transcriptOps:["GET","/sessions/{sessionId}/transcript/ops"],transcriptPlan:["GET","/sessions/{sessionId}/transcript/plan"],procedure:["POST","/klient/call"],prompts:["GET","/sessions/{sessionId}/prompts"],prompt:["POST","/sessions/{sessionId}/prompts"],promptRead:["GET","/sessions/{sessionId}/prompts/{promptId}"],promptResume:["POST","/sessions/{sessionId}/prompts/{promptId}:resume"],promptAbort:["POST","/sessions/{sessionId}/prompts/{promptId}:abort"],steer:["POST","/sessions/{sessionId}/prompts/steer"],abort:["POST","/sessions/{sessionId}/abort"],approvals:["GET","/sessions/{sessionId}/approvals"],approval:["POST","/sessions/{sessionId}/approvals/{interactionId}"],questions:["GET","/sessions/{sessionId}/questions"],question:["POST","/sessions/{sessionId}/questions/{interactionId}"],taskList:["GET","/sessions/{sessionId}/tasks"],task:["GET","/sessions/{sessionId}/tasks/{taskId}"],agentTaskList:["GET","/sessions/{sessionId}/agent-tasks"],userMessages:["GET","/sessions/{sessionId}/user-messages"],skills:["GET","/sessions/{sessionId}/skills"],skillActivate:["POST","/sessions/{sessionId}/skills/{skillName}:activate"],context:["GET","/sessions/{sessionId}/context"],metrics:["GET","/sessions/{sessionId}/metrics"],media:["GET","/sessions/{sessionId}/media/{fileId}"],mediaPreview:["GET","/sessions/{sessionId}/media/{fileId}/preview"],fileUpload:["POST","/files"],file:["GET","/files/{fileId}"],tools:["GET","/tools"],models:["GET","/models"],providers:["GET","/providers"],auth:["GET","/auth"],configRead:["GET","/config"],usage:["GET","/usage"],requestGovernance:["GET","/usage/realtime"],agentActivity:["GET","/usage/realtime/agents"],usagePricing:["GET","/usage/pricing"],usageRescanStatus:["GET","/usage/rescan"],providerQuotaRead:["GET","/usage/provider-quotas"],workspaces:["GET","/workspaces"],workspace:["GET","/workspaces/{workspaceId}"],workspaceSkills:["GET","/workspaces/{workspaceId}/skills"],worktrees:["GET","/worktrees"],worktree:["GET","/worktrees/{worktreeId}"],worktreeInspect:["POST","/worktrees/{worktreeId}:inspect"],fsSearch:["POST","/sessions/{sessionId}/fs:search"],draftFsSearch:["POST","/workspace/fs:search"],htmlPreviewOpen:["POST","/fs:html-preview"],htmlPreviewClose:["DELETE","/fs:html-preview/{previewId}"],htmlPreviewResource:["GET","/html-preview/{previewId}/resource"],commands:["GET","/sessions/{sessionId}/commands"],agentCapabilities:["GET","/agents/capabilities"],agentConfig:["GET","/sessions/{sessionId}/agent-config"],agentConfigUpdate:["PATCH","/sessions/{sessionId}/agent-config"],profiles:["GET","/agents"],shippedProfiles:["GET","/agents/shipped"],previewModelMenu:["POST","/agents/{profileId}/model-menu:preview"],previewExecutorPrompt:["POST","/agents/{profileId}/executor-prompt:preview"],plugins:["GET","/plugins"],plugin:["GET","/plugins/{pluginId}"],pluginSettings:["GET","/plugins/{pluginId}/settings"],pluginCommands:["GET","/plugins/commands"],pluginPanels:["GET","/plugins/panels"],pluginPanelDocument:["GET","/plugins/{pluginId}/panels/{panelId}/document"],pluginPanelBridge:["POST","/plugins/{pluginId}/panels/{panelId}/bridge"],pluginMarketplace:["GET","/plugins/marketplace"],pluginRecommendations:["POST","/plugins/recommendations/match"],skins:["GET","/skins"],skin:["GET","/skins/{skinId}"],appearancePacks:["GET","/appearance/packs"],appearancePack:["GET","/appearance/packs/{packId}"],appearanceAsset:["GET","/appearance/packs/{packId}/files/{fileName}"],spacePreferences:["GET","/homes/{spaceId}/settings"],personas:["GET","/personas"],persona:["GET","/personas/{personaId}"],personaAvatar:["GET","/personas/{personaId}/avatar"],personaHome:["POST","/personas/{personaId}/home"],personaState:["PATCH","/personas/{personaId}/state"],bots:["GET","/bots"],botHome:["POST","/bots/{botId}/home"],rooms:["GET","/rooms"],roomItems:["GET","/rooms/items"],roomThreads:["GET","/rooms/threads"],room:["GET","/rooms/{roomId}"],roomLog:["GET","/rooms/{roomId}/log"],roomUsage:["GET","/rooms/{roomId}/usage"],roomMessage:["POST","/rooms/{roomId}/messages"],roomPause:["POST","/rooms/{roomId}/pause"],roomContinue:["POST","/rooms/{roomId}/continue"],roomStop:["POST","/rooms/{roomId}/stop"],cron:["GET","/cron"],threadMessages:["GET","/threads/messages"],search:["POST","/search"],searchStatus:["GET","/search/status"],mcpRuntime:["GET","/mcp/runtime/servers"],executors:["GET","/executors"],catalogProviders:["GET","/catalog/providers"],catalogProvider:["GET","/catalog/providers/{providerId}"],oauthUsage:["GET","/oauth/usage"],nbSearchCapabilities:["GET","/nb-search/capabilities"],requestIdentity:["GET","/request-identity"],notificationsSettings:["GET","/notifications/settings"],notificationsProviders:["GET","/notifications/providers"],notificationsDeliveries:["GET","/notifications/deliveries"],memorySources:["GET","/memory/sources"],memoryEntries:["GET","/memory/{scope}"],memoryEntry:["GET","/memory/{scope}/{entryId}"],memoryJournal:["GET","/memory/{scope}/journal"],memoryInbox:["GET","/memory/{scope}/inbox"]},ja=o=>!o||o==="."||o===".."||o.includes("/")||o.includes("\\");function La(o,e){const t=Object.entries(Na).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 v=!0;for(let f=0;f<r.length;f+=1){let y;try{y=decodeURIComponent(m[f+1])}catch{v=!1;break}if(ja(y)){v=!1;break}p[r[f]]=y}if(v)return{operation:n,params:p}}}function qa(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 U=s().min(1).max(512),$t=s().min(1).max(4096),Ke=g(U).max(256),Qe=h(["active","in_progress","paused","done","cancelled","superseded"]),Ee=K({root:$t,storageId:U,kind:h(["workspace","embedded"])}),$a=K({root:$t,storageId:U.optional(),kind:h(["workspace","embedded"])}),Ga=K({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"]}),Fa=K({title:s().trim().min(1).max(1e3).optional(),description:s().max(1e5).optional(),priority:h(["P0","P1","P2","P3"]).optional(),category:s().max(256).optional(),sessionIds:Ke.optional(),executionIds:Ke.optional(),status:Qe.optional()}).refine(o=>Object.keys(o).length>0,"An update requires a changed field."),Ba=O("action",[K({action:b("preview"),workspaceId:U.optional(),configuration:Ga.optional()}),K({action:b("list"),workspaceId:U.optional(),storage:Ee.optional(),sessionId:U.optional(),status:Qe.optional(),archived:S().optional(),cursor:U.optional(),limit:u().int().min(1).max(100).optional()}),K({action:b("show"),workspaceId:U,storage:Ee,id:U}),K({action:b("overview"),workspaceIds:g(U).min(1).max(32),status:Qe.optional(),limit:u().int().min(1).max(100).optional()})]),Va=O("action",[K({action:b("create"),workspaceId:U.optional(),requestKey:U,target:$a.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:Ke.optional(),executionIds:Ke.optional()}),K({action:b("update"),workspaceId:U,storage:Ee,id:U,expectedRevision:u().int().nonnegative().max(Number.MAX_SAFE_INTEGER),patch:Fa})]),gn=c({id:U,workspaceId:U,storage:Ee,title:s(),priority:s(),status:Qe,revision:u().int().nonnegative(),createdAt:s(),updatedAt:s(),completedAt:s().nullable(),archived:S(),category:s(),sessionIds:g(s()),executionIds:g(s())}),vn=gn.extend({description:s(),prd:s(),handoff:s().optional()}),Sn=c({code:s(),message:s()}),Xe=o=>O("ok",[c({ok:b(!0),value:o}),c({ok:b(!1),error:Sn})]),fn=c({workspaceId:U,storage:Ee.optional(),cards:g(gn),issues:g(Sn),nextCursor:s().optional()}),Ha=c({mode:h(["auto","global","fixed"]),workspaceId:U,root:$t,tasksDirectory:s(),existing:S(),kind:h(["workspace","embedded"]),storageId:U.optional(),selectionOnly:b(!0)}),yn=c({workspaceId:U,result:Xe(fn)}),Wa=Xe(q([vn,fn,Ha,g(yn)])),za=Xe(vn),Ka=Xe(g(yn)),Qa={read:{input:d([Ba]),output:Wa},write:{input:d([Va]),output:za},overview:{input:d([]),output:Ka}},Ya={read:{input:d([Vs]),output:Hs}},Xa=h(["running","streaming","tool_call","retrying"]),Ja=c({approvalId:s(),toolCallId:s().optional(),since:u()}),Za=c({toolCallId:s(),name:s(),since:u()}),ec=c({failedAttempt:u(),nextAttempt:u(),maxAttempts:u(),delayMs:u(),errorName:s().optional(),statusCode:u().optional()}),tc=c({turnId:u(),origin:k(),phase:Xa,stream:h(["assistant","thinking","tool_call"]).optional(),step:u(),ending:S(),endingReason:h(["aborted","max_steps","error"]).optional(),retry:ec.optional(),pendingApprovals:g(Ja),activeToolCalls:g(Za),since:u()}),oc=h(["completed","cancelled","failed","blocked"]),nc=c({turnId:u(),reason:oc,durationMs:u().optional(),at:u()}),sc=c({kind:s(),id:s(),since:u()}),ic=h(["ready","disposed"]),rc=c({lifecycle:ic,turn:tc.optional(),lastTurn:nc.optional(),background:g(sc)}),ac={state:{input:d([]),output:rc}},cc=o=>c({items:g(o),nextCursor:s().optional()}),P=o=>q([o,ae(),Ws()]).transform(e=>e??void 0),_=q([It(),ae()]).transform(()=>{}),wo=c({added:g(s()),removed:g(s()),changed:g(s())}),Gt=R(s(),s()),Eo=u().int().min(1).max(2147483647),Ft={enabled:S().optional(),startupTimeoutMs:Eo.optional(),toolTimeoutMs:Eo.optional(),enabledTools:g(s()).optional(),disabledTools:g(s()).optional()},Bt=c({transport:b("stdio"),runtime_id:s().min(1).optional(),command:s().min(1),args:g(s()).optional(),env:Gt.optional(),cwd:s().optional(),executor:h(["local","kaos"]).optional(),...Ft}),Vt=c({transport:b("http"),url:s().url(),headers:Gt.optional(),auth:b("oauth").optional(),bearerTokenEnvVar:s().min(1).optional(),...Ft}),Ht=c({transport:b("sse"),url:s().url(),headers:Gt.optional(),auth:b("oauth").optional(),bearerTokenEnvVar:s().min(1).optional(),...Ft}),Je=O("transport",[Bt,Vt,Ht]),bn=h(["global","plugin","caller"]),dc=c({id:s(),name:s()}),Y=c({cwd:s().min(1).optional()}),lc=c({cwd:s().min(1).optional(),verify:S().optional()}),Tt=O("transport",[Bt.extend({name:s().min(1)}),Vt.extend({name:s().min(1)}),Ht.extend({name:s().min(1)})]),Te=O("transport",[Bt.extend({envKeys:g(s()).optional()}),Vt.extend({headerKeys:g(s()).optional()}),Ht.extend({headerKeys:g(s()).optional()})]),Se=c({name:s(),config:Te,source:bn,origin:s(),mutable:S(),plugin:dc.optional()}),uc=c({name:s().min(1).optional(),server:Tt.optional(),cwd:s().min(1).optional()}),pc=c({success:S(),output:s()}),mc=c({name:s().min(1),cwd:s().min(1).optional()}),hc=c({state:h(["idle","stopped","unconfirmed"]),output:s()}),ie=O("source",[c({source:b("global"),name:s().min(1)}),c({source:b("plugin"),pluginId:s().min(1),serverName:s().min(1)})]),Wt=h(["not-applicable","bearer-token","oauth-required","oauth-authorized","oauth-expired","unavailable"]),gc=c({serverId:s(),locator:ie,runtimeName:s(),canonicalUrl:s().optional(),origin:bn,config:Te,enabled:S(),editable:S()}),vc=gc.extend({authStatus:Wt,checkedAt:u().optional(),error:s().optional()}),Sc=c({name:s(),authStatus:Wt}),wt=c({credentialId:s().regex(/^[a-f0-9]{64}$/)}),fc=wt.extend({serverName:s().min(1),displayUrl:s().min(1),origin:b("unknown")}),yc=c({canonicalUrl:nn()}),bc=O("status",[c({status:b("authorization-required"),flowId:s(),authorizationUrl:s()}),c({status:b("already-authorized")})]),_c=c({flowId:s().min(1),timeoutMs:u().int().min(1).max(2**31-1).optional()}),Ic={listServers:{input:d([Y.optional()]),output:g(Se)},getServer:{input:d([s().min(1),Y.optional()]),output:Se},addServer:{input:d([Tt,Y.optional()]),output:g(Se)},updateServer:{input:d([Tt,Y.optional()]),output:g(Se)},removeServer:{input:d([s().min(1),Y.optional()]),output:g(Se)},testServer:{input:d([uc]),output:pc},stopServer:{input:d([mc]),output:hc},listAuthStatuses:{input:d([lc.optional()]),output:g(Sc)},inspectServers:{input:d([g(ie).optional(),Y.optional()]),output:g(vc)},resolveServerByName:{input:d([s().min(1),Y.optional()]),output:ie},beginServerAuth:{input:d([ie,Y.optional()]),output:bc},completeServerAuth:{input:d([_c]),output:_},cancelServerAuth:{input:d([c({flowId:s().min(1)})]),output:_},resetServerAuth:{input:d([ie,Y.optional(),nn().optional()]),output:_},listStoredOAuthCredentials:{input:d([]),output:g(fc)},revealStoredOAuthCredential:{input:d([wt]),output:yc},revokeStoredOAuthCredential:{input:d([wt]),output:_}},zt=h(["direct","compact","fresh"]),Et=c({operationId:s().min(1),model:s().min(1),mode:zt,thinking:s().optional(),selectedFromModel:s().optional()}),ne=c({operationId:s(),agentId:s(),state:h(["pending","preparing","completed","failed","cancelled"]),fromModel:s(),toModel:s(),mode:zt,binding:c({model:s(),thinking:s()}).optional(),windowEpoch:u().int().nonnegative().optional(),summaryGenerated:S().optional(),error:c({code:s(),message:s()}).optional()}),_n=c({input:Et,receipt:ne,revision:u().int().nonnegative(),originalBinding:c({model:s(),thinking:s()}),queueIndex:u().int()}),Tc=c({type:b("prompt.model_switch_queued"),time:u().optional(),entry:_n.omit({queueIndex:!0}),queueIndex:u().int().nonnegative()}),wc=c({type:b("prompt.model_switch_status"),time:u().optional(),operationId:s(),receipt:ne}),Ec=c({type:b("turn.step.started"),time:u().optional(),turnId:u(),step:u(),stepId:s().optional()}),kc=c({type:b("turn.step.interrupted"),time:u().optional(),turnId:u(),step:u(),stepId:s().optional(),reason:s(),message:s().optional()}),Cc=c({type:b("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()}),Rc=c({type:b("hook.result"),time:u().optional(),turnId:u().optional(),hookEvent:s(),content:s(),blocked:S().optional()}),Z=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()})}),Pc=c({type:b("goal.updated"),time:u().optional(),snapshot:Z.nullable(),change:c({kind:h(["lifecycle","completion"]),status:Z.shape.status.optional(),reason:s().optional(),actor:h(["user","model","runtime","system"]).optional(),stats:c({turnsUsed:u(),tokensUsed:u(),wallClockMs:u()}).optional()}).optional()}),Oc=c({type:b("turn.started"),time:u().optional(),turnId:u(),origin:k(),prompt:s().optional(),promptId:s().optional()}),Ac=c({type:b("turn.ended"),time:u().optional(),turnId:u(),reason:h(["completed","cancelled","failed","blocked"]),error:k().optional(),durationMs:u().optional(),interruptReason:h(["user_cancelled","aborted","max_steps","error","filtered","blocked"]).optional()}),Mc=c({type:b("assistant.delta"),time:u().optional(),turnId:u(),step:u().optional(),stepId:s().optional(),partId:s().optional(),delta:s(),part:zs.optional()}),xc=c({type:b("thinking.delta"),time:u().optional(),turnId:u(),delta:s()}),Uc=c({type:b("tool.call.started"),time:u().optional(),turnId:u(),toolCallId:s(),name:s(),args:k(),description:s().optional(),display:k().optional()}),Dc=c({type:b("tool.call.delta"),time:u().optional(),turnId:u(),toolCallId:s(),name:s().optional(),argumentsPart:s().optional()}),Nc=c({type:b("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:k().optional(),replace:S().optional()})}),jc=c({type:b("tool.result"),time:u().optional(),turnId:u(),toolCallId:s(),output:k(),isError:S().optional(),synthetic:S().optional()}),Ze=k(),Kt=h(["agent_idle","subagents_done","tasks_done"]),Lc=c({type:b("prompt.submitted"),time:u().optional(),promptId:s(),userMessageId:s(),status:h(["running","queued","blocked"]),content:g(Ze),createdAt:s(),appendTiming:Kt.optional(),revision:u().int().nonnegative().optional()}),qc=c({type:b("prompt.queued"),time:u().optional(),promptId:s(),content:g(Ze),queueLength:u().int().nonnegative(),appendTiming:Kt.optional(),revision:u().int().nonnegative().optional()}),$c=c({type:b("prompt.started"),time:u().optional(),promptId:s()}),Gc=c({type:b("prompt.replaced"),time:u().optional(),promptId:s(),content:g(Ze),replacedAt:s(),message:k().optional(),revision:u().int().nonnegative().optional()}),Fc=c({type:b("prompt.timing_changed"),time:u().optional(),promptId:s(),appendTiming:Kt,revision:u().int().nonnegative(),changedAt:s()}),Bc=c({type:b("prompt.steered"),time:u().optional(),activePromptId:s(),promptIds:g(s()),content:g(Ze),steeredAt:s()}),Vc=c({type:b("prompt.completed"),time:u().optional(),promptId:s(),finishedAt:s(),reason:h(["completed","failed","blocked"]).optional()}),Hc=c({type:b("prompt.aborted"),time:u().optional(),promptId:s(),abortedAt:s(),beforeStart:S().optional()}),Wc=c({type:b("prompt.moved"),time:u().optional(),promptId:s(),targetIndex:u().int().nonnegative(),queuedPromptIds:g(s()),movedAt:s()}),zc=c({type:b("compaction.started"),time:u().optional(),trigger:h(["manual","auto"]),instruction:s().optional(),phase:h(["queued","running"]).optional()}),Kc=c({type:b("compaction.blocked"),time:u().optional(),turnId:u().optional()}),Qc=c({type:b("compaction.cancelled"),time:u().optional(),trigger:h(["manual","auto"]).optional(),reason:s().optional()}),Yc=c({type:b("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:g(s()).optional(),fallbackFrom:h(["relay","summarize"]).optional()})}),Xc=Ce({time:u().optional(),turnId:u(),toolCallId:s(),toolName:s(),action:s()}),Jc=Ce({time:u().optional(),turnId:u(),toolCallId:s()}),Zc=Ce({time:u().optional(),message:s()}),ed=c({type:b("warning"),time:u().optional(),message:s(),code:s().optional()}),td=Ce({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()}),od={"prompt.model_switch_queued":{kind:"stream",name:"events",type:"prompt.model_switch_queued",schema:Tc},"prompt.model_switch_status":{kind:"stream",name:"events",type:"prompt.model_switch_status",schema:wc},"turn.step.started":{kind:"stream",name:"events",type:"turn.step.started",schema:Ec},"turn.step.interrupted":{kind:"stream",name:"events",type:"turn.step.interrupted",schema:kc},"turn.step.retrying":{kind:"stream",name:"events",type:"turn.step.retrying",schema:Cc},"hook.result":{kind:"stream",name:"events",type:"hook.result",schema:Rc},"goal.updated":{kind:"stream",name:"events",type:"goal.updated",schema:Pc},"turn.started":{kind:"stream",name:"events",type:"turn.started",schema:Oc},"turn.ended":{kind:"stream",name:"events",type:"turn.ended",schema:Ac},"assistant.delta":{kind:"stream",name:"events",type:"assistant.delta",schema:Mc},"thinking.delta":{kind:"stream",name:"events",type:"thinking.delta",schema:xc},"tool.call.started":{kind:"stream",name:"events",type:"tool.call.started",schema:Uc},"tool.call.delta":{kind:"stream",name:"events",type:"tool.call.delta",schema:Dc},"tool.progress":{kind:"stream",name:"events",type:"tool.progress",schema:Nc},"tool.result":{kind:"stream",name:"events",type:"tool.result",schema:jc},"prompt.submitted":{kind:"stream",name:"events",type:"prompt.submitted",schema:Lc},"prompt.queued":{kind:"stream",name:"events",type:"prompt.queued",schema:qc},"prompt.started":{kind:"stream",name:"events",type:"prompt.started",schema:$c},"prompt.replaced":{kind:"stream",name:"events",type:"prompt.replaced",schema:Gc},"prompt.moved":{kind:"stream",name:"events",type:"prompt.moved",schema:Wc},"prompt.timing_changed":{kind:"stream",name:"events",type:"prompt.timing_changed",schema:Fc},"prompt.steered":{kind:"stream",name:"events",type:"prompt.steered",schema:Bc},"prompt.completed":{kind:"stream",name:"events",type:"prompt.completed",schema:Vc},"prompt.aborted":{kind:"stream",name:"events",type:"prompt.aborted",schema:Hc},"compaction.started":{kind:"stream",name:"events",type:"compaction.started",schema:zc},"compaction.blocked":{kind:"stream",name:"events",type:"compaction.blocked",schema:Kc},"compaction.cancelled":{kind:"stream",name:"events",type:"compaction.cancelled",schema:Qc},"compaction.completed":{kind:"stream",name:"events",type:"compaction.completed",schema:Yc},"permission.approval.requested":{kind:"stream",name:"events",type:"permission.approval.requested",schema:Xc},"permission.approval.resolved":{kind:"stream",name:"events",type:"permission.approval.resolved",schema:Jc},error:{kind:"stream",name:"events",type:"error",schema:Zc},warning:{kind:"stream",name:"events",type:"warning",schema:ed},"agent.status.updated":{kind:"stream",name:"events",type:"agent.status.updated",schema:td}};function In(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 Tn=Ks.transform(In),nd=Qs.transform(o=>({...o,selection:In(o.selection),effective:{...o.effective,kiki_context:[...o.effective.kiki_context]}})),sd=c({type:b("text"),text:s()}),id=c({type:b("image_url"),imageUrl:c({url:s(),id:s().optional()})}),rd=c({type:b("video_url"),videoUrl:c({url:s(),id:s().optional()})}),wn=O("type",[sd,id,rd]);c({});const ad=c({execution:Tn.optional(),afterModelSwitch:s().min(1).optional(),modelSwitchMode:h(["direct","compact","fresh"]).optional(),personaGreetingReply:S().optional(),profile:s().optional(),model:s().optional(),thinking:s().min(1).nullable().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()}),kt=c({input:g(wn),execution:ad.optional(),appendTiming:h(["agent_idle","subagents_done","tasks_done"]).optional(),disabledTools:g(s()).optional(),promptId:s().min(1).optional()}),cd=c({name:s(),args:s().optional()}),dd=kt.extend({skills:g(cd).min(1)}),ko=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()}),ld=c({input:g(wn)}),ud=c({name:s(),args:s().optional(),afterModelSwitch:s().min(1).optional()}),Ct=c({turn_id:u()}),Rt=c({code:s(),message:s(),name:s().optional(),details:R(s(),k()).optional(),retryable:S(),get cause(){return Rt.optional()}}),pd=c({promptId:s(),turnId:u().optional(),state:h(["completed","failed","cancelled","blocked"]),result:O("type",[c({type:b("completed"),steps:u(),truncated:S()}),c({type:b("failed"),steps:u(),error:Rt}),c({type:b("cancelled"),steps:u(),reason:Rt})]).optional()});c({turnId:u().optional()});const md=c({command:s(),commandId:s().optional()}),hd=c({stdout:s(),stderr:s(),isError:S().optional(),backgrounded:S().optional()});c({commandId:s()});c({model:s()});const gd=c({model:s(),providerName:s().optional()});c({effort:s().min(1)});const vd=c({effort:s()}),Sd=c({rebuilt:g(h(["profile","prompt_fields","skills","instructions","plugins","mcp","injections"])),changed:S(),changes:c({profile:S(),promptFields:S(),skills:S(),instructions:S(),plugins:S(),mcp:S(),injections:S()}),readiness:c({mcp:g(c({runtimeName:s(),connection:h(["enabled","disabled","connecting","connected","failed","unavailable"]),error:s().optional()})),plugins:c({state:h(["ready","pending","failed","unavailable"]),errors:g(s())})})}),En=h(["summarize","auto","fresh"]),fd=c({strategy:En,source:h(["session","profile","global","default","subagent","executor"]),shadow:S()}),Ue=c({workspaceId:s(),runtimeId:s()}),yd=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()}),Be=h(["manual","auto","review","yolo"]);c({mode:Be});const bd=c({state:h(["idle","running"]),activeTurnId:u().optional(),pendingTurnIds:g(u()),hasPendingRequests:S(),activeTraceId:s().optional()}),Ve=c({inputOther:u(),output:u(),inputCacheRead:u(),inputCacheCreation:u()}),_d=c({byModel:R(s(),Ve).optional(),currentTurn:Ve.optional(),total:Ve.optional()});c({history:g(k()),tokenCount:u()});const Id=c({name:s(),description:s().optional(),source:s()});c({name:s(),args:s().optional()});const Td=q([ae(),c({id:s(),content:s(),path:s()})]);c({id:s().optional()});c({activeOnly:S().optional(),limit:u().optional()});const wd=h(["running","completed","failed","timed_out","killed","lost"]),De={taskId:s(),description:s(),status:wd,detached:S().optional(),startedAt:u(),endedAt:q([u(),ae()]),stopReason:s().optional(),terminalNotificationSuppressed:S().optional(),timeoutMs:u().optional(),receipt:Ys.optional(),receiptVerification:h(["verified","legacy_unverified","invalid"]).optional()},Ne=O("kind",[c({kind:b("process"),command:s(),pid:u(),exitCode:q([u(),ae()]),...De}),c({kind:b("agent"),agentId:s().optional(),profile:s().optional(),model:s().optional(),thinkingEffort:s().optional(),...De}),c({kind:b("question"),questionCount:u(),toolCallId:s().optional(),...De}),c({kind:b("media"),jobId:s(),...De})]);c({taskId:s(),reason:s().optional()});c({taskId:s(),tail:u().optional()});const Ed={getGoal:{input:d([]),output:c({goal:Z.nullable()})},createGoal:{input:d([c({objective:s(),completionCriterion:s().optional(),followUpTiming:h(["subagents_done","tasks_done"]).optional(),initialStatus:h(["active","paused"]).optional(),replace:S().optional()})]),output:Z},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(),budgetLimits:Xs.optional()})]),output:Z},pauseGoal:{input:d([]),output:Z},resumeGoal:{input:d([c({reason:s().optional(),continueIfPaused:S().optional(),continueIfBlocked:S().optional()}).optional()]),output:Z},cancelGoal:{input:d([]),output:Z}},kd={switchModel:{input:d([Et]),output:ne},getModelSwitch:{input:d([s()]),output:P(ne)},listModelSwitches:{input:d([]),output:g(_n)},updateModelSwitch:{input:d([Et,u().int().nonnegative().optional()]),output:ne},cancelModelSwitch:{input:d([s()]),output:ne},recoverModelSwitch:{input:q([d([s(),b("retry"),zt.optional()]),d([s(),b("keep_original")])]),output:ne},submit:{input:d([kt]),output:P(Ct)},submitAndWait:{input:d([kt]),output:pd},submitSteer:{input:d([ld]),output:P(Ct)},resumeRecoveredQueue:{input:d([]),output:_}},Cd={activate:{input:d([ud]),output:q([ko,Ct])},promptWithSkills:{input:d([dd]),output:ko}},Rd={reconcileWhenIdle:{input:d([s()]),output:_}},Pd={rebuild:{input:d([]),output:Sd}},Od={undo:{input:d([u().int().positive().max(Number.MAX_SAFE_INTEGER)]),output:u()}},Ad={activate:{input:d([c({pluginId:s(),commandName:s(),args:s().optional()})]),output:_}},Md={refreshSessionStart:{input:d([]),output:_}},xd={shutdown:{input:d([s().optional()]),output:_}},Ud={cancelFromUser:{input:d([u().optional()]),output:_},status:{input:d([]),output:bd}},Dd={mode:{input:d([]),output:Be},setMode:{input:d([Be]),output:_},setModeAndBroadcast:{input:d([Be]),output:_}},Nd={list:{input:d([]),output:g(Id)},run:{input:d([s(),s().optional()]),output:_}},jd={get:{input:d([]),output:Ue},set:{input:d([Ue]),output:Ue},switch:{input:d([s()]),output:Ue}},Ld={get:{input:d([]),output:g(k())},append:{input:d([k()]),output:_},clear:{input:d([]),output:_}},qd={appendImported:{input:d([k()]),output:_}},$d={statusSize:{input:d([]),output:u()}},Gd={run:{input:d([md]),output:hd},cancel:{input:d([s()]),output:_}},Co=c({definitionId:s().optional(),source:h(["declared","inherited-default","builtin-default"]).optional(),activeTools:g(s()).readonly().optional(),currentTools:g(s()).readonly().optional(),revision:s().optional(),canRefresh:S(),reason:h(["main_only","binding_restricted","source_changed","source_unavailable"]).optional()}),Fd={isToolActive:{input:d([s(),h(["builtin","user","mcp","plugin"]).optional()]),output:S()}},Bd={inspectToolPolicy:{input:d([]),output:Co},refreshToolPolicy:{input:d([s().min(1)]),output:Co},getModel:{input:d([]),output:s()},setModel:{input:d([s()]),output:gd},setEffort:{input:d([s()]),output:vd},setThinking:{input:d([s()]),output:_},getEffectiveThinkingLevel:{input:d([]),output:s()},getModelCapabilities:{input:d([]),output:yd},getAgentsMdWarning:{input:d([]),output:P(s())}},Vd={status:{input:d([]),output:_d}},Hd={status:{input:d([]),output:Td},enter:{input:d([]),output:_},clear:{input:d([]),output:_},cancel:{input:d([s().optional()]),output:_}},Wd=c({name:s(),transport:h(["stdio","http","sse"]),status:h(["pending","connected","failed","disabled","needs-auth","removed"]),toolCount:u(),error:s().optional()}),zd=c({locator:ie,override:h(["on","off","inherit"])}),Ro=c({locator:ie,runtimeName:s(),origin:h(["global","plugin","caller"]),config:O("transport",[Te.options[0].omit({env:!0}),Te.options[1].omit({headers:!0}),Te.options[2].omit({headers:!0})]),authStatus:Wt,connection:h(["enabled","disabled","connecting","connected","failed","unavailable"]),override:h(["on","off","inherit"]),error:s().optional()}),Kd={list:{input:d([]),output:g(Wd)},waitForInitialLoad:{input:d([]),output:_},initialLoadDurationMs:{input:d([]),output:u()},reconnect:{input:d([s()]),output:_},connect:{input:d([s(),Je]),output:_},listMcpSessionCapabilities:{input:d([]),output:g(Ro)},setMcpSessionOverride:{input:d([zd]),output:Ro}},Qd=c({source:h(["manual","auto"]),instruction:s().optional()}),Yd={begin:{input:d([Qd]),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:fd},setContextStrategyOverride:{input:d([En.nullable()]),output:_}},Xd={list:{input:d([S().optional(),u().optional()]),output:g(Ne)},stopByUser:{input:d([s()]),output:P(Ne)},stop:{input:d([s(),s().optional()]),output:P(Ne)},detach:{input:d([s()]),output:P(Ne)},readOutput:{input:d([s(),u().optional()]),output:s()}},kn=h(["pending","authenticated","denied","failed","expired","cancelled"]),Jd=O("status",[c({flow_id:s(),provider:s(),status:b("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:b("authenticated")})]),Zd=c({flow_id:s(),provider:s(),status:kn,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()}),el=c({cancelled:S(),status:kn}),tl=c({logged_out:b(!0),provider:s()}),Cn=c({loggedIn:S(),provider:s().optional()}),ol=c({changed:g(c({provider_id:s(),provider_name:s(),added:u(),removed:u()})),unchanged:g(s()),failed:g(c({provider:s(),reason:s()}))}),nl=c({region:h(["mainland-cn","global"]).optional()}),sl=c({id:s(),label:s(),provider:s(),protocol:s(),signed_in:S(),auth_source:Js.optional(),connection_state:h(["ready","refresh_required","reconnect_required","signed_out"]).optional(),account:O("state",[c({state:b("known"),id:s()}),c({state:b("unknown")})]),quota:O("state",[c({state:b("known"),label:s(),remaining:u(),unit:h(["count","percent"]),reset_at:s().optional()}),c({state:b("unknown")})])}),il={probeOriginal:{input:d([ei]),output:io},connectOriginal:{input:d([Zs]),output:io},listMethods:{input:d([]),output:g(sl)},startLogin:{input:d([s().optional(),nl.optional()]),output:Jd},getFlow:{input:d([s().optional()]),output:P(Zd)},cancelLogin:{input:d([s().optional()]),output:el},logout:{input:d([s().optional()]),output:tl},status:{input:d([s().optional()]),output:Cn},refreshOAuthProviderModels:{input:d([]),output:ol}},rl={summarize:{input:d([]),output:g(Cn)},ensureReady:{input:d([s().optional()]),output:_}},al=c({id:s(),state:h(["ok","missing","failed"]),reason:s().optional(),detail:s().optional(),optional:S().optional()}),cl=c({running:S(),step:s().optional(),percent:u().optional(),error:s().optional(),note:s().optional()}),je=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:g(al),plan:c({artifact:c({version:s(),url:s(),sha256:s(),metadataUrl:s(),maxBytes:u()}),destination:s(),browserExtensionUrl:s().optional(),note:s()}).optional(),install:cl}),dl={listCapabilities:{input:d([]),output:g(je)},getCapability:{input:d([s()]),output:je},installCapability:{input:d([s(),s().optional(),h(["driver-only","managed-browser"]).optional()]),output:je},cancelCapability:{input:d([s()]),output:je}},Po=new Map,ll=new Set;function E(o){for(const e of Object.values(o.codes)){const t=Po.get(e);if(t!==void 0&&t!==o.codes)throw new Error(`error code '${e}' is registered by two different domains`);Po.set(e,o.codes)}for(const e of o.retryable??[])ll.add(e);for(const[e,t]of Object.entries(o.info??{}));}const Rn={codes:{INTERNAL:"internal",NOT_IMPLEMENTED:"not_implemented",VALIDATION_FAILED:"validation.failed"},info:{internal:{title:"Internal error",retryable:!1,public:!0,action:"Inspect logs or report the issue with diagnostics."},not_implemented:{title:"Not implemented",retryable:!1,public:!0,action:"This feature is not implemented yet."}}};E(Rn);const Pn={codes:{REQUEST_IDENTITY_UNSUPPORTED:"request_identity.unsupported",REQUEST_IDENTITY_CONFLICT:"request_identity.conflict",REQUEST_IDENTITY_INVALID:"request_identity.invalid",REQUEST_IDENTITY_NOT_FOUND:"request_identity.not_found",REQUEST_IDENTITY_UPDATE_FAILED:"request_identity.update_failed"},info:{"request_identity.unsupported":{title:"Request identity unsupported",retryable:!1,public:!0,action:"Choose a request identity policy supported by the selected protocol."},"request_identity.conflict":{title:"Request identity conflict",retryable:!1,public:!0,action:"Remove conflicting legacy fields or custom headers."},"request_identity.invalid":{title:"Invalid request identity",retryable:!1,public:!0,action:"Correct the request identity policy values."},"request_identity.not_found":{title:"Request identity not found",retryable:!1,public:!0,action:"Reload the identity list and pick an existing identity."},"request_identity.update_failed":{title:"Request identity update check failed",retryable:!0,public:!0,action:"Check the network or the installed CLI, then check again. The current version stays in use."}}};E(Pn);const ul=/^(?:[a-z][a-z0-9_]{0,31}|custom:[a-z0-9][a-z0-9_-]{0,47})$/u,On=h(["codex_compatible","claude_code_compatible","grok_build_compatible","opencode_compatible","kimi_code","none"]),An=s().regex(ul),Mn=O("mode",[c({mode:b("none")}).strict(),c({mode:b("codex_default")}).strict(),c({mode:b("custom"),value:s().min(1).refine(o=>!/[\u0000-\u001F\u007F]/u.test(o))}).strict()]),pl=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:Mn.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(Yt,{message:"request identity overrides must contain a leaf value"}),Qt=c({preset:On.optional(),profile:An.optional(),overrides:pl.optional()}).strict().refine(xn,{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"}),ml=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:Mn.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(Yt,{message:"request identity overrides must contain a leaf value"});c({preset:On.optional(),profile:An.optional(),overrides:ml.optional()}).strict().refine(xn,{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 xn(o){return o.preset!==void 0||o.profile!==void 0||o.overrides!==void 0}function Yt(o){return o===void 0?!1:o===null||typeof o!="object"?!0:Object.values(o).some(Yt)}h(["connected","error","unconfigured"]);const hl=c({systemPrompt:s(),messages:g(k()),tools:g(k()).optional(),responseFormat:k().optional()}),gl=c({cacheKey:s().optional(),temperature:u().optional(),topP:u().optional(),thinkingEffort:s().optional(),maxCompletionTokens:u().optional()}).optional(),vl=c({type:s()}).passthrough(),Sl={listModels:{input:d([]),output:g(oi)},listProviders:{input:d([]),output:g(ro)},getProvider:{input:d([s()]),output:ro},setDefaultModel:{input:d([s()]),output:ti},generate:{input:d([s(),hl,gl]),chunk:vl,streaming:!0}},fl=c({scope:h(["all","oauth"]).optional(),providerId:s().optional(),apiKey:s().min(1).optional()}),yl={listDiscoveredModels:{input:d([]),output:si},refreshProviderModels:{input:d([fl.optional()]),output:ni}},Xt=h(["user","memory"]),bl=c({value:k().optional(),defaultValue:k().optional(),userValue:k().optional(),memoryValue:k().optional()}),_l=c({domain:s().optional(),severity:h(["warning","error"]),message:s()}),Il=d([s(),k(),Xt.optional()]).superRefine(([o,e],t)=>{o==="requestIdentity"&&Jt(e,t,[1],!1)}),Tl=d([s(),k(),Xt.optional()]).superRefine(([o,e],t)=>{o==="requestIdentity"&&Jt(e,t,[1],!0)}),wl=d([R(s(),k()),Xt.optional()]).superRefine(([o],e)=>{Object.hasOwn(o,"requestIdentity")&&Jt(o.requestIdentity,e,[0,"requestIdentity"],!0)});function Jt(o,e,t,n){if(n&&o==null)return;const i=Qt.safeParse(o);if(!i.success)for(const a of i.error.issues)e.addIssue({...a,path:[...t,...a.path]})}const El={get:{input:d([s()]),output:k()},inspect:{input:d([s()]),output:bl},getAll:{input:d([]),output:R(s(),k())},set:{input:Il,output:_},replace:{input:Tl,output:_},replaceSections:{input:wl,output:_},reload:{input:d([]),output:_},diagnostics:{input:d([]),output:g(_l)}},G={input:d([]),output:s()},kl={input:d([]),output:c({productName:s(),version:s(),platform:s(),userAgentSuffix:s().optional()})},Cl={platform:G,arch:G,cwd:G,osHomeDir:G,homeDir:G,configPath:G,clientVersion:G,clientIdentity:kl,sessionsDir:G,blobsDir:G,storeDir:G,cacheDir:G,logsDir:G},Un=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()}),Rl=c({name:s().optional(),mimeType:s().optional(),expiresInSec:u().optional()}),Pl=c({meta:Un,data:s()}),Ol={save:{input:d([s(),s().min(1),Rl]),output:Un},get:{input:d([s().min(1)]),output:Pl},delete:{input:d([s().min(1)]),output:_}},Oo=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()}),Al={enabled:{input:d([s()]),output:S()},snapshot:{input:d([]),output:R(s(),S())},enabledIds:{input:d([]),output:g(s())},explain:{input:d([s()]),output:P(Oo)},explainAll:{input:d([]),output:g(Oo)}},Ml=c({name:s().min(1),path:s().min(1),is_dir:b(!0)}),xl=c({path:s().min(1),parent:s().min(1).nullable(),entries:g(Ml)}),Ul=c({home:s().min(1),recent_roots:g(s().min(1))}),Dl={browse:{input:d([s().optional()]),output:xl},home:{input:d([]),output:Ul}},Nl=h(["openai-codex","grok-build","kimi-code"]),jl=h(["file","keyring","encrypted"]),Ll=c({kind:b("local_original"),provider:Nl,homeDir:s().min(1),storageBackend:jl,authFile:s().min(1).optional(),accountId:s().min(1).optional(),userId:s().min(1).optional(),scope:s().min(1).optional()}).strict().superRefine((o,e)=>{o.provider!=="kimi-code"&&o.accountId===void 0&&e.addIssue({code:"custom",path:["accountId"],message:"An original account identity is required."}),o.provider==="kimi-code"&&(o.storageBackend==="encrypted"||o.accountId!==void 0||o.userId!==void 0||o.scope!==void 0)&&e.addIssue({code:"custom",message:"Kimi Code sources select a credential slot, not an account identity."})}),Dn=c({storage:h(["file","keyring"]),key:s().min(1),oauthHost:s().min(1).optional(),source:Ll.optional()}),ql=h(["anthropic","openai","openai_responses","google-genai"]),Nn=c({providerId:s().optional(),baseUrl:s().optional(),apiKey:s().optional(),oauth:Dn.optional(),protocol:ql.optional(),name:s().optional(),aliases:g(s()).optional(),provider:s().optional(),model:s().optional(),maxContextSize:u().int().min(1).optional(),maxOutputSize:u().int().min(1).optional(),capabilities:g(s()).optional(),displayName:s().optional(),reasoningKey:s().optional(),adaptiveThinking:S().optional(),betaApi:S().optional(),supportEfforts:g(s()).optional(),defaultEffort:s().optional(),requestIdentity:Qt.optional()}),$l=Nn.omit({providerId:!0,baseUrl:!0,apiKey:!0,oauth:!0,protocol:!0,name:!0,aliases:!0,provider:!0,model:!0,betaApi:!0,requestIdentity:!0}).partial(),ft=Nn.extend({overrides:$l.optional(),pricingModel:s().trim().min(1).optional()}).passthrough(),Gl={get:{input:d([s()]),output:P(ft)},list:{input:d([]),output:R(s(),ft)},set:{input:d([s(),ft]),output:_},delete:{input:d([s()]),output:_}},Fl=c({baseRevision:s().min(1).optional()}),Bl={readModel:{input:d([s()]),output:at},createModel:{input:d([ci]),output:at},updateModel:{input:d([s(),ai]),output:at},deleteModel:{input:d([s(),Fl.optional()]),output:It()},readProvider:{input:d([s()]),output:rt},createProvider:{input:d([ri]),output:rt},updateProvider:{input:d([s(),ii]),output:rt},deleteProvider:{input:d([s()]),output:It()}},Vl=c({severity:h(["error","warn","info"]),message:s()}),Hl=c({name:s().optional(),email:s().optional()}),Wl=c({skill:s()}),zl=c({displayName:s().optional(),shortDescription:s().optional(),longDescription:s().optional(),developerName:s().optional(),websiteURL:s().optional()}),Kl=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()}),Ql=c({path:s(),name:s()}),Yl=h(["kimi-plugin-root","kimi-plugin-dir","claude-code"]),Pt=h(["local-path","zip-url","github"]),Xl=h(["ok","error"]),Ot=c({kind:h(["branch","tag","sha"]),value:s()}),Jl=c({name:s(),version:s().optional(),description:s().optional(),keywords:g(s()).optional(),author:Hl.optional(),homepage:s().optional(),license:s().optional(),icon:s().optional(),skills:g(s()).optional(),agents:g(s()).optional(),sessionStart:Wl.optional(),mcpServers:R(s(),Je).optional(),hooks:g(Kl).optional(),commands:g(Ql).optional(),interface:zl.optional(),skillInstructions:s().optional(),systemPrompt:s().optional(),unsupportedComponents:g(s()).optional()}),Zl=c({name:s(),runtimeName:s(),enabled:S(),transport:h(["stdio","http","sse"]),command:s().optional(),args:g(s()).optional(),cwd:s().optional(),url:s().optional(),envKeys:g(s()).optional(),headerKeys:g(s()).optional()}),Ao=c({owner:s(),repo:s(),ref:Ot,installedSha:s().optional()}),He=c({id:s(),displayName:s(),version:s().optional(),icon:s().optional(),enabled:S(),globalEnabled:S(),state:Xl,skillCount:u(),mcpServerCount:u(),enabledMcpServerCount:u(),hookCount:u(),commandCount:u(),hasErrors:S(),source:Pt,originalSource:s().optional(),github:Ao.optional(),zipSha256:s().optional(),rollback:c({version:s().optional(),source:Pt,originalSource:s().optional(),github:Ao.optional(),zipSha256:s().optional()}).optional()}),eu=He.extend({root:s(),installedAt:s(),updatedAt:s().optional(),manifestKind:Yl.optional(),manifestPath:s().optional(),manifest:Jl.optional(),mcpServers:g(Zl),shadowedManifestPath:s().optional(),diagnostics:g(Vl)}),tu=c({added:g(s()),removed:g(s()),errors:g(c({id:s(),message:s()}))}),ou=c({id:s(),source:Pt,current:Ot.optional(),latest:Ot,displayVersion:s(),updateAvailable:S()}),nu=c({pluginId:s(),name:s(),description:s(),body:s(),path:s()}),su=sn.extend({fingerprint:s().optional(),consent:S().optional(),defaultEnabled:S().optional()}),iu=c({id:s(),enabled:S()}),ru=c({id:s(),server:s(),enabled:S()}),au=c({id:s(),deleteData:S().optional()}),cu=c({id:s()}),du={listPlugins:{input:d([]),output:g(He)},previewPlugin:{input:d([sn]),output:di},installPlugin:{input:d([su]),output:He},rollbackPlugin:{input:d([c({id:s()})]),output:He},setPluginEnabled:{input:d([iu]),output:_},setPluginMcpServerEnabled:{input:d([ru]),output:_},removePlugin:{input:d([au]),output:_},reloadPlugins:{input:d([]),output:tu},getPluginInfo:{input:d([cu]),output:eu},listPluginCommands:{input:d([]),output:g(nu)},checkUpdates:{input:d([]),output:g(ou)}},lu={sources:{input:d([]),output:g(bi)},discover:{input:d([gi]),output:fi},preview:{input:d([hi]),output:Si},start:{input:d([mi]),output:ge},jobs:{input:d([pi.optional()]),output:c({items:g(ge),cursor:s().nullable()})},job:{input:d([s()]),output:ge},cancel:{input:d([s()]),output:ge},resume:{input:d([s()]),output:ge},archives:{input:d([ui.optional()]),output:c({items:g(yi),cursor:s().nullable()})},read:{input:d([li]),output:vi}},uu={list:{input:d([]),output:g(Ae)},get:{input:d([s()]),output:P(ct)},export:{input:d([s()]),output:Ri},preview:{input:d([ki]),output:Ci},install:{input:d([Ei]),output:Ae},checkUpdates:{input:d([]),output:g(Ae)},update:{input:d([wi]),output:Ae},fork:{input:d([Ti]),output:ct},saveLocal:{input:d([Ii]),output:ct},remove:{input:d([_i]),output:_},listMarkets:{input:d([]),output:g(dt)},addMarket:{input:d([ao]),output:dt},updateMarket:{input:d([ao]),output:dt},removeMarket:{input:d([s()]),output:_}},pu={managedSources:{input:d([]),output:g(Me)},sourceSettings:{input:d([Ni]),output:Me},updateSource:{input:d([Di]),output:Me},addScriptSource:{input:d([Ui]),output:Me},sources:{input:d([]),output:g(lo)},setSources:{input:d([xi]),output:g(lo)},catalog:{input:d([c({id:s().min(1)}).strict()]),output:Li},providers:{input:d([]),output:co},capabilities:{input:d([Mi]),output:q([Ai,c({providers:co}).strict()])},voices:{input:d([Oi]),output:ji},jobs:{input:d([Pi.optional()]),output:g(We)},job:{input:d([s().min(1)]),output:We}},mu={cancel:{input:d([s().min(1)]),output:We},resume:{input:d([s().min(1)]),output:We}},hu=c({definition:qi.optional(),id:s().optional(),name:s().optional(),title:s().optional(),job:s().optional(),profile:s().optional(),modelAlias:s().optional(),thinkingEffort:s().optional(),greeting:s().optional(),greetings:g(s()).optional(),roomGreeting:s().optional(),delivery:h(["reply","message"]).optional(),memory:c({shared:g(h(["global","workspace"]))}).optional(),skills:g(s()).optional(),tags:g(s()).optional(),notes:s().optional(),homeWorkspace:s().optional(),description:s().optional(),examples:s().optional(),extensions:k().optional(),expectedRevision:s().optional()}).strict(),gu=c({memory:c({status:h(["committed","pending","failed"]),error:s().optional()}).strict()}).strict(),vu={list:{input:d([$i.optional()]),output:g(Fi)},get:{input:d([s()]),output:P(lt)},put:{input:d([hu]),output:lt},duplicate:{input:d([s(),c({id:s().optional(),name:s().optional()}).optional()]),output:lt},archive:{input:d([s(),S().optional()]),output:Gi},delete:{input:d([s(),s().optional()]),output:gu}},Su={list:{input:d([]),output:g(pt)},enable:{input:d([ut]),output:pt},ensureHomeSession:{input:d([ut]),output:pt},update:{input:d([ut,Bi]),output:or}},fu={list:{input:d([]),output:g(z)},listItems:{input:d([]),output:g(nr)},get:{input:d([B]),output:P(z)},create:{input:d([Xi]),output:z},createFromThreads:{input:d([Yi]),output:z},searchThreads:{input:d([Qi.optional()]),output:tr},addMember:{input:d([B,Ki]),output:z},removeMember:{input:d([B,zi]),output:z},update:{input:d([B,Wi]),output:z},delete:{input:d([B]),output:_},postUserMessage:{input:d([B,Hi]),output:er},pause:{input:d([B]),output:z},continue:{input:d([B]),output:z},stop:{input:d([B]),output:z},log:{input:d([B,Vi.optional()]),output:Zi},usage:{input:d([B]),output:Ji}},yu=s(),Mo=R(s(),s()),bu=h(["static","discover","oauth-catalog"]),_u=Qt,Iu=c({modelSource:bu.optional(),baseUrl:s().optional(),customHeaders:Mo.optional(),defaultModel:s().optional(),requestIdentity:_u.optional(),type:yu.optional(),apiKey:s().optional(),oauth:Dn.optional(),env:Mo.optional(),source:R(s(),k()).optional()}),yt=sr((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},Iu),Tu={get:{input:d([s()]),output:P(yt)},list:{input:d([]),output:R(s(),yt)},set:{input:d([s(),yt]),output:_},delete:{input:d([s()]),output:_}},jn=c({agentVersion:s().optional(),image:S().optional(),audio:S().optional(),fork:S().optional(),nativeSteering:S().optional(),questionForm:S().optional(),planApproval:S().optional(),models:g(s()).optional(),thinkingLevels:g(s()).optional(),authMethods:g(s()).optional(),resume:S().optional(),load:S().optional(),permissionModes:g(s()).optional()}),Zt=c({execution:nd.optional(),homedir:s().optional(),type:h(["main","sub","independent"]).optional(),parentAgentId:q([s(),ae()]).optional(),delegator:O("kind",[c({kind:b("agent"),agentId:s()}),c({kind:b("external"),delegationId:s()})]).optional(),forkedFrom:s().optional(),labels:R(s(),s()).optional(),displayName:s().optional(),userLabel:s().optional(),model:s().optional(),thinkingEffort:s().optional(),executor:s().optional(),executorProtocol:s().optional(),negotiated:jn.optional(),allowKikiSubagents:S().optional(),status:h(["completed","failed","cancelled"]).optional(),completedAt:u().optional(),resultSummary:s().optional(),error:s().optional(),usage:Ve.optional(),contextTokens:u().optional(),toolCallCount:u().int().nonnegative().optional()}),Ln=c({worktreeId:s(),branch:s(),sourceRoot:s(),baseRef:s()}),wu=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:Ln.optional(),forkedFrom:s().optional(),agents:R(s(),Zt).optional(),custom:R(s(),k()).optional(),sshHosts:R(s(),s()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),Eu=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:Ln.optional(),forkedFrom:s().optional(),agents:R(s(),Zt).optional(),custom:R(s(),k()).optional(),sshHosts:R(s(),s()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),ku=h(["id","version","title","titleKind","lastPrompt","delivery","createdAt","updatedAt","activityUpdatedAt","archived","archivedAt","cwd","worktree","forkedFrom","agents","custom","sshHosts","lastTurnReason","usage"]),Cu=c({changed:g(ku)}),Ru={read:{input:d([]),output:wu},getAgentExecutor:{input:d([s().min(1)]),output:P(s())},update:{input:d([Eu]),output:_},setTitle:{input:d([s()]),output:_},setArchived:{input:d([S()]),output:_},registerAgent:{input:d([s(),Zt]),output:_}},xo=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:R(s(),k()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional(),executorId:s().optional(),negotiated:jn.optional(),allowKikiSubagents:S().optional()}),Pu=c({workspaceIds:g(s()).optional(),sessionId:s().optional(),includeArchived:S().optional(),limit:u().optional(),childOf:s().optional(),before:s().optional(),after:s().optional()}),Ou=c({workspaceIds:g(s()).optional(),includeArchived:S().optional()}),Au={listRecent:{input:d([Pu]),output:cc(xo)},get:{input:d([s()]),output:P(xo)},count:{input:d([Ou]),output:u()}},Le=c({id:s(),root:s(),name:s(),createdAt:u(),lastOpenedAt:u(),pinned:S()}),Mu=c({name:s().optional(),pinned:S().optional()}),xu={list:{input:d([]),output:g(Le)},get:{input:d([s()]),output:P(Le)},createOrTouch:{input:d([s(),s().optional()]),output:Le},update:{input:d([s(),Mu]),output:P(Le)},delete:{input:d([s()]),output:_}},Q=c({hostId:s().trim().min(1),workspaceId:s().trim().min(1),sessionId:s().trim().min(1),personaId:s().optional(),name:s().optional(),bridgeId:s().uuid().optional(),connectionId:s().uuid().optional()}),Uu=c({ref:Q,title:s().optional(),updatedAt:u().int().nonnegative(),createdAt:u().int().nonnegative(),state:h(["cold","idle","running"])}),Du=c({workspaceId:s().trim().min(1).optional(),cursor:s().min(1).optional(),limit:u().int().min(1).max(100).optional()}),Nu=c({threads:g(Uu),nextCursor:s().optional()}),ju=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","external","mixed","unknown","thread_created"]),bridgedPeer:c({source:Q,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:Q,messageId:s().min(1)}).optional(),input:s(),output:s()}),Lu=c({thread:Q,contentRef:jt.optional(),cursor:s().min(1).optional(),limit:u().int().min(1).max(100).optional()}),F=g(jt).optional(),qu=ir.extend({contentRefs:F,attachmentIds:g(s()).optional()}),$u=rr.extend({contentRefs:F}),Gu=ar.extend({contentRefs:F,agentRefs:g(br).optional()}),Fu=cr.extend({contentRefs:F}),Bu=O("kind",[qu,$u,Gu,Fu]),Vu=dr.extend({frames:g(Bu)}),Hu=lr.extend({contentRefs:F,attachmentIds:g(s()).optional(),steps:g(Vu),execution:ur.extend({losses:g(s())}).optional()}),Wu=O("kind",[Hu,mr.extend({contentRefs:F}),pr]),zu=rn.extend({items:g(Wu),tasks:g(yr.extend({contentRefs:F})),interactions:g(fr.extend({contentRefs:F})).default([]),attachments:g(Sr.extend({contentRefs:F})).default([]),todos:g(vr.extend({contentRefs:F})).default([]),prompts:g(gr.extend({contentRefs:F})).default([]),meta:hr.extend({contentRefs:F})}),Ku=c({thread:Q,turns:g(ju),nextCursor:s().optional(),view:c({transcript:zu.optional(),segment:an.optional()}).optional()}),Qu=c({target:Q,content:s().min(1).max(1e5),idempotencyKey:s().min(1).max(256)}).strict(),Yu=c({messageId:s().min(1),targetSeq:u().int().nonnegative(),acceptedAt:u().int().nonnegative(),deduplicated:S(),delivery:h(["pending","delivered","undeliverable"])}),Xu=c({ref:Q,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()}),Ju=c({thread:Q,cursor:s().min(1).optional()}),Zu=c({threads:g(Ju).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)})}),ep=c({thread:Q,cursor:s().min(1),activities:g(Xu)}),tp=c({threads:g(ep),timedOut:S()}),Uo=c({ref:Q,title:s().optional(),deleted:S(),archived:S()}),op=c({messageId:s().describe("Stable recipient main-agent prompt id and user-message id, including steered delivery and retries; navigate only delivered records."),source:O("kind",[c({kind:b("thread"),thread:Uo}),c({kind:b("room"),roomId:s()})]),target:Uo,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()}),np=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),sp=c({items:g(op),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()}),ip={listMessages:{input:d([np.optional()]),output:sp},hostId:{input:d([]),output:s().min(1)},listThreads:{input:d([Du.optional()]),output:Nu},readThread:{input:d([Lu]),output:Ku},sendMessage:{input:d([Qu]),output:Yu},waitThreads:{input:d([Zu]),output:tp},getWorkspaceOverride:{input:d([s().trim().min(1)]),output:P(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()}},rp=c({busy:S(),mainTurnActive:S(),pendingInteraction:h(["none","approval","question"]),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),ap={state:{input:d([]),output:rp}},Do=d([c({targetAgentId:s().min(1),content:s().min(1),idempotencyKey:s().min(1).max(256)}).strict()]),cp={sendUserMessage:{input:Do,output:c({message:c({messageId:s(),sessionId:s(),sourceAgentId:s(),sourceTaskName:s(),senderKind:b("user").optional(),targetAgentId:s(),targetTaskName:s(),content:s(),acceptedAt:u(),targetSeq:u()}),deduplicated:S(),delivery:h(["queued","delivered"]),payloadConflict:S(),resumed:S().optional()})},sendUserMessageReceipt:{input:Do,output:c({message:c({messageId:s(),sessionId:s(),sourceAgentId:s(),sourceTaskName:s(),senderKind:b("user").optional(),targetAgentId:s(),targetTaskName:s(),acceptedAt:u(),targetSeq:u()}),deduplicated:S(),delivery:h(["queued","delivered"]),payloadConflict:S(),resumed:S().optional()})}},dp=c({id:s().optional(),sessionId:s().optional(),agentId:s().optional(),turnId:u().optional(),toolCallId:s().optional(),toolName:s(),action:s(),display:k(),approvalRule:s().optional()}),lp=c({decision:h(["approved","rejected","cancelled"]),scope:b("session").optional(),feedback:s().optional(),selectedLabel:s().optional(),selectedOptionId:s().optional()}),up={listPending:{input:d([]),output:g(dp)},decide:{input:d([s(),lp]),output:_}},qn=h(["approval","question","user_tool"]),pp=c({agentId:s().optional(),turnId:u().optional()}),$n=c({id:s(),kind:qn,payload:k(),origin:pp,createdAt:u()}),mp=c({id:s(),response:k()}),hp={listPending:{input:d([qn.optional()]),output:g($n)},respond:{input:d([s(),k()]),output:_},acquireConsumer:{input:d([s()]),output:_},releaseConsumer:{input:d([s()]),output:_},hasConsumer:{input:d([]),output:S()},isRecentlyResolved:{input:d([s()]),output:S()}},gp=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:g(s()).optional(),waitForSessionMs:u().nonnegative().finite().optional(),mainAgentBinding:c({execution:Tn.optional(),persona:s().optional(),profile:s().optional(),model:s().optional(),thinking:s().nullable().optional()}).optional(),mcpServers:R(s(),Je).optional()}),No=c({additionalDirs:g(s()).optional(),waitForSessionMs:u().nonnegative().finite().optional(),mcpServers:R(s(),Je).optional()}),Gn=c({sourceSessionId:s(),newSessionId:s().optional(),title:s().optional(),metadata:R(s(),k()).optional(),turnIndex:u().optional()}),vp=Gn.omit({turnIndex:!0}),fe=Ce({id:s(),kind:s()}),Sp={countPendingBackgroundTasks:{input:d([]),output:u()},drainBackgroundTasks:{input:d([u().positive().finite()]),output:_}},fp={create:{input:d([gp]),output:fe},resume:{input:d([s(),No.optional()]),output:P(fe)},close:{input:d([s()]),output:_},archive:{input:d([s()]),output:_},restore:{input:d([s(),No.optional()]),output:P(fe)},delete:{input:d([s()]),output:_},fork:{input:d([Gn]),output:fe},createChild:{input:d([vp]),output:fe}},yp=c({label:s(),description:s().optional()}),bp=c({question:s(),header:s().optional(),body:s().optional(),options:g(yp),multiSelect:S().optional(),otherLabel:s().optional(),otherDescription:s().optional()}),Fn=R(s(),q([s(),b(!0)])),_p=c({answers:Fn,method:h(["enter","space","number_key"]).optional()}),Ip=q([ae(),Fn,_p]),Tp=c({id:s().optional(),turnId:u().optional(),toolCallId:s().optional(),questions:g(bp)}),wp={listPending:{input:d([]),output:g(Tp)},answer:{input:d([s(),Ip]),output:_},dismiss:{input:d([s()]),output:_}},Ep=c({name:s(),description:s(),path:s(),source:h(["project","user","extra","builtin"]),type:s().optional(),disableModelInvocation:S().optional(),isSubSkill:S().optional()}),kp={list:{input:d([]),output:g(Ep)}},Cp={generateTitle:{input:d([c({force:S().optional(),source:h(["user_prompts","first_turn","digest"]).optional()}).optional()]),output:P(s())}},Rp={start:{input:d([]),output:s()}},Pp=c({id:s(),cron:s(),prompt:s(),createdAt:u(),recurring:S().optional(),deliveryMode:h(["queue","steer","idle"]).optional(),paused:S().optional(),lastFiredAt:u().optional(),tags:R(s(),s()).optional()}),Op={list:{input:d([]),output:g(Pp)},getNextFireTime:{input:d([]),output:u().nullable()},getNextFireForTask:{input:d([s()]),output:u().nullable()}},Ap={generateAgentsMd:{input:d([]),output:_},cancelInit:{input:d([]),output:_}},Mp=c({title:s(),status:h(["pending","in_progress","done"])}),xp={getTodos:{input:d([s().optional()]),output:g(Mp)}};function jo(o){return"streaming"in o&&o.streaming===!0}const Lo={agentGoalService:Ed,agentLifecycleService:Sp,sessionCronService:Op,sessionBtwService:Rp,sessionInitService:Ap,sessionTodoService:xp,taskBoardService:Qa,agentPanelService:Ya,sessionIndex:Au,workspaceService:xu,configService:El,providerService:Tu,modelService:Gl,modelResolver:Sl,modelCatalogMutation:Bl,providerDiscovery:yl,oauthService:il,authSummaryService:rl,flagService:Al,pluginService:du,recipeService:uu,pluginImportService:lu,pluginMediaService:pu,agentPluginMediaService:mu,personaStore:vu,botService:Su,roomService:fu,capabilityService:dl,hostFolderBrowser:Dl,bootstrapService:Cl,threadCommunicationService:ip,fileService:Ol,mcpManagementService:Ic,sessionManager:fp,sessionMetadata:Ru,agentCollaborationMessagingService:cp,sessionActivityView:ap,sessionInteractionService:hp,sessionApprovalService:up,sessionQuestionService:wp,sessionSkillCatalog:kp,sessionTitleService:Cp,agentPromptService:kd,agentSkillService:Cd,agentLoopService:Ud,agentExecutionService:xd,agentContextInjectorService:Rd,agentContextMemoryService:Ld,agentContextMutationService:qd,agentContextRebuildService:Pd,agentConversationUndoService:Od,agentPluginCommandService:Ad,agentPluginService:Md,agentPermissionModeService:Dd,agentCommandService:Nd,agentRuntimeBindingService:jd,agentTokenCountingService:$d,agentActivityView:ac,agentShellCommandService:Gd,agentProfileService:Bd,agentToolPolicyService:Fd,agentUsageService:Vd,agentPlanService:Hd,agentTaskService:Xd,agentMcpService:Kd,agentFullCompactionService:Yd},qo=c({domain:s(),source:h(["load","reload","set"]),value:k(),previousValue:k()}),Up=c({added:g(s()),removed:g(s()),errors:g(c({id:s(),message:s()}))}),Dp=c({agentId:s(),sessionId:s(),title:s().optional(),patch:c({title:s().optional(),isCustomTitle:S().optional(),lastPrompt:s().optional()})}),Np=c({changed:g(c({provider_id:s(),provider_name:s(),added:u(),removed:u()})),unchanged:g(s()),failed:g(c({provider:s(),reason:s()}))}),jp=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()}),ye={installId:s().min(1),version:s().min(1)},Lp=O("stage",[c({...ye,stage:b("download"),receivedBytes:u().nonnegative(),totalBytes:u().positive().optional()}),c({...ye,stage:b("extract")}),c({...ye,stage:b("activate")}),c({...ye,stage:b("done")}),c({...ye,stage:b("failed"),error:s(),timedOut:S()})]),qp={"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:_r},"search.indexStateChanged":{kind:"bus",type:"event.search.index_state_changed",schema:jp},"executors.antigravityInstallProgress":{kind:"bus",type:"event.executor.antigravity_install_progress",schema:Lp},"config.changed":{kind:"emitter",service:"configService",event:"onDidChangeConfiguration",schema:qo},"config.sectionChanged":{kind:"emitter",service:"configService",event:"onDidSectionChange",schema:qo},"kosong.providers.changed":{kind:"emitter",service:"providerService",event:"onDidChangeProviders",schema:wo},"kosong.models.changed":{kind:"emitter",service:"modelService",event:"onDidChangeModels",schema:wo},"plugins.reloaded":{kind:"emitter",service:"pluginService",event:"onDidReload",schema:Up},"plugins.changed":{kind:"bus",type:"event.plugin.changed",schema:c({}).strict()},"session.archived":{kind:"bus",type:"event.session.archived",schema:c({sessionId:s()})},"session.metaUpdated":{kind:"bus",type:"session.meta.updated",schema:Dp},"kosong.changed":{kind:"bus",type:"event.model_catalog.changed",schema:Np}},$p={"metadata.changed":{kind:"emitter",service:"sessionMetadata",event:"onDidChangeMetadata",schema:Cu},"skills.changed":{kind:"emitter",service:"sessionSkillCatalog",event:"onDidChange",schema:s()},"interactions.changed":{kind:"stream",name:"interactions",schema:g($n)},"interactions.resolved":{kind:"stream",name:"interactions:resolved",schema:mp}};class he 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 $o(o,e,t){const n=e.input.safeParse(t);if(!n.success)throw new he("input",o,n.error.issues,t);return n.data}function Gp(o,e,t){const n=e.output.safeParse(t);if(!n.success)throw new he("output",o,n.error.issues,t);return n.data}function Fp(o,e,t){const n=e.chunk.safeParse(t);if(!n.success)throw new he("chunk",o,n.error.issues,t);return n.data}function Bp(o,e,t){const n=e.safeParse(t);return n.success?{ok:!0,data:n.data}:{ok:!1,error:new he("event",o,n.error.issues,t)}}function qe(o){switch(o.kind){case"bus":return"bus";case"stream":return`stream:${o.name}`;case"emitter":return`emitter:${o.service}:${o.event}`}}function Go(o){if(typeof o!="object"||o===null)return;const e=o.type;return typeof e=="string"?e:void 0}class Vp{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,y)=>{a=f,r=y}),resolve:a,reject:r};m.promise.catch(()=>{});let p;try{p=this.acquire(e,m)}catch(f){throw n.delete(i),n.size===0&&this.listeners.delete(e),f}let v=!1;return{ready:m.promise,dispose:()=>{v||(v=!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 y of e.events){const I=this.registrations[y];if(I===void 0)throw new Error(`unknown event: ${y}`);n.set(qe(I),I)}const i=new Set,a=[];let r=!1,l=0,m=!1,p;const v={dispose:()=>{if(!r){r=!0,l+=1,p?.abort();for(const y of a)y.dispose();this.observations.delete(v)}}},f=()=>{l+=1,p?.abort(),!(r||m||i.size!==n.size)&&(m=!0,queueMicrotask(()=>{if(m=!1,r||i.size!==n.size)return;const y=l;p=new AbortController;const I=p.signal;Promise.resolve().then(()=>{if(!(r||y!==l))return e.read(I)}).then(w=>{if(!(r||y!==l))try{t(w)}catch(C){this.reportError(C instanceof Error?C:new Error(String(C)))}},w=>{r||y!==l||(v.dispose(),this.reportError(w instanceof Error?w:new Error(String(w))))})}))};this.observations.add(v);try{for(const[y,I]of n){const w=I.kind==="emitter"?{kind:"emitter",service:I.service,event:I.event}:{kind:"stream",name:I.kind==="bus"?"events":I.name};a.push(this.channel.listen(this.scope,w,()=>{f()},C=>{r||(i.delete(y),f(),this.reportError(C))},()=>{r||(i.add(y),f())}))}}catch(y){throw v.dispose(),y}return v}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=qe(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=qe(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(!(qe(i)!==e||!this.listeners.has(n))){if(i.kind==="bus"){if(Go(t)!==i.type)continue;this.deliverValidated(n,i,t.payload);continue}if(i.kind==="stream"&&i.type!==void 0){if(Go(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=Bp(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 Hp(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 Wp(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 zp(o){return{list:()=>o("recipeService","list",[]),get:e=>o("recipeService","get",[e]),export:e=>o("recipeService","export",[e]),preview:e=>o("recipeService","preview",[e]),install:e=>o("recipeService","install",[e]),checkUpdates:()=>o("recipeService","checkUpdates",[]),update:e=>o("recipeService","update",[e]),fork:e=>o("recipeService","fork",[e]),saveLocal:e=>o("recipeService","saveLocal",[e]),remove:e=>o("recipeService","remove",[e]),markets:{list:()=>o("recipeService","listMarkets",[]),add:e=>o("recipeService","addMarket",[e]),update:e=>o("recipeService","updateMarket",[e]),remove:e=>o("recipeService","removeMarket",[e])}}}function Kp(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 Qp(o){return{managedSources:()=>o("pluginMediaService","managedSources",[]),sourceSettings:e=>o("pluginMediaService","sourceSettings",[e]),updateSource:e=>o("pluginMediaService","updateSource",[e]),addScriptSource:e=>o("pluginMediaService","addScriptSource",[e]),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 Yp(o){return{cancel:e=>o("agentPluginMediaService","cancel",[e]),resume:e=>o("agentPluginMediaService","resume",[e])}}const Fo=32768;function Xp(o){let e="";for(let t=0;t<o.length;t+=Fo)e+=String.fromCodePoint(...o.subarray(t,t+Fo));return btoa(e)}function Jp(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 Zp(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 em=7e4,Bo=["platform","arch","cwd","osHomeDir","homeDir","configPath","sessionsDir","blobsDir","storeDir","cacheDir","logsDir"],tm=15*6e4,om=3e4;function nm(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([...Bo.map(r=>t("bootstrapService",r,[])),t("bootstrapService","clientIdentity",[])]).then(r=>{const l=Object.fromEntries(Bo.map((p,v)=>[p,r[v]])),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:v,title:f,persona:y,delivery:I,mcpServers:w,mainAgentBinding:C})=>{const M=y===void 0?C:{...C,persona:y},$={sessionId:(await o({},"sessionManager","create",[{sessionId:r,workDir:l,ephemeral:m,delivery:I,additionalDirs:p,waitForSessionMs:v,mcpServers:w,mainAgentBinding:M}])).id};return f!==void 0&&await o($,"sessionMetadata","setTitle",[f]),o($,"sessionMetadata","read",[])}},bots:Hp(t),rooms:Wp(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:Zp},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;sm(f);const y={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,y])}const m=r,p=m.capabilities?Object.entries(m.capabilities).filter(([,f])=>f).map(([f])=>f):void 0,v={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,v])}),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",[])},recipes:zp(t),imports:Kp(t),media:Qp(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:em}),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:v},f)=>t("fileService","save",[Xp(r),l,{name:m,mimeType:p,expiresInSec:v}],f),get:async r=>{const l=await t("fileService","get",[r]);return{meta:l.meta,data:Jp(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??tm)+om,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 sm(o){const e=o;for(const t of["requestAttribution","requestOriginator"])if(t in e)throw new TypeError(`${t} was removed; use requestIdentity`)}function im(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??{},getAgentExecutor:async a=>await o(t,"sessionMetadata","getAgentExecutor",[a])??void 0,sendUserAgentMessage:a=>o(t,"agentCollaborationMessagingService","sendUserMessage",[a],{timeoutMs:0}),sendUserAgentMessageReceipt:a=>o(t,"agentCollaborationMessagingService","sendUserMessageReceipt",[a],{timeoutMs:0})}}c({});const rm=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=>Ye(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),am=c({agentId:s().min(1),since:cn,grade:h(["turn","block","delta"]).optional()}).refine(o=>Ye(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),cm=c({agentId:s().min(1),kind:h(["task","attachment","prompt","tool"]),id:s().min(1)}).refine(o=>Ye(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),dm=c({agentId:s().min(1),ref:jt,range:S().optional()}).refine(o=>Ye(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),lm=an,um=c({sessionCursor:Re,transcriptGrades:Ir,transcriptSince:R(s(),cn).optional()}),ce=u().int().nonnegative(),pm=c({type:b("status"),status:h(["connecting","open","closed"]),generation:ce,detail:s().optional()}),mm=c({type:b("ready"),currentSessionCursor:Re,reconnected:S(),generation:ce}),hm=c({type:b("sessionCursorAdvanced"),cursor:Re,generation:ce,rosterAgentId:s().min(1).optional(),title:s().optional()}),gm=c({type:b("historyRewritten"),reason:h(["edit_resend","regenerate"]),targetMessageId:s().min(1),cursor:Re,generation:ce}),vm=c({type:b("transcript"),event:Tr,generation:ce}),Sm=c({type:b("resyncRequired"),reason:wr,currentSessionCursor:Re,generation:ce}),fm=c({type:b("protocolError"),detail:s(),recoverable:S(),generation:ce}),ym=O("type",[fm,pm,mm,hm,gm,vm,Sm]),bm=Cr,_m=rn,Im=kr,Tm=Er;function wm(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,v)=>{const f=p.safeParse(v);if(!f.success)throw new he(l,m,f.error.issues,v);return f.data};return{async snapshot(l){const m=await a().snapshot(e,l);return t?r("output","session.view.snapshot",bm,m):m},transcript:{async page(l,m){const p=t?r("input","session.view.transcript.page",rm,l):l,v=await a().transcriptPage(e,p,m);return t?r("output","session.view.transcript.page",_m,v):v},async catchUp(l,m){const p=t?r("input","session.view.transcript.catchUp",am,l):l,v=await a().transcriptCatchUp(e,p,m);return t?r("output","session.view.transcript.catchUp",Im,v):v},...o?.transcriptEntities===void 0?{}:{async entities(l,m){const p=r("input","session.view.transcript.entities",Rr,{agent_id:l.agentId,kind:l.kind,cursor:l.cursor,limit:l.limit}),v=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",Pr,v)}},...o?.transcriptContent===void 0?{}:{async content(l,m){const p=r("input","session.view.transcript.content",dm,l),v=await a().transcriptContent(e,p,m);return r("output","session.view.transcript.content",lm,v)}},...o?.transcriptDetail===void 0?{}:{async detail(l,m){const p=t?r("input","session.view.transcript.detail",cm,l):l,v=await a().transcriptDetail(e,p,m);return t?r("output","session.view.transcript.detail",Tm,v):v}}},subscribe(l,m){const p=t?r("input","session.view.subscribe",um,l):l;return a().subscribe(e,p,v=>{if(!t){m(v);return}const f=ym.safeParse(v);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 et=s().min(1),Vo=o=>c({body:o}),Ho=c({target:et}),J=o=>c({target:et,body:o}),Wo=c({target:et,query:c({agent_id:s().min(1).optional()}).optional()}),Bn={read:{method:"GET",suffix:"",input:c({}),output:uo,okCodes:[0]},submit:{method:"POST",suffix:"/prompts",input:Vo(Yr),output:$r,okCodes:[0],timeoutMs:0},edit:{method:"POST",suffix:"/messages/{target}:edit",input:J(un),output:po,okCodes:[0]},regenerate:{method:"POST",suffix:"/messages/{target}:regenerate",input:J(ln),output:po,okCodes:[0]},fork:{method:"POST",suffix:":fork",input:Vo(dn),output:uo,okCodes:[0]},abort:{method:"POST",suffix:"/prompts/{target}:abort",input:Wo,output:qr,okCodes:[0,40903]},abortTurn:{method:"POST",suffix:"/turns/{target}:abort",input:Ho,output:Lr,okCodes:[0]},move:{method:"POST",suffix:"/prompts/{target}:move",input:J(Qr),output:jr,okCodes:[0]},replace:{method:"POST",suffix:"/prompts/{target}:replace",input:J(Kr),output:Nr,okCodes:[0]},timing:{method:"POST",suffix:"/prompts/{target}:timing",input:J(zr),output:Dr,okCodes:[0]},hold:{method:"POST",suffix:"/prompts/{target}:hold",input:J(Wr),output:Ur,okCodes:[0]},steer:{method:"POST",suffix:"/prompts/{target}:steer",input:Wo,output:xr,okCodes:[0]},approve:{method:"POST",suffix:"/approvals/{target}",input:J(Hr),output:Mr,okCodes:[0]},answer:{method:"POST",suffix:"/questions/{target}",input:J(Vr),output:Ar,okCodes:[0]},dismiss:{method:"POST",suffix:"/questions/{target}:dismiss",input:Ho,output:Or,okCodes:[0,40909]},cancelTask:{method:"POST",suffix:"/tasks/{target}:cancel",input:c({target:et,query:Br.optional()}),output:q([Gr,Fr]),okCodes:[0,40904]}};function zo(o,e){return e===void 0||e==="main"?{target:o}:{target:o,query:{agent_id:e}}}function Em(o,e,t){const n=(a,r,l,m)=>{const p=l.safeParse(m);if(!p.success)throw new he(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=Bn[a],m=`session.commands.${a}`,p=t?n("input",m,l.input,r):r,v=await o.execute(e,a,p);return t?n("output",m,l.output,v):v};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",zo(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",zo(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 km(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:Yp((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]),shutdownExecution:n=>o(e,"agentExecutionService","shutdown",n===void 0?[]:[n]),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",[]),inspectToolPolicy:()=>o(e,"agentProfileService","inspectToolPolicy",[]),refreshToolPolicy:n=>o(e,"agentProfileService","refreshToolPolicy",[n]),isToolEnabled:(n,i)=>o(e,"agentToolPolicyService","isToolActive",[n,i]),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]),listMcpSessionCapabilities:()=>o(e,"agentMcpService","listMcpSessionCapabilities",[]),setMcpSessionOverride:n=>o(e,"agentMcpService","setMcpSessionOverride",[n]),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 Cm(o,e={}){const t=e.validate??!0,n=async(l,m,p,v,f)=>{const y=Lo[m]?.[p];if(y===void 0)throw new Error(`no contract registered for ${m}.${p}`);if(jo(y))throw new Error(`${m}.${p} is a streaming procedure — use callStream instead`);const I=`${m}.${p}`,w=t?$o(I,y,v):v,C=await o.call(l,m,p,w,f);return t?Gp(I,y,C):C},i=(l,m,p,v)=>{const f=Lo[m]?.[p];if(f===void 0)throw new Error(`no contract registered for ${m}.${p}`);if(!jo(f))throw new Error(`${m}.${p} is not a streaming procedure — use call instead`);const y=`${m}.${p}`,I=t?$o(y,f,v):v,w=o.stream(l,m,p,I);if(!t)return w;const C=f;return{[Symbol.asyncIterator](){const M=w[Symbol.asyncIterator]();return{async next(){const D=await M.next();return D.done?{done:!0,value:void 0}:{done:!1,value:Fp(y,C,D.value)}},async return(D){return await M.return?.(D),{done:!0,value:void 0}}}}}},a=new Set,r=(l,m)=>{const p=new Vp(o,t,l,m);return a.add(p),p};return{rest:o.rest,terminal:qa(o.terminal),global:nm(n,i),events:r({},qp),session(l){const m={sessionId:l};return{...im(n,l),events:r(m,$p),view:wm(o.sessionView,l,t),commands:Em(o.sessionCommands,l,t),agent(p){const v={sessionId:l,agentId:p};return{...km(n,v),events:r(v,od)}}}},close:()=>{for(const l of a)l.close();return a.clear(),o.close()}}}const eo={kind:"unknown",hasMoreOlder:!0};function Rm(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:eo,read:to(t.read),snapshot:Hn(t.snapshot)}};if(n==="transcript.ops"){const i=t.ops;return Array.isArray(i)?{...o,event:{...t,ops:i.map(Vn)}}:o}return o}function Pm(o){return o===null||typeof o!="object"?o:{...o,coverage:eo,read:to(o.read),tool_call_count:void 0}}function Om(o){if(o===null||typeof o!="object")return o;const e=o.batches;return Array.isArray(e)?{...o,batches:e.map(Am)}:o}function Am(o){if(o===null||typeof o!="object")return o;const e=o.ops;return Array.isArray(e)?{...o,ops:e.map(Vn)}:o}function Vn(o){if(o===null||typeof o!="object")return o;const e=o;return e.op==="reset"?{...e,coverage:eo,read:to(e.read),snapshot:Hn(e.snapshot)}:e.op==="tool.count.set"?{...e,count:void 0}:o}function to(o){return{source:o!==null&&typeof o=="object"&&(o.source==="live"||o.source==="cold"||o.source==="derived")?o.source:"derived",readiness:"partial",reason:"source_unverified"}}function Hn(o){return o===null||typeof o!="object"?o:{...o,toolCallCount:void 0,toolCallCountKnown:!1}}const Mm=250;function xm(o,e){let t=!1;for(const[n,i]of Object.entries(e)){const a=o[n];if(a===void 0){if(i!=="turn")return!1;t=!0}else if(a!==i)return!1}return t&&Object.keys(o).every(n=>Object.hasOwn(e,n))}class Um{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.transcriptGrades,m=a.input.transcriptSince===void 0?void 0:Object.fromEntries(Object.entries(a.input.transcriptSince).filter(([p])=>_o[Io(r,p)]<=_o[Io(l,p)]));a.input={...a.input,transcriptGrades:r,transcriptSince:m},this.host.isOpen()&&(xm(l,r)?this.scheduleAttach(a):(this.clearAttachTimer(a),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.clearAttachTimer(a),this.host.isOpen()&&this.host.send({type:"view_detach",id:i}),n({type:"status",status:"closed",generation:this.generation}))}}}opened(){this.generation+=1;for(const e of this.views.values())this.clearAttachTimer(e),e.handler({type:"status",status:"open",generation:this.generation}),this.attach(e)}disconnected(e){for(const 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(){for(const e of this.views.values())this.clearAttachTimer(e);this.views.clear()}receive(e){if(e.type!=="view_signal"&&e.type!=="view_error")return!1;const 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),this.clearAttachTimer(t),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=pn(n)?n:Rm(n);t.handler(a)}return!0}scheduleAttach(e){this.clearAttachTimer(e),e.attachTimer=setTimeout(()=>{e.attachTimer=void 0,this.views.has(e.id)&&this.host.isOpen()&&this.attach(e)},Mm)}clearAttachTimer(e){e.attachTimer!==void 0&&(clearTimeout(e.attachTimer),e.attachTimer=void 0)}attach(e){this.clearAttachTimer(e),this.host.send({type:"view_attach",id:e.id,sessionId:e.sessionId,data:{input:e.input,generation:this.generation,reconnected:e.attachCount>0,transcript_coverage_version:mn}}),e.attachCount+=1}}const $e=(o,e)=>JSON.stringify([o,e]);class Dm{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=$e(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($e(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($e(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=$e(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 Nm=Math.ceil((8<<20)*4/3)+65536,Wn={codes:{REQUEST_LIMIT_REJECTED:"request.limit_rejected",REQUEST_QUEUE_TIMEOUT:"request.queue_timeout",REQUEST_QUEUE_FULL:"request.queue_full",AGENT_ANCESTOR_LIMIT:"request.agent_ancestor_limit"},info:{"request.agent_ancestor_limit":{title:"Parent occupies this agent limit",public:!0,retryable:!1,action:"Select subagents only, separate main and subagent rules, or increase the matching rule limit."},"request.limit_rejected":{title:"Local request limit reached",public:!0,retryable:!1,action:"Wait for active requests to finish or change the matching concurrency rule."},"request.queue_timeout":{title:"Local request queue timed out",public:!0,retryable:!1,action:"Retry the turn or adjust the local waiting budget."},"request.queue_full":{title:"Local request queue full",public:!0,retryable:!1,action:"Wait for queued requests to drain before retrying."}}};E(Wn);const zn={codes:{DISPATCH_LIMIT_EXCEEDED:"dispatch.limit_exceeded"}};E(zn);const Kn={codes:{AGENT_NOT_FOUND:"agent.not_found",AGENT_REMOVED:"agent.removed",AGENT_ALREADY_EXISTS:"agent.already_exists",AGENT_ALREADY_RUNNING:"agent.already_running",AGENT_NOT_A_SUBAGENT:"agent.not_a_subagent",AGENT_NOT_OWNED:"agent.not_owned",AGENT_TYPE_NOT_ALLOWED:"agent.type_not_allowed",AGENT_MAX_TOKENS_EXCEEDED:"agent.max_tokens_exceeded"}};E(Kn);const Qn={codes:{AUTH_LOGIN_REQUIRED:"auth.login_required",AUTH_PROVISIONING_REQUIRED:"auth.provisioning_required",AUTH_TOKEN_MISSING:"auth.token_missing",AUTH_TOKEN_UNAUTHORIZED:"auth.token_unauthorized",AUTH_MODEL_NOT_RESOLVED:"auth.model_not_resolved"},info:{"auth.login_required":{title:"Login required",retryable:!1,public:!0,action:"Run /login to authenticate with the OAuth provider."},"auth.provisioning_required":{title:"Provider provisioning required",retryable:!1,public:!0,action:"Configure a provider via /login or the providers endpoint."},"auth.token_missing":{title:"Provider credential missing",retryable:!1,public:!0,action:"Configure an API key or complete OAuth login for the provider."},"auth.token_unauthorized":{title:"Provider credential unauthorized",retryable:!1,public:!0,action:"Re-authenticate with the OAuth provider."},"auth.model_not_resolved":{title:"Model not resolved",retryable:!1,public:!0,action:"Set a default model or configure the requested model alias."}}};E(Qn);const Yn={codes:{TASK_ID_EMPTY:"task.task_id_empty",TASK_EMPTY_AGENT_RECEIPT:"task.empty_agent_receipt",TASK_LIMIT_EXCEEDED:"task.limit_exceeded"},retryable:["task.limit_exceeded"],info:{"task.empty_agent_receipt":{title:"Missing agent receipt",retryable:!1,public:!0,action:"Inspect preserved work and the original turn, then resume the same agent with a new prompt ID and request a final receipt."}}};E(Yn);const Xn={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"]};E(Xn);const jm="config.invalid",Lm="provider.api_error",qm="provider.filtered",$m="provider.rate_limit",Gm="provider.auth_error",Fm="provider.connection_error",Bm="provider.overloaded",Vm="context.overflow",Jn={codes:{PROVIDER_API_ERROR:Lm,PROVIDER_FILTERED:qm,PROVIDER_RATE_LIMIT:$m,PROVIDER_AUTH_ERROR:Gm,PROVIDER_CONNECTION_ERROR:Fm,PROVIDER_OVERLOADED:Bm,CONTEXT_OVERFLOW:Vm},retryable:["provider.rate_limit","provider.connection_error","provider.overloaded","context.overflow"],info:{"provider.rate_limit":{title:"Provider rate limit",retryable:!0,public:!0,action:"Retry after the provider rate limit resets."},"provider.filtered":{title:"Provider filtered response",retryable:!1,public:!0,action:"Revise the prompt or model configuration to avoid provider safety filtering."},"provider.auth_error":{title:"Provider authentication failed",retryable:!1,public:!0,action:"Check provider credentials and authentication configuration."},"provider.overloaded":{title:"Provider overloaded",retryable:!0,public:!0,action:"Retry after the provider recovers from overload."},"context.overflow":{title:"Context overflow",retryable:!0,public:!0,action:"Compact the conversation or retry with fewer tokens."}}};E(Jn);const Zn={codes:{CONFIG_INVALID:jm,CONFIG_PERSIST_BLOCKED:"config.persist_blocked"}};E(Zn);const es={codes:{BROWSER_INVALID:"browser.invalid",BROWSER_NOT_FOUND:"browser.not_found",BROWSER_DISABLED:"browser.disabled",BROWSER_DISCONNECTED:"browser.disconnected",BROWSER_EXECUTION_FAILED:"browser.execution_failed",BROWSER_BUSY:"browser.busy",BROWSER_VERSION:"browser.version",BROWSER_TARGET:"browser.target",BROWSER_REQUIRES_ACTION:"browser.requires_action",BROWSER_UNSUPPORTED:"browser.unsupported"},info:{"browser.invalid":{title:"Invalid browser configuration or request",retryable:!1,public:!0},"browser.not_found":{title:"Browser connection not found",retryable:!1,public:!0},"browser.disabled":{title:"Browser connection is disabled",retryable:!1,public:!0},"browser.disconnected":{title:"Browser connection is disconnected",retryable:!1,public:!0},"browser.execution_failed":{title:"Browser command failed",retryable:!1,public:!0},"browser.busy":{title:"Browser connection is busy",retryable:!1,public:!0},"browser.version":{title:"Unsupported browser driver version",retryable:!1,public:!0},"browser.target":{title:"Browser target is no longer available",retryable:!1,public:!0},"browser.requires_action":{title:"Browser setup or approval required",retryable:!1,public:!0},"browser.unsupported":{title:"Unsupported browser provider or operation",retryable:!1,public:!0}}};E(es);const ts={codes:{CAPABILITY_NOT_FOUND:"capability.not_found",CAPABILITY_UNSUPPORTED:"capability.unsupported",CAPABILITY_INSTALL_IN_PROGRESS:"capability.install_in_progress"}};E(ts);const os={codes:{CRON_EXPRESSION_INVALID:"cron.expression_invalid"}};E(os);const ns={codes:{DEBUG_SCOPE_NOT_FOUND:"debug.scope_not_found",DEBUG_TOKEN_NOT_FOUND:"debug.token_not_found"}};E(ns);const ss={codes:{EVENT_DUPLICATE_EVENT:"event.duplicate_event",EVENT_SCHEMA_MISSING:"event.schema_missing"},info:{"event.duplicate_event":{title:"Duplicate event type",retryable:!1,public:!0,action:"Two event classes registered the same type; rename one. This is a build-time bug."},"event.schema_missing":{title:"Durable event without schema",retryable:!1,public:!0,action:"A durable event class must declare a zod payload schema for replay."}}};E(ss);const is={codes:{EXECUTOR_BUSY:"executor.busy",EXECUTOR_CANCELLED:"executor.cancelled",EXECUTOR_CLOSED:"executor.closed",EXECUTOR_DISCONNECTED:"executor.disconnected",EXECUTOR_INVALID_SESSION_REF:"executor.invalid_session_ref",EXECUTOR_PROTOCOL_ERROR:"executor.protocol_error",EXECUTOR_SESSION_OPEN_FAILED:"executor.session_open_failed",EXECUTOR_SESSION_FAILED:"executor.session_failed",EXECUTOR_AUTHENTICATION_REQUIRED:"executor.authentication_required",EXECUTOR_SPAWN_FAILED:"executor.spawn_failed",EXECUTOR_STARTUP_TIMEOUT:"executor.startup_timeout"},retryable:["executor.disconnected","executor.startup_timeout"],info:{"executor.session_failed":{title:"External session failed",retryable:!1,public:!0,action:"Use the recovery actions reported by the external harness; do not replay the prompt automatically."}}};E(is);var ee;(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})(ee||(ee={}));function Hm(o,e,t,n="instance"){const i=e;i[ee.DI_TARGET]===e?i[ee.DI_DEPENDENCIES].push({id:o,index:t,kind:n}):(i[ee.DI_DEPENDENCIES]=[{id:o,index:t,kind:n}],i[ee.DI_TARGET]=e)}function tt(o){const e=ee.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");Hm(t,i,r)};return Object.defineProperty(t,"toString",{value:function(){return o},enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(t,Wm,{value:!0,enumerable:!1}),ee.serviceIds.set(o,t),t}const Wm=Symbol("serviceIdentifier");tt("instantiationService");const zm=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}(?::?\d{2})?)$/,Ko=s().refine(o=>zm.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"}),Xr):new Date(t).toISOString()});c({id:s().min(1),name:s().min(1),media_type:s().min(1),size:u().int().nonnegative(),created_at:Ko,expires_at:Ko.optional()});tt("fileService");const rs={codes:{FILE_NOT_FOUND:"file.not_found"},info:{"file.not_found":{title:"File not found",retryable:!1,public:!0,action:"Check the file_id or upload the file again."}}};E(rs);const as={codes:{FS_PATH_NOT_FOUND:"fs.path_not_found",FS_PERMISSION_DENIED:"fs.permission_denied",FS_PATH_ESCAPES:"fs.path_escapes",FS_IS_DIRECTORY:"fs.is_directory",FS_IS_BINARY:"fs.is_binary",FS_TOO_LARGE:"fs.too_large",FS_ALREADY_EXISTS:"fs.already_exists",FS_TOO_MANY_RESULTS:"fs.too_many_results",FS_GREP_TIMEOUT:"fs.grep_timeout",FS_GIT_UNAVAILABLE:"fs.git_unavailable"}};E(as);const cs={codes:{COMPACTION_FAILED:"compaction.failed",COMPACTION_UNABLE:"compaction.unable"}};E(cs);const ds={codes:{GOAL_ALREADY_EXISTS:"goal.already_exists",GOAL_NOT_FOUND:"goal.not_found",GOAL_OBJECTIVE_EMPTY:"goal.objective_empty",GOAL_OBJECTIVE_TOO_LONG:"goal.objective_too_long",GOAL_STATUS_INVALID:"goal.status_invalid",GOAL_METADATA_RESERVED:"goal.metadata_reserved",GOAL_NOT_RESUMABLE:"goal.not_resumable",GOAL_UNSUPPORTED_AGENT:"goal.unsupported_agent"},info:{"goal.already_exists":{title:"A goal is already active",retryable:!1,public:!0,action:"Use `/goal replace <objective>` to replace the current goal."},"goal.not_found":{title:"No goal found",retryable:!1,public:!0,action:"Start a goal with `/goal <objective>` first."},"goal.objective_empty":{title:"Goal objective is empty",retryable:!1,public:!0,action:"Provide a non-empty objective."},"goal.objective_too_long":{title:"Goal objective is too long",retryable:!1,public:!0,action:"Keep the objective under 4000 characters; reference long details by file path."},"goal.status_invalid":{title:"Invalid goal status transition",retryable:!1,public:!0,action:"Only an active goal can be paused; resume a blocked goal with `/goal resume`."},"goal.metadata_reserved":{title:"Goal metadata is reserved",retryable:!1,public:!0,action:"Do not write metadata.custom.goal directly; use the goal lifecycle methods."},"goal.not_resumable":{title:"Goal is not resumable",retryable:!1,public:!0,action:"Only paused or blocked goals can be resumed."},"goal.unsupported_agent":{title:"Goals are unavailable for subagents",retryable:!1,public:!0,action:"Run goal lifecycle commands on the main agent."}}};E(ds);const ls={codes:{LOOP_MAX_STEPS_EXCEEDED:"loop.max_steps_exceeded",LOOP_EMPTY_COMPLETION:"loop.empty_completion",TURN_AGENT_BUSY:"turn.agent_busy"},retryable:["turn.agent_busy"],info:{"loop.empty_completion":{title:"Empty subagent completion",retryable:!1,public:!0,action:"Inspect the original turn and preserved work, then resume the same agent with a new prompt ID. An empty provider completion is not a task receipt."},"loop.max_steps_exceeded":{title:"Loop max steps exceeded",retryable:!1,public:!0,action:'Raise loop_control.max_steps_per_turn in config.toml, or run "/kiki-ops update loop_control.max_steps_per_turn" then "/reload".'}}};E(ls);const us={codes:{MCP_SERVER_NOT_FOUND:"mcp.server_not_found",MCP_SERVER_DISABLED:"mcp.server_disabled",MCP_STARTUP_FAILED:"mcp.startup_failed",MCP_TOOL_NAME_COLLISION:"mcp.tool_name_collision",MCP_OAUTH_FAILED:"mcp.oauth_failed",MCP_COMPUTER_BUSY:"mcp.computer_busy",MCP_COMPUTER_OUTCOME_UNKNOWN:"mcp.computer_outcome_unknown",MCP_COMPUTER_STOP_UNCONFIRMED:"mcp.computer_stop_unconfirmed"}};E(us);const ps={codes:{PROVIDER_NOT_FOUND:"provider.not_found",PROVIDER_ALREADY_EXISTS:"provider.already_exists",MODEL_NOT_FOUND:"model.not_found",MODEL_ALREADY_EXISTS:"model.already_exists",REVISION_CONFLICT:"model_catalog.revision_conflict"},info:{"provider.not_found":{title:"Provider not found",retryable:!1,public:!0,action:"Check the provider id or configure the provider first."},"provider.already_exists":{title:"Provider already exists",retryable:!1,public:!0,action:"Choose another provider id or edit the existing connection."},"model.not_found":{title:"Model not found",retryable:!1,public:!0,action:"Check the model alias or configure the model first."},"model.already_exists":{title:"Model already exists",retryable:!1,public:!0,action:"Choose another local model id; an existing model is never overwritten."},"model_catalog.revision_conflict":{title:"Configuration changed",retryable:!0,public:!0,action:"Re-read the entity and reapply the edit against the current revision."}}};E(ps);const ms={codes:{OS_FS_NOT_FOUND:"os.fs.not_found",OS_FS_IS_DIRECTORY:"os.fs.is_directory",OS_FS_NOT_DIRECTORY:"os.fs.not_directory",OS_FS_ALREADY_EXISTS:"os.fs.already_exists",OS_FS_PERMISSION_DENIED:"os.fs.permission_denied",OS_FS_NOT_EMPTY:"os.fs.not_empty",OS_FS_UNAVAILABLE:"os.fs.unavailable",OS_FS_UNKNOWN:"os.fs.unknown"},retryable:["os.fs.unavailable","os.fs.unknown"],info:{"os.fs.not_found":{title:"Path not found",retryable:!1,public:!0},"os.fs.is_directory":{title:"Path is a directory",retryable:!1,public:!0},"os.fs.not_directory":{title:"Path is not a directory",retryable:!1,public:!0},"os.fs.already_exists":{title:"Path already exists",retryable:!1,public:!0},"os.fs.permission_denied":{title:"Permission denied",retryable:!1,public:!0,action:"Check the file permissions of the target path."},"os.fs.not_empty":{title:"Directory not empty",retryable:!1,public:!0},"os.fs.unavailable":{title:"Filesystem unavailable",retryable:!0,public:!0},"os.fs.unknown":{title:"Filesystem error",retryable:!0,public:!0}}};E(ms);tt("hostProcessService");const we={codes:{OS_PROCESS_SPAWN_FAILED:"os.process.spawn_failed",OS_PROCESS_KILL_FAILED:"os.process.kill_failed",SHELL_GIT_BASH_NOT_FOUND:"shell.git_bash_not_found"},info:{"os.process.spawn_failed":{title:"Failed to spawn process",retryable:!1,public:!0,action:"Check that the command exists and is executable."},"os.process.kill_failed":{title:"Failed to kill process",retryable:!1,public:!0},"shell.git_bash_not_found":{title:"Git Bash not found",retryable:!1,public:!0,action:"Install Git for Windows so shell commands can run under Git Bash."}}};E(we);we.codes.OS_PROCESS_SPAWN_FAILED,we.codes.OS_PROCESS_KILL_FAILED,we.codes.SHELL_GIT_BASH_NOT_FOUND;const hs={codes:{PLUGIN_NOT_FOUND:"plugin.not_found",PLUGIN_LOAD_FAILED:"plugin.load_failed",PLUGIN_READ_ONLY:"plugin.read_only"}};E(hs);const gs={codes:{MODEL_NOT_CONFIGURED:"model.not_configured",MODEL_CONFIG_INVALID:"model.config_invalid",PROFILE_CONSTRAINT_VIOLATION:"profile.constraint_violation",THINKING_ALIAS_CONFLICT:"profile.thinking_alias_conflict",PROFILE_UNKNOWN:"profile.unknown",PERSONA_UNKNOWN:"persona.unknown",PROFILE_ALREADY_BOUND:"profile.already_bound",PROFILE_NOT_BOUND:"profile.not_bound",COGNITION_FILE_MISSING:"profile.cognition_file_missing",COGNITION_PATH_INVALID:"profile.cognition_path_invalid",TOOL_PATTERN_INACTIVE:"profile.tool_pattern_inactive"}};E(gs);const vs={codes:{REQUEST_INVALID:"request.invalid",REQUEST_WORK_DIR_REQUIRED:"request.work_dir_required",REQUEST_PROMPT_INPUT_EMPTY:"request.prompt_input_empty",PROMPT_ID_CONFLICT:"prompt.id_conflict",PROMPT_NOT_FOUND:"prompt.not_found",PROMPT_ALREADY_COMPLETED:"prompt.already_completed",SESSION_BUSY:"session.busy"}};E(vs);const Ss={codes:{CATALOG_UNAVAILABLE:"modelsDev.catalog_unavailable",CATALOG_ENTRY_NOT_FOUND:"modelsDev.catalog_entry_not_found",CATALOG_IMPORT_INVALID:"modelsDev.import_invalid",REGISTRY_IMPORT_INVALID:"modelsDev.registry_import_invalid",PROVIDER_OAUTH_MANAGED:"provider.oauth_managed"},info:{"modelsDev.catalog_unavailable":{title:"models.dev directory unavailable",retryable:!0,public:!0,action:"Check the network connection to models.dev and try again."},"modelsDev.catalog_entry_not_found":{title:"Directory entry not found",retryable:!1,public:!0,action:"Check the catalog id against the models.dev directory listing."},"modelsDev.import_invalid":{title:"Directory entry not importable",retryable:!1,public:!0,action:"Pick another entry or supply the required base_url."},"modelsDev.registry_import_invalid":{title:"Custom registry not importable",retryable:!1,public:!0,action:"Check the registry URL and credentials."},"provider.oauth_managed":{title:"Provider managed by OAuth login",retryable:!1,public:!0,action:"Log out via the OAuth flow instead of editing the provider."}}};E(Ss);const fs={codes:{SESSION_EXPORT_NOT_FOUND:"session.export_not_found",SESSION_EXPORT_MISSING_VERSION:"session.export_missing_version",SESSION_EXPORT_OUTPUT_CONFLICT:"session.export_output_conflict",SESSION_EXPORT_TOO_LARGE:"session.export_too_large"}};E(fs);const ys={codes:{SESSION_INDEX_BUILDING:"session.index_building"},retryable:["session.index_building"]};E(ys);const bs={codes:{SESSION_NOT_FOUND:"session.not_found",SESSION_ALREADY_EXISTS:"session.already_exists",SESSION_ID_INVALID:"session.id_invalid",SESSION_CLOSED:"session.closed",SESSION_FORK_ACTIVE_TURN:"session.fork_active_turn",SESSION_FORK_EXTERNAL_DELEGATION:"session.fork_external_delegation",SESSION_UNDO_UNAVAILABLE:"session.undo_unavailable",SESSION_CURSOR_MISMATCH:"session.cursor_mismatch",MESSAGE_ACTION_UNAVAILABLE:"message.action_unavailable",SESSION_INIT_FAILED:"session.init_failed",SESSION_PLAN_MODE_INVALID:"session.plan_mode_invalid",SESSION_TITLE_GENERATION_FAILED:"session.title_generation_failed"},retryable:["session.fork_active_turn"]};E(bs);const _s={codes:{SKILL_NOT_FOUND:"skill.not_found",SKILL_TYPE_UNSUPPORTED:"skill.type_unsupported",SKILL_NAME_EMPTY:"skill.name_empty",SKILL_PARSE_FAILED:"skill.parse_failed",SKILL_NESTED_TOO_DEEP:"skill.nested_too_deep"}};E(_s);const Is={codes:{STATE_DUPLICATE_FOLD:"state.duplicate_fold",STATE_DURABILITY_MISMATCH:"state.durability_mismatch",STATE_CYCLE:"state.cycle"},info:{"state.duplicate_fold":{title:"Duplicate state fold",retryable:!1,public:!0,action:"A state registered two folds for the same event; merge them."},"state.durability_mismatch":{title:"Transient state folds durable event",retryable:!1,public:!0,action:"A non-durable state cannot fold a durable event; mark the state durable."},"state.cycle":{title:"Event dispatch cycle",retryable:!1,public:!0,action:"A subscriber re-dispatches endlessly; break the event cycle."}}};E(Is);const Ts={codes:{STORAGE_NOT_FOUND:"storage.not_found",STORAGE_DECODE_FAILED:"storage.decode_failed",STORAGE_CORRUPTED:"storage.corrupted",STORAGE_IO_FAILED:"storage.io_failed",STORAGE_LOCKED:"storage.locked",STORAGE_PERMISSION_DENIED:"storage.permission_denied",STORAGE_DISK_FULL:"storage.disk_full"},retryable:["storage.io_failed","storage.locked"],info:{"storage.not_found":{title:"Stored value not found",retryable:!1,public:!0},"storage.decode_failed":{title:"Stored value could not be decoded",retryable:!1,public:!0,action:"Inspect the stored document; it is not valid for its declared format."},"storage.corrupted":{title:"Stored data is corrupted",retryable:!1,public:!0,action:"Inspect the backing store; the corrupted entry must be repaired or dropped."},"storage.io_failed":{title:"Storage I/O failed",retryable:!0,public:!0},"storage.locked":{title:"Storage is locked",retryable:!0,public:!0,action:"Another process holds the store; close it or retry later."},"storage.permission_denied":{title:"Storage permission denied",retryable:!1,public:!0,action:"Check the permissions of the storage directory."},"storage.disk_full":{title:"Storage disk full",retryable:!1,public:!0,action:"Free up disk space and retry."}}};E(Ts);tt("fileSystemStorageService");const ws={codes:{TERMINAL_NOT_FOUND:"terminal.not_found"}};E(ws);const Es={codes:{TURN_ID_CONFLICT:"usage.turn_id_conflict"}};E(Es);const ks={codes:{WIRE_UNKNOWN_RECORD:"wire.unknown_record",WIRE_MIGRATION_MISSING:"wire.migration_missing",RECORDS_WRITE_FAILED:"records.write_failed"},info:{"wire.unknown_record":{title:"Unknown wire record",retryable:!1,public:!0,action:"The record was written by a newer version; upgrade or drop it."},"wire.migration_missing":{title:"Wire migration missing",retryable:!1,public:!0,action:"The wire file predates the supported migration chain; start a new session."},"records.write_failed":{title:"Wire journal write failed",retryable:!1,public:!0}}};E(ks);const Cs={codes:{WORKSPACE_NOT_FOUND:"workspace.not_found"}};E(Cs);const Rs={codes:{ROUTE_FEATURE_DISABLED:"agent_profile_route.feature_disabled",ROUTE_INVALID_ID:"agent_profile_route.invalid_id",ROUTE_UNKNOWN:"agent_profile_route.unknown",ROUTE_BASE_MISMATCH:"agent_profile_route.base_mismatch",ROUTE_BASE_MISSING:"agent_profile_route.base_missing",ROUTE_BINDING_CONFLICT:"agent_profile_route.binding_conflict",ROUTE_MODEL_ALIAS_MISSING:"agent_profile_route.model_alias_missing",ROUTE_SWITCH_FORBIDDEN:"agent_profile_route.switch_forbidden",ROUTE_INVALID_SIDECAR:"agent_profile_route.invalid_sidecar",ROUTE_DUPLICATE:"agent_profile_route.duplicate",SCOPED_PROFILE_UNAVAILABLE:"agent_profile_source.unavailable"}};E(Rs);const Ps={codes:{PROFILE_NOT_FOUND:"agent_profile_write.not_found",PROFILE_READ_ONLY:"agent_profile_write.read_only",PROFILE_ALREADY_EXISTS:"agent_profile_write.already_exists"}};E(Ps);({...Wn.codes,...Rn.codes,...zn.codes,...Kn.codes,...Qn.codes,...Yn.codes,...Xn.codes,...Jn.codes,...Zn.codes,...es.codes,...ts.codes,...os.codes,...ns.codes,...is.codes,...rs.codes,...as.codes,...cs.codes,...ds.codes,...ls.codes,...us.codes,...ps.codes,...Pn.codes,...ms.codes,...we.codes,...hs.codes,...gs.codes,...vs.codes,...Ss.codes,...fs.codes,...ys.codes,...bs.codes,..._s.codes,...Ts.codes,...ws.codes,...Es.codes,...ks.codes,...Cs.codes,...Rs.codes,...Ps.codes,...ss.codes,...Is.codes});class j extends Error{constructor(e,t,n,i,a,r,l){super(t),this.code=e,this.details=n,this.reason=i,this.requestId=a,this.data=r,this.source=l,this.name="RPCError"}}const Os=1024*1024+64*1024;async function Km(o,e=Os){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 j(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 Qo(o){const e=o.format??Ym(o.filename),t=o.filename??`persona.${e}`,n=new FormData;return n.append("file",new Blob([As(o.data)],{type:Xm(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 Qm(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([As(o)],{type:n}),`avatar.${i}`),a}function As(o){return o.slice().buffer}function Ym(o){const e=o?.toLowerCase();if(e?.endsWith(".png"))return"png";if(e?.endsWith(".charx"))return"charx";if(e?.endsWith(".json"))return"json"}function Xm(o){return o==="png"?"image/png":o==="charx"?"application/zip":"application/json"}function Jm(o){return{configuration:async e=>mo.parse(await o.json("/output-layer/configuration",{...e,query:{session_id:e?.sessionId}})),configure:async(e,t)=>mo.parse(await o.json("/output-layer/configuration",{...t,method:"PUT",body:e})),stream:(e,t,n)=>o.raw("/output-layer/stream",{...n,method:"POST",body:Jr.parse(e),timeoutMs:n?.timeoutMs??0},async i=>{if(!i.ok)throw new Error(`Output layer request failed (${i.status})`);if(!i.headers.get("content-type")?.includes("application/x-ndjson")){const v=await i.json();throw new Error(v.msg??"Output layer stream unavailable")}if(i.body===null)throw new Error("Output layer response has no body");const a=i.body.getReader(),r=new TextDecoder;let l="",m=!1;const p=v=>{if(!v.trim())return;const f=Zr.parse(JSON.parse(v));m||=["completed","cancelled","failed"].includes(f.type),t(f)};try{for(;;){const{value:v,done:f}=await a.read();l+=r.decode(v,{stream:!f});let y;for(;(y=l.indexOf(`
|
|
2
|
-
`))>=0;)p(l.slice(0,y)),l=l.slice(y+1);if(f)break}if(p(l),!m)throw new Error("Output layer stream ended before completion")}finally{await a.cancel(),a.releaseLock()}})}}function Zm(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 eh(o){if(!/^[0-9a-f-]{36}$/.test(o.connectionId))throw new Error("Invalid connectionId");const e=o.endpoint.replace(/\/+$/,""),t=e+"/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");if(p==="POST"&&m.pathname==="/api/fs:html-preview"||p==="DELETE"&&/^\/api\/fs:html-preview\/[^/]+$/.test(m.pathname)){const D=new Headers({"content-type":"application/json"});o.token!==void 0&&D.set("authorization",`Bearer ${o.token}`);const $=p==="POST"?t+"/html-preview":e+m.pathname;return n($,{...l,headers:D,method:p,redirect:"error",credentials:"same-origin"})}const v=La(p,m.pathname);if(v===void 0)throw new j(40301,"Operation is not available to a remote space");const f={};for(const[D,$]of m.searchParams){const W=f[D];f[D]=W===void 0?$:Array.isArray(W)?[...W,$]:[W,$]}const y=["media","mediaPreview","file","appearanceAsset","personaAvatar"].includes(v.operation),I=new Headers(l.headers??(r instanceof Request?r.headers:void 0));if(v.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 w=typeof l.body=="string"?JSON.parse(l.body):void 0,C={operation:v.operation,params:v.params,query:f,body:w,headers:{ifNoneMatch:I.get("if-none-match")??void 0,range:I.get("range")??void 0}},M=new Headers({"content-type":"application/json"});return o.token!==void 0&&M.set("authorization",`Bearer ${o.token}`),n(t+(y?"/download":"/call"),{method:"POST",headers:M,body:JSON.stringify(C),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 th(o){const e="/web-access";return{status:async()=>xe.parse(await o.json(e)),enable:async t=>xe.parse(await o.json(e,{method:"PUT",body:oa.parse(t)})),disable:async()=>xe.parse(await o.json(e,{method:"DELETE"})),issueLink:async()=>ta.parse(await o.json(e+"/links",{method:"POST",body:{}})),revoke:async t=>xe.parse(await o.json(e+"/revoke",{method:"POST",body:{sessionId:t}})),current:async()=>mt.parse(await o.json(e+"/session",{skipAuth:!0})),exchange:async t=>mt.parse(await o.json(e+"/exchange",{method:"POST",body:ea.parse(t),skipAuth:!0})),logout:async()=>mt.parse(await o.json(e+"/logout",{method:"POST",body:{},skipAuth:!0}))}}function oh(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 nh(o){const e="/usage-export",t=(n,i)=>`${e}/destinations/${encodeURIComponent(n)}/${i}`;return{status:async()=>X.parse(await o.json(e)),saveDraft:async n=>ht.parse(await o.json(e+"/destinations",{method:"POST",body:aa.parse(n)})),beginVibeAuth:async(n,i)=>gt.parse(await o.json(t(n,"auth/begin"),{method:"POST",body:ra.parse(i)})),pollVibeAuth:async n=>gt.parse(await o.json(`${e}/auth/${encodeURIComponent(n)}/poll`,{method:"POST",body:{}})),cancelVibeAuth:async n=>gt.parse(await o.json(`${e}/auth/${encodeURIComponent(n)}/cancel`,{method:"POST",body:{}})),preview:async n=>ho.parse(await o.json(t(n,"preview"))),testProtocol:n=>o.json(t(n,"test"),{method:"POST",body:{}}),enable:async(n,i)=>ht.parse(await o.json(t(n,"enable"),{method:"POST",body:ia.parse(i)})),disable:async n=>ht.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=>X.parse(await o.json(t(n,"sync"),{method:"POST",body:{}})),backfill:async(n,i)=>ho.parse(await o.json(t(n,"backfill"),{method:"POST",body:sa.parse(i)})),diagnostics:async()=>X.parse(await o.json(e+"/diagnostics")),exportLocal:n=>o.json(t(n,"export")),rebuild:async n=>X.parse(await o.json(e+"/rebuild",{method:"POST",body:{force:n}})),retry:async n=>X.parse(await o.json(t(n,"retry"),{method:"POST",body:{}})),setQueueCapacity:async n=>X.parse(await o.json(e+"/queue-capacity",{method:"PUT",body:{bytes:n}})),clearQueue:async(n,i)=>X.parse(await o.json(t(n,"clear-queue"),{method:"POST",body:{acknowledge:i}})),withdraw:async(n,i)=>X.parse(await o.json(t(n,"withdraw"),{method:"POST",body:{acknowledge:i}})),handoff:async n=>ve.nullable().parse(await o.json(t(n,"handoff"))),planHandoff:async(n,i)=>ve.parse(await o.json(t(n,"handoff/plan"),{method:"POST",body:{cutoff_at:i}})),armHandoff:async(n,i)=>ve.parse(await o.json(t(n,"handoff/arm"),{method:"POST",body:na.parse(i)})),refreshHandoff:async n=>ve.nullable().parse(await o.json(t(n,"handoff/refresh"),{method:"POST",body:{}})),rollbackHandoff:async(n,i,a)=>ve.parse(await o.json(t(n,"handoff/rollback"),{method:"POST",body:{cutoff_at:i,acknowledge:a}}))}}function sh(o){const e="/usage/provider-quotas";return{snapshot:async()=>vt.parse(await o.json(e)),refresh:async t=>vt.parse(await o.json(e+"/refresh",{method:"POST",body:da.parse({source_id:t})})),setEnabled:async(t,n)=>vt.parse(await o.json(e+"/enabled",{method:"PUT",body:ca.parse({source_id:t,enabled:n})}))}}function ih(o){const e="/external-clients",t=i=>`${e}/${encodeURIComponent(i)}`,n=i=>`${e}/sessions/${encodeURIComponent(i)}`;return{list:i=>o.json(e,i),create:(i,a)=>o.json(e,{...a,method:"POST",body:i}),update:(i,a,r)=>o.json(t(i),{...r,method:"PATCH",body:a}),revoke:(i,a)=>o.json(t(i),{...a,method:"DELETE"}),sessions:(i,a)=>o.json(`${t(i)}/sessions`,a),stdio:(i,a)=>o.json(`${t(i)}/stdio`,{...a,method:"POST",body:{}}),listener:i=>o.json(`${e}/listener`,i),configureListener:(i,a)=>o.json(`${e}/listener`,{...a,method:"PUT",body:i}),authorizations:i=>o.json(`${e}/authorizations`,i),respondAuthorization:(i,a,r)=>o.json(`${e}/authorizations/${encodeURIComponent(i)}/respond`,{...r,method:"POST",body:a}),saveText:(i,a,r)=>o.json(`${n(i)}/text`,{...r,method:"POST",body:a}),materials:(i,a)=>o.json(`${n(i)}/materials`,a),continue:(i,a,r)=>o.json(`${n(i)}/continue`,{...r,method:"POST",body:a??{}}),closeSession:(i,a)=>o.json(`${n(i)}/close`,{...a,method:"POST",body:{}}),stopSession:(i,a)=>o.json(`${n(i)}/stop`,{...a,method:"POST",body:{}})}}const rh=c({preview_id:s().regex(/^[a-f0-9]{64}$/u),url:s().min(1),mime:s().min(1),size:u().int().nonnegative(),expires_at:u().int().positive()}).strict();function ah(o){return{outputLayer:Jm(o),externalClients:ih(o),webAccess:th(o),connections:Zm(o),threadBridges:oh(o),usageExport:nh(o),providerQuotas:sh(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,t)=>o.json("/usage",{query:e,signal:t?.signal}),requestGovernance:()=>o.json("/usage/realtime"),agentActivity:()=>o.json("/usage/realtime/agents"),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}),openPreset:(e,t={})=>o.json(`/browser/setup/${encodeURIComponent(e)}:open`,{method:"POST",body:t}),updatePreset:(e,t={})=>o.json(`/browser/setup/${encodeURIComponent(e)}:update`,{method:"POST",body:t}),createShortcut:(e,t={})=>o.json(`/browser/setup/${encodeURIComponent(e)}:shortcut`,{method:"POST",body:t}),cancelSetup:e=>o.json(`/browser/setup/${encodeURIComponent(e)}:cancel`,{method:"POST",body:{}}),list:()=>o.json("/browser/connections"),saveSettings:e=>o.json("/config",{method:"POST",body:{browser_control:e}}),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={},t)=>o.json("/sessions",{signal:t?.signal,timeoutMs:t?.timeoutMs,query:{page_size:e.page_size??50,before_id:e.before_id,after_id:e.after_id,busy:e.busy,include_archive:e.include_archive,include_ephemeral:e.include_ephemeral,archived_only:e.archived_only,q:e.q,exclude_empty:e.exclude_empty,workspace_id:e.workspace_id,persona:e.persona}}),listEphemeral:(e={})=>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,t={})=>o.json("/sessions/"+encodeURIComponent(e)+":archive",{method:"POST",body:t}),restore:e=>o.json("/sessions/"+encodeURIComponent(e)+":restore",{method:"POST",body:{}}),deleteArchived:async(e,t={})=>go.parse(await o.json("/sessions/"+encodeURIComponent(e)+":delete-archived",{method:"POST",body:pa.parse(t),timeoutMs:0})),deleteAllArchived:async()=>go.parse(await o.json("/sessions:delete-archived",{method:"POST",body:{},timeoutMs:0})),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,t={})=>o.json(`/sessions/${encodeURIComponent(e)}/prompts`,{query:{admission:t.admission,agent_id:t.agent_id,cursor:t.cursor}}),getPrompt:(e,t,n={})=>o.json(`/sessions/${encodeURIComponent(e)}/prompts/${encodeURIComponent(t)}`,{query:{admission:n.admission,agent_id:n.agent_id}}),resumePrompt:(e,t,n,i={})=>o.json(`/sessions/${encodeURIComponent(e)}/prompts/${encodeURIComponent(t)}:resume`,{method:"POST",body:n,query:{agent_id:i.agent_id}}),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=la.parse(t);return ua.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)=>ue(o,`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(t)}`,{signal:n?.signal,timeoutMs:n?.timeoutMs,headers:le(n)}),mediaPreview:async(e,t,n)=>ue(o,`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(t)}/preview`,{query:{media_type:n?.mediaType},signal:n?.signal,timeoutMs:n?.timeoutMs,headers:le(n)},To),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:le(i)},a=>At(a,n,i?.signal)),openMediaPlayback:async(e,t,n)=>rh.parse(await o.json(`/sessions/${encodeURIComponent(e)}/media-playback`,{method:"POST",body:{file_id:t},signal:n?.signal,timeoutMs:n?.timeoutMs??15e3})),closeMediaPlayback:async(e,t)=>{await o.json(`/sessions/media-playback/${encodeURIComponent(e)}`,{method:"DELETE",signal:t?.signal,timeoutMs:t?.timeoutMs??1e4})},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:Qo(e)}),importCard:e=>o.json("/personas/import",{method:"POST",rawBody:Qo(e)}),exportCard:(e,t,n)=>ue(o,`/personas/${encodeURIComponent(e)}/export`,{query:{format:t,includeMemory:n?.includeMemory},signal:n?.signal,timeoutMs:n?.timeoutMs}),getAvatar:(e,t)=>ue(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:Qm(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:{list:e=>o.json("/skills",{query:{cwd:e}}),readBuiltinContent:(e,t)=>o.json(`/skills/${encodeURIComponent(e)}:content`,{signal:t?.signal,timeoutMs:t?.timeoutMs}),previewHostInstall:(e,t)=>o.json(`/skills/${encodeURIComponent(t)}:preview-install`,{method:"POST",body:{host:e}}),installHost:(e,t,n)=>o.json(`/skills/${encodeURIComponent(t)}:install`,{method:"POST",body:{host:e,revision:n,confirmed:!0}})},skins:{list:()=>o.json("/skins",{allowMissingRoute:!0}),get:e=>o.json(`/skins/${encodeURIComponent(e)}`)},workspaces:{list:()=>o.json("/workspaces"),listCatalog:()=>o.json("/workspaces",{query:{view:"catalog"}}),detail:e=>o.json(`/workspaces/${encodeURIComponent(e)}`),trust:e=>o.json(`/workspaces/${encodeURIComponent(e)}/trust`),setTrust:(e,t)=>o.json(`/workspaces/${encodeURIComponent(e)}/${t?"trust":"untrust"}`,{method:"POST"}),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}}),updateCatalog:(e,t)=>o.json(`/workspaces/${encodeURIComponent(e)}`,{method:"PATCH",query:{view:"catalog"},body:t}),remove:e=>o.json(`/workspaces/${encodeURIComponent(e)}`,{method:"DELETE"}),listSkills:e=>o.json(`/workspaces/${encodeURIComponent(e)}/skills`),getTrust:e=>o.json(`/workspaces/${encodeURIComponent(e)}/trust`),untrust:e=>o.json(`/workspaces/${encodeURIComponent(e)}/untrust`,{method:"POST"})},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}),inspect:e=>o.json("/homes:inspect",{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}})},imSessions:{snapshot:()=>o.json("/im/sessions"),catalog:()=>o.json("/im/sessions/catalog"),setPolicy:e=>o.json("/im/sessions/policy",{method:"PUT",body:e}),paste:(e,t)=>o.json("/im/sessions/paste",{method:"POST",body:{text:e,...t===void 0?{}:{instance_id:t}}}),check:e=>o.json(`/im/sessions/instances/${encodeURIComponent(e)}/check`,{method:"POST",body:{}}),listen:(e,t)=>o.json(`/im/sessions/instances/${encodeURIComponent(e)}/listen`,{method:"POST",body:{listening:t}}),confirm:(e,t)=>o.json(`/im/sessions/discoveries/${encodeURIComponent(e)}/confirm`,{method:"POST",body:t}),dismiss:e=>o.json(`/im/sessions/discoveries/${encodeURIComponent(e)}/dismiss`,{method:"POST",body:{}}),updateBinding:(e,t)=>o.json(`/im/sessions/bindings/${encodeURIComponent(e)}`,{method:"PATCH",body:t}),removeBinding:e=>o.json(`/im/sessions/bindings/${encodeURIComponent(e)}`,{method:"DELETE"}),startWechatQr:()=>o.json("/im/sessions/wechat/qrcode",{method:"POST",body:{}}),pollWechatQr:(e,t)=>o.json(`/im/sessions/wechat/qrcode/${encodeURIComponent(e)}/poll`,{method:"POST",body:t===void 0?{}:{verify_code:t}}),cancelWechatQr:e=>o.json(`/im/sessions/wechat/qrcode/${encodeURIComponent(e)}/cancel`,{method:"POST",body:{}})},secrets:{reveal:e=>o.json("/secrets:reveal",{method:"POST",body:{ref:e}})},executors:{list:()=>o.json("/executors"),listInstallations:e=>o.json("/executors/installations",e),install:(e,t)=>o.json(`/executors/${encodeURIComponent(e)}/install`,{...t,method:"POST",body:{}}),rollback:(e,t)=>o.json(`/executors/${encodeURIComponent(e)}/rollback`,{...t,method:"POST",body:{}}),getModels:(e,t)=>o.json(`/executors/${encodeURIComponent(e)}/models`,t),refreshModels:(e,t)=>o.json(`/executors/${encodeURIComponent(e)}/models:refresh`,{...t,method:"POST",body:{}}),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}),previewFile:(e,t)=>o.json("/agent-profiles/file-preview",{...t,method:"POST",body: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:{openHtmlPreview:(e,t)=>o.json("/fs:html-preview",{...t,method:"POST",body:e}),closeHtmlPreview:async(e,t)=>{await o.json(`/fs:html-preview/${encodeURIComponent(e)}`,{...t,method:"DELETE"})},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)=>ue(o,"/fs:content",{query:{path:e},signal:t?.signal,timeoutMs:t?.timeoutMs,headers:le(t)}),readHostMediaPreview:(e,t)=>ue(o,"/fs:content",{query:{path:e,preview:"media"},signal:t?.signal,timeoutMs:t?.timeoutMs,headers:le(t)},To),downloadHostFile:(e,t,n)=>o.raw("/fs:content",{method:"GET",expectBinary:!0,query:{path:e},signal:n?.signal,timeoutMs:n?.timeoutMs??0,headers:le(n)},i=>At(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:{navigation:()=>o.json("/plugins/navigation"),usage:e=>o.json("/plugins/usage",{query:e}),setUsage:e=>o.json("/plugins/usage",{method:"POST",body:e}),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:e=>o.json("/plugins/panels",{query:e}),panelDocument:(e,t,n)=>o.json(`/plugins/${encodeURIComponent(e)}/panels/${encodeURIComponent(t)}/document`,{query:n}),panelBridge:(e,t,n)=>o.json(`/plugins/${encodeURIComponent(e)}/panels/${encodeURIComponent(t)}/bridge`,{method:"POST",body:n}),commands:e=>o.json("/plugins/commands",{query:e}),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 le(o){return{...o?.ifNoneMatch===void 0?{}:{"if-none-match":o.ifNoneMatch},...o?.range===void 0?{}:{range:o.range}}}function Ms(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 At(o,e,t,n=1/0){const i=Ms(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 v=0;v<p.value.byteLength;v+=64*1024){t?.throwIfAborted();const f=p.value.subarray(v,Math.min(p.value.byteLength,v+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 ue(o,e,t,n){return o.raw(e,{...t,method:"GET",expectBinary:!0},async i=>{if(n===void 0)return{...Ms(i),bytes:new Uint8Array(await i.arrayBuffer())};const a=[],r=await At(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 xs(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 Mt(o){return o.agentId!==void 0?"agent":o.sessionId!==void 0?"session":o.workspaceId!==void 0?"workspace":"core"}function ch(o,e,t){return{scope:Mt(o),service:e,method:t,workspaceId:o.workspaceId,sessionId:o.sessionId,agentId:o.agentId}}function dh(o){return JSON.stringify(o)}function lh(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 uh=3e4,ph=500,mh="kimi-code.bearer.",Us="transport.timeout";class hh{endpoint;token;fetchImpl;defaultTimeoutMs;readingTimeoutMs;socket;activeCalls=new Set;rest;closed=!1;terminal={listTerminals:async e=>ga.parse(await this.viewRequest(this.terminalPath(e),{})),createTerminal:async(e,t={})=>vo.parse(await this.viewRequest(this.terminalPath(e),{},{method:"POST",body:ha.parse(t),okCodes:[0]})),getTerminal:async(e,t)=>vo.parse(await this.viewRequest(this.terminalPath(e,t),{})),closeTerminal:async(e,t)=>ma.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:async(e,t,n)=>{const i=Bn[t],a=n,r=i.suffix.replace("{target}",encodeURIComponent(a.target??"")),l=await this.viewRequest(`/api/sessions/${encodeURIComponent(e)}${r}`,{agent_id:a.query?.agent_id,receipt:t==="submit"?"true":void 0},{method:i.method,body:i.method==="GET"?void 0:a.body??{},okCodes:i.okCodes,timeoutMs:"timeoutMs"in i?i.timeoutMs:void 0});if(t==="submit"&&l!==null&&typeof l=="object"&&!("content"in l)){const{resolved_media:m,resolved_parts:p,...v}=va.parse(l),f=a.body.content,y=new Map,I=p??m?.map(({index:C,content:M})=>({index:C,content:[M]}))??[];for(const C of I){if(C.index>=f.length||f[C.index]?.type==="text"||y.has(C.index))throw new j(50001,"Invalid prompt receipt media projection");y.set(C.index,C.content)}const w=f.flatMap((C,M)=>y.get(M)??[C]);return{...v,content:w}}return l}};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:mn},{signal:i?.signal,timeoutMs:i?.timeoutMs});return pn(a)?a:e==="page"?Pm(a):Om(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,r)=>{if(a.status===404&&t.allowMissingRoute===!0){await a.body?.cancel();return}const l=/\/klient\/session-view\//.test(e)||/\/transcript(?:\/(?:detail|details|ops))?$/.test(e),m=await this.readEnvelope(a,t.signal,l?Os:4*1024*1024);r(m.request_id);const p=t.okCodes??[0];if(a.ok===!1||!p.includes(m.code))throw new j(p.includes(m.code)?a.status:m.code,m.msg,m.details,m.reason,m.request_id,m.data);return m.data})}requestRaw(e,t,n){const i=t??{};return this.performFetch(e,i,async(a,r)=>{const l=a.headers.get("content-type")??"";if((a.ok||a.status===304&&i.headers?.["if-none-match"]!==void 0)&&!(i.jsonErrorOnSuccess===!0&&l.includes("json")))return n(a);const m=await this.readEnvelope(a,i.signal);r(m.request_id);const p=i.okCodes??[0];throw new j(p.includes(m.code)?a.status:m.code,m.msg,m.details,m.reason,m.request_id,m.data)})}async performFetch(e,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>Nm)throw new j(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,p=performance.now();let v="headers",f;const y=m===0?void 0:setTimeout(()=>{r.signal.aborted||(f=v,r.abort())},m),I=t.signal,w=()=>{r.abort(I?.reason)};I?.aborted===!0?w():I?.addEventListener("abort",w,{once:!0});try{const M=(t.baseUrl??this.endpoint).replace(/\/+$/u,""),D=e.startsWith("/api/")?e:`/api${e}`,$=globalThis.location?.origin,W=M===""?new URL(D,$??"http://localhost"):new URL(`${M}${D}`);for(const[A,Oe]of Object.entries(t.query??{}))if(Array.isArray(Oe))for(const Bs of Oe)W.searchParams.append(A,Bs);else Oe!==void 0&&W.searchParams.set(A,String(Oe));const de=new Headers({accept:t.expectBinary===!0?"application/octet-stream":"application/json",...t.headers}),nt=de.get("x-request-id");let st=nt!==null&&bo(nt)?nt:Ua();de.set("x-request-id",st),this.token!==void 0&&t.skipAuth!==!0&&de.set("authorization",`Bearer ${this.token}`),t.body!==void 0&&!de.has("content-type")&&de.set("content-type","application/json");const so=A=>{typeof A=="string"&&bo(A)&&(st=A)},Pe=()=>this.transportTimeoutError({method:t.method??"GET",path:W.pathname,phase:f??v,timeoutMs:m,elapsedMs:Math.round(performance.now()-p),request_id:st});let it;try{const A=e==="/api/klient/call"?W.toString():W;it=await this.fetchImpl(A,{method:t.method??"GET",body:i,headers:Object.fromEntries(de),signal:r.signal,redirect:"error"})}catch(A){throw f!==void 0?Pe():this.closed&&r.signal.aborted?new Error("http closed",{cause:A}):A instanceof j?A:new j(-1,A instanceof Error?A.message:"Connection failed",void 0,"transport.network",void 0,void 0,"transport")}if(so(it.headers.get("x-request-id")),v="body",f!==void 0)throw Pe();try{const A=await n(it,so);if(f!==void 0)throw Pe();return A}catch(A){throw f!==void 0?Pe():this.closed&&r.signal.aborted?new Error("http closed",{cause:A}):A instanceof TypeError&&!r.signal.aborted?new j(-1,A.message,void 0,"transport.network",void 0,void 0,"transport"):A}}finally{y!==void 0&&clearTimeout(y),I?.removeEventListener("abort",w),this.activeCalls.delete(l)}}transportTimeoutError(e){return new j(50001,`call timed out after ${e.timeoutMs}ms`,e,Us,e.request_id,void 0,"transport")}async readEnvelope(e,t,n=4*1024*1024){let i;try{i=await Km(e,n)}catch(a){throw Sh(a)||t?.aborted===!0||!(a instanceof SyntaxError)?a:new j(e.status,`HTTP ${e.status} — non-JSON response`)}if(i===null||typeof i.code!="number"||typeof i.msg!="string")throw new j(e.status,`HTTP ${e.status} — non-JSON response`);return i}constructor(e){const 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??uh,this.readingTimeoutMs=e.readingTimeoutMs??(()=>0),this.socket=new gh({endpoint:t,eventsUrl:e.eventsUrl,token:e.token,WebSocket:e.WebSocket,onDiagnostic:e.onSocketDiagnostic}),this.rest=ah({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:ch(e,t,n),params:xs(i)},timeoutMs:a?.timeoutMs,signal:a?.signal})}stream(e,t,n,i){return this.closed?fh(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 gh{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 Dm({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 Um({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??vh(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:Mt(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:Mt(e),service:t,method:n,arg:xs(i),workspaceId:e.workspaceId,sessionId:e.sessionId,agentId:e.agentId},sent:!1,push(y){if(l)return;const I={done:!1,value:y},w=r.shift();w===void 0?a.push(I):w.resolve(I)},end:()=>{if(l)return;l=!0,m!==void 0&&this.streams.delete(m);const y={done:!0,value:void 0},I=r.shift();I===void 0?a.push(y):I.resolve(y);for(const w of r)w.resolve({done:!0,value:void 0});r.length=0},error:y=>{if(l)return;l=!0,m!==void 0&&this.streams.delete(m);const I=r.shift();I===void 0?a.push(y):I.reject(y);for(const w of r)w.reject(y);r.length=0}};let v=!1;const f=()=>{if(!v){v=!0;try{this.requireWebSocket()}catch(y){p.error(y instanceof Error?y:new Error(String(y)));return}m=this.nextId(),p.frame={...p.frame,id:m},this.streams.set(m,p),this.ensureConnected(),this.state==="open"&&this.sendStream(p)}};return{next:()=>{f();const y=a.shift();return y instanceof Error?Promise.reject(y):y!==void 0?Promise.resolve(y):l?Promise.resolve({done:!0,value:void 0}):new Promise((I,w)=>{r.push({resolve:I,reject:w})})},return:()=>{if(!l){if(l=!0,m!==void 0){const y=this.streams.get(m);this.streams.delete(m),y?.sent===!0&&this.state==="open"&&this.send({type:"stream_cancel",id:m})}for(const y of r)y.resolve({done:!0,value:void 0});r.length=0}return Promise.resolve({done:!0,value:void 0})}}}}}close(){if(this.closed)return;this.closed=!0,this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.state="closed",this.ws?.close(1e3,"klient closed"),this.ws=void 0;const e=new Error("http event socket closed");this.notifyDisconnect(e);for(const 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?[`${mh}${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(lh(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(ph*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(dh(e))}catch{}}nextId(){return this.seq+=1,`${this.idPrefix}_${this.seq}`}}function Yo(o){return new j(typeof o.code=="number"?o.code:50001,o.msg??"error",o.details,o.reason)}function vh(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 Sh(o){return typeof o=="object"&&o!==null&&"name"in o&&o.name==="AbortError"}function fh(o){return{[Symbol.asyncIterator](){return{async next(){throw o}}}}}function yh(o){return Cm(new hh(o),o)}class N extends Error{code;requestId;data;details;source;reason;constructor(e){super(`${e.msg} (code ${e.code})`),this.name="ApiError",this.code=e.code,this.data=e.data,this.details=e.details,this.requestId=e.request_id,this.source=e.source??"server",this.reason=e.reason}}const V={INVALID_RESPONSE:-3,TIMEOUT:-2,REQUEST_INVALID:40001,UNAUTHORIZED:40101,SESSION_NOT_FOUND:40401,PROMPT_NOT_FOUND:40402,QUESTION_NOT_FOUND:40405,SKILL_NOT_FOUND:40415,SESSION_BUSY:40901,APPROVAL_ALREADY_RESOLVED:40902,COMPACTION_UNABLE:40910,SESSION_UNDO_UNAVAILABLE:40911,SKILL_NOT_ACTIVATABLE:40912,APPROVAL_EXPIRED:41001,QUESTION_EXPIRED:41002,TERMINAL_NOT_FOUND:40414,MESSAGE_ACTION_UNAVAILABLE:40936,SESSION_CURSOR_MISMATCH:40937,SESSION_INDEX_BUILDING:40939};function bh(o){return o instanceof N&&o.source==="transport"}const _h=/\s*\(code -?\d+\)$/;function Ih(o){const e=o.replace(_h,"").trim();return!!(e==="session.not_found"||/^session not found$/i.test(e)||/^(?:temporary )?session \S+ does not exist$/i.test(e))}const Th={"*":"off",main:"delta"};function Zh(o){return o===void 0||o==="main"?Th:{"*":"off",main:"off",[o]:"delta"}}function wh(o){const e=async i=>{try{return await i()}catch(a){throw a instanceof j?new N({code:a.code,msg:a.message,data:a.data,details:a.details,request_id:a.requestId,source:a.source,reason:a.reason}):a}},t=i=>o.session(i).commands,n=(i,a)=>e(async()=>{if(!await o.session(i).resume())throw new j(40401,`session ${i} does not exist`);return a()});return{getSession:i=>e(()=>t(i).read()),submitPrompt:(i,a)=>e(()=>t(i).submit(a)),editMessage:(i,a,r)=>n(i,()=>t(i).edit(a,un.parse(r))),regenerateMessage:(i,a,r)=>n(i,()=>t(i).regenerate(a,ln.parse(r))),forkSession:(i,a)=>e(()=>t(i).fork(dn.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 Xo=/^\/api\/sessions\/[^/]+\/document-preview\/assets\/[A-Za-z0-9_-]{16,128}$/;function Eh(o){const e=o.trim();if(Xo.test(e))return e;const t=(()=>{try{return new URL(e,"http://example.test")}catch{return}})();if(t===void 0)throw new Error("Preview asset URL is not a readable document-preview asset path.");const n=t.pathname;if(t.origin!=="http://example.test"||!Xo.test(n))throw new Error("Preview asset URL does not belong to this connection.");return n}const x="main",pe={roster:1,live:2,task:3};function xt(o,e){if(o===e)return 0;if(o===x)return-1;if(e===x)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 kh(o,e){if(o.agentId===x||e.agentId===x)return xt(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:xt(o.agentId,e.agentId)}function oo(){return Object.create(null)}function Ch(){return{roots:Object.freeze([]),byId:Object.freeze(oo())}}function bt(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 Rh(o,e){if(o===e)return!0;if(o===void 0||e===void 0||!bt(o.currentTurn,e.currentTurn)||!bt(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=>bt(o.byModel?.[i],e.byModel?.[i]))}function Ph(o,e){return o===e?!0:o.agentId===e.agentId&&o.createdAt===e.createdAt&&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.thinkingEffortExplicit===e.thinkingEffortExplicit&&o.executorId===e.executorId&&o.executorProtocol===e.executorProtocol&&o.contextTokens===e.contextTokens&&o.maxContextTokens===e.maxContextTokens&&Rh(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 eg(o,e){if(o===void 0||o===e)return e;const t=oo(),n=new Set,i=v=>{const f=t[v];if(f!==void 0)return f;const y=e.byId[v];if(y===void 0)return;if(n.has(v))return t[v]=y,y;n.add(v);const I=o.byId[v];let w=I!==void 0;for(const M of y.childIds){const D=i(M);(D===void 0||D!==o.byId[M])&&(w=!1)}n.delete(v);const C=I!==void 0&&w&&Ph(I,y)?I:y;return t[v]=C,C};for(const v of e.roots)i(v.agentId);for(const v of Object.keys(e.byId))i(v);const a=e.roots.map(v=>t[v.agentId]),r=Object.keys(o.byId),l=Object.keys(e.byId),m=r.length===l.length&&l.every(v=>t[v]===o.byId[v]),p=a.length===o.roots.length&&a.every((v,f)=>v===o.roots[f]);return m&&p?o:{roots:p?o.roots:a,byId:t}}function tg(o,e,t){const n=new Map;for(const p of Dh(t??[])){const v=js(p),f=Ge(n,v);Oh(f,p)}for(const p of e??[]){if(!re(p.agentId))continue;const v=Ge(n,p.agentId);Ah(v,p)}for(const p of o){if(!re(p.subagentId))continue;const v=Ge(n,p.subagentId);Mh(v,p)}if(n.size===0)return Ch();for(const p of n.values())(p.rosterParentAgentId??p.parentAgentId)===x&&!n.has(x)&&Ge(n,x);const i=new Map;for(const p of n.values())i.set(p.agentId,xh(p,n));Uh(i);const a=new Map;for(const p of n.keys())a.set(p,[]);const r=[];for(const[p,v]of i){if(v===void 0){r.push(p);continue}a.get(v).push(p)}const l=(p,v)=>kh(n.get(p),n.get(v));for(const p of a.values())p.sort(l);if(r.sort(l),n.has(x)&&!i.get(x)){const p=n.get(x);if(p.status===void 0){const v=a.get(x)??[];p.status=v.some(f=>{const y=n.get(f);return y!==void 0&&te(y.status??"completed")})?"running":"completed"}}const m=oo();for(const p of n.values()){const v=i.get(p.agentId),f=re(p.name)?p.name:p.agentId,y=p.status??"unknown",I={agentId:p.agentId,createdAt:p.createdAt,parentAgentId:v,parentToolCallId:p.parentToolCallId,name:f,label:re(p.label)?p.label:f,model:p.model,thinkingEffort:p.thinkingEffort,thinkingEffortExplicit:p.thinkingEffortExplicit,executorId:p.executorId,executorProtocol:p.executorProtocol,contextTokens:p.contextTokens,maxContextTokens:p.maxContextTokens,usage:p.usage,status:y,refreshing:p.refreshing,refreshingUntil:p.refreshingUntil,busy:Lh(y,p.busy),toolCallCount:p.toolCallCount,toolCallCountKnown:p.toolCallCountKnown,startedAt:p.startedAt,endedAt:p.endedAt,description:p.description,summary:p.summary,error:p.error,childIds:a.get(p.agentId)??[]};m[p.agentId]=I}return{roots:r.map(p=>m[p]),byId:m}}function og(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 ng(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 Ge(o,e){const t=o.get(e);if(t!==void 0)return t;const n={agentId:e,createdAt:void 0,parentAgentId:void 0,rosterParentAgentId:void 0,parentToolCallId:void 0,name:void 0,label:void 0,model:void 0,thinkingEffort:void 0,thinkingEffortExplicit:void 0,executorId:void 0,executorProtocol:void 0,contextTokens:void 0,maxContextTokens:void 0,usage:void 0,status:void 0,refreshing:void 0,refreshingUntil:void 0,statusAuthority:0,statusStartedAt:void 0,statusEndedAt:void 0,taskId:void 0,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 Ds(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 Oh(o,e){const t=me(e.status,e.detached===!0),n=T(e.startedAt,e.started_at),i=T(e.endedAt,e.completed_at);o.parentAgentId=o.parentAgentId??H(e.parentAgentId??e.parent_agent_id),o.parentToolCallId=o.parentToolCallId??H(e.parentToolCallId??e.parent_tool_call_id),o.name=o.name??T(e.name,e.description),o.description=T(e.description)??o.description,(t===void 0?o.status===void 0&&o.disposedAt===void 0:no(o,t,pe.task,n,i).accepted)&&(o.model=T(e.model)??o.model,o.thinkingEffort=T(e.thinkingEffort,e.thinking_effort)??o.thinkingEffort,o.thinkingEffortExplicit=e.thinkingEffortExplicit??e.thinking_effort_explicit??o.thinkingEffortExplicit,o.executorId=T(e.executorId,e.executor_id)??o.executorId,o.executorProtocol=T(e.executorProtocol,e.executor_protocol)??o.executorProtocol,o.startedAt??=n,o.endedAt??=i,o.summary=o.summary??T(e.summary,e.output_preview),o.error=o.error??T(e.error,e.stateReason,e.state_reason),t!==void 0&&t!=="unknown"&&(o.taskId=H(e.id)??o.taskId),e.detached===!0&&o.busy===void 0&&t==="background"&&(o.busy=!0))}function Ah(o,e){o.createdAt??=T(e.createdAt);const t=H(e.parentAgentId);t!==void 0&&(o.rosterParentAgentId=t),o.parentAgentId=t??o.parentAgentId,o.parentToolCallId=T(e.parentToolCallId)??o.parentToolCallId,o.name=T(e.name,e.label)??o.name,o.label=T(e.label)??o.label,o.description=T(e.description)??o.description,Ds(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,Ns(o,n,pe.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=me(e.status,e.detached===!0),l=e.statusSource===void 0?pe.roster:4,m=e.statusSource==="metadata"&&r==="unknown",p=L(e.endedAt??e.startedAt),v=p!==void 0&&o.statusStartedAt!==void 0&&p<o.statusStartedAt,f=e.statusSource!==void 0&&!m&&!v&&(r==="idle"||r==="unknown"),y=o.taskId!==void 0&&te(o.status??"unknown"),I=o.status==="completed"||o.status==="failed"||o.status==="cancelled",w=f&&(y||I);f&&!w&&(o.status=r,o.statusAuthority=l,o.busy=!1);const C=!w&&(f||(r===void 0?o.status===void 0&&o.disposedAt===void 0:no(o,r,l,e.startedAt,e.endedAt).accepted));a&&(o.refreshing=!0,o.refreshingUntil=e.refreshingUntil),C&&(o.model=T(e.model)??o.model,o.thinkingEffort=T(e.thinkingEffort)??o.thinkingEffort,o.thinkingEffortExplicit=e.thinkingEffortExplicit??o.thinkingEffortExplicit,o.executorId=T(e.executorId)??o.executorId,o.executorProtocol=T(e.executorProtocol)??o.executorProtocol,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??=T(e.startedAt),o.endedAt??=T(e.endedAt),o.summary=T(e.summary)??o.summary,o.error=T(e.error)??o.error)}function Ns(o,e,t){o.status===void 0||!te(o.status)||o.statusStartedAt!==void 0&&o.statusStartedAt>e||(o.status="unknown",o.statusAuthority=t,Ls(o),o.busy=!1)}function Mh(o,e){if(o.createdAt??=T(e.createdAt),o.parentAgentId=o.parentAgentId??H(e.parentAgentId),o.parentToolCallId=T(e.parentToolCallId)??o.parentToolCallId,(e.name!==e.subagentId||o.name===void 0)&&(o.name=T(e.name)??o.name),o.label=T(e.label)??o.label,o.description=T(e.description)??o.description,Ds(o,e.toolCallCount,e.toolCallCountKnown,e.toolCallCountAuthoritative),o.statusAuthority===4&&(o.status==="unknown"||o.status==="idle")&&te(me(e.status)??"unknown"))return;const t=L(e.disposedAt);t!==void 0&&(o.disposedAt===void 0||t>o.disposedAt)&&(o.disposedAt=t,Ns(o,t,pe.live));const n=me(e.status);(n===void 0?o.status===void 0&&o.disposedAt===void 0:no(o,n,pe.live,e.startedAt,e.endedAt).accepted)&&(o.model=T(e.model)??o.model,o.thinkingEffort=T(e.thinkingEffort)??o.thinkingEffort,o.thinkingEffortExplicit=e.thinkingEffortExplicit??o.thinkingEffortExplicit,o.executorId=T(e.executorId)??o.executorId,o.executorProtocol=T(e.executorProtocol)??o.executorProtocol,o.contextTokens=e.contextTokens??o.contextTokens,o.maxContextTokens=e.maxContextTokens??o.maxContextTokens,o.usage=e.usage??o.usage,n!==void 0&&(o.busy=te(n)),o.startedAt??=T(e.startedAt),o.endedAt??=T(e.endedAt),o.summary=T(e.summary)??o.summary,o.error=T(e.error)??o.error)}function xh(o,e){const t=o.rosterParentAgentId??o.parentAgentId;if(!(t===void 0||t===o.agentId)&&e.has(t))return t}function Uh(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,v)=>xt(v,p)>0?v: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 js(o){return H(o.agentId)}function Dh(o){const e=new Map;for(const t of o){const n=js(t);if(n===void 0)continue;const i=e.get(n);(i===void 0||Nh(t,i))&&e.set(n,t)}return[...e.values()]}function Nh(o,e){const t=L(T(o.startedAt,o.started_at)),n=L(T(e.startedAt,e.started_at)),i=L(T(o.endedAt,o.completed_at)),a=L(T(e.endedAt,e.completed_at)),r=H(o.id),l=H(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=me(o.status,o.detached===!0),v=me(e.status,e.detached===!0),f=p===void 0?-1:ke(p),y=v===void 0?-1:ke(v);return f!==y?f>y:i!==a?i===void 0?!1:a===void 0?!0:i>a:r!==l?r===void 0?!1:l===void 0?!0:r>l:Jo(o)>Jo(e)}function Jo(o){return JSON.stringify([H(o.id)??"",o.kind??"",o.description??"",o.name??"",o.status??"",o.model??"",T(o.thinkingEffort,o.thinking_effort)??"",T(o.startedAt,o.started_at)??"",T(o.endedAt,o.completed_at)??"",T(o.summary,o.output_preview)??"",H(o.parentAgentId??o.parent_agent_id)??"",H(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 me(o,e=!1){if(!re(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 ke(o){return o==="unknown"?0:o==="completed"||o==="failed"||o==="cancelled"||o==="lost"?2:1}function Zo(o){return o==="suspended"?2:te(o)?1:0}function jh(o,e,t){if(ke(e)===2||o.disposedAt===void 0)return!1;const n=L(t);return n===void 0||n<=o.disposedAt}function Ls(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 no(o,e,t,n,i){const a=o.status===void 0?-1:ke(o.status),r=ke(e),l=L(n),m=L(i);if(jh(o,e,n))return{accepted:!1,newGeneration:!1};const p=a>0&&r>0,v=L(o.startedAt),y=te(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&&v!==void 0&&l>v||p&&l!==void 0&&o.statusEndedAt!==void 0&&l>o.statusEndedAt;if(t<pe.task&&r===2&&o.taskId!==void 0)return{accepted:!1,newGeneration:!1};const w=p&&o.statusStartedAt!==void 0&&m!==void 0&&o.statusStartedAt>=m;if(!y&&w)return{accepted:!1,newGeneration:!1};const C=o.status===void 0?-1:Zo(o.status),M=Zo(e),D=r===a&&(r===1?M<C||M===C&&t<o.statusAuthority:t<o.statusAuthority),$=r<a||D;return!y&&$?{accepted:!1,newGeneration:!1}:(y?(Ls(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:y})}function te(o){return o==="running"||o==="suspended"||o==="background"}function Lh(o,e){return o==="completed"||o==="failed"||o==="cancelled"||o==="lost"||o==="idle"?!1:te(o)||e===!0}function re(o){return o!==void 0&&o!==""}function H(o){return re(o)?o:void 0}function T(...o){for(const e of o)if(re(e))return e}const en=200,qh=5e3,tn=1e3,be=[],Ut=new Set;let qs=[];function oe(o,e=Date.now()){be.push({...o,at:e}),be.length>en&&be.splice(0,be.length-en),qs=be.slice();for(const t of Ut)t()}function $h(){return qs}function sg(o){return Ut.add(o),()=>{Ut.delete(o)}}function Gh(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(`
|
|
3
|
-
`)}let Fe=0,_t=null;function ig(){if(typeof window>"u"||typeof document>"u")return()=>{};if(Fe+=1,Fe===1){const o=()=>{oe({kind:"visibility",state:document.visibilityState})},e=()=>{oe({kind:"focus",focused:!0})},t=()=>{oe({kind:"focus",focused:!1})},n=()=>{oe({kind:"online",online:!0})},i=()=>{oe({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-tn;a=m,p>=qh&&oe({kind:"timer_gap",gapMs:p,visibility:document.visibilityState},m)},tn),l=window;l.__kikiConnectionLog=()=>Gh($h()),_t=()=>{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()=>{Fe-=1,Fe===0&&(_t?.(),_t=null)}}function Fh(o){return o instanceof N&&o.code===V.SESSION_INDEX_BUILDING}function Bh(o){return Ih(o)}function on(o){if(typeof o!="object"||o===null||Array.isArray(o))return!1;const e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function _e(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 N({code:V.INVALID_RESPONSE,msg:`Invalid config response: ${e} must be a string or string array`,data:o})}function Dt(o){if(!on(o))throw new N({code:V.INVALID_RESPONSE,msg:"Invalid config response: data must be a plain object",data:o});const e=o.tools;if(e!=null&&!on(e))throw new N({code:V.INVALID_RESPONSE,msg:"Invalid config response: tools must be a plain object",data:e});const t=e??{};return{...o,extra_agent_dirs:_e(o.extra_agent_dirs,"extra_agent_dirs"),skip_builtin_profile_installation:_e(o.skip_builtin_profile_installation,"skip_builtin_profile_installation"),disabled_named_profiles:_e(o.disabled_named_profiles,"disabled_named_profiles"),tools:{...t,enabled:_e(t.enabled,"tools.enabled"),disabled:_e(t.disabled,"tools.disabled")}}}const Vh=["user","feedback","project","reference"],Hh=40423,Wh=40944;function zh(o){const e=o.endpoint===""?globalThis.location.origin:o.endpoint;return new Fs({baseUrl:e,token:o.token,timeoutMs:o.timeoutMs,onSessionMutation:o.onSessionMutation,transport:eh({...o,endpoint:e})})}class $s extends Error{constructor(){super("External agent messages support text only. Remove attachments and retry."),this.name="ExternalAgentAttachmentUnsupportedError"}}class ot extends Error{constructor(e){super("Native child prompt result unknown",{cause:e}),this.name="NativeChildPromptSendError"}}class Gs extends ot{constructor(e){super(e),this.name="NativeChildPromptConflictError"}}function Kh(o){const e=o instanceof ot?o.cause:o;return e instanceof N&&e.code===40001}class Fs{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=yh({endpoint:this.baseUrl,token:this.token,timeoutMs:e.timeoutMs,readingTimeoutMs:()=>this.readingOptions().timeoutMs,onSocketDiagnostic:n=>{oe(n)},...e.transport});const t=wh(this.klient);this.sessions={...t,listDurableIngress:(n,i)=>this.run(()=>this.rest.sessions.listPrompts(n,{admission:"durable",agent_id:i?.agentId,cursor:i?.cursor})),getDurableIngress:(n,i,a)=>this.run(()=>this.rest.sessions.getPrompt(n,i,{admission:"durable",agent_id:a})),resumeDurableIngress:(n,i,a,r)=>this.runSessionMutation(n,()=>this.rest.sessions.resumePrompt(n,i,a,{agent_id:r})),submitPrompt:(...n)=>this.runSessionMutation(n[0],()=>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:Sa().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 j){const n=t.reason===Us;throw new N({code:n?V.TIMEOUT:t.code,msg:n?t.message.replace("call timed out",So("en","common.requestTimedOut")):t.message,data:t.data??null,details:t.details,request_id:t.requestId,source:t.source,reason:t.reason})}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={},t){return this.run(()=>this.rest.sessions.list(e,t))}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=>{const n={...t},i=n.resource,a=i==="live_agent"?"agent_execution":i==="agent_execution"||i==="model_request"?i:void 0,r=(t.roles??[]).filter(l=>l==="main"||l==="subagent"||l==="independent");return{id:t.id,resource:a,scope:t.scope,models:t.models===void 0?void 0:[...t.models],providers:t.providers===void 0?void 0:[...t.providers],executors:t.executors===void 0?void 0:[...t.executors],profiles:t.profiles===void 0?void 0:[...t.profiles],roles:r.length===0?void 0:r,subagents_only:t.subagentsOnly??n.subagents_only===!0,max_concurrent:t.maxConcurrent??(typeof n.max_concurrent=="number"?n.max_concurrent:void 0),overflow:t.overflow,max_wait_ms:t.maxWaitMs??(typeof n.max_wait_ms=="number"?n.max_wait_ms:void 0),enabled:t.enabled}})}})}getAgentActivity(){return this.run(()=>this.rest.agentActivity())}getProviderQuotas(){return this.run(()=>this.rest.providerQuotas.snapshot())}refreshProviderQuota(e){return this.run(()=>this.rest.providerQuotas.refresh(e))}setProviderQuotaEnabled(e,t){return this.run(()=>this.rest.providerQuotas.setEnabled(e,t))}getUsageRescan(){return this.run(()=>this.rest.usageRescan.status())}startUsageRescan(){return this.run(()=>this.rest.usageRescan.start())}getUsage(e,t){return this.run(()=>this.rest.usage(e,t))}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,t={}){return this.run(async()=>{const n=t.include_attached??!0,i=await this.rest.sessions.archive(e,{...t,include_attached:n});if(n&&i.outcomes===void 0)throw new Error("The connected server cannot confirm archiving attached conversations. Refresh the list and update the server before retrying.");if(!i.archived||i.outcomes?.some(a=>!a.ok)){const a=i.outcomes?.filter(r=>!r.ok).map(r=>`${r.id}: ${r.message}`).join("; ");throw new Error(`Some conversations could not be archived. Retry to finish archiving${a?`: ${a}`:"."}`)}return i})}restoreSession(e){return this.run(()=>this.rest.sessions.restore(e))}deleteArchivedSession(e,t={}){return this.run(()=>this.rest.sessions.deleteArchived(e,t))}deleteAllArchivedSessions(){return this.run(()=>this.rest.sessions.deleteAllArchived())}getSessionGoal(e){return this.run(()=>this.rest.sessions.goal(e))}createAgentGoal(e,t){return this.run(()=>this.klient.session(e).agent(x).createGoal(t))}updateAgentGoal(e,t){return this.run(()=>this.klient.session(e).agent(x).updateGoal(t))}pauseAgentGoal(e){return this.run(()=>this.klient.session(e).agent(x).pauseGoal())}resumeAgentGoal(e,t={}){return this.run(()=>this.klient.session(e).agent(x).resumeGoal(t))}cancelAgentGoal(e){return this.run(()=>this.klient.session(e).agent(x).cancelGoal())}resumeRecoveredQueue(e){return this.run(()=>this.klient.session(e).agent(x).resumeRecoveredPromptQueue())}listMessages(e,t={}){return this.run(()=>this.rest.sessions.listMessages(e,t))}listPrompts(e,t={}){return this.run(()=>this.rest.sessions.listPrompts(e,t))}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===x?!0:(await this.run(()=>this.klient.session(e).getAgentExecutor(t))??"native")==="native"}async sendAgentMessage(e,t,n,i,a,r){const l=this.klient.session(e);if((await this.run(()=>l.getAgentExecutor(t))??"native")!=="native"){if(i?.some(f=>f.type!=="text"))throw new $s;return this.run(()=>l.sendUserAgentMessageReceipt({targetAgentId:t,content:n,idempotencyKey:a}))}const p=i===void 0?[{type:"text",text:n}]:[...i],v=t!==x&&p.every(f=>f.type==="text");try{await this.submitPrompt(e,{content:p,agent_id:t,after_model_switch:r,prompt_id:v?a:void 0})}catch(f){throw v&&f instanceof N&&f.code===40938?new Gs(f):t!==x?new ot(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 Dt(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 fa.parse(await this.run(this.rest.nbSearch.capabilities()))}async testNbSearch(e){return ya.parse(await this.run(this.rest.nbSearch.test({signal:e})))}async readNbSearchKeyUsage(e,t=!1,n){return ba.parse(await this.run(this.rest.nbSearch.keyUsage(e,t,{signal:n})))}async readNbSearchCredential(e,t=!1){return fo.parse(await this.run(this.rest.nbSearch.readCredential(e,t)))}async revealSecret(e){return _a.parse(await this.run(this.rest.secrets.reveal(e)))}async writeNbSearchCredential(e,t,n,i){return fo.parse(await this.run(this.rest.nbSearch.writeCredential(e,t,n,i)))}get requestIdentity(){const e=this.rest.requestIdentity,t=async n=>ka.parse(await this.run(n));return{get:()=>t(e.get()),preview:async n=>Ia.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))}}get imSessions(){const e=this.rest.imSessions,t=n=>(...i)=>this.run(()=>n(...i));return{snapshot:t(e.snapshot.bind(e)),catalog:t(e.catalog.bind(e)),setPolicy:t(e.setPolicy.bind(e)),paste:t(e.paste.bind(e)),check:t(e.check.bind(e)),listen:t(e.listen.bind(e)),confirm:t(e.confirm.bind(e)),dismiss:t(e.dismiss.bind(e)),updateBinding:t(e.updateBinding.bind(e)),removeBinding:t(e.removeBinding.bind(e)),startWechatQr:t(e.startWechatQr.bind(e)),pollWechatQr:t(e.pollWechatQr.bind(e)),cancelWechatQr:t(e.cancelWechatQr.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))}previewAgentProfileFile(e,t){return this.run(this.rest.agents.previewFile(e,t))}createAgentProfile(e){return this.run(this.rest.agents.create(e))}updateNamedAgentProfile(e,t){return this.run(this.rest.agents.update(e,t))}listShippedAgentProfiles(){return this.run(this.rest.agents.shipped.list())}restoreShippedAgentProfile(e){return this.run(this.rest.agents.shipped.restore(e))}async readHostFile(e,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,t){return this.run(this.rest.skills.previewHostInstall(e,t))}installHostSkill(e,t,n){return this.run(this.rest.skills.installHost(e,t,n))}async previewHostFile(e,t=512001,n){return this.run(this.rest.filesystem.previewHostFile(e,t,{...this.readingOptions(),...n}))}async openHtmlPreview(e,t){return this.run(this.rest.filesystem.openHtmlPreview(e,t))}async closeHtmlPreview(e,t){return this.run(this.rest.filesystem.closeHtmlPreview(e,t))}async openHostMediaPreview(e,t){const n=await this.memoryRequest("POST","/fs:media-preview",{body:e,signal:t?.signal,timeoutMs:15e3});if(typeof n!="object"||n===null)throw new N({code:V.INVALID_RESPONSE,msg:"Media preview could not be opened",data:null});const i=n;if(typeof i.preview_id!="string"||typeof i.url!="string"||typeof i.mime!="string"||typeof i.size!="number"||typeof i.expires_at!="number")throw new N({code:V.INVALID_RESPONSE,msg:"Media preview could not be opened",data:null});return{preview_id:i.preview_id,url:Qh(this.baseUrl,i.url),mime:i.mime,size:i.size,expires_at:i.expires_at}}async closeHostMediaPreview(e){await this.memoryRequest("DELETE",`/fs:media-preview/${encodeURIComponent(e)}`,{timeoutMs:1e4})}cachedPreviewBytes(e,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",v),a.users-=1,a.users===0&&this.previewFlights.get(e)===a&&(this.previewFlights.delete(e),a.controller.abort()),f())},v=()=>{p(()=>{l(n?.reason)})};n?.addEventListener("abort",v,{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=Da(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())}listWorkspaceCatalog(){return this.run(this.rest.workspaces.listCatalog())}getWorkspaceDetails(e){return this.run(this.rest.workspaces.detail(e))}renameWorkspace(e,t){return this.run(this.rest.workspaces.rename(e,t))}setWorkspacePinned(e,t){return this.run(this.rest.workspaces.setPinned(e,t))}renameWorkspaceCatalog(e,t){return this.run(this.rest.workspaces.updateCatalog(e,{name:t}))}setWorkspacePinnedCatalog(e,t){return this.run(this.rest.workspaces.updateCatalog(e,{pinned:t}))}setWorkspaceTrust(e,t){return this.run(this.rest.workspaces.setTrust(e,t))}removeWorkspace(e){return this.run(this.rest.workspaces.remove(e))}getWorkspaceTrust(e){return this.run(this.rest.workspaces.getTrust(e))}trustWorkspace(e){return this.run(this.rest.workspaces.trust(e))}untrustWorkspace(e){return this.run(this.rest.workspaces.untrust(e))}getAuth(){return this.run(this.rest.auth.summary())}listProviders(){return this.run(this.klient.global.kosong.listProviders().then(e=>({items:[...e]})))}listCatalogProviders(){return this.run(()=>this.rest.catalog.list())}importCatalogProvider(e){return this.run(()=>this.rest.catalog.importProvider(e,{timeoutMs:9e4}))}getManagedUsage(e){return this.run(()=>this.rest.oauth.usage(e))}getCatalogProvider(e){return this.run(this.rest.catalog.provider(e))}refreshProvider(e,t){return this.run(this.klient.global.kosong.refreshProviders({providerId:e,apiKey:t}))}async probeProviderDraft(e){const t=n=>{const i=Ca(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 N))throw n;return Ta(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))}listRecipes(){return this.run(this.klient.global.recipes.list())}getRecipe(e){return this.run(this.klient.global.recipes.get(e))}previewRecipe(e){return this.run(this.klient.global.recipes.preview(e))}installRecipe(e){return this.run(this.klient.global.recipes.install(e))}checkRecipeUpdates(){return this.run(this.klient.global.recipes.checkUpdates())}updateRecipe(e){return this.run(this.klient.global.recipes.update(e))}forkRecipe(e){return this.run(this.klient.global.recipes.fork(e))}saveLocalRecipe(e){return this.run(this.klient.global.recipes.saveLocal(e))}removeRecipe(e){return this.run(this.klient.global.recipes.remove(e))}listRecipeMarkets(){return this.run(this.klient.global.recipes.markets.list())}addRecipeMarket(e){return this.run(this.klient.global.recipes.markets.add(e))}updateRecipeMarket(e){return this.run(this.klient.global.recipes.markets.update(e))}removeRecipeMarket(e){return this.run(this.klient.global.recipes.markets.remove(e))}exportRecipe(e){return this.run(this.klient.global.recipes.export(e))}getProviderEntity(e){return this.run(this.klient.global.kosong.readProviderEntity(e))}createProvider(e){return this.run(this.klient.global.kosong.createProvider(e))}updateProvider(e,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`)}removeExecutorRegistration(e){return this.memoryRequest("POST",`/executors/${encodeURIComponent(e)}/registration:remove`,{body:{}})}setBrowserControlEnabled(e){return this.patchConfig({browser_control:{enabled:e}})}setComputerControlEnabled(e){return this.patchConfig({computer_control:{enabled:e}})}getAntigravityBinaries(){return this.memoryRequest("GET","/executors/antigravity-acp/binaries")}installAntigravityBinary(e){return this.memoryRequest("POST","/executors/antigravity-acp/binaries/install",{body:e===void 0?{}:{version:e},timeoutMs:11*6e4})}activateAntigravityBinary(e){return this.memoryRequest("POST","/executors/antigravity-acp/binaries/activate",{body:{version:e}})}startAntigravityLogin(e){return this.memoryRequest("POST","/executors/antigravity-acp/login/start",{body:{method_id:e}})}completeAntigravityLogin(e,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(e){return this.run(this.rest.plugins.panels(e))}getPluginPanelDocument(e,t,n){return this.run(this.rest.plugins.panelDocument(e,t,n))}listPluginCommands(e){return this.run(this.rest.plugins.commands(e))}getPluginUsage(e){return this.run(this.rest.plugins.usage(e))}pluginNavigation(){return this.run(this.rest.plugins.navigation())}setPluginUsage(e){return this.run(this.rest.plugins.setUsage(e))}callPluginPanelBridge(e,t,n){return this.run(this.rest.plugins.panelBridge(e,t,n))}restartMcpServer(e){return this.run(this.rest.runtime.restartMcpServer(e))}listDraftSkills(e){return this.run(this.rest.skills.list(e))}listWorkspaceSkills(e){return this.run(this.rest.workspaces.listSkills(e))}listSessionSkills(e){return this.run(this.rest.sessions.listSkills(e))}rebuildContext(e){return this.run(this.klient.session(e).agent("main").rebuildContext())}activateSkill(e,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[I,w]of Object.entries(l))w!==void 0&&a.searchParams.set(I,w);const m={accept:"application/json"};this.token!==void 0&&(m.authorization=`Bearer ${this.token}`),n.body!==void 0&&(m["content-type"]="application/json");const p=n.timeoutMs===0?void 0:AbortSignal.timeout(n.timeoutMs??3e4),v=n.signal===void 0?p:p===void 0?n.signal:AbortSignal.any([n.signal,p]);let f;try{f=await(this.transport?.fetch??fetch)(a,{method:e,headers:m,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:v})}catch(I){throw I instanceof DOMException&&I.name==="TimeoutError"?new N({code:V.TIMEOUT,msg:So("en","common.requestTimedOut"),data:null}):I}let y;try{y=await f.json()}catch{y=null}if(y===null||typeof y!="object"||!("code"in y)||typeof y.code!="number"||!("msg"in y)||typeof y.msg!="string")throw new N({code:V.INVALID_RESPONSE,msg:`HTTP ${f.status} — non-JSON response`,data:null});if(y.code!==0)throw new N({code:y.code,msg:y.msg,data:"data"in y?y.data??null:null,details:"details"in y?y.details:void 0,request_id:"request_id"in y&&typeof y.request_id=="string"?y.request_id:void 0});return"data"in y?y.data:null}async readDocumentPreviewAsset(e,t){const n=Eh(e),i=this.baseUrl.replace(/\/+$/u,""),a=i===""?new URL(n,globalThis.location?.origin??"http://localhost"):new URL(`${i}${n}`),r={accept:"*/*"};this.token!==void 0&&(r.authorization=`Bearer ${this.token}`);const l=await(this.transport?.fetch??fetch)(a,{headers:r,signal:t});if(!l.ok)throw new N({code:V.INVALID_RESPONSE,msg:`Preview asset could not be read (HTTP ${l.status})`,data:null});return{bytes:new Uint8Array(await l.arrayBuffer()),mime:l.headers.get("content-type")??"application/octet-stream"}}async listWorkPresets(){return wa.parse(await this.memoryRequest("GET","/work-presets"))}async enableWorkPreset(e,t){return St.parse(await this.memoryRequest("POST",`/work-presets/${encodeURIComponent(e)}/enable`,{body:{consent:!0,install_prerequisites:t}}))}async updateWorkPreset(e,t){return St.parse(await this.memoryRequest("PATCH",`/work-presets/${encodeURIComponent(e)}`,{body:t}))}async removeWorkPreset(e){return St.parse(await this.memoryRequest("DELETE",`/work-presets/${encodeURIComponent(e)}`))}async documentPreview(e,t,n){return Ea.parse(await this.memoryRequest("POST",`/sessions/${encodeURIComponent(e)}/document-preview`,{body:t,signal:n,...this.readingOptions()}))}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))}getSessionOptionalCapabilities(e){return this.memoryRequest("GET",`/sessions/${encodeURIComponent(e)}/optional-capabilities`)}setSessionOptionalCapability(e,t){return this.memoryRequest("POST",`/sessions/${encodeURIComponent(e)}/optional-capabilities`,{body:t})}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 Dt(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:Nt(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:Nt(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))}}function Qh(o,e){if(/^https?:\/\//iu.test(e))return e;const t=o.replace(/\/+$/u,""),n=t===""?globalThis.location?.origin??"http://localhost":t;return new URL(e,`${n}/`).toString()}const Yh=40945,Xh=40946;function Nt(o){const e=o.name.toLowerCase();return o.type==="image/png"||e.endsWith(".png")?"png":e.endsWith(".charx")?"charx":"json"}const rg=Object.freeze(Object.defineProperty({__proto__:null,API_CODES:V,ApiError:N,ExternalAgentAttachmentUnsupportedError:$s,KikiClient:Fs,MEMORY_NOT_FOUND:Hh,MEMORY_REVISION_CONFLICT:Wh,MEMORY_TYPES:Vh,NativeChildPromptConflictError:Gs,NativeChildPromptSendError:ot,PERSONA_ALREADY_EXISTS:Yh,PERSONA_REVISION_CONFLICT:Xh,createRemoteSpaceClient:zh,isDefinitivePromptRejection:Kh,isSessionIndexBuildingError:Fh,isSessionNotFoundMessage:Bh,isUnconfirmedTransportError:bh,parseKikiConfigResponse:Dt,personaCardFormatOf:Nt},Symbol.toStringTag,{value:"Module"}));export{N as A,Th as D,$s as E,_o as G,Fs as K,x as M,ot as N,Xh as P,j as R,V as a,tg as b,zh as c,Ih as d,bh as e,ng as f,Io as g,Da as h,Bh as i,Wh as j,og as k,Kh as l,Fh as m,Vh as n,Hh as o,Yh as p,sg as q,$h as r,eg as s,Zh as t,Gh as u,rg as v,ig as w};
|