sliccy 6.256.20 → 6.256.21
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/ui/.vite/manifest.json +180 -180
- package/dist/ui/assets/{account-store-CuQyRnib.js → account-store--QH_gRlz.js} +1 -1
- package/dist/ui/assets/{account-store-CEqw_XTp.js → account-store-CbKQrU_A.js} +1 -1
- package/dist/ui/assets/{adobe-DLwRzZCw.js → adobe-BBZZjXPq.js} +1 -1
- package/dist/ui/assets/{adobe-B4Y2A2AD.js → adobe-D6tf-vd0.js} +1 -1
- package/dist/ui/assets/{agent-panels-DrtCqAV-.js → agent-panels-DwoeuEZJ.js} +1 -1
- package/dist/ui/assets/{almost-bash-shell-headless-pwdOe3YW.js → almost-bash-shell-headless-IexVAylq.js} +11 -11
- package/dist/ui/assets/{apply-layout-CH3UhXCP.js → apply-layout-DyJWDEg0.js} +1 -1
- package/dist/ui/assets/{azure-openai-CxZFHgjG.js → azure-openai-DfNYV355.js} +1 -1
- package/dist/ui/assets/{azure-openai-5qDnHBYT.js → azure-openai-mzyA6ec_.js} +1 -1
- package/dist/ui/assets/{cdp-C8HHv5qA.js → cdp-D4hCZeiK.js} +3 -3
- package/dist/ui/assets/{cerebras-Czbq-0qg.js → cerebras-DCpB0UlY.js} +1 -1
- package/dist/ui/assets/{cerebras-B1cY7cfF.js → cerebras-nIWXceol.js} +1 -1
- package/dist/ui/assets/{composer-speech-DeLPAAnL.js → composer-speech-tLlsFK5D.js} +1 -1
- package/dist/ui/assets/{connect-surface-Du9dcsgG.js → connect-surface-XwtqAfeO.js} +1 -1
- package/dist/ui/assets/{directed-approval-Ch4rtrAp.js → directed-approval-BHC1QE2R.js} +1 -1
- package/dist/ui/assets/{emscripten-vfs-hook-BYpqS-pK.js → emscripten-vfs-hook-D27gwwXv.js} +1 -1
- package/dist/ui/assets/{frozen-archive-writer-CXRaBKpe.js → frozen-archive-writer-Cixi7_NJ.js} +1 -1
- package/dist/ui/assets/{frozen-session-delete-Cd8Hp2Od.js → frozen-session-delete-2eh2Yhbl.js} +1 -1
- package/dist/ui/assets/{frozen-session-identity-XzcVW8UL.js → frozen-session-identity-DoWKIEpR.js} +1 -1
- package/dist/ui/assets/{gelatiere-unit-BIIKTgS2.js → gelatiere-unit-BqTcFkxk.js} +1 -1
- package/dist/ui/assets/{github-DOfti7_n.js → github-BhZHOxKc.js} +1 -1
- package/dist/ui/assets/{github-D0xw3eYJ.js → github-DN2OBZNS.js} +1 -1
- package/dist/ui/assets/{github-copilot-BVDlkmAY.js → github-copilot-CQhrDhDZ.js} +1 -1
- package/dist/ui/assets/{github-copilot-C1c9Cctf.js → github-copilot-Dgi-j2_O.js} +1 -1
- package/dist/ui/assets/{hear-Bf5HwOni.js → hear-BDUAwa28.js} +1 -1
- package/dist/ui/assets/{hidden-page-input-DDEF33JC.js → hidden-page-input-01CnfmMB.js} +1 -1
- package/dist/ui/assets/{hidden-page-input-A06qdSVm.js → hidden-page-input-CBbLsDx2.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-CemAn96I.js → js-realm-worker-CDJhvYJx.js} +2 -2
- package/dist/ui/assets/{jsh-executor-DGOAl5iJ.js → jsh-executor-BVFFU-rP.js} +3 -3
- package/dist/ui/assets/{kernel-worker-DQZWnLpe.js → kernel-worker-965_891X.js} +9 -9
- package/dist/ui/assets/{lick-ws-bridge-B-61k0Zh.js → lick-ws-bridge-D4PsA45A.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-DbJ8yf-k.js → lick-ws-bridge-DuAP_Xb5.js} +1 -1
- package/dist/ui/assets/{live-session-curation-zfkDVdK3.js → live-session-curation-BB61f9E8.js} +1 -1
- package/dist/ui/assets/{live-session-curation-CLbx1I_X.js → live-session-curation-CGxamyw3.js} +1 -1
- package/dist/ui/assets/{live-session-snapshot-3Eb9FMGE.js → live-session-snapshot-BDyBgtvN.js} +1 -1
- package/dist/ui/assets/{local-llm-D2S0cCYP.js → local-llm-CEQQXhGE.js} +1 -1
- package/dist/ui/assets/{local-llm-RFZ66ynj.js → local-llm-Cy5E3lJo.js} +1 -1
- package/dist/ui/assets/{main-CN0eXvpe.js → main-C8hdX5_E.js} +3 -3
- package/dist/ui/assets/{main-cherry-CsLIn0Jy.js → main-cherry-ykXNeN9-.js} +1 -1
- package/dist/ui/assets/{mcp-command-Co4BM7rI.js → mcp-command-w6OUcgfO.js} +10 -10
- package/dist/ui/assets/{memory-curation-seam-DitfDTyZ.js → memory-curation-seam-C4r6A-jq.js} +1 -1
- package/dist/ui/assets/{memory-write-execute-DnPv8AaN.js → memory-write-execute-C_0rryC9.js} +1 -1
- package/dist/ui/assets/{merge-folded-cost-into-frozen-C24isZFN.js → merge-folded-cost-into-frozen-C9I1ykhe.js} +1 -1
- package/dist/ui/assets/{new-session-Bz-zsmnA.js → new-session-k7LcBmG5.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-CowVQxka.js → oauth-bootstrap-qTw880dW.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-BW5xLMjU.js → onboarding-orchestrator-B5XUC4QP.js} +1 -1
- package/dist/ui/assets/{openai-codex-D-mRHUJ_.js → openai-codex-BpfRFQ9A.js} +1 -1
- package/dist/ui/assets/{openai-codex-BIUq5T-M.js → openai-codex-BtEdGRUK.js} +1 -1
- package/dist/ui/assets/{openrouter-B8wWwNw8.js → openrouter-CGkUkGLm.js} +1 -1
- package/dist/ui/assets/{openrouter-euDNOeLU.js → openrouter-D9PB_Wxr.js} +1 -1
- package/dist/ui/assets/{openrouter-free-CxpCaBRA.js → openrouter-free-BfihlWk1.js} +1 -1
- package/dist/ui/assets/{openrouter-free-DF0yibHR.js → openrouter-free-Brc9YCWo.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BfiowYVD.js → openrouter-oauth-DIBlm_UZ.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-cciCymss.js → openrouter-oauth-DdrrVt3S.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-B3eqfWJ0.js → panel-rpc-handlers-BmON86n5.js} +2 -2
- package/dist/ui/assets/{panelize-shell-BfSgnfgs.js → panelize-shell-Dt3FXNpB.js} +1 -1
- package/dist/ui/assets/{pi-edit-execution-ji-kHMKJ.js → pi-edit-execution-iaL4Mz3u.js} +1 -1
- package/dist/ui/assets/{provider-BKtPDkWZ.js → provider-B8I1Mys2.js} +1 -1
- package/dist/ui/assets/{provider-CSI-1cw8.js → provider-CN-5jpvI.js} +1 -1
- package/dist/ui/assets/{provider-settings-CjUgLZVJ.js → provider-settings-B5CKyKdE.js} +1 -1
- package/dist/ui/assets/provider-store-access-D3cir6Mf.js +1 -0
- package/dist/ui/assets/provider-store-access-DruVrLP2.js +1 -0
- package/dist/ui/assets/{providers-BME8SM7Y.js → providers-CnawElFK.js} +1 -1
- package/dist/ui/assets/{providers-DUsi8UJy.js → providers-s2pRjrQo.js} +2 -2
- package/dist/ui/assets/{quick-llm-BgX8DGOf.js → quick-llm-DcceQmkj.js} +1 -1
- package/dist/ui/assets/{realm-inprocess-B-o6MXXm.js → realm-inprocess-48bEemKF.js} +2 -2
- package/dist/ui/assets/{realm-unhandled-rejections--yOMYML4.js → realm-unhandled-rejections-BqWjiqaB.js} +1 -1
- package/dist/ui/assets/{realm-unhandled-rejections-B_sD1Eqh.js → realm-unhandled-rejections-DpKKv_Sg.js} +1 -1
- package/dist/ui/assets/{remote-terminal-view-D95a_lGP.js → remote-terminal-view-ML6zl31u.js} +2 -2
- package/dist/ui/assets/{restore-BUvJhiTF.js → restore-Uo3FkyTn.js} +1 -1
- package/dist/ui/assets/{run-BwR10Tfc.js → run-7BBLWyxm.js} +2 -2
- package/dist/ui/assets/{run-DX49FiKl.js → run-BZUVJe9B.js} +2 -2
- package/dist/ui/assets/{run-b9uA0T1r.js → run-tb90H7t4.js} +1 -1
- package/dist/ui/assets/{serve-command-B5HZS1FV.js → serve-command-C1oMKVa-.js} +2 -2
- package/dist/ui/assets/{serve-runtime-CqUYUISo.js → serve-runtime-BMkuNcbl.js} +1 -1
- package/dist/ui/assets/{session-command-memory-c8nM2oAl.js → session-command-memory-lm81X-Is.js} +2 -2
- package/dist/ui/assets/{session-jsonl-BwJt_n1u.js → session-jsonl-eXAElh6W.js} +1 -1
- package/dist/ui/assets/{session-search-index-DumLK4vT.js → session-search-index-ByisDLR5.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-CIolNdqX.js → setup-feature-flags-remote-z293EM8V.js} +1 -1
- package/dist/ui/assets/{setup-model-catalog-D5oj1TnB.js → setup-model-catalog-DFfU37vS.js} +1 -1
- package/dist/ui/assets/{silent-renew-backoff-BwsIHdH7.js → silent-renew-backoff-B0lMVNh5.js} +1 -1
- package/dist/ui/assets/slicc-version-DGCQeyP5.js +1 -0
- package/dist/ui/assets/{soundscape-gX8pyQsR.js → soundscape-DHszzPsM.js} +1 -1
- package/dist/ui/assets/{speak-DUmL0M9L.js → speak-DZZSpSqs.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-el_STA97.js → sprinkle-manager-CMAEGvh9.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-C9fr3WHR.js → sprinkle-renderer-DcsYmznT.js} +1 -1
- package/dist/ui/assets/{sudo-ZExTT5ER.js → sudo-YyLShRTX.js} +1 -1
- package/dist/ui/assets/{supervisor-CuK_w37s.js → supervisor-BJNQ0Sie.js} +1 -1
- package/dist/ui/assets/{sync-dialog-Y1I8wtI7.js → sync-dialog-OIBe84rb.js} +1 -1
- package/dist/ui/assets/{transformers-env-CFMmsFPt.js → transformers-env-DlTQEcvy.js} +1 -1
- package/dist/ui/assets/{tray-leader-WA8nmGPu.js → tray-leader-x0HDgpHa.js} +1 -1
- package/dist/ui/assets/{tray-leave-runtime-Dnbn_g0R.js → tray-leave-runtime-B6ZqjKqA.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-D5lGknCp.js → tray-sidecar-C08eb6rV.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-B_0cdTwX.js → upgrade-detection-BZOEx1T3.js} +1 -1
- package/dist/ui/assets/{upgrade-to-seven-YOHOuBIz.js → upgrade-to-seven-Pi7N3s4V.js} +1 -1
- package/dist/ui/assets/{voice-reply-Du8td5dw.js → voice-reply-D0KspY5L.js} +1 -1
- package/dist/ui/assets/{wc-attach-BQmRGrD1.js → wc-attach-C--w91hS.js} +2 -2
- package/dist/ui/assets/{wc-browser-mLBbjD7x.js → wc-browser-Bwwt12VY.js} +1 -1
- package/dist/ui/assets/{wc-computers-D4cVXfw8.js → wc-computers-CEYTEbzK.js} +1 -1
- package/dist/ui/assets/{wc-detached-DJvs-BOI.js → wc-detached-BMfwyvTN.js} +1 -1
- package/dist/ui/assets/{wc-extension-C8pEK7qU.js → wc-extension-WVBzb68j.js} +2 -2
- package/dist/ui/assets/{wc-follower-DH7hCy3x.js → wc-follower-CfQXvNqW.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-DKRGLBWN.js → wc-follower-oauth-CRA3bG2x.js} +1 -1
- package/dist/ui/assets/{wc-gelatiere-CJpfn7Ca.js → wc-gelatiere-CFupkA18.js} +1 -1
- package/dist/ui/assets/{wc-live-mNieNNOh.js → wc-live-jfkgv1D5.js} +5 -5
- package/dist/ui/assets/{wc-nav-mcV-muIN.js → wc-nav-CMmiK8CR.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-DhNdAmF2.js → wc-onboarding-DwK2Xo_f.js} +2 -2
- package/dist/ui/assets/{wc-permissions-DfXcDHFY.js → wc-permissions-sEzYJY5L.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-BO7LIBQk.js → wc-placeholder-dACLWYRH.js} +2 -2
- package/dist/ui/assets/{wc-profile-export-K9m6pZBL.js → wc-profile-export-0_MWQlQi.js} +3 -3
- package/dist/ui/assets/{wc-secret-request-DFNuYRtA.js → wc-secret-request-Bj6AEfhW.js} +1 -1
- package/dist/ui/assets/{wc-settings-KPmFCSeh.js → wc-settings-D36d5og0.js} +3 -3
- package/dist/ui/assets/{wc-shell-DUnQ3yem.js → wc-shell-Dviry0M3.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-_FC-kTdg.js → wc-shortcut-config-BEJ7hCGM.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-CGU4-WKU.js → wc-sprinkles-CCEvPCsZ.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-BXCZhTfg.js → wc-transcript-export-BLZIE8ep.js} +2 -2
- package/dist/ui/assets/{wc-tray-B4fcMI28.js → wc-tray-Bpsl7Mew.js} +4 -4
- package/dist/ui/assets/welcome-detection-CWqP_ofb.js +1 -0
- package/dist/ui/assets/{whisper-session-B4xkoupa.js → whisper-session-CmQR_O2N.js} +2 -2
- package/dist/ui/assets/{xai-grok-BJ0tBHY1.js → xai-grok-BjEcnSUJ.js} +1 -1
- package/dist/ui/assets/{xai-grok-DA654XhD.js → xai-grok-DNyRhPcB.js} +1 -1
- package/dist/ui/index.html +3 -3
- package/dist/ui/packages/webapp/index.html +3 -3
- package/dist/ui/packages/webapp/upgrade-to-seven.html +1 -1
- package/dist/ui/upgrade-to-seven.html +1 -1
- package/package.json +2 -2
- package/dist/ui/assets/provider-store-access-B8DHQMsm.js +0 -1
- package/dist/ui/assets/provider-store-access-DR6dk4La.js +0 -1
- package/dist/ui/assets/slicc-version-DtrTeMyR.js +0 -1
- package/dist/ui/assets/welcome-detection-JV0kEwvY.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-DBVvNlSN.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,o as d,p as f,r as p,t as m,u as ee,v as te,y as ne}from"./almost-bash-shell-headless-pwdOe3YW.js";import{t as h}from"./logger-Cx6Y120U.js";import{r as re,t as ie}from"./base64-BPBW1Gzr.js";import{i as ae,r as oe}from"./handoff-link-B3It6xQY.js";import{C as se,a as ce,b as le,f as ue,g as de,h as fe,i as pe,m as me,p as he,v as ge,x as _e,y as ve}from"./account-store-CuQyRnib.js";import{n as ye}from"./proxied-fetch-1DfC_94U.js";import{t as be}from"./sha256-DynDhwRL.js";import{t as xe}from"./slugify-BYJ6QVAt.js";import{i as Se,n as Ce,t as we}from"./archive-redaction-Bi6veJCs.js";import{a as Te,o as Ee}from"./host-command-CkJyrXy3.js";import{h as De}from"./snapshot-Cb8PXNj1.js";import{t as Oe}from"./panel-rpc-accessor-B4BfPLSo.js";import{n as ke}from"./panel-rpc-BJU93e51.js";import{i as Ae,l as je,o as Me,r as Ne}from"./feature-flags-CoR3q8DD.js";import{a as Pe,t as Fe}from"./providers-BME8SM7Y.js";import{c as Ie,d as Le,o as Re,s as ze,t as Be,u as Ve}from"./api-endpoint-D8lUKmPu.js";import{_ as He,a as Ue,c as We,l as Ge,m as Ke,p as qe,s as Je,u as Ye}from"./models-7tbZ9MB5.js";import{o as Xe,t as Ze}from"./compat-CuWVDYYO.js";import{i as Qe,n as $e,r as et,t as tt}from"./context-compaction-BvTawIjc.js";import{t as nt}from"./utf16-clip-Dcxt-q1C.js";import{r as rt,t as it}from"./core-TaEErdII.js";import{n as at}from"./float-topology-87nCRxRw.js";import{t as ot}from"./secrets-bridge-client-DlJPW3h4.js";import{n as st,t as ct}from"./image-markers-B82WnSyf.js";import{i as lt}from"./tool-ui-blvQ8qgI.js";import{l as ut,t as dt}from"./claude-model-version-BlyDyuTC.js";import{a as ft,n as pt,t as mt}from"./path-utils-DNJG-zQf.js";import{t as ht}from"./merge-file-core-YFxa1Gy8.js";import{i as gt,n as _t,r as vt,t as yt}from"./workspace-mode-CIL8WpBe.js";import{C as bt,D as xt,E as St,O as Ct,S as wt,T as Tt,_ as Et,a as Dt,c as Ot,d as kt,f as At,g as jt,h as Mt,l as Nt,m as Pt,n as Ft,o as It,p as Lt,r as Rt,s as zt,t as Bt,u as Vt,v as Ht,w as Ut,y as Wt}from"./record-DTUQtot0.js";import{a as Gt,c as Kt,d as qt,i as Jt,l as Yt,n as Xt,o as Zt,r as Qt,s as $t,u as en}from"./descriptor-3sZ9zo81.js";import{o as tn,p as nn,t as rn}from"./frozen-archive-format-7wcOWvsT.js";import{n as an,t as on}from"./thinking-level-5x0UAu9N.js";import{t as g}from"./types-D8gIX-W-.js";import{i as sn,n as cn}from"./mount-index-LvDi_MEB.js";import{a as ln,i as un,n as dn,r as fn,s as pn,t as mn}from"./signed-fetch-DcYblAfC.js";import{n as hn}from"./mount-table-store-xM3U8UHg.js";import{t as gn}from"./remote-cache-MMXYpOmA.js";import"./mount-CYYBDAvT.js";import{i as _n,n as vn,r as yn}from"./fs-BhKa6zpE.js";import{i as bn,n as xn,t as Sn}from"./key-D3gIEgUz.js";import{n as Cn,r as wn,t as Tn}from"./tray-leader-status-BPM2zVsj.js";import"./tray-runtime-config-BvQtvIxB.js";import{r as En}from"./slicc-version-DtrTeMyR.js";import{r as Dn}from"./virtual-device-paths-C4gV0QwB.js";import{a as On}from"./gelatiere-constants-BYJlhm8R.js";import{a as kn,i as An,r as jn}from"./cost-command-CG3mKA1r.js";import{_ as Mn,a as Nn,c as Pn,d as Fn,f as In,g as Ln,h as Rn,l as zn,m as Bn,n as Vn,p as Hn,r as Un,s as Wn,t as Gn,u as Kn,v as qn}from"./sudoers-2C-BpgXh.js";import{n as Jn,r as Yn,t as Xn}from"./sudo-fs-Ou8-0Q4u.js";import{t as Zn}from"./llm-session-id-BkEQhxBR.js";import{t as Qn}from"./src-SFACrjnb.js";import{a as $n,i as er,n as tr,o as nr,s as rr}from"./memory-budget-CFfevxz_.js";import{i as ir,n as ar,r as or,t as sr}from"./frontmatter-DRCezvro.js";import{i as cr}from"./browser-DKcnER7J.js";import{c as lr,r as ur,s as dr}from"./pipe-status-BBrT3VeG.js";import{n as fr}from"./just-bash-compat-DWUHpp9U.js";import{t as pr}from"./jsh-discovery-D7D5iKYT.js";import{t as mr}from"./process-manager-Dy17Kify.js";import{a as hr,i as gr,s as _r,t as vr}from"./jsh-executor-DGOAl5iJ.js";import{C as yr,_ as br,b as xr,f as Sr,h as Cr,l as wr,n as Tr,r as Er,x as Dr}from"./sync-exec-dispatch-Cy_hRFJu.js";import{t as Or}from"./lick-target-env-8JxfVcIV.js";const kr=[`/workspace`,`/shared`,`/scoops`,`/home`];var Ar=class{pending=/* @__PURE__ */ new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function jr(e,t,n,r){return new Promise((i,a)=>{if(r?.signal?.aborted){a(r.error());return}let o=null,s=!1,c,l=()=>{s=!0,clearTimeout(u),c&&r?.signal?.removeEventListener(`abort`,c),o?.()},u=setTimeout(()=>{l(),a(Error(n))},t);r?.signal&&(c=()=>{l(),a(r.error())},r.signal.addEventListener(`abort`,c,{once:!0})),o=e(e=>{l(),i(e)}),s&&o()})}const Mr=h(`cdp`);function Nr(e){return e===4001?`CDP connection superseded by another SLICC tab/window on this instance`:e===4002?`CDP connection reset by proxy (upstream Chrome connection was re-established)`:`CDP connection closed`}var Pr=class{ws=null;nextId=1;_superseded=!1;pending=new Ar;listeners=/* @__PURE__ */ new Map;_state=`disconnected`;stateListeners=/* @__PURE__ */ new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(/* @__PURE__ */ Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,Mr.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Mr.error(`Connection failed`,{url:t}),this.cleanup(),i(/* @__PURE__ */ Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),Mr.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};t&&(a.params=t),n&&(a.sessionId=n),Mr.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}on(e,t){let n=this.listeners.get(e);n||(n=/* @__PURE__ */ new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return jr(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Mr.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Mr.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,/* @__PURE__ */ Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;Mr.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){e===4001?(this._superseded=!0,Mr.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Mr.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Mr.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Nr(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}};function Fr({attempt:e,baseMs:t,capMs:n,jitter:r=0,maxShift:i,random:a=Math.random}){let o=Math.max(0,e);i!==void 0&&(o=Math.min(o,i));let s=t*2**o,c=n===void 0?s:Math.min(n,s);if(r<=0)return c;let l=c+Math.round(c*r*a());return n===void 0?l:Math.min(n,l)}function Ir(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Lr(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Rr=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function zr(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Rr.map(e=>Br(i,e,t,r)))).filter(e=>e!==null)}async function Br(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(/* @__PURE__ */ Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal,redirect:`manual`,credentials:`omit`});return e.status!==200||!Vr(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Vr(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}var Hr=class extends Error{constructor(e=`CDP bridge rejected the session token (bridge-token-required). Open SLICC again from Sliccstart to pick up a fresh token.`){super(e),this.name=`CdpBridgeRejectedError`}},Ur=class extends Error{constructor(){super(`CDP reconnect is backing off`),this.name=`CdpReconnectBackoffError`}};function Wr(e,t=Math.random){return Fr({attempt:e,baseMs:250,capMs:3e4,jitter:.2,maxShift:16,random:t})}function Gr(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var Kr=class{lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;reconnectAttempt=0;reconnectNotBefore=0;bridgeRejection=null;bridgeRejectedHandler=null;bridgeRejectedNotified=!1;classifyConnectFailure=async()=>`transient`;primeConnectOptions(e){this.lastConnectOptions=e?{...e}:{}}setSupersededHandler(e){this.supersededHandler=e}setBridgeRejectedHandler(e){this.bridgeRejectedHandler=e}setConnectFailureClassifier(e){this.classifyConnectFailure=e}async connect(e,t){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new Hr(this.bridgeRejection);this.lastConnectOptions=t?{...t}:{};try{await e.connect({url:t?.url??Gr(),timeout:t?.timeout,...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t),this.bridgeRejection?new Hr(this.bridgeRejection):e}this.noteReconnectSuccess()}async ensureLocalConnected(e){if(e.superseded===!0){this.notifySuperseded();return}if(e.state===`disconnected`){this.throwIfReconnectPaused();let t=this.lastConnectOptions;try{await e.connect({url:t?.url??Gr(),...t?.timeout===void 0?{}:{timeout:t.timeout},...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t??void 0),this.bridgeRejection?new Hr(this.bridgeRejection):e}this.noteReconnectSuccess()}}async ensureConnected(e){if(e.client.superseded===!0){this.notifySuperseded();return}if(e.client.state===`disconnected`){this.throwIfReconnectPaused();let t=e.client;e.restoreLocalAfterRemoteDrop(),e.clearSessionsForTransport(t),e.getClient().state===`disconnected`&&await this.connect(e.getClient(),this.lastConnectOptions??void 0)}}throwIfReconnectPaused(){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new Hr(this.bridgeRejection);if(Date.now()<this.reconnectNotBefore)throw new Ur}noteReconnectSuccess(){this.reconnectAttempt=0,this.reconnectNotBefore=0,this.supersededNotified=!1}async noteReconnectFailure(e){if(await this.classifyConnectFailure({url:e?.url??``,...e?.protocols===void 0?{}:{protocols:e.protocols}})===`terminal`){this.bridgeRejection=new Hr().message,this.notifyBridgeRejected();return}let t=Wr(this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectNotBefore=Date.now()+t}notifyBridgeRejected(){if(!this.bridgeRejectedNotified){this.bridgeRejectedNotified=!0;try{this.bridgeRejectedHandler?.()}catch{}}}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}},qr=class extends Error{step;name=`CommandAbortedError`;constructor(e){super(`Browser command aborted while ${e}. A CDP round trip already in flight cannot be cancelled, so it may still have been applied to the page; nothing after it was started.`),this.step=e}};function Jr(e,t){if(e?.aborted)throw new qr(t)}function Yr(e,t){return e?{signal:e,error:()=>new qr(t)}:void 0}function Xr(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new qr(n));return}let a=()=>{clearTimeout(o),i(new qr(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Zr(e,t,n){return t?t.aborted?Promise.reject(new qr(n)):new Promise((r,i)=>{let a=()=>i(new qr(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var Qr=class{contexts=/* @__PURE__ */ new Map;for(e,t){let n=`${t}:${e}`,r=this.contexts.get(n);return r||(r=/* @__PURE__ */ new Map,this.contexts.set(n,r)),r}peek(e,t){return this.contexts.get(`${t}:${e}`)}drop(e){this.contexts.delete(`main:${e}`),this.contexts.delete(`isolated:${e}`)}get size(){return this.contexts.size}};const $r=h(`har-recorder`);var ei=class{recordings=/* @__PURE__ */ new Map;client;fs;eventCleanup=/* @__PURE__ */ new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Jr(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Jr(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Jr(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:/* @__PURE__ */ new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),$r.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{$r.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{$r.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;n&&r&&i!=null&&e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return ti(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return $r.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return $r.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),$r.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return $r.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function ti(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){$r.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return $r.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var ni=class extends Error{name=`HiddenPageWheelError`;constructor(){super(`The tab is hidden (or could not be checked) and focus emulation is not available, so Chrome would not answer a wheel event`)}};function ri(e,t){return e===`Input.dispatchMouseEvent`?t?.type===`mouseMoved`?`move`:t?.type===`mouseWheel`?`wheel`:null:null}function ii(e,t,n,r){return`(() => {
|
|
1
|
+
import{n as e}from"./rolldown-runtime-DBVvNlSN.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,o as d,p as f,r as p,t as m,u as ee,v as te,y as ne}from"./almost-bash-shell-headless-IexVAylq.js";import{t as h}from"./logger-Cx6Y120U.js";import{r as re,t as ie}from"./base64-BPBW1Gzr.js";import{i as ae,r as oe}from"./handoff-link-B3It6xQY.js";import{C as se,a as ce,b as le,f as ue,g as de,h as fe,i as pe,m as me,p as he,v as ge,x as _e,y as ve}from"./account-store--QH_gRlz.js";import{n as ye}from"./proxied-fetch-1DfC_94U.js";import{t as be}from"./sha256-DynDhwRL.js";import{t as xe}from"./slugify-BYJ6QVAt.js";import{i as Se,n as Ce,t as we}from"./archive-redaction-Bi6veJCs.js";import{a as Te,o as Ee}from"./host-command-CkJyrXy3.js";import{h as De}from"./snapshot-Cb8PXNj1.js";import{t as Oe}from"./panel-rpc-accessor-B4BfPLSo.js";import{n as ke}from"./panel-rpc-BJU93e51.js";import{i as Ae,l as je,o as Me,r as Ne}from"./feature-flags-CoR3q8DD.js";import{a as Pe,t as Fe}from"./providers-CnawElFK.js";import{c as Ie,d as Le,o as Re,s as ze,t as Be,u as Ve}from"./api-endpoint-D8lUKmPu.js";import{_ as He,a as Ue,c as We,l as Ge,m as Ke,p as qe,s as Je,u as Ye}from"./models-7tbZ9MB5.js";import{o as Xe,t as Ze}from"./compat-CuWVDYYO.js";import{i as Qe,n as $e,r as et,t as tt}from"./context-compaction-BvTawIjc.js";import{t as nt}from"./utf16-clip-Dcxt-q1C.js";import{r as rt,t as it}from"./core-TaEErdII.js";import{n as at}from"./float-topology-87nCRxRw.js";import{t as ot}from"./secrets-bridge-client-DlJPW3h4.js";import{n as st,t as ct}from"./image-markers-B82WnSyf.js";import{i as lt}from"./tool-ui-blvQ8qgI.js";import{l as ut,t as dt}from"./claude-model-version-BlyDyuTC.js";import{a as ft,n as pt,t as mt}from"./path-utils-DNJG-zQf.js";import{t as ht}from"./merge-file-core-YFxa1Gy8.js";import{i as gt,n as _t,r as vt,t as yt}from"./workspace-mode-CIL8WpBe.js";import{C as bt,D as xt,E as St,O as Ct,S as wt,T as Tt,_ as Et,a as Dt,c as Ot,d as kt,f as At,g as jt,h as Mt,l as Nt,m as Pt,n as Ft,o as It,p as Lt,r as Rt,s as zt,t as Bt,u as Vt,v as Ht,w as Ut,y as Wt}from"./record-DTUQtot0.js";import{a as Gt,c as Kt,d as qt,i as Jt,l as Yt,n as Xt,o as Zt,r as Qt,s as $t,u as en}from"./descriptor-3sZ9zo81.js";import{o as tn,p as nn,t as rn}from"./frozen-archive-format-7wcOWvsT.js";import{n as an,t as on}from"./thinking-level-5x0UAu9N.js";import{t as g}from"./types-D8gIX-W-.js";import{i as sn,n as cn}from"./mount-index-LvDi_MEB.js";import{a as ln,i as un,n as dn,r as fn,s as pn,t as mn}from"./signed-fetch-DcYblAfC.js";import{n as hn}from"./mount-table-store-xM3U8UHg.js";import{t as gn}from"./remote-cache-MMXYpOmA.js";import"./mount-CYYBDAvT.js";import{i as _n,n as vn,r as yn}from"./fs-BhKa6zpE.js";import{i as bn,n as xn,t as Sn}from"./key-D3gIEgUz.js";import{n as Cn,r as wn,t as Tn}from"./tray-leader-status-BPM2zVsj.js";import"./tray-runtime-config-BvQtvIxB.js";import{r as En}from"./slicc-version-DGCQeyP5.js";import{r as Dn}from"./virtual-device-paths-C4gV0QwB.js";import{a as On}from"./gelatiere-constants-BYJlhm8R.js";import{a as kn,i as An,r as jn}from"./cost-command-CG3mKA1r.js";import{_ as Mn,a as Nn,c as Pn,d as Fn,f as In,g as Ln,h as Rn,l as zn,m as Bn,n as Vn,p as Hn,r as Un,s as Wn,t as Gn,u as Kn,v as qn}from"./sudoers-2C-BpgXh.js";import{n as Jn,r as Yn,t as Xn}from"./sudo-fs-Ou8-0Q4u.js";import{t as Zn}from"./llm-session-id-BkEQhxBR.js";import{t as Qn}from"./src-SFACrjnb.js";import{a as $n,i as er,n as tr,o as nr,s as rr}from"./memory-budget-CFfevxz_.js";import{i as ir,n as ar,r as or,t as sr}from"./frontmatter-DRCezvro.js";import{i as cr}from"./browser-DKcnER7J.js";import{c as lr,r as ur,s as dr}from"./pipe-status-BBrT3VeG.js";import{n as fr}from"./just-bash-compat-DWUHpp9U.js";import{t as pr}from"./jsh-discovery-D7D5iKYT.js";import{t as mr}from"./process-manager-Dy17Kify.js";import{a as hr,i as gr,s as _r,t as vr}from"./jsh-executor-BVFFU-rP.js";import{C as yr,_ as br,b as xr,f as Sr,h as Cr,l as wr,n as Tr,r as Er,x as Dr}from"./sync-exec-dispatch-Cy_hRFJu.js";import{t as Or}from"./lick-target-env-8JxfVcIV.js";const kr=[`/workspace`,`/shared`,`/scoops`,`/home`];var Ar=class{pending=/* @__PURE__ */ new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function jr(e,t,n,r){return new Promise((i,a)=>{if(r?.signal?.aborted){a(r.error());return}let o=null,s=!1,c,l=()=>{s=!0,clearTimeout(u),c&&r?.signal?.removeEventListener(`abort`,c),o?.()},u=setTimeout(()=>{l(),a(Error(n))},t);r?.signal&&(c=()=>{l(),a(r.error())},r.signal.addEventListener(`abort`,c,{once:!0})),o=e(e=>{l(),i(e)}),s&&o()})}const Mr=h(`cdp`);function Nr(e){return e===4001?`CDP connection superseded by another SLICC tab/window on this instance`:e===4002?`CDP connection reset by proxy (upstream Chrome connection was re-established)`:`CDP connection closed`}var Pr=class{ws=null;nextId=1;_superseded=!1;pending=new Ar;listeners=/* @__PURE__ */ new Map;_state=`disconnected`;stateListeners=/* @__PURE__ */ new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(/* @__PURE__ */ Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,Mr.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Mr.error(`Connection failed`,{url:t}),this.cleanup(),i(/* @__PURE__ */ Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),Mr.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};t&&(a.params=t),n&&(a.sessionId=n),Mr.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}on(e,t){let n=this.listeners.get(e);n||(n=/* @__PURE__ */ new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return jr(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Mr.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Mr.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,/* @__PURE__ */ Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;Mr.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){e===4001?(this._superseded=!0,Mr.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Mr.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Mr.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Nr(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}};function Fr({attempt:e,baseMs:t,capMs:n,jitter:r=0,maxShift:i,random:a=Math.random}){let o=Math.max(0,e);i!==void 0&&(o=Math.min(o,i));let s=t*2**o,c=n===void 0?s:Math.min(n,s);if(r<=0)return c;let l=c+Math.round(c*r*a());return n===void 0?l:Math.min(n,l)}function Ir(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Lr(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Rr=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function zr(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Rr.map(e=>Br(i,e,t,r)))).filter(e=>e!==null)}async function Br(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(/* @__PURE__ */ Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal,redirect:`manual`,credentials:`omit`});return e.status!==200||!Vr(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Vr(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}var Hr=class extends Error{constructor(e=`CDP bridge rejected the session token (bridge-token-required). Open SLICC again from Sliccstart to pick up a fresh token.`){super(e),this.name=`CdpBridgeRejectedError`}},Ur=class extends Error{constructor(){super(`CDP reconnect is backing off`),this.name=`CdpReconnectBackoffError`}};function Wr(e,t=Math.random){return Fr({attempt:e,baseMs:250,capMs:3e4,jitter:.2,maxShift:16,random:t})}function Gr(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var Kr=class{lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;reconnectAttempt=0;reconnectNotBefore=0;bridgeRejection=null;bridgeRejectedHandler=null;bridgeRejectedNotified=!1;classifyConnectFailure=async()=>`transient`;primeConnectOptions(e){this.lastConnectOptions=e?{...e}:{}}setSupersededHandler(e){this.supersededHandler=e}setBridgeRejectedHandler(e){this.bridgeRejectedHandler=e}setConnectFailureClassifier(e){this.classifyConnectFailure=e}async connect(e,t){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new Hr(this.bridgeRejection);this.lastConnectOptions=t?{...t}:{};try{await e.connect({url:t?.url??Gr(),timeout:t?.timeout,...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t),this.bridgeRejection?new Hr(this.bridgeRejection):e}this.noteReconnectSuccess()}async ensureLocalConnected(e){if(e.superseded===!0){this.notifySuperseded();return}if(e.state===`disconnected`){this.throwIfReconnectPaused();let t=this.lastConnectOptions;try{await e.connect({url:t?.url??Gr(),...t?.timeout===void 0?{}:{timeout:t.timeout},...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t??void 0),this.bridgeRejection?new Hr(this.bridgeRejection):e}this.noteReconnectSuccess()}}async ensureConnected(e){if(e.client.superseded===!0){this.notifySuperseded();return}if(e.client.state===`disconnected`){this.throwIfReconnectPaused();let t=e.client;e.restoreLocalAfterRemoteDrop(),e.clearSessionsForTransport(t),e.getClient().state===`disconnected`&&await this.connect(e.getClient(),this.lastConnectOptions??void 0)}}throwIfReconnectPaused(){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new Hr(this.bridgeRejection);if(Date.now()<this.reconnectNotBefore)throw new Ur}noteReconnectSuccess(){this.reconnectAttempt=0,this.reconnectNotBefore=0,this.supersededNotified=!1}async noteReconnectFailure(e){if(await this.classifyConnectFailure({url:e?.url??``,...e?.protocols===void 0?{}:{protocols:e.protocols}})===`terminal`){this.bridgeRejection=new Hr().message,this.notifyBridgeRejected();return}let t=Wr(this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectNotBefore=Date.now()+t}notifyBridgeRejected(){if(!this.bridgeRejectedNotified){this.bridgeRejectedNotified=!0;try{this.bridgeRejectedHandler?.()}catch{}}}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}},qr=class extends Error{step;name=`CommandAbortedError`;constructor(e){super(`Browser command aborted while ${e}. A CDP round trip already in flight cannot be cancelled, so it may still have been applied to the page; nothing after it was started.`),this.step=e}};function Jr(e,t){if(e?.aborted)throw new qr(t)}function Yr(e,t){return e?{signal:e,error:()=>new qr(t)}:void 0}function Xr(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new qr(n));return}let a=()=>{clearTimeout(o),i(new qr(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Zr(e,t,n){return t?t.aborted?Promise.reject(new qr(n)):new Promise((r,i)=>{let a=()=>i(new qr(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var Qr=class{contexts=/* @__PURE__ */ new Map;for(e,t){let n=`${t}:${e}`,r=this.contexts.get(n);return r||(r=/* @__PURE__ */ new Map,this.contexts.set(n,r)),r}peek(e,t){return this.contexts.get(`${t}:${e}`)}drop(e){this.contexts.delete(`main:${e}`),this.contexts.delete(`isolated:${e}`)}get size(){return this.contexts.size}};const $r=h(`har-recorder`);var ei=class{recordings=/* @__PURE__ */ new Map;client;fs;eventCleanup=/* @__PURE__ */ new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Jr(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Jr(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Jr(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:/* @__PURE__ */ new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),$r.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{$r.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{$r.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;n&&r&&i!=null&&e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return ti(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return $r.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return $r.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),$r.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return $r.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function ti(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){$r.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return $r.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var ni=class extends Error{name=`HiddenPageWheelError`;constructor(){super(`The tab is hidden (or could not be checked) and focus emulation is not available, so Chrome would not answer a wheel event`)}};function ri(e,t){return e===`Input.dispatchMouseEvent`?t?.type===`mouseMoved`?`move`:t?.type===`mouseWheel`?`wheel`:null:null}function ii(e,t,n,r){return`(() => {
|
|
2
2
|
const dx = ${JSON.stringify(n)}, dy = ${JSON.stringify(r)};
|
|
3
3
|
const canScroll = (el) => {
|
|
4
4
|
const style = getComputedStyle(el);
|
|
@@ -964,7 +964,7 @@ import{n as e}from"./rolldown-runtime-DBVvNlSN.js";import{_ as t,a as n,c as r,d
|
|
|
964
964
|
this.scrollIntoView({ block: 'center', inline: 'center' });
|
|
965
965
|
const r = this.getBoundingClientRect();
|
|
966
966
|
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
967
|
-
}`,returnByValue:!0})).result?.value}async resolveNodeCenter(e){let t=await this.resolveNodeObjectId(e),n=await this.nodeBox(t);if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async boundingBox(e){await this.send(`DOM.enable`);let t=(await this.send(`DOM.getDocument`,{depth:0})).root.nodeId,n;try{n=(await this.send(`DOM.querySelector`,{nodeId:t,selector:e})).nodeId}catch{return null}if(!n)return null;let r=(await this.send(`DOM.getBoxModel`,{nodeId:n})).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function vi(e,t){if(t.push({frameId:e.frame.id,parentFrameId:e.frame.parentId,url:e.frame.url,name:e.frame.name??``,securityOrigin:e.frame.securityOrigin}),Array.isArray(e.childFrames))for(let n of e.childFrames)vi(n,t)}function yi(e){let t=e.exceptionDetails;return t?t.exception?.description??t.text:null}function bi(e,t){let n=yi(e);if(n!==null)throw Error(`${t}: ${n}`);return e.result?.value}function xi(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Cannot find context with specified id`)||t.includes(`Execution context was destroyed`)}function Si(e){let t={role:De(e.role,`unknown`),name:De(e.name)},n=De(e.value);n!==``&&(t.value=n);let r=De(e.description);return r!==``&&(t.description=r),typeof e.ref==`string`&&/^e[0-9]+$/.test(e.ref)&&(t.ref=e.ref),typeof e.refSeq==`number`&&Number.isSafeInteger(e.refSeq)&&(t.refSeq=e.refSeq),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>Si(e)).filter(e=>e.role!==`unknown`)),t}function Ci(e){let t=e??{queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0};return{queueDepth:t.queueDepth,totalWaitMs:t.tabWaitMs+t.bridgeWaitMs,tabWaitMs:t.tabWaitMs,bridgeWaitMs:t.bridgeWaitMs,acquisitions:t.acquisitions}}var wi=class{tabLocks=/* @__PURE__ */ new Map;bridgeLock=Promise.resolve();bridgeHold=null;bridgeWaiters=0;tabLockStats=/* @__PURE__ */ new Map;getStats(e){if(e!==void 0)return Ci(this.tabLockStats.get(e));let t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0};for(let e of this.tabLockStats.values())t.queueDepth+=e.queueDepth,t.tabWaitMs+=e.tabWaitMs,t.bridgeWaitMs+=e.bridgeWaitMs,t.acquisitions+=e.acquisitions;return Ci(t)}countersFor(e){let t=this.tabLockStats.get(e);return t||(t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0},this.tabLockStats.set(e,t)),t}liveOwner(){return this.bridgeHold?.owner}reentrantOwner(e){let t=this.bridgeHold;if(t&&e!==null&&t.targetId===e)return t.owner}async holdTabLock(e,t,n){Jr(t,`starting a command on tab ${e}`);let r=this.countersFor(e);r.queueDepth+=1;let i;try{i=await this.acquireTabLock(e,r,t)}catch(e){throw--r.queueDepth,e}try{return await n(r)}finally{--r.queueDepth,i()}}async acquireTabLock(e,t,n){let r,i=new Promise(e=>{r=e}),a=this.tabLocks.get(e);this.tabLocks.set(e,i);let o=()=>{this.tabLocks.get(e)===i&&this.tabLocks.delete(e),r()};if(a!=null){let r=Date.now();try{await Zr(a,n,`queued for the lock on tab ${e}`)}catch(e){throw t.tabWaitMs+=Date.now()-r,a.then(o,o),e}t.tabWaitMs+=Date.now()-r}return o}async acquireBridgeLock(e){if(e?.owner!==void 0&&this.bridgeHold?.owner===e.owner)return()=>void 0;let t,n=new Promise(e=>{t=e}),r=this.bridgeLock,i=this.bridgeHold!==null||this.bridgeWaiters>0;if(this.bridgeLock=n,i){this.bridgeWaiters+=1;let t=Date.now();try{await r}finally{--this.bridgeWaiters}e?.counters&&(e.counters.bridgeWaitMs+=Date.now()-t)}let a={release:t,owner:Symbol(`bridge-hold`),targetId:e?.targetId??null};this.bridgeHold=a;let o=!1;return()=>{o||(o=!0,this.bridgeHold===a&&(this.bridgeHold=null),t())}}async runGlobal(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e),targetId:e});try{return await t()}finally{n()}}},Ti=class{overrides=/* @__PURE__ */ new Map;get(e){return this.overrides.get(e)}set(e,t){this.overrides.set(e,t)}delete(e){this.overrides.delete(e)}has(e){return this.overrides.has(e)}get size(){return this.overrides.size}};const Ei=h(`browser-api`),Di=[`Session with given id not found`,`Target closed`,`No session with given id`,`No tab attached for sessionId`];var Oi=class extends Error{};function ki(e){let t=e instanceof Error?e.message:String(e);return Di.some(e=>t.includes(e))}var Ai=class{inner;onApplied;route;onStateChange;constructor(e,t,n){this.inner=e,this.onApplied=t,this.route=n,e.onStateChange&&(this.onStateChange=t=>e.onStateChange(t))}get state(){return this.inner.state}get superseded(){return this.inner.superseded}get isExtensionBridge(){return this.inner.isExtensionBridge}connect(e){return this.inner.connect(e)}disconnect(){this.inner.disconnect()}async send(e,t,n,r){let i=await this.route(this.inner,e,t,n,()=>this.forward(e,t,n,r));return n&&this.onApplied(n),i}forward(e,t,n,r){return r===void 0?this.inner.send(e,t,n):this.inner.send(e,t,n,r)}on(e,t){this.inner.on(e,t)}off(e,t){this.inner.off(e,t)}once(e,t){return this.inner.once(e,t)}},ji=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;frames=new Qr;sessions=new ai(32,(e,t)=>{Ei.debug(`Evicting least-recently-used CDP session`,{targetId:e}),this.detachSession(e,t)});_listenedTransports=/* @__PURE__ */ new Set;_sessionReplacedSubs=/* @__PURE__ */ new Map;locks=new wi;viewports=new Ti;hiddenPages=null;hiddenPagesLoad=null;hiddenPagePins=/* @__PURE__ */ new Map;facadeSessions=/* @__PURE__ */ new Map;connection=new Kr;_onSessionChange;handleJavaScriptDialogOpening=e=>{this.dismissJavaScriptDialog(e)};async dismissJavaScriptDialog(e){let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.transportForSession(t).send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),Ei.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){Ei.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}handleExecutionContextCreated=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this.frames.for(t,`main`).set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.executionContextId;if(typeof n!=`number`)return;let r=this.frames.peek(t,`main`);if(r)for(let[e,t]of r)t===n&&r.delete(e)};handleExecutionContextsCleared=e=>{let t=this.eventSessionId(e);t&&this.frames.peek(t,`main`)?.clear()};eventSessionId(e){let t=e.sessionId;return typeof t==`string`?t:this.sessionId}handleDetachedFromTarget=e=>{let t=e.sessionId;if(typeof t!=`string`)return;this.hiddenPages?.forgetSession(t),this.facadeSessions.delete(t);let n=this.sessions.findBySessionId(t);n&&this.forgetSession(n[0],n[1])};handleTargetDestroyed=e=>{let t=e.targetId;if(typeof t!=`string`)return;let n=this.sessions.findByTargetOrLocalId(t)[0];n&&this.forgetSession(n[0],n[1])};constructor(e){this.client=e??new Pr,this.localClient=this.client,this.addTransportListeners(this.client)}getTransport(){return this.accountedTransportFor(this.client)}getUnderlyingTransport(){return this.client}_accountedTransports=/* @__PURE__ */ new WeakMap;accountedTransportFor(e){if(e instanceof Ai)return e;let t=this._accountedTransports.get(e);return t||(t=new Ai(e,e=>this.noteApplied(e),(e,t,n,r,i)=>this.routeSend(e,t,n,r,i)),this._accountedTransports.set(e,t)),t}noteApplied(e){this.sessions.noteApplied(e)}createHarRecorder(e,t){return new ei(t,e)}setSessionChangeCallback(e){this._onSessionChange=e}onSessionReplaced(e,t){let n=this._sessionReplacedSubs.get(e);return n||(n=/* @__PURE__ */ new Set,this._sessionReplacedSubs.set(e,n)),n.add(t),()=>{let n=this._sessionReplacedSubs.get(e);n&&(n.delete(t),n.size===0&&this._sessionReplacedSubs.delete(e))}}getSessionId(){return this.sessionId}getAttachedTargetId(){return this.attachedTargetId}async withTab(e,t,n){let r=n?.signal;return this.locks.holdTabLock(e,r,async n=>{let i=this.sessions.pin(e);try{return n.acquisitions+=1,await this.runOnTab(e,t,r)}finally{i()}})}async runOnTab(e,t,n){try{return await this.attemptOnTab(e,t,n)}catch(r){if(r instanceof Oi||!ki(r))throw r;return Ei.warn(`Stale CDP session — re-attaching and retrying once`,{targetId:e,error:r instanceof Error?r.message:String(r)}),this.invalidateSession(e),await this.attemptOnTab(e,t,n)}}async attemptOnTab(e,t,n){let r=await this.attachHandle(e,this.locks.reentrantOwner(e),n);Jr(n,`about to run a command on tab ${e}`);let i=r.sessionId,a=this.sessions.appliedCount(i);this.hiddenPagePins.set(e,(this.hiddenPagePins.get(e)??0)+1);try{return await t(r)}catch(t){if(!ki(t))throw t;let n=this.sessions.appliedCount(i)-a;if(n===0)throw t;this.invalidateSession(e);let r=t instanceof Error?t.message:String(t);throw Ei.warn(`CDP session reset mid-command — not replaying`,{targetId:e,applied:n,reason:r}),new Oi(`The CDP session for tab ${e} was reset mid-command, after ${n} command(s) had already been applied, so the outcome is unknown. The tab has been re-armed: check the page state before repeating this command. (underlying error: ${r})`)}finally{await this.unpinHiddenPage(e)}}async unpinHiddenPage(e){let t=(this.hiddenPagePins.get(e)??1)-1;if(t>0){this.hiddenPagePins.set(e,t);return}this.hiddenPagePins.delete(e),await this.hiddenPages?.unpinned(e)}async routeSend(e,t,n,r,i){if(t===`Target.attachToTarget`){let e=await i(),t=e.sessionId,r=n?.targetId;return typeof t==`string`&&typeof r==`string`&&this.facadeSessions.set(t,r),e}if(r===void 0||t!==`Emulation.setFocusEmulationEnabled`&&ri(t,n)===null)return i();let a=this.hiddenPages??await this.loadHiddenPages();return a?a.route(e,t,n,r,i):i()}loadHiddenPages(){return this.hiddenPagesLoad??=import(`./hidden-page-input-DDEF33JC.js`).then(({HiddenPageInput:e})=>(this.hiddenPages=new e({targetOf:e=>this.sessions.findBySessionId(e)?.[0]??this.facadeSessions.get(e),pinned:e=>this.hiddenPagePins.has(e),isGone:ki}),this.hiddenPages),e=>(Ei.warn(`Hidden-page input gate failed to load; pointer input goes out as is`,{error:e instanceof Error?e.message:String(e)}),this.hiddenPagesLoad=null,null)),this.hiddenPagesLoad}async attachHandle(e,t,n){let r=await this.attachToPageOwned(e,t,n),i=this.sessions.get(e);return new _i(this,e,r,this.accountedTransportFor(i?.transport??this.client),n)}handleFor(e,t){return new _i(this,e,t.sessionId,this.accountedTransportFor(t.transport))}getTabLockStats(e){return this.locks.getStats(e)}async runGlobal(e,t){return this.locks.runGlobal(e,t)}viewportOverride(e){return this.viewports.get(e)}recordViewportOverride(e,t){this.viewports.set(e,t)}frameContexts(e,t){return this.frames.for(e,t)}dropFrameContexts(e){this.frames.drop(e)}async reapplyViewportOverride(e,t){let n=this.viewports.get(e);if(n)try{await this.handleFor(e,t).applyViewportOverride(n)}catch(t){Ei.warn(`Failed to re-apply viewport override on re-attach`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:e.kind,capabilities:e.capabilities}));return[...e,...r]}async connect(e){await this.connection.connect(this.client,e)}async reconnectIfNeeded(){await this.ensureConnected(),this.client!==this.localClient&&await this.ensureLocalConnected()}primeConnectOptions(e){this.connection.primeConnectOptions(e)}setCdpSupersededHandler(e){this.connection.setSupersededHandler(e)}setCdpBridgeRejectedHandler(e){this.connection.setBridgeRejectedHandler(e)}setCdpConnectFailureClassifier(e){this.connection.setConnectFailureClassifier(e)}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async openWindow(e,t={}){await this.ensureConnected(),await this.ensureLocalConnected(),Pi(t);let n=t.focus!==!1,r={url:e||`about:blank`,newWindow:!0,background:!n};t.decorated===!1&&(r.decorated=!1);let i=t.state;i&&i!==`normal`?r.windowState=i:(t.width!==void 0&&(r.width=t.width),t.height!==void 0&&(r.height=t.height),t.left!==void 0&&(r.left=t.left),t.top!==void 0&&(r.top=t.top),i&&(r.windowState=i));let a=(await this.localClient.send(`Target.createTarget`,r)).targetId;if(typeof a!=`string`||!a)throw Error(`Target.createTarget did not return a usable targetId`);return a}async getWindowBounds(e){await this.ensureConnected();let t=Ii((await(await this.transportForWindowOps(e)).send(`Browser.getWindowForTarget`,{targetId:Ni(e)})).bounds),n=await this.readDevicePixelRatio(e);return{...t,dpr:n}}async setWindowBounds(e,t){await this.ensureConnected(),Pi(t);let n=await this.transportForWindowOps(e),r=Ni(e),i=await n.send(`Browser.getWindowForTarget`,{targetId:r}),a=i.windowId;if(typeof a!=`number`)throw Error(`Browser.getWindowForTarget did not return a windowId`);let o=Ii(i.bounds),s=t.state;(t.left!==void 0||t.top!==void 0||t.width!==void 0||t.height!==void 0)&&o.state!==`normal`&&await n.send(`Browser.setWindowBounds`,{windowId:a,bounds:{windowState:`normal`}});let c={};s&&s!==`normal`?c.windowState=s:(t.left!==void 0&&(c.left=t.left),t.top!==void 0&&(c.top=t.top),t.width!==void 0&&(c.width=t.width),t.height!==void 0&&(c.height=t.height),s&&(c.windowState=s)),await n.send(`Browser.setWindowBounds`,{windowId:a,bounds:c});let l=Ii((await n.send(`Browser.getWindowBounds`,{windowId:a})).bounds),u=await this.readDevicePixelRatio(e);return{...l,dpr:u}}async readDevicePixelRatio(e){try{let t=await this.withTab(e,e=>e.evaluate(`window.devicePixelRatio`,{awaitPromise:!1,returnByValue:!0}));return typeof t==`number`&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}async transportForWindowOps(e){if(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);return this.trayTargetProvider.createRemoteTransport(n,r)}return await this.ensureLocalConnected(),this.localClient}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.viewports.delete(e),await this.dropSession(e),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let e=this.trayTargetProvider.createRemoteTransport(n,r);try{await e.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}return}}await this.localClient.send(`Target.closeTarget`,{targetId:e})}disconnect(){this.clearSessions(),this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){return this.attachToPageOwned(e,this.locks.reentrantOwner(e))}async attachToPageOwned(e,t,n){let r=await this.locks.acquireBridgeLock({owner:t,targetId:e,counters:this.locks.countersFor(e)});try{await this.ensureConnected();let t=this.sessions.get(e);return t?(this.activateSession(e,t),t.sessionId):await(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)?this.attachRemoteTarget(e,n):this.attachLocalTarget(e,n))}finally{r()}}async selectTab(e){await this.withTab(e,async()=>void 0)}async bringTabToFront(e){await this.withTab(e,e=>e.bringToFront())}async attachRemoteTarget(e,t){let n=e.indexOf(`:`),r=e.substring(0,n),i=e.substring(n+1),a=this.trayTargetProvider?.createRemoteTransport?.(r,i);if(!a)throw Error(`No remote transport for target ${e}`);Jr(t,`about to attach to tray tab ${e}`);let o={sessionId:(await a.send(`Target.attachToTarget`,{targetId:i,flatten:!0})).sessionId,transport:a,remote:{runtimeId:r,localTargetId:i}};return this.rememberSession(e,o),this.activateSession(e,o),Jr(t,`about to enable Page on tray tab ${e}`),await a.send(`Page.enable`,{},o.sessionId),Jr(t,`about to restore the viewport of tray tab ${e}`),await this.reapplyViewportOverride(e,o),this.notifySessionChange(e,o),o.sessionId}async attachLocalTarget(e,t){this.useLocalTransport(),await this.ensureLocalConnected(),Jr(t,`about to attach to tab ${e}`);let n={sessionId:(await this.localClient.send(`Target.attachToTarget`,{targetId:e,flatten:!0})).sessionId,transport:this.localClient};return this.rememberSession(e,n),this.activateSession(e,n),Jr(t,`about to enable Page on tab ${e}`),await this.localClient.send(`Page.enable`,{},n.sessionId),Jr(t,`about to restore the viewport of tab ${e}`),await this.reapplyViewportOverride(e,n),this.notifySessionChange(e,n),n.sessionId}async detach(){let e=this.attachedTargetId;e&&(await this.dropSession(e),this.useLocalTransport())}async wakeCapture(e,t){let n=await this.locks.acquireBridgeLock({owner:this.locks.reentrantOwner(e.targetId),targetId:e.targetId});try{return await this.wakeCaptureLocked(e,t,this.locks.liveOwner())}finally{n()}}async wakeCaptureLocked(e,t,n){let r=e.targetId,i=await this.findFocusedLocalPage(r,n).catch(()=>null),a=await this.attachHandle(r,n);try{return await a.send(`Page.bringToFront`),await a.send(`Page.captureScreenshot`,t)}finally{if(i)try{await(await this.attachHandle(i,n)).send(`Page.bringToFront`),await this.attachToPageOwned(r,n)}catch{}}}async findFocusedLocalPage(e,t){let n=await this.listPages();for(let r of n)if(r.targetId&&r.targetId!==e&&!r.targetId.includes(`:`))try{if(await(await this.attachHandle(r.targetId,t)).evaluate(`document.hasFocus()`)===!0)return r.targetId}catch{}return null}async ensureLocalConnected(){await this.connection.ensureLocalConnected(this.localClient)}async ensureConnected(){await this.connection.ensureConnected({client:this.client,restoreLocalAfterRemoteDrop:()=>{this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null)},clearSessionsForTransport:e=>this.clearSessionsForTransport(e),getClient:()=>this.client})}transportForSession(e){return this.sessions.findBySessionId(e)?.[1].transport??this.client}addTransportListeners(e){this._listenedTransports.has(e)||(this._listenedTransports.add(e),e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.on(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.on(`Target.targetDestroyed`,this.handleTargetDestroyed))}releaseLifecycleTransport(e){e!==this.localClient&&this._listenedTransports.has(e)&&(this.sessions.anyOnTransport(e)||(this._listenedTransports.delete(e),e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.off(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.off(`Target.targetDestroyed`,this.handleTargetDestroyed)))}setClient(e){this.addTransportListeners(e),this.client=e}useLocalTransport(){let e=this.remoteTargetInfo;this.remoteTargetInfo=null,this.setClient(this.localClient),e&&(this.sessions.anyMatchingRemote(e.runtimeId,e.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.runtimeId,e.localTargetId))}rememberSession(e,t){this.addTransportListeners(t.transport),this.sessions.remember(e,t)}activateSession(e,t){t.remote?(this.setClient(t.transport),this.remoteTargetInfo={...t.remote}):this.client!==t.transport&&this.useLocalTransport(),this.sessionId=t.sessionId,this.attachedTargetId=e,this.sessions.touch(e,t)}notifySessionChange(e,t){let n=this.accountedTransportFor(t.transport);this._onSessionChange?.(t.sessionId,n,e);let r=this._sessionReplacedSubs.get(e);if(r)for(let i of[...r])try{i(t.sessionId,n,e)}catch(t){Ei.warn(`session-replaced subscriber threw`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}forgetSession(e,t){this.unregisterSession(e),this.disposeSessionTransport(t)}unregisterSession(e){let t=this.sessions.get(e);t&&this.dropFrameContexts(t.sessionId),this.sessions.delete(e),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disposeSessionTransport(e){this.releaseLifecycleTransport(e.transport),e.remote&&(this.sessions.anyMatchingRemote(e.remote.runtimeId,e.remote.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.remote.runtimeId,e.remote.localTargetId))}async detachSession(e,t){this.unregisterSession(e);try{await t.transport.send(`Target.detachFromTarget`,{sessionId:t.sessionId})}catch{}finally{this.disposeSessionTransport(t)}}async dropSession(e){let t=this.sessions.get(e);if(!t){this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null);return}await this.detachSession(e,t)}invalidateSession(e){let t=this.sessions.get(e);t&&this.forgetSession(e,t)}clearSessionsForTransport(e){for(let[t,n]of this.sessions.snapshot())n.transport===e&&this.forgetSession(t,n)}clearSessions(){for(let[e,t]of this.sessions.snapshot())this.forgetSession(e,t);this.sessions.clear(),this.sessionId=null,this.attachedTargetId=null}};const Mi=/* @__PURE__ */ new Set([`normal`,`minimized`,`maximized`,`fullscreen`]);function Ni(e){let t=e.indexOf(`:`);return t>=0?e.substring(t+1):e}function Pi(e){let t=e.state;if(t&&t!==`normal`){if(!Mi.has(t))throw Error(`window state must be one of ${[...Mi].join(`|`)} (got ${JSON.stringify(t)})`);if(e.left!==void 0||e.top!==void 0||e.width!==void 0||e.height!==void 0)throw Error(`window state '${t}' cannot be combined with left/top/width/height (chrome.windows + CDP both reject the mix)`)}}function Fi(e){return typeof e==`object`&&!!e}function Ii(e){let t=Fi(e)?e:{},n=t.windowState??t.state,r=typeof n==`string`&&Mi.has(n)?n:`normal`;return{left:Li(t.left,0),top:Li(t.top,0),width:Li(t.width,0),height:Li(t.height,0),state:r}}function Li(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}const Ri=h(`panel-rpc-cdp`);var zi=class{getPanelRpc;runtimeId;localTargetId;timeoutMs;eventListeners=/* @__PURE__ */ new Map;pendingOnce=/* @__PURE__ */ new Set;key;_state=`connected`;pushRegistered=!1;constructor(e,t,n,r=3e4){this.getPanelRpc=e,this.runtimeId=t,this.localTargetId=n,this.timeoutMs=r,this.key=`${t}:${n}`}get state(){return this._state}async connect(){}disconnect(){this._state=`disconnected`;for(let e of this.pendingOnce)clearTimeout(e.timer),e.reject(/* @__PURE__ */ Error(`Transport disconnected`));this.pendingOnce.clear();let e=this.getPanelRpc();e&&(this.pushRegistered&&=(e.unregisterPushTarget(this.key),!1),e.call(`remote-cdp-detach`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId}).catch(e=>{Ri.error(`remote-cdp detach failed (page-side session may leak)`,{key:this.key,error:e instanceof Error?e.message:String(e)})})),this.eventListeners.clear()}async send(e,t,n,r){if(this._state===`disconnected`)throw Error(`Transport disconnected`);let i=this.getPanelRpc();if(!i)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let a=r??this.timeoutMs,o=Math.max(a,ke)+5e3;return i.call(`remote-cdp-send`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,method:e,params:t,sessionId:n,timeout:a},{timeoutMs:o})}on(e,t){let n=this.eventListeners.get(e),r=!n||n.size===0;n||(n=/* @__PURE__ */ new Set,this.eventListeners.set(e,n)),n.add(t),r&&this.subscribe(e)}off(e,t){let n=this.eventListeners.get(e);n&&(n.delete(t),n.size===0&&(this.eventListeners.delete(e),this.unsubscribe(e)))}once(e,t){return new Promise((n,r)=>{let i=t??this.timeoutMs,a={reject:r,timer:void 0},o=()=>{clearTimeout(a.timer),this.pendingOnce.delete(a),this.off(e,s)};a.timer=setTimeout(()=>{o(),r(/* @__PURE__ */ Error(`Remote CDP event timed out: ${e}`))},i);let s=e=>{o(),n(e)};this.pendingOnce.add(a),this.on(e,s)})}handleEvent(e,t){let n=this.eventListeners.get(e);if(n)for(let e of[...n])e(t)}ensurePushRegistered(e){this.pushRegistered||=(e.registerPushTarget(this.key,e=>this.handleEvent(e.method,e.params??{})),!0)}subscribe(e){let t=this.getPanelRpc();if(!t){Ri.error(`remote-cdp subscribe skipped: no panel-RPC client`,{key:this.key,event:e});return}this.ensurePushRegistered(t),t.call(`remote-cdp-subscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Ri.error(`remote-cdp subscribe failed; events for this transport will not arrive`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}unsubscribe(e){let t=this.getPanelRpc();t&&t.call(`remote-cdp-unsubscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Ri.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function Bi(e){let t=/* @__PURE__ */ new Map,n=(e,t)=>`${e}:${t}`;return{getTargets(){return[]},createRemoteTransport(r,i){let a=n(r,i),o=t.get(a);return o||(o=new zi(e,r,i),t.set(a,o)),o},removeRemoteTransport(e,r){let i=n(e,r),a=t.get(i);a&&(a.disconnect(),t.delete(i))},async openRemoteTab(t,n){let r=e();if(!r)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let{targetId:i}=await r.call(`remote-open-tab`,{runtimeId:t,url:n});return i}}}function Vi(e){return`slicc_feature_flags_remote:${e}`}let Hi=null;function Ui(e,t){let n=Gi(t);Hi=e,Ne(e,Ki(n,e)??{})}function Wi(e,t){if(!Hi||e!==void 0&&e!==Vi(Hi))return!1;let n=Gi(t);return je(Hi,Ki(n,Hi)??{}),!0}function Gi(e){if(e!==void 0)return e;try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function Ki(e,t){try{let n=e?.getItem(Vi(t));return n?qi(JSON.parse(n)):null}catch{return null}}function qi(e){return!Ji(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function Ji(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Yi=h(`stale-asset`),Xi=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Zi(e){return Xi.test(e)}let Qi=null;function $i(e){if(!e){Qi=null;return}Qi=e}function ea(e=!1){if(!Qi||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Qi,replayTurn:e})}finally{t.close()}}function ta(e){Zi(e instanceof Error?e.message:String(e))&&ea()}function na(e,t){return!e||e===t?!1:(Yi.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),ea(),!0)}let ra=null;function ia(e){ra=e??null}function aa(){return ra}var oa=class{_state=`disconnected`;nextCommandId=1;listeners=/* @__PURE__ */ new Map;pendingCommands=new Ar;unsubscribe=null;stateListeners=/* @__PURE__ */ new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;opts;label;constructor(e){this.opts=e,this.label=e.label??`CDP transport`}get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);this.unsubscribe||=this.opts.subscribeIncoming(e=>this.handleIncoming(e)),this._state=`connected`,this.notifyState(`connected`)}disconnect(){this.unsubscribe?.(),this.unsubscribe=null;let e=`${this.label} disconnected`;this.pendingCommands.rejectAll(e),this.listeners.clear(),this._state=`disconnected`,this.notifyState(`disconnected`,e)}async send(e,t,n,r=3e4){if(this._state!==`connected`)throw Error(`${this.label} is not connected`);let i=this.nextCommandId++,a=this.opts.buildCommandEnvelope(i,e,t,n),o=this.pendingCommands.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.opts.sendEnvelope(a).catch(e=>{this.pendingCommands.reject(i,/* @__PURE__ */ Error(`Failed to send CDP command: ${e instanceof Error?e.message:String(e)}`))}),o}on(e,t){let n=this.listeners.get(e),r=!n;n||(n=/* @__PURE__ */ new Set,this.listeners.set(e,n)),n.add(t),r&&this.opts.onSubscribeEvent?.(e)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&(this.listeners.delete(e),this.opts.onUnsubscribeEvent?.(e)))}once(e,t=3e4){return jr(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleIncoming(e){let t=this.opts.parseControl?.(e)??null;if(t){this.handleControl(t);return}let n=this.opts.parseResponse(e);if(n){this.handleResponse(n);return}let r=this.opts.parseEvent(e);r&&this.handleEvent(r)}handleControl(e){if(e.kind===`ready`){this.opts.onUpstreamReady?.();return}let t=e.reason??`upstream connection reset`,n=`${this.label}: upstream CDP connection was reset (${t})`;this.pendingCommands.rejectAll(n),this._state=`disconnected`,this.opts.onUpstreamReset?.(t),this.notifyState(`disconnected`,n)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}handleResponse(e){if(!this.pendingCommands.has(e.id)){this.opts.onUnknownResponseId?.(e.id);return}e.error?this.pendingCommands.reject(e.id,Error(e.error)):this.pendingCommands.resolve(e.id,e.result??{})}handleEvent(e){let t=this.listeners.get(e.method);if(t)for(let n of t)try{n(e.params??{})}catch(t){this.opts.onListenerError?.(e.method,t)}}};function sa(e){let t=!1,n=()=>{t||(t=!0,typeof e.start==`function`&&e.start())};return{onMessage:t=>{let r=e=>{t(e.data)};return e.addEventListener(`message`,r),n(),()=>{e.removeEventListener(`message`,r)}},send:(t,n)=>{n&&n.length>0?e.postMessage(t,n):e.postMessage(t)}}}function ca(e){let t=sa(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var la=class extends oa{constructor(e){let t=sa(e),n=0;super({label:`WorkerCdpProxy`,buildCommandEnvelope:(e,t,r,i)=>({type:`cdp-cmd`,id:e,method:t,params:r,sessionId:i,gen:n}),sendEnvelope:e=>(t.send(e),Promise.resolve()),subscribeIncoming:e=>t.onMessage(e),parseResponse:e=>{let t=e;if(t?.type!==`cdp-response`)return null;if(typeof t.id!=`number`||!Number.isFinite(t.id))return console.warn(`[WorkerCdpProxy] dropping cdp-response with invalid id`,t),null;let n=e;return{id:n.id,result:n.result,error:n.error}},parseEvent:e=>{let t=e;if(t?.type!==`cdp-event`)return null;if(typeof t.method!=`string`)return console.warn(`[WorkerCdpProxy] dropping cdp-event with invalid method`,t),null;let n=e;return{method:n.method,params:n.params}},parseControl:e=>{let t=e;return t?.type===`cdp-reset`?typeof t.reason==`string`?{kind:`reset`,reason:t.reason}:{kind:`reset`}:t?.type===`cdp-ready`?{kind:`ready`}:null},onUpstreamReset:e=>{n+=1,console.warn(`[WorkerCdpProxy] page CDP connection reset; sessions are stale`,e)},onUpstreamReady:()=>{console.info(`[WorkerCdpProxy] page CDP connection restored`)},onSubscribeEvent:e=>{t.send({type:`cdp-subscribe`,event:e})},onUnsubscribeEvent:e=>{t.send({type:`cdp-unsubscribe`,event:e})}})}};function ua(e,t){return e.find(e=>e.folder===t)??e.find(e=>e.folder===`${t}-scoop`)??e.find(e=>e.name===t)}const da={assign:0,create:0,clone:0,discard:0,update:0};function fa(e,t,n){return e>=t&&e<=n}function pa(e){return e===8205}function ma(e){return fa(e,55296,56319)}function ha(e){return fa(e,127462,127487)}function ga(e){return fa(e,65024,65039)}function _a(e){return fa(e,768,879)||fa(e,6832,6911)||fa(e,7616,7679)||fa(e,65056,65071)}function va(e){return e>65535?2:1}function ya(e,t){for(;t<e.length;){let n=e.codePointAt(t);if(_a(n)||ga(n))t+=va(n);else break}return t}function ba(e,t){let n=e.codePointAt(t),r=t+va(n);for(r=ya(e,r);r<e.length-1&&pa(e.codePointAt(r));){let t=e.codePointAt(r+1);r+=1+va(t),r=ya(e,r)}return ha(n)&&r<e.length&&ha(e.codePointAt(r))&&(r+=va(e.codePointAt(r))),r}function xa(e){return e>=768&&(ma(e)||_a(e)||ga(e)||pa(e))}function Sa(e){let t=0,n=0;for(;n<e.length;)n=ba(e,n),t++;return t}function Ca(e,t){let n=0,r=0;for(;r<e.length;)if(r=ba(e,r),++n>=t)return!0;return!1}function wa(e,t){let n=0,r=0;for(;r<e.length;)if(r=ba(e,r),++n>t)return!1;return!0}function Ta(e,t){if(t===0)return!0;if(e.length<t)return!1;let n=0;for(;;){if(xa(e.charCodeAt(n)))return Ca(e,t);if(++n>=t)return!0}}function Ea(e,t){if(e.length<=t)return!0;let n=0;for(;;){if(xa(e.charCodeAt(n)))return wa(e,t);if(++n>t)return!1}}var Da=/* @__PURE__ */ e({Counted:()=>Xa,Entries:()=>$a,EntriesRegExp:()=>Qa,Every:()=>Ka,EveryAll:()=>qa,GraphemeCount:()=>Ua,HasPropertyKey:()=>w,IsArray:()=>_,IsBigInt:()=>Oa,IsBoolean:()=>ka,IsClassInstance:()=>Va,IsConstructor:()=>Aa,IsDeepEqual:()=>io,IsEqual:()=>S,IsFunction:()=>ja,IsGreaterEqualThan:()=>za,IsGreaterThan:()=>Ia,IsInteger:()=>Ma,IsLessEqualThan:()=>Ra,IsLessThan:()=>La,IsMaxLength:()=>Wa,IsMinLength:()=>Ga,IsMultipleOf:()=>Ba,IsNull:()=>Na,IsNumber:()=>v,IsObject:()=>y,IsObjectNotArray:()=>Pa,IsString:()=>b,IsSymbol:()=>Fa,IsUndefined:()=>x,IsUnsafePropertyKey:()=>Za,IsValueLike:()=>Ha,Keys:()=>T,ShiftLeft:()=>C,Some:()=>Ja,SomeAll:()=>Ya,Symbols:()=>eo,Values:()=>to});function _(e){return Array.isArray(e)}function Oa(e){return S(typeof e,`bigint`)}function ka(e){return S(typeof e,`boolean`)}function Aa(e){if(x(e)||!ja(e))return!1;let t=Function.prototype.toString.call(e);return!!(/^class\s/.test(t)||/\[native code\]/.test(t))}function ja(e){return S(typeof e,`function`)}function Ma(e){return Number.isInteger(e)}function Na(e){return S(e,null)}function v(e){return Number.isFinite(e)}function Pa(e){return y(e)&&!_(e)}function y(e){return S(typeof e,`object`)&&!Na(e)}function b(e){return S(typeof e,`string`)}function Fa(e){return S(typeof e,`symbol`)}function x(e){return S(e,void 0)}function S(e,t){return e===t}function Ia(e,t){return e>t}function La(e,t){return e<t}function Ra(e,t){return e<=t}function za(e,t){return e>=t}function Ba(e,t){if(Oa(e)||Oa(t))return BigInt(e)%BigInt(t)===0n;if(!v(e)||Ma(e)&&1/t%1==0)return!0;let n=e%t;return Math.min(Math.abs(n),Math.abs(n-t),Math.abs(n+t))<1e-10}function Va(e){if(!y(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return!Na(t)&&S(typeof t.constructor,`function`)&&!(S(t.constructor,globalThis.Object)||S(t.constructor.name,`Object`))}function Ha(e){return Oa(e)||ka(e)||Na(e)||v(e)||b(e)||x(e)}function Ua(e){return Sa(e)}function Wa(e,t){return Ea(e,t)}function Ga(e,t){return Ta(e,t)}function Ka(e,t,n){return e.every((e,r)=>r<t||n(e,r))}function qa(e,t,n){let r=!0;return e.forEach((e,i)=>{i>=t&&!n(e,i)&&(r=!1)}),r}function Ja(e,t){return e.some((e,n)=>t(e,n))}function Ya(e,t){let n=!1;return e.forEach((e,r)=>{t(e,r)&&(n=!0)}),n}function Xa(e,t){return e.reduce((e,n,r)=>t(n,r)?++e:e,0)}function C(e,t,n){return S(e.length,0)?n():t(e[0],e.slice(1))}function Za(e){return S(e,`__proto__`)||S(e,`constructor`)||S(e,`prototype`)}function w(e,t){return Za(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function Qa(e){return T(e).map(t=>[RegExp(`^${t}$`),e[t]])}function $a(e){return Object.entries(e)}function T(e){return Object.getOwnPropertyNames(e)}function eo(e){return Object.getOwnPropertySymbols(e)}function to(e){return Object.values(e)}function no(e,t){if(!y(t))return!1;let n=T(e);return S(n.length,T(t).length)&&n.every(n=>io(e[n],t[n]))}function ro(e,t){return _(t)&&S(e.length,t.length)&&e.every((n,r)=>io(e[r],t[r]))}function io(e,t){return _(e)?ro(e,t):y(e)?no(e,t):S(e,t)}const ao=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function oo(e){return ao.test(e)}function so(e,t){return`(${e} && ${t})`}function E(e,t){return`(${e} || ${t})`}function co(e){return`!(${e})`}function lo(e){return`Array.isArray(${e})`}function uo(e){return`typeof ${e} === "bigint"`}function fo(e){return`typeof ${e} === "boolean"`}function po(e){return`Number.isInteger(${e})`}function mo(e){return`${e} === null`}function ho(e){return`Number.isFinite(${e})`}function go(e){return so(_o(e),co(lo(e)))}function _o(e){return`typeof ${e} === "object" && ${e} !== null`}function vo(e){return`typeof ${e} === "string"`}function yo(e){return`typeof ${e} === "symbol"`}function bo(e){return`${e} === undefined`}function xo(e){return`typeof ${e} === "function"`}function So(e){return`Guard.IsConstructor(${e})`}function Co(e,t){return`${e} === ${t}`}function wo(e,t){return`${e} > ${t}`}function To(e,t){return`${e} < ${t}`}function Eo(e,t){return`${e} <= ${t}`}function Do(e,t){return`${e} >= ${t}`}function Oo(e,t){return`Guard.IsMinLength(${e}, ${t})`}function ko(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Ao(e,t,n,r){return S(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => (${r}))`:`${e}.every((${n[0]}, ${n[1]}) => (${n[1]} < ${t}) || (${r}))`}function jo(e,t,n){return`${e}.some((${t[0]}, ${t[1]}) => ${n})`}function Mo(e,t,n){return`((value) => { let result = false; value.forEach((${t[0]}, ${t[1]}) => { if (${n}) result = true }); return result })(${e})`}function No(e,t,n){return`${e}.reduce((result, ${t[0]}, ${t[1]}) => (${n}) ? ++result : result, 0)`}function Po(e){return`Object.entries(${e})`}function Fo(e){return`Object.getOwnPropertyNames(${e})`}function Io(e,t){return S(t,`"__proto__"`)||S(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function Lo(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function Ro(e){return`[${e.join(`, `)}]`}function zo(e,t){return`((${e.join(`, `)}) => ${t})`}function D(e,t){return`${e}(${t.join(`, `)})`}function Bo(e,t){return`new ${e}(${t.join(`, `)})`}function O(e,t){return`${e}${oo(t)?`.${t}`:`[${k(t)}]`}`}function k(e){if(!Ha(e))throw Error(`Unsupported Constant`);return b(e)?JSON.stringify(e):`${e}`}function Vo(e,t,n){return`(${e} ? ${t} : ${n})`}function Ho(e){return`{ ${e.join(`; `)}; }`}function Uo(e,t){return`const ${e} = ${t}`}function Wo(e,t){return`if(${e}) { ${t} }`}function Go(e){return`return ${e}`}function Ko(e){return S(e.length,0)?`true`:e.reduce((e,t)=>so(e,t))}function qo(e){return S(e.length,0)?`false`:e.reduce((e,t)=>E(e,t))}function Jo(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}function Yo(e){return e instanceof Boolean}function Xo(e){return e instanceof Number}function Zo(e){return e instanceof String}function Qo(e){return globalThis.ArrayBuffer.isView(e)}function $o(e){return e instanceof globalThis.RegExp}function es(e){return e instanceof globalThis.Date}function ts(e){return e instanceof globalThis.Set}function ns(e){return e instanceof globalThis.Map}var rs=Da;const is={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function as(){return is}function os(e){return as().immutableTypes?Object.freeze(e):e}function ss(e,t){return da.assign+=1,os({...e,...t})}function cs(e){return e}function ls(e){return w(e,`~kind`)||w(e,`~unsafe`)}function us(e){let t={};for(let n of T(e)){if(Za(n))continue;let r=Object.getOwnPropertyDescriptor(e,n);r.value=vs(r.value),S(r.enumerable,!0)?t[n]=r.value:Object.defineProperty(t,n,r)}return t}function ds(e){let t={};for(let n of T(e))Za(n)||(t[n]=vs(e[n]));for(let n of eo(e))t[n]=vs(e[n]);return t}function fs(e){return Va(e)?cs(e):ls(e)?us(e):ds(e)}function ps(e){return e.map(e=>vs(e))}function ms(e){return e.slice()}function hs(e){return new RegExp(e.source,e.flags)}function gs(e){return new Map(vs([...e.entries()]))}function _s(e){return new Set(vs([...e.values()]))}function vs(e){return Qo(e)?ms(e):$o(e)?hs(e):ns(e)?gs(e):ts(e)?_s(e):_(e)?ps(e):y(e)?fs(e):e}function ys(e){return da.clone+=1,vs(e)}function bs(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function xs(e,t){return{...e,...t}}function A(e,t,n={}){da.create+=1;let r=xs(t,n);return os(as().enumerableKind?xs(r,e):bs(r,e))}function Ss(e,t){da.discard+=1;let n={};for(let r of T(e)){if(t.includes(r))continue;let i=Object.getOwnPropertyDescriptor(e,r);i.value=ys(i.value),Object.defineProperty(n,r,i)}return os(n)}function j(e,t,n){da.update+=1;let r=as(),i=ys(e);for(let e of Object.keys(t))Object.defineProperty(i,e,{configurable:!0,writable:!0,enumerable:r.enumerableKind,value:t[e]});for(let e of Object.keys(n))Object.defineProperty(i,e,{configurable:!0,enumerable:!0,writable:!0,value:n[e]});return os(i)}function M(e,t){return y(e)&&w(e,`~kind`)&&S(e[`~kind`],t)}function Cs(e){return y(e)}function N(e,t,n){return A({"~kind":`Deferred`},{type:`deferred`,action:e,parameters:t,options:n},{})}function ws(e){return M(e,`Deferred`)}function Ts(e){return j(e,{"~readonly":!0},{})}function Es(e,t){return j(Ts(e),{},t)}function Ds(e,t,n,r){return Es(U(e,t,n),r)}function Os(e){return j(e,{"~optional":!0},{})}function ks(e,t){return j(Os(e),{},t)}function As(e,t,n,r){return ks(U(e,t,n),r)}function js(e,t){return A({"~kind":`Array`},{type:`array`,items:e},t)}function Ms(e){return M(e,`Array`)}function Ns(e){return Ss(e,[`~kind`,`type`,`items`])}function Ps(e,t,n={}){return A({"~kind":`Constructor`},{type:`constructor`,parameters:e,instanceType:t},n)}function Fs(e){return M(e,`Constructor`)}function Is(e){return Ss(e,[`~kind`,`type`,`parameters`,`instanceType`])}function Ls(e,t,n={}){return A({"~kind":`Function`},{type:`function`,parameters:e,returnType:t},n)}function Rs(e){return M(e,`Function`)}function zs(e){return Ss(e,[`~kind`,`type`,`parameters`,`returnType`])}function Bs(e,t){return A({"~kind":`Ref`},{$ref:e},t)}function Vs(e){return M(e,`Ref`)}function Hs(e,t){return A({"~kind":`Generic`},{type:`generic`,parameters:e,expression:t})}function Us(e){return M(e,`Generic`)}function Ws(e){return A({"~kind":`Any`},{},e)}function Gs(e){return M(e,`Any`)}function Ks(e){return A({"~kind":`Never`},{not:{}},e)}function qs(e){return M(e,`Never`)}function Js(e,t={}){return ks(e,t)}function Ys(e){return Cs(e)&&w(e,`~optional`)}function Xs(e){return T(e).filter(t=>!Ys(e[t]))}function Zs(e){return T(e)}function Qs(e){return to(e)}function P(e,t={}){let n=Xs(e);return A({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}function F(e){return M(e,`Object`)}function $s(e){return Ss(e,[`~kind`,`type`,`properties`,`required`])}function ec(e){return A({"~kind":`Unknown`},{},e)}function tc(e){return M(e,`Unknown`)}function nc(e,t,n){return A({"~kind":`Cyclic`},{$defs:T(e).reduce((t,n)=>({...t,[n]:j(e[n],{},{$id:n})}),{}),$ref:t},n)}function rc(e){return M(e,`Cyclic`)}function ic(e){return Pa(e)&&w(e,`~unsafe`)&&Na(e[`~unsafe`])}function ac(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}function oc(e){return M(e,`Infer`)}function sc(e,t,n,r={}){return A({"~kind":`Dependent`},{if:e,then:t,else:n},r)}function cc(e){return M(e,`Dependent`)}function lc(e){return Ss(e,[`~kind`,`if`,`then`,`else`])}function uc(e){return M(e,`Enum`)}function dc(e,t={}){return A({"~kind":`Intersect`},{allOf:e},t)}function I(e){return M(e,`Intersect`)}function fc(e){return Ss(e,[`~kind`,`allOf`])}let pc;function mc(){try{return gc(`null`)(),!0}catch{return!1}}function hc(){return x(pc)&&(pc=mc()),pc&&as().useAcceleration}function gc(...e){return new globalThis.Function(...e)}function _c(){throw Error(`Unreachable`)}var vc=/* @__PURE__ */ e({Hash:()=>qc,HashCode:()=>Kc});function yc(e){let t=/* @__PURE__ */ new Set,n=e;for(;n&&n!==Object.prototype;){for(let e of Reflect.ownKeys(n))e!==`constructor`&&typeof e!=`symbol`&&t.add(e);n=Object.getPrototypeOf(n)}return[...t]}function bc(e){return typeof e==`number`}var xc;(function(e){e[e.Array=0]=`Array`,e[e.BigInt=1]=`BigInt`,e[e.Boolean=2]=`Boolean`,e[e.Date=3]=`Date`,e[e.Constructor=4]=`Constructor`,e[e.Function=5]=`Function`,e[e.Null=6]=`Null`,e[e.Number=7]=`Number`,e[e.Object=8]=`Object`,e[e.RegExp=9]=`RegExp`,e[e.String=10]=`String`,e[e.Symbol=11]=`Symbol`,e[e.TypeArray=12]=`TypeArray`,e[e.Undefined=13]=`Undefined`})(xc||={});let Sc=BigInt(`14695981039346656037`);const[Cc,wc]=[BigInt(`1099511628211`),BigInt(`18446744073709551616`)],Tc=Array.from({length:256}).map((e,t)=>BigInt(t)),Ec=/* @__PURE__ */ new Float64Array(1),Dc=new DataView(Ec.buffer),Oc=new Uint8Array(Ec.buffer);function kc(e){Sc^=Tc[e],Sc=Sc*Cc%wc}function Ac(e){kc(xc.Array);for(let t of e)Gc(t)}function jc(e){kc(xc.BigInt),Dc.setBigInt64(0,e);for(let e of Oc)kc(e)}function Mc(e){kc(xc.Boolean),kc(+!!e)}function Nc(e){kc(xc.Constructor),Gc(e.toString())}function Pc(e){kc(xc.Date),Gc(e.getTime())}function Fc(e){kc(xc.Function),Gc(e.toString())}function Ic(e){kc(xc.Null)}function Lc(e){kc(xc.Number),Dc.setFloat64(0,e,!0);for(let e of Oc)kc(e)}function Rc(e){kc(xc.Object);for(let t of yc(e).sort())Gc(t),Gc(e[t])}function zc(e){kc(xc.RegExp),Vc(e.toString())}const Bc=new TextEncoder;function Vc(e){kc(xc.String);for(let t of Bc.encode(e))kc(t)}function Hc(e){kc(xc.Symbol),Gc(e.toString())}function Uc(e){kc(xc.TypeArray);let t=new Uint8Array(e.buffer);for(let e=0;e<t.length;e++)kc(t[e])}function Wc(e){return kc(xc.Undefined)}function Gc(e){return Qo(e)?Uc(e):es(e)?Pc(e):$o(e)?zc(e):Yo(e)?Mc(e.valueOf()):Zo(e)?Vc(e.valueOf()):Xo(e)?Lc(e.valueOf()):bc(e)?Lc(e):_(e)?Ac(e):ka(e)?Mc(e):Oa(e)?jc(e):Aa(e)?Nc(e):Na(e)?Ic(e):y(e)?Rc(e):b(e)?Vc(e):Fa(e)?Hc(e):x(e)?Wc(e):ja(e)?Fc(e):_c()}function Kc(e){return Sc=BigInt(`14695981039346656037`),Gc(e),Sc}function qc(e){return Kc(e).toString(16).padStart(16,`0`)}function Jc(e){switch(e.keyword){case`additionalProperties`:return`must not have additional properties`;case`anyOf`:return`must match a schema in anyOf`;case`boolean`:return`schema is false`;case`const`:return`must be equal to constant`;case`contains`:return`must contain at least 1 valid item`;case`dependencies`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`dependentRequired`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`enum`:return`must be equal to one of the allowed values`;case`exclusiveMaximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`exclusiveMinimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`format`:return`must match format "${e.params.format}"`;case`if`:return`must match "${e.params.failingKeyword}" schema`;case`maxItems`:return`must not have more than ${e.params.limit} items`;case`maxLength`:return`must not have more than ${e.params.limit} characters`;case`maxProperties`:return`must not have more than ${e.params.limit} properties`;case`maximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`minItems`:return`must not have fewer than ${e.params.limit} items`;case`minLength`:return`must not have fewer than ${e.params.limit} characters`;case`minProperties`:return`must not have fewer than ${e.params.limit} properties`;case`minimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`multipleOf`:return`must be multiple of ${e.params.multipleOf}`;case`not`:return`must not be valid`;case`oneOf`:return`must match exactly one schema in oneOf`;case`pattern`:return`must match pattern "${e.params.pattern}"`;case`propertyNames`:return`property names ${e.params.propertyNames.join(`, `)} are invalid`;case`required`:return`must have required properties ${e.params.requiredProperties.join(`, `)}`;case`type`:return typeof e.params.type==`string`?`must be ${e.params.type}`:`must be either ${e.params.type.join(` or `)}`;case`unevaluatedItems`:return`must not have unevaluated items`;case`unevaluatedProperties`:return`must not have unevaluated properties`;case`uniqueItems`:return`must not have duplicate items`;case`~refine`:return e.params.message;default:return`an unknown validation error occurred`}}let Yc=Jc;function Xc(){return Yc}function Zc(e){return Cs(e)&&w(e,`~codec`)&&y(e[`~codec`])&&w(e[`~codec`],`encode`)&&w(e[`~codec`],`decode`)}function Qc(e){return Cs(e)&&w(e,`~immutable`)}function $c(e,t={}){return Es(e,t)}function el(e){return Cs(e)&&w(e,`~readonly`)}function tl(e){return A({"~kind":`BigInt`},{type:`bigint`},e)}function nl(e){return M(e,`BigInt`)}function rl(e){return M(e,`Boolean`)}const il=`-?(?:0|[1-9][0-9]*)`;function al(e){return A({"~kind":`Integer`},{type:`integer`},e)}function ol(e){return M(e,`Integer`)}var sl=class extends Error{constructor(e){super(`Invalid Literal value`),Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}};function cl(e){return Oa(e)?`bigint`:ka(e)?`boolean`:v(e)?`number`:b(e)?`string`:(()=>{throw new sl(e)})()}function ll(e,t){return A({"~kind":`Literal`},{type:cl(e),const:e},t)}function ul(e){return Oa(e)||ka(e)||v(e)||b(e)}function dl(e){return hl(e)&&Oa(e.const)}function fl(e){return hl(e)&&ka(e.const)}function pl(e){return hl(e)&&v(e.const)}function ml(e){return hl(e)&&b(e.const)}function hl(e){return M(e,`Literal`)}function gl(e){return A({"~kind":`Null`},{type:`null`},e)}function _l(e){return M(e,`Null`)}const vl=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function yl(e){return A({"~kind":`Number`},{type:`number`},e)}function bl(e){return M(e,`Number`)}function xl(e){return A({"~kind":`Symbol`},{type:`symbol`},e)}function Sl(e){return M(e,`Symbol`)}function Cl(e){return A({"~kind":`String`},{type:`string`},e)}function wl(e){return M(e,`String`)}function Tl(e,t={}){return A({"~kind":`Union`},{anyOf:e},t)}function L(e){return M(e,`Union`)}function El(e){return Ss(e,[`~kind`,`anyOf`])}function Dl(e){let t=$d(e);return S(t.length,2)?t[0]:[]}function Ol(e){return!0}function kl(e){return C(e,(e,t)=>jl(e)?kl(t):!1,()=>!0)}function Al(e){return!S(e.length,0)&&kl(e)}function jl(e){return L(e)?Al(e.anyOf):hl(e)?Ol(e.const):!1}function Ml(e){return Al(e)}function Nl(e){return A({"~kind":`TemplateLiteral`},{type:`string`,pattern:e},{})}function Pl(e,t,n=[]){return C(e,(e,r)=>Pl(r,t,[...n,`${e}${t}`]),()=>n)}function Fl(e,t){return S(e.length,0)?[`${t}`]:Pl(e,t)}function Il(e,t,n=[]){return C(t,(t,r)=>Il(e,r,[...n,...Ll(e,t)]),()=>n)}function Ll(e,t){return L(t)?Il(e,t.anyOf):hl(t)?Fl(e,t.const):_c()}function Rl(e,t){return C(t,(t,n)=>Rl(Ll(e,t),n),()=>e)}function zl(e){return e.map(e=>ll(e))}function Bl(e){return Tl(zl(Rl([],e)))}function Vl(e){return S(e.length,0)?_c():S(e.length,1)&&hl(e[0])?e[0]:Bl(e)}function Hl(e){let t=Dl(e);return S(t.length,0)?Cl():Ml(t)?Vl(t):Nl(e)}function Ul(e){let t=Hl(e);return xf(t)?Cl():t}function Wl(e,t){return A({"~kind":`Record`},{type:`object`,patternProperties:{[e]:t}})}function Gl(e){return Wl(Zu,e)}function Kl(e){return P({true:e,false:e})}function ql(e,t={}){let[n,r,i]=[e,e.length,!1];return A({"~kind":`Tuple`},{type:`array`,additionalItems:i,items:n,minItems:r},t)}function Jl(e){return M(e,`Tuple`)}function Yl(e){return Ss(e,[`~kind`,`type`,`items`,`minItems`,`additionalItems`])}function Xl(e){return Ss(e,[`~readonly`])}function Zl(e,t){return j(Xl(e),{},t)}function Ql(e,t,n,r){return Zl(U(e,t,n),r)}function $l(e,t={}){return Zl(e,t)}function eu(e){return Ss(e,[`~optional`])}function tu(e,t){return j(eu(e),{},t)}function nu(e,t,n,r){return tu(U(e,t,n),r)}function ru(e,t={}){return tu(e,t)}function iu(e){return e.reduceRight((e,t,n)=>({[n]:t,...e}),{})}function au(e){return P(iu(e.items))}function ou(e){return F(e)||Jl(e)}function su(e,t){return el(e)?!!el(t):!1}function cu(e,t){return Ys(e)?!!Ys(t):!1}function lu(e,t){let n=su(e,t),r=cu(e,t),i=$l(ru(Du([e,t])));return n&&r?$c(Js(i)):n&&!r?$c(i):!n&&r?Js(i):i}function uu(e,t,n){return n in e?n in t?lu(e[n],t[n]):e[n]:n in t?t[n]:Ks()}function du(e,t){return[.../* @__PURE__ */ new Set([...T(e),...T(t)])].reduce((n,r)=>({...n,[r]:uu(e,t,r)}),{})}function fu(e){return F(e)?e.properties:Jl(e)?iu(e.items):{}}function pu(e,t){return P(du(fu(e),fu(t)))}function mu(e,t){let n=Sm(e,t);return S(n,2)?e:S(n,3)||S(n,0)?t:Ks()}function hu(e,t){let n=ou(e),r=ou(t);return n&&r?pu(e,t):n&&!r?e:!n&&r?t:mu(e,t)}function gu(e,t){return qs(e)||Gs(e)?e:tc(e)||qs(t)||Gs(t)?t:tc(t)?e:hu(e,t)}function _u(e,t){return L(e)||L(t)}function vu(e,t){let n=Au(e),r=Au(t);return _u(n,r)?Du([n,r]):gu(n,r)}function yu(e,t,n=[]){return C(t,(t,r)=>yu(e,r,[...n,vu(t,e)]),()=>S(n.length,0)?[e]:n)}function bu(e,t,n=[]){return C(e,(e,r)=>bu(r,t,[...n,...xu([e],t)]),()=>n)}function xu(e,t=[]){return C(e,(e,n)=>L(e)?xu(n,bu(e.anyOf,t)):xu(n,yu(e,t)),()=>t)}function Su(e,t){return Ef(xm({},e,t))?[]:[e]}function Cu(e,t,n=[]){return C(e,(e,r)=>Cu(r,t,[...n,...Su(e,t)]),()=>n)}function wu(e,t){let n=Au(e);return ku(Cu(L(n)?n.anyOf:[n],t))}function Tu(e,t,n){return ku([Du([e,t]),wu(n,e)])}function Eu(e,t=[]){return C(e,(e,n)=>Eu(n,[...t,ll(e)]),()=>ku(t))}function Du(e){return ku(Em(xu(e)))}function Ou(e){return Au(Ul(e))}function ku(e){return ju(Em(e))}function Au(e){return cc(e)?Tu(e.if,e.then,e.else):uc(e)?Eu(e.enum):I(e)?Du(e.allOf):xf(e)?Ou(e.pattern):L(e)?ku(e.anyOf):e}function ju(e){return S(e.length,1)?e[0]:S(e.length,0)?Ks():Tl(e)}function Mu(e,t){return Ku(Eu(e),t)}function Nu(e,t){return Wl(Yu,t)}function Pu(e,t){return Ku(Du(e),t)}function Fu(e,t){return b(e)||v(e)?P({[e]:t}):S(e,!1)?P({false:t}):S(e,!0)?P({true:t}):P({})}function Iu(e,t){return Wl(Xu,t)}function Lu(e,t){return w(e,`pattern`)&&(b(e.pattern)||e.pattern instanceof RegExp)?Wl(e.pattern.toString(),t):Wl(Zu,t)}function Ru(e,t){return Ml(Dl(e))?Ku(Ou(e),t):Wl(e,t)}function zu(e){return L(e)?Bu(e.anyOf):[e]}function Bu(e,t=[]){return C(e,(e,n)=>Bu(n,[...t,...zu(e)]),()=>t)}function Vu(e){return e.some(e=>wl(e)||bl(e)||ol(e))}function Hu(e,t){return S(Vu(e),!0)?Wl(Zu,t):void 0}function Uu(e,t){return e.reduce((e,n)=>hl(n)&&(b(n.const)||v(n.const))?{...e,[n.const]:t}:e,{})}function Wu(e,t){return P(Uu(e,t))}function Gu(e,t){let n=Bu(e),r=Hu(n,t);return Cs(r)?r:Wu(n,t)}function Ku(e,t){return Gs(e)?Gl(t):rl(e)?Kl(t):uc(e)?Mu(e.enum,t):ol(e)?Nu(e,t):I(e)?Pu(e.allOf,t):hl(e)?Fu(e.const,t):bl(e)?Iu(e,t):L(e)?Gu(e.anyOf,t):wl(e)?Lu(e,t):xf(e)?Ru(e.pattern,t):P({})}function qu(e,t,n){return H([e])?j(Ku(e,t),{},n):Qu(e,t,n)}function Ju(e,t,n,r,i){return qu(U(e,t,n),U(e,t,r),i)}const Yu=`^${il}$`,Xu=`^${vl}$`,Zu=`^.*$`;function Qu(e,t,n={}){return N(`Record`,[e,t],n)}function $u(e,t,n={}){return qu(e,t,n)}function ed(e,t){return Wl(e,t)}function td(e){return S(e,Zu)?Cl():S(e,Yu)?al():S(e,Xu)?yl():Hl(e)}function nd(e){return T(e.patternProperties)[0]}function rd(e){return td(nd(e))}function id(e){return e.patternProperties[nd(e)]}function ad(e){return M(e,`Record`)}function od(e){return A({"~kind":`Rest`},{type:`rest`,items:e},{})}function sd(e){return M(e,`Rest`)}function cd(e){return M(e,`This`)}function ld(e){return A({"~kind":`Undefined`},{type:`undefined`},e)}function ud(e){return M(e,`Undefined`)}function dd(e){return M(e,`Void`)}function fd(e){return tl()}function pd(e){return Cl()}function md(e){return yl()}function hd(e){return al()}function gd(e){return Ks()}function _d(e){return ll(e)}function vd(e){return e}function yd(e){return Tl(e[1])}function bd(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function xd(e){return[e[0],...e[1]]}function Sd(e){return e}function Cd(e){return e[1]}function wd(e){return S(e.length,2)}function Td(e,t,n){return wd(e)?t(e[0],e[1]):n()}function Ed(e,t){return S(t.indexOf(e),0)?[e,t.slice(e.length)]:[]}function Dd(e,t){for(let n=0;n<e.length;n++){let r=Ed(e[n],t);if(wd(r))return r}return[]}function Od(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}const kd=[...Od(97,122),...Od(65,90)],Ad=[`0`,...Od(49,57)];function jd(e){let t=e.indexOf(`*/`);return S(t,-1)?``:e.slice(t+2)}function Md(e){let t=e.indexOf(`
|
|
967
|
+
}`,returnByValue:!0})).result?.value}async resolveNodeCenter(e){let t=await this.resolveNodeObjectId(e),n=await this.nodeBox(t);if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async boundingBox(e){await this.send(`DOM.enable`);let t=(await this.send(`DOM.getDocument`,{depth:0})).root.nodeId,n;try{n=(await this.send(`DOM.querySelector`,{nodeId:t,selector:e})).nodeId}catch{return null}if(!n)return null;let r=(await this.send(`DOM.getBoxModel`,{nodeId:n})).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function vi(e,t){if(t.push({frameId:e.frame.id,parentFrameId:e.frame.parentId,url:e.frame.url,name:e.frame.name??``,securityOrigin:e.frame.securityOrigin}),Array.isArray(e.childFrames))for(let n of e.childFrames)vi(n,t)}function yi(e){let t=e.exceptionDetails;return t?t.exception?.description??t.text:null}function bi(e,t){let n=yi(e);if(n!==null)throw Error(`${t}: ${n}`);return e.result?.value}function xi(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Cannot find context with specified id`)||t.includes(`Execution context was destroyed`)}function Si(e){let t={role:De(e.role,`unknown`),name:De(e.name)},n=De(e.value);n!==``&&(t.value=n);let r=De(e.description);return r!==``&&(t.description=r),typeof e.ref==`string`&&/^e[0-9]+$/.test(e.ref)&&(t.ref=e.ref),typeof e.refSeq==`number`&&Number.isSafeInteger(e.refSeq)&&(t.refSeq=e.refSeq),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>Si(e)).filter(e=>e.role!==`unknown`)),t}function Ci(e){let t=e??{queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0};return{queueDepth:t.queueDepth,totalWaitMs:t.tabWaitMs+t.bridgeWaitMs,tabWaitMs:t.tabWaitMs,bridgeWaitMs:t.bridgeWaitMs,acquisitions:t.acquisitions}}var wi=class{tabLocks=/* @__PURE__ */ new Map;bridgeLock=Promise.resolve();bridgeHold=null;bridgeWaiters=0;tabLockStats=/* @__PURE__ */ new Map;getStats(e){if(e!==void 0)return Ci(this.tabLockStats.get(e));let t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0};for(let e of this.tabLockStats.values())t.queueDepth+=e.queueDepth,t.tabWaitMs+=e.tabWaitMs,t.bridgeWaitMs+=e.bridgeWaitMs,t.acquisitions+=e.acquisitions;return Ci(t)}countersFor(e){let t=this.tabLockStats.get(e);return t||(t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0},this.tabLockStats.set(e,t)),t}liveOwner(){return this.bridgeHold?.owner}reentrantOwner(e){let t=this.bridgeHold;if(t&&e!==null&&t.targetId===e)return t.owner}async holdTabLock(e,t,n){Jr(t,`starting a command on tab ${e}`);let r=this.countersFor(e);r.queueDepth+=1;let i;try{i=await this.acquireTabLock(e,r,t)}catch(e){throw--r.queueDepth,e}try{return await n(r)}finally{--r.queueDepth,i()}}async acquireTabLock(e,t,n){let r,i=new Promise(e=>{r=e}),a=this.tabLocks.get(e);this.tabLocks.set(e,i);let o=()=>{this.tabLocks.get(e)===i&&this.tabLocks.delete(e),r()};if(a!=null){let r=Date.now();try{await Zr(a,n,`queued for the lock on tab ${e}`)}catch(e){throw t.tabWaitMs+=Date.now()-r,a.then(o,o),e}t.tabWaitMs+=Date.now()-r}return o}async acquireBridgeLock(e){if(e?.owner!==void 0&&this.bridgeHold?.owner===e.owner)return()=>void 0;let t,n=new Promise(e=>{t=e}),r=this.bridgeLock,i=this.bridgeHold!==null||this.bridgeWaiters>0;if(this.bridgeLock=n,i){this.bridgeWaiters+=1;let t=Date.now();try{await r}finally{--this.bridgeWaiters}e?.counters&&(e.counters.bridgeWaitMs+=Date.now()-t)}let a={release:t,owner:Symbol(`bridge-hold`),targetId:e?.targetId??null};this.bridgeHold=a;let o=!1;return()=>{o||(o=!0,this.bridgeHold===a&&(this.bridgeHold=null),t())}}async runGlobal(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e),targetId:e});try{return await t()}finally{n()}}},Ti=class{overrides=/* @__PURE__ */ new Map;get(e){return this.overrides.get(e)}set(e,t){this.overrides.set(e,t)}delete(e){this.overrides.delete(e)}has(e){return this.overrides.has(e)}get size(){return this.overrides.size}};const Ei=h(`browser-api`),Di=[`Session with given id not found`,`Target closed`,`No session with given id`,`No tab attached for sessionId`];var Oi=class extends Error{};function ki(e){let t=e instanceof Error?e.message:String(e);return Di.some(e=>t.includes(e))}var Ai=class{inner;onApplied;route;onStateChange;constructor(e,t,n){this.inner=e,this.onApplied=t,this.route=n,e.onStateChange&&(this.onStateChange=t=>e.onStateChange(t))}get state(){return this.inner.state}get superseded(){return this.inner.superseded}get isExtensionBridge(){return this.inner.isExtensionBridge}connect(e){return this.inner.connect(e)}disconnect(){this.inner.disconnect()}async send(e,t,n,r){let i=await this.route(this.inner,e,t,n,()=>this.forward(e,t,n,r));return n&&this.onApplied(n),i}forward(e,t,n,r){return r===void 0?this.inner.send(e,t,n):this.inner.send(e,t,n,r)}on(e,t){this.inner.on(e,t)}off(e,t){this.inner.off(e,t)}once(e,t){return this.inner.once(e,t)}},ji=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;frames=new Qr;sessions=new ai(32,(e,t)=>{Ei.debug(`Evicting least-recently-used CDP session`,{targetId:e}),this.detachSession(e,t)});_listenedTransports=/* @__PURE__ */ new Set;_sessionReplacedSubs=/* @__PURE__ */ new Map;locks=new wi;viewports=new Ti;hiddenPages=null;hiddenPagesLoad=null;hiddenPagePins=/* @__PURE__ */ new Map;facadeSessions=/* @__PURE__ */ new Map;connection=new Kr;_onSessionChange;handleJavaScriptDialogOpening=e=>{this.dismissJavaScriptDialog(e)};async dismissJavaScriptDialog(e){let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.transportForSession(t).send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),Ei.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){Ei.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}handleExecutionContextCreated=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this.frames.for(t,`main`).set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.executionContextId;if(typeof n!=`number`)return;let r=this.frames.peek(t,`main`);if(r)for(let[e,t]of r)t===n&&r.delete(e)};handleExecutionContextsCleared=e=>{let t=this.eventSessionId(e);t&&this.frames.peek(t,`main`)?.clear()};eventSessionId(e){let t=e.sessionId;return typeof t==`string`?t:this.sessionId}handleDetachedFromTarget=e=>{let t=e.sessionId;if(typeof t!=`string`)return;this.hiddenPages?.forgetSession(t),this.facadeSessions.delete(t);let n=this.sessions.findBySessionId(t);n&&this.forgetSession(n[0],n[1])};handleTargetDestroyed=e=>{let t=e.targetId;if(typeof t!=`string`)return;let n=this.sessions.findByTargetOrLocalId(t)[0];n&&this.forgetSession(n[0],n[1])};constructor(e){this.client=e??new Pr,this.localClient=this.client,this.addTransportListeners(this.client)}getTransport(){return this.accountedTransportFor(this.client)}getUnderlyingTransport(){return this.client}_accountedTransports=/* @__PURE__ */ new WeakMap;accountedTransportFor(e){if(e instanceof Ai)return e;let t=this._accountedTransports.get(e);return t||(t=new Ai(e,e=>this.noteApplied(e),(e,t,n,r,i)=>this.routeSend(e,t,n,r,i)),this._accountedTransports.set(e,t)),t}noteApplied(e){this.sessions.noteApplied(e)}createHarRecorder(e,t){return new ei(t,e)}setSessionChangeCallback(e){this._onSessionChange=e}onSessionReplaced(e,t){let n=this._sessionReplacedSubs.get(e);return n||(n=/* @__PURE__ */ new Set,this._sessionReplacedSubs.set(e,n)),n.add(t),()=>{let n=this._sessionReplacedSubs.get(e);n&&(n.delete(t),n.size===0&&this._sessionReplacedSubs.delete(e))}}getSessionId(){return this.sessionId}getAttachedTargetId(){return this.attachedTargetId}async withTab(e,t,n){let r=n?.signal;return this.locks.holdTabLock(e,r,async n=>{let i=this.sessions.pin(e);try{return n.acquisitions+=1,await this.runOnTab(e,t,r)}finally{i()}})}async runOnTab(e,t,n){try{return await this.attemptOnTab(e,t,n)}catch(r){if(r instanceof Oi||!ki(r))throw r;return Ei.warn(`Stale CDP session — re-attaching and retrying once`,{targetId:e,error:r instanceof Error?r.message:String(r)}),this.invalidateSession(e),await this.attemptOnTab(e,t,n)}}async attemptOnTab(e,t,n){let r=await this.attachHandle(e,this.locks.reentrantOwner(e),n);Jr(n,`about to run a command on tab ${e}`);let i=r.sessionId,a=this.sessions.appliedCount(i);this.hiddenPagePins.set(e,(this.hiddenPagePins.get(e)??0)+1);try{return await t(r)}catch(t){if(!ki(t))throw t;let n=this.sessions.appliedCount(i)-a;if(n===0)throw t;this.invalidateSession(e);let r=t instanceof Error?t.message:String(t);throw Ei.warn(`CDP session reset mid-command — not replaying`,{targetId:e,applied:n,reason:r}),new Oi(`The CDP session for tab ${e} was reset mid-command, after ${n} command(s) had already been applied, so the outcome is unknown. The tab has been re-armed: check the page state before repeating this command. (underlying error: ${r})`)}finally{await this.unpinHiddenPage(e)}}async unpinHiddenPage(e){let t=(this.hiddenPagePins.get(e)??1)-1;if(t>0){this.hiddenPagePins.set(e,t);return}this.hiddenPagePins.delete(e),await this.hiddenPages?.unpinned(e)}async routeSend(e,t,n,r,i){if(t===`Target.attachToTarget`){let e=await i(),t=e.sessionId,r=n?.targetId;return typeof t==`string`&&typeof r==`string`&&this.facadeSessions.set(t,r),e}if(r===void 0||t!==`Emulation.setFocusEmulationEnabled`&&ri(t,n)===null)return i();let a=this.hiddenPages??await this.loadHiddenPages();return a?a.route(e,t,n,r,i):i()}loadHiddenPages(){return this.hiddenPagesLoad??=import(`./hidden-page-input-01CnfmMB.js`).then(({HiddenPageInput:e})=>(this.hiddenPages=new e({targetOf:e=>this.sessions.findBySessionId(e)?.[0]??this.facadeSessions.get(e),pinned:e=>this.hiddenPagePins.has(e),isGone:ki}),this.hiddenPages),e=>(Ei.warn(`Hidden-page input gate failed to load; pointer input goes out as is`,{error:e instanceof Error?e.message:String(e)}),this.hiddenPagesLoad=null,null)),this.hiddenPagesLoad}async attachHandle(e,t,n){let r=await this.attachToPageOwned(e,t,n),i=this.sessions.get(e);return new _i(this,e,r,this.accountedTransportFor(i?.transport??this.client),n)}handleFor(e,t){return new _i(this,e,t.sessionId,this.accountedTransportFor(t.transport))}getTabLockStats(e){return this.locks.getStats(e)}async runGlobal(e,t){return this.locks.runGlobal(e,t)}viewportOverride(e){return this.viewports.get(e)}recordViewportOverride(e,t){this.viewports.set(e,t)}frameContexts(e,t){return this.frames.for(e,t)}dropFrameContexts(e){this.frames.drop(e)}async reapplyViewportOverride(e,t){let n=this.viewports.get(e);if(n)try{await this.handleFor(e,t).applyViewportOverride(n)}catch(t){Ei.warn(`Failed to re-apply viewport override on re-attach`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:e.kind,capabilities:e.capabilities}));return[...e,...r]}async connect(e){await this.connection.connect(this.client,e)}async reconnectIfNeeded(){await this.ensureConnected(),this.client!==this.localClient&&await this.ensureLocalConnected()}primeConnectOptions(e){this.connection.primeConnectOptions(e)}setCdpSupersededHandler(e){this.connection.setSupersededHandler(e)}setCdpBridgeRejectedHandler(e){this.connection.setBridgeRejectedHandler(e)}setCdpConnectFailureClassifier(e){this.connection.setConnectFailureClassifier(e)}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async openWindow(e,t={}){await this.ensureConnected(),await this.ensureLocalConnected(),Pi(t);let n=t.focus!==!1,r={url:e||`about:blank`,newWindow:!0,background:!n};t.decorated===!1&&(r.decorated=!1);let i=t.state;i&&i!==`normal`?r.windowState=i:(t.width!==void 0&&(r.width=t.width),t.height!==void 0&&(r.height=t.height),t.left!==void 0&&(r.left=t.left),t.top!==void 0&&(r.top=t.top),i&&(r.windowState=i));let a=(await this.localClient.send(`Target.createTarget`,r)).targetId;if(typeof a!=`string`||!a)throw Error(`Target.createTarget did not return a usable targetId`);return a}async getWindowBounds(e){await this.ensureConnected();let t=Ii((await(await this.transportForWindowOps(e)).send(`Browser.getWindowForTarget`,{targetId:Ni(e)})).bounds),n=await this.readDevicePixelRatio(e);return{...t,dpr:n}}async setWindowBounds(e,t){await this.ensureConnected(),Pi(t);let n=await this.transportForWindowOps(e),r=Ni(e),i=await n.send(`Browser.getWindowForTarget`,{targetId:r}),a=i.windowId;if(typeof a!=`number`)throw Error(`Browser.getWindowForTarget did not return a windowId`);let o=Ii(i.bounds),s=t.state;(t.left!==void 0||t.top!==void 0||t.width!==void 0||t.height!==void 0)&&o.state!==`normal`&&await n.send(`Browser.setWindowBounds`,{windowId:a,bounds:{windowState:`normal`}});let c={};s&&s!==`normal`?c.windowState=s:(t.left!==void 0&&(c.left=t.left),t.top!==void 0&&(c.top=t.top),t.width!==void 0&&(c.width=t.width),t.height!==void 0&&(c.height=t.height),s&&(c.windowState=s)),await n.send(`Browser.setWindowBounds`,{windowId:a,bounds:c});let l=Ii((await n.send(`Browser.getWindowBounds`,{windowId:a})).bounds),u=await this.readDevicePixelRatio(e);return{...l,dpr:u}}async readDevicePixelRatio(e){try{let t=await this.withTab(e,e=>e.evaluate(`window.devicePixelRatio`,{awaitPromise:!1,returnByValue:!0}));return typeof t==`number`&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}async transportForWindowOps(e){if(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);return this.trayTargetProvider.createRemoteTransport(n,r)}return await this.ensureLocalConnected(),this.localClient}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.viewports.delete(e),await this.dropSession(e),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let e=this.trayTargetProvider.createRemoteTransport(n,r);try{await e.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}return}}await this.localClient.send(`Target.closeTarget`,{targetId:e})}disconnect(){this.clearSessions(),this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){return this.attachToPageOwned(e,this.locks.reentrantOwner(e))}async attachToPageOwned(e,t,n){let r=await this.locks.acquireBridgeLock({owner:t,targetId:e,counters:this.locks.countersFor(e)});try{await this.ensureConnected();let t=this.sessions.get(e);return t?(this.activateSession(e,t),t.sessionId):await(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)?this.attachRemoteTarget(e,n):this.attachLocalTarget(e,n))}finally{r()}}async selectTab(e){await this.withTab(e,async()=>void 0)}async bringTabToFront(e){await this.withTab(e,e=>e.bringToFront())}async attachRemoteTarget(e,t){let n=e.indexOf(`:`),r=e.substring(0,n),i=e.substring(n+1),a=this.trayTargetProvider?.createRemoteTransport?.(r,i);if(!a)throw Error(`No remote transport for target ${e}`);Jr(t,`about to attach to tray tab ${e}`);let o={sessionId:(await a.send(`Target.attachToTarget`,{targetId:i,flatten:!0})).sessionId,transport:a,remote:{runtimeId:r,localTargetId:i}};return this.rememberSession(e,o),this.activateSession(e,o),Jr(t,`about to enable Page on tray tab ${e}`),await a.send(`Page.enable`,{},o.sessionId),Jr(t,`about to restore the viewport of tray tab ${e}`),await this.reapplyViewportOverride(e,o),this.notifySessionChange(e,o),o.sessionId}async attachLocalTarget(e,t){this.useLocalTransport(),await this.ensureLocalConnected(),Jr(t,`about to attach to tab ${e}`);let n={sessionId:(await this.localClient.send(`Target.attachToTarget`,{targetId:e,flatten:!0})).sessionId,transport:this.localClient};return this.rememberSession(e,n),this.activateSession(e,n),Jr(t,`about to enable Page on tab ${e}`),await this.localClient.send(`Page.enable`,{},n.sessionId),Jr(t,`about to restore the viewport of tab ${e}`),await this.reapplyViewportOverride(e,n),this.notifySessionChange(e,n),n.sessionId}async detach(){let e=this.attachedTargetId;e&&(await this.dropSession(e),this.useLocalTransport())}async wakeCapture(e,t){let n=await this.locks.acquireBridgeLock({owner:this.locks.reentrantOwner(e.targetId),targetId:e.targetId});try{return await this.wakeCaptureLocked(e,t,this.locks.liveOwner())}finally{n()}}async wakeCaptureLocked(e,t,n){let r=e.targetId,i=await this.findFocusedLocalPage(r,n).catch(()=>null),a=await this.attachHandle(r,n);try{return await a.send(`Page.bringToFront`),await a.send(`Page.captureScreenshot`,t)}finally{if(i)try{await(await this.attachHandle(i,n)).send(`Page.bringToFront`),await this.attachToPageOwned(r,n)}catch{}}}async findFocusedLocalPage(e,t){let n=await this.listPages();for(let r of n)if(r.targetId&&r.targetId!==e&&!r.targetId.includes(`:`))try{if(await(await this.attachHandle(r.targetId,t)).evaluate(`document.hasFocus()`)===!0)return r.targetId}catch{}return null}async ensureLocalConnected(){await this.connection.ensureLocalConnected(this.localClient)}async ensureConnected(){await this.connection.ensureConnected({client:this.client,restoreLocalAfterRemoteDrop:()=>{this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null)},clearSessionsForTransport:e=>this.clearSessionsForTransport(e),getClient:()=>this.client})}transportForSession(e){return this.sessions.findBySessionId(e)?.[1].transport??this.client}addTransportListeners(e){this._listenedTransports.has(e)||(this._listenedTransports.add(e),e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.on(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.on(`Target.targetDestroyed`,this.handleTargetDestroyed))}releaseLifecycleTransport(e){e!==this.localClient&&this._listenedTransports.has(e)&&(this.sessions.anyOnTransport(e)||(this._listenedTransports.delete(e),e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.off(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.off(`Target.targetDestroyed`,this.handleTargetDestroyed)))}setClient(e){this.addTransportListeners(e),this.client=e}useLocalTransport(){let e=this.remoteTargetInfo;this.remoteTargetInfo=null,this.setClient(this.localClient),e&&(this.sessions.anyMatchingRemote(e.runtimeId,e.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.runtimeId,e.localTargetId))}rememberSession(e,t){this.addTransportListeners(t.transport),this.sessions.remember(e,t)}activateSession(e,t){t.remote?(this.setClient(t.transport),this.remoteTargetInfo={...t.remote}):this.client!==t.transport&&this.useLocalTransport(),this.sessionId=t.sessionId,this.attachedTargetId=e,this.sessions.touch(e,t)}notifySessionChange(e,t){let n=this.accountedTransportFor(t.transport);this._onSessionChange?.(t.sessionId,n,e);let r=this._sessionReplacedSubs.get(e);if(r)for(let i of[...r])try{i(t.sessionId,n,e)}catch(t){Ei.warn(`session-replaced subscriber threw`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}forgetSession(e,t){this.unregisterSession(e),this.disposeSessionTransport(t)}unregisterSession(e){let t=this.sessions.get(e);t&&this.dropFrameContexts(t.sessionId),this.sessions.delete(e),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disposeSessionTransport(e){this.releaseLifecycleTransport(e.transport),e.remote&&(this.sessions.anyMatchingRemote(e.remote.runtimeId,e.remote.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.remote.runtimeId,e.remote.localTargetId))}async detachSession(e,t){this.unregisterSession(e);try{await t.transport.send(`Target.detachFromTarget`,{sessionId:t.sessionId})}catch{}finally{this.disposeSessionTransport(t)}}async dropSession(e){let t=this.sessions.get(e);if(!t){this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null);return}await this.detachSession(e,t)}invalidateSession(e){let t=this.sessions.get(e);t&&this.forgetSession(e,t)}clearSessionsForTransport(e){for(let[t,n]of this.sessions.snapshot())n.transport===e&&this.forgetSession(t,n)}clearSessions(){for(let[e,t]of this.sessions.snapshot())this.forgetSession(e,t);this.sessions.clear(),this.sessionId=null,this.attachedTargetId=null}};const Mi=/* @__PURE__ */ new Set([`normal`,`minimized`,`maximized`,`fullscreen`]);function Ni(e){let t=e.indexOf(`:`);return t>=0?e.substring(t+1):e}function Pi(e){let t=e.state;if(t&&t!==`normal`){if(!Mi.has(t))throw Error(`window state must be one of ${[...Mi].join(`|`)} (got ${JSON.stringify(t)})`);if(e.left!==void 0||e.top!==void 0||e.width!==void 0||e.height!==void 0)throw Error(`window state '${t}' cannot be combined with left/top/width/height (chrome.windows + CDP both reject the mix)`)}}function Fi(e){return typeof e==`object`&&!!e}function Ii(e){let t=Fi(e)?e:{},n=t.windowState??t.state,r=typeof n==`string`&&Mi.has(n)?n:`normal`;return{left:Li(t.left,0),top:Li(t.top,0),width:Li(t.width,0),height:Li(t.height,0),state:r}}function Li(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}const Ri=h(`panel-rpc-cdp`);var zi=class{getPanelRpc;runtimeId;localTargetId;timeoutMs;eventListeners=/* @__PURE__ */ new Map;pendingOnce=/* @__PURE__ */ new Set;key;_state=`connected`;pushRegistered=!1;constructor(e,t,n,r=3e4){this.getPanelRpc=e,this.runtimeId=t,this.localTargetId=n,this.timeoutMs=r,this.key=`${t}:${n}`}get state(){return this._state}async connect(){}disconnect(){this._state=`disconnected`;for(let e of this.pendingOnce)clearTimeout(e.timer),e.reject(/* @__PURE__ */ Error(`Transport disconnected`));this.pendingOnce.clear();let e=this.getPanelRpc();e&&(this.pushRegistered&&=(e.unregisterPushTarget(this.key),!1),e.call(`remote-cdp-detach`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId}).catch(e=>{Ri.error(`remote-cdp detach failed (page-side session may leak)`,{key:this.key,error:e instanceof Error?e.message:String(e)})})),this.eventListeners.clear()}async send(e,t,n,r){if(this._state===`disconnected`)throw Error(`Transport disconnected`);let i=this.getPanelRpc();if(!i)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let a=r??this.timeoutMs,o=Math.max(a,ke)+5e3;return i.call(`remote-cdp-send`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,method:e,params:t,sessionId:n,timeout:a},{timeoutMs:o})}on(e,t){let n=this.eventListeners.get(e),r=!n||n.size===0;n||(n=/* @__PURE__ */ new Set,this.eventListeners.set(e,n)),n.add(t),r&&this.subscribe(e)}off(e,t){let n=this.eventListeners.get(e);n&&(n.delete(t),n.size===0&&(this.eventListeners.delete(e),this.unsubscribe(e)))}once(e,t){return new Promise((n,r)=>{let i=t??this.timeoutMs,a={reject:r,timer:void 0},o=()=>{clearTimeout(a.timer),this.pendingOnce.delete(a),this.off(e,s)};a.timer=setTimeout(()=>{o(),r(/* @__PURE__ */ Error(`Remote CDP event timed out: ${e}`))},i);let s=e=>{o(),n(e)};this.pendingOnce.add(a),this.on(e,s)})}handleEvent(e,t){let n=this.eventListeners.get(e);if(n)for(let e of[...n])e(t)}ensurePushRegistered(e){this.pushRegistered||=(e.registerPushTarget(this.key,e=>this.handleEvent(e.method,e.params??{})),!0)}subscribe(e){let t=this.getPanelRpc();if(!t){Ri.error(`remote-cdp subscribe skipped: no panel-RPC client`,{key:this.key,event:e});return}this.ensurePushRegistered(t),t.call(`remote-cdp-subscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Ri.error(`remote-cdp subscribe failed; events for this transport will not arrive`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}unsubscribe(e){let t=this.getPanelRpc();t&&t.call(`remote-cdp-unsubscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Ri.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function Bi(e){let t=/* @__PURE__ */ new Map,n=(e,t)=>`${e}:${t}`;return{getTargets(){return[]},createRemoteTransport(r,i){let a=n(r,i),o=t.get(a);return o||(o=new zi(e,r,i),t.set(a,o)),o},removeRemoteTransport(e,r){let i=n(e,r),a=t.get(i);a&&(a.disconnect(),t.delete(i))},async openRemoteTab(t,n){let r=e();if(!r)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let{targetId:i}=await r.call(`remote-open-tab`,{runtimeId:t,url:n});return i}}}function Vi(e){return`slicc_feature_flags_remote:${e}`}let Hi=null;function Ui(e,t){let n=Gi(t);Hi=e,Ne(e,Ki(n,e)??{})}function Wi(e,t){if(!Hi||e!==void 0&&e!==Vi(Hi))return!1;let n=Gi(t);return je(Hi,Ki(n,Hi)??{}),!0}function Gi(e){if(e!==void 0)return e;try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function Ki(e,t){try{let n=e?.getItem(Vi(t));return n?qi(JSON.parse(n)):null}catch{return null}}function qi(e){return!Ji(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function Ji(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Yi=h(`stale-asset`),Xi=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Zi(e){return Xi.test(e)}let Qi=null;function $i(e){if(!e){Qi=null;return}Qi=e}function ea(e=!1){if(!Qi||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Qi,replayTurn:e})}finally{t.close()}}function ta(e){Zi(e instanceof Error?e.message:String(e))&&ea()}function na(e,t){return!e||e===t?!1:(Yi.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),ea(),!0)}let ra=null;function ia(e){ra=e??null}function aa(){return ra}var oa=class{_state=`disconnected`;nextCommandId=1;listeners=/* @__PURE__ */ new Map;pendingCommands=new Ar;unsubscribe=null;stateListeners=/* @__PURE__ */ new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;opts;label;constructor(e){this.opts=e,this.label=e.label??`CDP transport`}get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);this.unsubscribe||=this.opts.subscribeIncoming(e=>this.handleIncoming(e)),this._state=`connected`,this.notifyState(`connected`)}disconnect(){this.unsubscribe?.(),this.unsubscribe=null;let e=`${this.label} disconnected`;this.pendingCommands.rejectAll(e),this.listeners.clear(),this._state=`disconnected`,this.notifyState(`disconnected`,e)}async send(e,t,n,r=3e4){if(this._state!==`connected`)throw Error(`${this.label} is not connected`);let i=this.nextCommandId++,a=this.opts.buildCommandEnvelope(i,e,t,n),o=this.pendingCommands.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.opts.sendEnvelope(a).catch(e=>{this.pendingCommands.reject(i,/* @__PURE__ */ Error(`Failed to send CDP command: ${e instanceof Error?e.message:String(e)}`))}),o}on(e,t){let n=this.listeners.get(e),r=!n;n||(n=/* @__PURE__ */ new Set,this.listeners.set(e,n)),n.add(t),r&&this.opts.onSubscribeEvent?.(e)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&(this.listeners.delete(e),this.opts.onUnsubscribeEvent?.(e)))}once(e,t=3e4){return jr(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleIncoming(e){let t=this.opts.parseControl?.(e)??null;if(t){this.handleControl(t);return}let n=this.opts.parseResponse(e);if(n){this.handleResponse(n);return}let r=this.opts.parseEvent(e);r&&this.handleEvent(r)}handleControl(e){if(e.kind===`ready`){this.opts.onUpstreamReady?.();return}let t=e.reason??`upstream connection reset`,n=`${this.label}: upstream CDP connection was reset (${t})`;this.pendingCommands.rejectAll(n),this._state=`disconnected`,this.opts.onUpstreamReset?.(t),this.notifyState(`disconnected`,n)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}handleResponse(e){if(!this.pendingCommands.has(e.id)){this.opts.onUnknownResponseId?.(e.id);return}e.error?this.pendingCommands.reject(e.id,Error(e.error)):this.pendingCommands.resolve(e.id,e.result??{})}handleEvent(e){let t=this.listeners.get(e.method);if(t)for(let n of t)try{n(e.params??{})}catch(t){this.opts.onListenerError?.(e.method,t)}}};function sa(e){let t=!1,n=()=>{t||(t=!0,typeof e.start==`function`&&e.start())};return{onMessage:t=>{let r=e=>{t(e.data)};return e.addEventListener(`message`,r),n(),()=>{e.removeEventListener(`message`,r)}},send:(t,n)=>{n&&n.length>0?e.postMessage(t,n):e.postMessage(t)}}}function ca(e){let t=sa(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var la=class extends oa{constructor(e){let t=sa(e),n=0;super({label:`WorkerCdpProxy`,buildCommandEnvelope:(e,t,r,i)=>({type:`cdp-cmd`,id:e,method:t,params:r,sessionId:i,gen:n}),sendEnvelope:e=>(t.send(e),Promise.resolve()),subscribeIncoming:e=>t.onMessage(e),parseResponse:e=>{let t=e;if(t?.type!==`cdp-response`)return null;if(typeof t.id!=`number`||!Number.isFinite(t.id))return console.warn(`[WorkerCdpProxy] dropping cdp-response with invalid id`,t),null;let n=e;return{id:n.id,result:n.result,error:n.error}},parseEvent:e=>{let t=e;if(t?.type!==`cdp-event`)return null;if(typeof t.method!=`string`)return console.warn(`[WorkerCdpProxy] dropping cdp-event with invalid method`,t),null;let n=e;return{method:n.method,params:n.params}},parseControl:e=>{let t=e;return t?.type===`cdp-reset`?typeof t.reason==`string`?{kind:`reset`,reason:t.reason}:{kind:`reset`}:t?.type===`cdp-ready`?{kind:`ready`}:null},onUpstreamReset:e=>{n+=1,console.warn(`[WorkerCdpProxy] page CDP connection reset; sessions are stale`,e)},onUpstreamReady:()=>{console.info(`[WorkerCdpProxy] page CDP connection restored`)},onSubscribeEvent:e=>{t.send({type:`cdp-subscribe`,event:e})},onUnsubscribeEvent:e=>{t.send({type:`cdp-unsubscribe`,event:e})}})}};function ua(e,t){return e.find(e=>e.folder===t)??e.find(e=>e.folder===`${t}-scoop`)??e.find(e=>e.name===t)}const da={assign:0,create:0,clone:0,discard:0,update:0};function fa(e,t,n){return e>=t&&e<=n}function pa(e){return e===8205}function ma(e){return fa(e,55296,56319)}function ha(e){return fa(e,127462,127487)}function ga(e){return fa(e,65024,65039)}function _a(e){return fa(e,768,879)||fa(e,6832,6911)||fa(e,7616,7679)||fa(e,65056,65071)}function va(e){return e>65535?2:1}function ya(e,t){for(;t<e.length;){let n=e.codePointAt(t);if(_a(n)||ga(n))t+=va(n);else break}return t}function ba(e,t){let n=e.codePointAt(t),r=t+va(n);for(r=ya(e,r);r<e.length-1&&pa(e.codePointAt(r));){let t=e.codePointAt(r+1);r+=1+va(t),r=ya(e,r)}return ha(n)&&r<e.length&&ha(e.codePointAt(r))&&(r+=va(e.codePointAt(r))),r}function xa(e){return e>=768&&(ma(e)||_a(e)||ga(e)||pa(e))}function Sa(e){let t=0,n=0;for(;n<e.length;)n=ba(e,n),t++;return t}function Ca(e,t){let n=0,r=0;for(;r<e.length;)if(r=ba(e,r),++n>=t)return!0;return!1}function wa(e,t){let n=0,r=0;for(;r<e.length;)if(r=ba(e,r),++n>t)return!1;return!0}function Ta(e,t){if(t===0)return!0;if(e.length<t)return!1;let n=0;for(;;){if(xa(e.charCodeAt(n)))return Ca(e,t);if(++n>=t)return!0}}function Ea(e,t){if(e.length<=t)return!0;let n=0;for(;;){if(xa(e.charCodeAt(n)))return wa(e,t);if(++n>t)return!1}}var Da=/* @__PURE__ */ e({Counted:()=>Xa,Entries:()=>$a,EntriesRegExp:()=>Qa,Every:()=>Ka,EveryAll:()=>qa,GraphemeCount:()=>Ua,HasPropertyKey:()=>w,IsArray:()=>_,IsBigInt:()=>Oa,IsBoolean:()=>ka,IsClassInstance:()=>Va,IsConstructor:()=>Aa,IsDeepEqual:()=>io,IsEqual:()=>S,IsFunction:()=>ja,IsGreaterEqualThan:()=>za,IsGreaterThan:()=>Ia,IsInteger:()=>Ma,IsLessEqualThan:()=>Ra,IsLessThan:()=>La,IsMaxLength:()=>Wa,IsMinLength:()=>Ga,IsMultipleOf:()=>Ba,IsNull:()=>Na,IsNumber:()=>v,IsObject:()=>y,IsObjectNotArray:()=>Pa,IsString:()=>b,IsSymbol:()=>Fa,IsUndefined:()=>x,IsUnsafePropertyKey:()=>Za,IsValueLike:()=>Ha,Keys:()=>T,ShiftLeft:()=>C,Some:()=>Ja,SomeAll:()=>Ya,Symbols:()=>eo,Values:()=>to});function _(e){return Array.isArray(e)}function Oa(e){return S(typeof e,`bigint`)}function ka(e){return S(typeof e,`boolean`)}function Aa(e){if(x(e)||!ja(e))return!1;let t=Function.prototype.toString.call(e);return!!(/^class\s/.test(t)||/\[native code\]/.test(t))}function ja(e){return S(typeof e,`function`)}function Ma(e){return Number.isInteger(e)}function Na(e){return S(e,null)}function v(e){return Number.isFinite(e)}function Pa(e){return y(e)&&!_(e)}function y(e){return S(typeof e,`object`)&&!Na(e)}function b(e){return S(typeof e,`string`)}function Fa(e){return S(typeof e,`symbol`)}function x(e){return S(e,void 0)}function S(e,t){return e===t}function Ia(e,t){return e>t}function La(e,t){return e<t}function Ra(e,t){return e<=t}function za(e,t){return e>=t}function Ba(e,t){if(Oa(e)||Oa(t))return BigInt(e)%BigInt(t)===0n;if(!v(e)||Ma(e)&&1/t%1==0)return!0;let n=e%t;return Math.min(Math.abs(n),Math.abs(n-t),Math.abs(n+t))<1e-10}function Va(e){if(!y(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return!Na(t)&&S(typeof t.constructor,`function`)&&!(S(t.constructor,globalThis.Object)||S(t.constructor.name,`Object`))}function Ha(e){return Oa(e)||ka(e)||Na(e)||v(e)||b(e)||x(e)}function Ua(e){return Sa(e)}function Wa(e,t){return Ea(e,t)}function Ga(e,t){return Ta(e,t)}function Ka(e,t,n){return e.every((e,r)=>r<t||n(e,r))}function qa(e,t,n){let r=!0;return e.forEach((e,i)=>{i>=t&&!n(e,i)&&(r=!1)}),r}function Ja(e,t){return e.some((e,n)=>t(e,n))}function Ya(e,t){let n=!1;return e.forEach((e,r)=>{t(e,r)&&(n=!0)}),n}function Xa(e,t){return e.reduce((e,n,r)=>t(n,r)?++e:e,0)}function C(e,t,n){return S(e.length,0)?n():t(e[0],e.slice(1))}function Za(e){return S(e,`__proto__`)||S(e,`constructor`)||S(e,`prototype`)}function w(e,t){return Za(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function Qa(e){return T(e).map(t=>[RegExp(`^${t}$`),e[t]])}function $a(e){return Object.entries(e)}function T(e){return Object.getOwnPropertyNames(e)}function eo(e){return Object.getOwnPropertySymbols(e)}function to(e){return Object.values(e)}function no(e,t){if(!y(t))return!1;let n=T(e);return S(n.length,T(t).length)&&n.every(n=>io(e[n],t[n]))}function ro(e,t){return _(t)&&S(e.length,t.length)&&e.every((n,r)=>io(e[r],t[r]))}function io(e,t){return _(e)?ro(e,t):y(e)?no(e,t):S(e,t)}const ao=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function oo(e){return ao.test(e)}function so(e,t){return`(${e} && ${t})`}function E(e,t){return`(${e} || ${t})`}function co(e){return`!(${e})`}function lo(e){return`Array.isArray(${e})`}function uo(e){return`typeof ${e} === "bigint"`}function fo(e){return`typeof ${e} === "boolean"`}function po(e){return`Number.isInteger(${e})`}function mo(e){return`${e} === null`}function ho(e){return`Number.isFinite(${e})`}function go(e){return so(_o(e),co(lo(e)))}function _o(e){return`typeof ${e} === "object" && ${e} !== null`}function vo(e){return`typeof ${e} === "string"`}function yo(e){return`typeof ${e} === "symbol"`}function bo(e){return`${e} === undefined`}function xo(e){return`typeof ${e} === "function"`}function So(e){return`Guard.IsConstructor(${e})`}function Co(e,t){return`${e} === ${t}`}function wo(e,t){return`${e} > ${t}`}function To(e,t){return`${e} < ${t}`}function Eo(e,t){return`${e} <= ${t}`}function Do(e,t){return`${e} >= ${t}`}function Oo(e,t){return`Guard.IsMinLength(${e}, ${t})`}function ko(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Ao(e,t,n,r){return S(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => (${r}))`:`${e}.every((${n[0]}, ${n[1]}) => (${n[1]} < ${t}) || (${r}))`}function jo(e,t,n){return`${e}.some((${t[0]}, ${t[1]}) => ${n})`}function Mo(e,t,n){return`((value) => { let result = false; value.forEach((${t[0]}, ${t[1]}) => { if (${n}) result = true }); return result })(${e})`}function No(e,t,n){return`${e}.reduce((result, ${t[0]}, ${t[1]}) => (${n}) ? ++result : result, 0)`}function Po(e){return`Object.entries(${e})`}function Fo(e){return`Object.getOwnPropertyNames(${e})`}function Io(e,t){return S(t,`"__proto__"`)||S(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function Lo(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function Ro(e){return`[${e.join(`, `)}]`}function zo(e,t){return`((${e.join(`, `)}) => ${t})`}function D(e,t){return`${e}(${t.join(`, `)})`}function Bo(e,t){return`new ${e}(${t.join(`, `)})`}function O(e,t){return`${e}${oo(t)?`.${t}`:`[${k(t)}]`}`}function k(e){if(!Ha(e))throw Error(`Unsupported Constant`);return b(e)?JSON.stringify(e):`${e}`}function Vo(e,t,n){return`(${e} ? ${t} : ${n})`}function Ho(e){return`{ ${e.join(`; `)}; }`}function Uo(e,t){return`const ${e} = ${t}`}function Wo(e,t){return`if(${e}) { ${t} }`}function Go(e){return`return ${e}`}function Ko(e){return S(e.length,0)?`true`:e.reduce((e,t)=>so(e,t))}function qo(e){return S(e.length,0)?`false`:e.reduce((e,t)=>E(e,t))}function Jo(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}function Yo(e){return e instanceof Boolean}function Xo(e){return e instanceof Number}function Zo(e){return e instanceof String}function Qo(e){return globalThis.ArrayBuffer.isView(e)}function $o(e){return e instanceof globalThis.RegExp}function es(e){return e instanceof globalThis.Date}function ts(e){return e instanceof globalThis.Set}function ns(e){return e instanceof globalThis.Map}var rs=Da;const is={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function as(){return is}function os(e){return as().immutableTypes?Object.freeze(e):e}function ss(e,t){return da.assign+=1,os({...e,...t})}function cs(e){return e}function ls(e){return w(e,`~kind`)||w(e,`~unsafe`)}function us(e){let t={};for(let n of T(e)){if(Za(n))continue;let r=Object.getOwnPropertyDescriptor(e,n);r.value=vs(r.value),S(r.enumerable,!0)?t[n]=r.value:Object.defineProperty(t,n,r)}return t}function ds(e){let t={};for(let n of T(e))Za(n)||(t[n]=vs(e[n]));for(let n of eo(e))t[n]=vs(e[n]);return t}function fs(e){return Va(e)?cs(e):ls(e)?us(e):ds(e)}function ps(e){return e.map(e=>vs(e))}function ms(e){return e.slice()}function hs(e){return new RegExp(e.source,e.flags)}function gs(e){return new Map(vs([...e.entries()]))}function _s(e){return new Set(vs([...e.values()]))}function vs(e){return Qo(e)?ms(e):$o(e)?hs(e):ns(e)?gs(e):ts(e)?_s(e):_(e)?ps(e):y(e)?fs(e):e}function ys(e){return da.clone+=1,vs(e)}function bs(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function xs(e,t){return{...e,...t}}function A(e,t,n={}){da.create+=1;let r=xs(t,n);return os(as().enumerableKind?xs(r,e):bs(r,e))}function Ss(e,t){da.discard+=1;let n={};for(let r of T(e)){if(t.includes(r))continue;let i=Object.getOwnPropertyDescriptor(e,r);i.value=ys(i.value),Object.defineProperty(n,r,i)}return os(n)}function j(e,t,n){da.update+=1;let r=as(),i=ys(e);for(let e of Object.keys(t))Object.defineProperty(i,e,{configurable:!0,writable:!0,enumerable:r.enumerableKind,value:t[e]});for(let e of Object.keys(n))Object.defineProperty(i,e,{configurable:!0,enumerable:!0,writable:!0,value:n[e]});return os(i)}function M(e,t){return y(e)&&w(e,`~kind`)&&S(e[`~kind`],t)}function Cs(e){return y(e)}function N(e,t,n){return A({"~kind":`Deferred`},{type:`deferred`,action:e,parameters:t,options:n},{})}function ws(e){return M(e,`Deferred`)}function Ts(e){return j(e,{"~readonly":!0},{})}function Es(e,t){return j(Ts(e),{},t)}function Ds(e,t,n,r){return Es(U(e,t,n),r)}function Os(e){return j(e,{"~optional":!0},{})}function ks(e,t){return j(Os(e),{},t)}function As(e,t,n,r){return ks(U(e,t,n),r)}function js(e,t){return A({"~kind":`Array`},{type:`array`,items:e},t)}function Ms(e){return M(e,`Array`)}function Ns(e){return Ss(e,[`~kind`,`type`,`items`])}function Ps(e,t,n={}){return A({"~kind":`Constructor`},{type:`constructor`,parameters:e,instanceType:t},n)}function Fs(e){return M(e,`Constructor`)}function Is(e){return Ss(e,[`~kind`,`type`,`parameters`,`instanceType`])}function Ls(e,t,n={}){return A({"~kind":`Function`},{type:`function`,parameters:e,returnType:t},n)}function Rs(e){return M(e,`Function`)}function zs(e){return Ss(e,[`~kind`,`type`,`parameters`,`returnType`])}function Bs(e,t){return A({"~kind":`Ref`},{$ref:e},t)}function Vs(e){return M(e,`Ref`)}function Hs(e,t){return A({"~kind":`Generic`},{type:`generic`,parameters:e,expression:t})}function Us(e){return M(e,`Generic`)}function Ws(e){return A({"~kind":`Any`},{},e)}function Gs(e){return M(e,`Any`)}function Ks(e){return A({"~kind":`Never`},{not:{}},e)}function qs(e){return M(e,`Never`)}function Js(e,t={}){return ks(e,t)}function Ys(e){return Cs(e)&&w(e,`~optional`)}function Xs(e){return T(e).filter(t=>!Ys(e[t]))}function Zs(e){return T(e)}function Qs(e){return to(e)}function P(e,t={}){let n=Xs(e);return A({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}function F(e){return M(e,`Object`)}function $s(e){return Ss(e,[`~kind`,`type`,`properties`,`required`])}function ec(e){return A({"~kind":`Unknown`},{},e)}function tc(e){return M(e,`Unknown`)}function nc(e,t,n){return A({"~kind":`Cyclic`},{$defs:T(e).reduce((t,n)=>({...t,[n]:j(e[n],{},{$id:n})}),{}),$ref:t},n)}function rc(e){return M(e,`Cyclic`)}function ic(e){return Pa(e)&&w(e,`~unsafe`)&&Na(e[`~unsafe`])}function ac(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}function oc(e){return M(e,`Infer`)}function sc(e,t,n,r={}){return A({"~kind":`Dependent`},{if:e,then:t,else:n},r)}function cc(e){return M(e,`Dependent`)}function lc(e){return Ss(e,[`~kind`,`if`,`then`,`else`])}function uc(e){return M(e,`Enum`)}function dc(e,t={}){return A({"~kind":`Intersect`},{allOf:e},t)}function I(e){return M(e,`Intersect`)}function fc(e){return Ss(e,[`~kind`,`allOf`])}let pc;function mc(){try{return gc(`null`)(),!0}catch{return!1}}function hc(){return x(pc)&&(pc=mc()),pc&&as().useAcceleration}function gc(...e){return new globalThis.Function(...e)}function _c(){throw Error(`Unreachable`)}var vc=/* @__PURE__ */ e({Hash:()=>qc,HashCode:()=>Kc});function yc(e){let t=/* @__PURE__ */ new Set,n=e;for(;n&&n!==Object.prototype;){for(let e of Reflect.ownKeys(n))e!==`constructor`&&typeof e!=`symbol`&&t.add(e);n=Object.getPrototypeOf(n)}return[...t]}function bc(e){return typeof e==`number`}var xc;(function(e){e[e.Array=0]=`Array`,e[e.BigInt=1]=`BigInt`,e[e.Boolean=2]=`Boolean`,e[e.Date=3]=`Date`,e[e.Constructor=4]=`Constructor`,e[e.Function=5]=`Function`,e[e.Null=6]=`Null`,e[e.Number=7]=`Number`,e[e.Object=8]=`Object`,e[e.RegExp=9]=`RegExp`,e[e.String=10]=`String`,e[e.Symbol=11]=`Symbol`,e[e.TypeArray=12]=`TypeArray`,e[e.Undefined=13]=`Undefined`})(xc||={});let Sc=BigInt(`14695981039346656037`);const[Cc,wc]=[BigInt(`1099511628211`),BigInt(`18446744073709551616`)],Tc=Array.from({length:256}).map((e,t)=>BigInt(t)),Ec=/* @__PURE__ */ new Float64Array(1),Dc=new DataView(Ec.buffer),Oc=new Uint8Array(Ec.buffer);function kc(e){Sc^=Tc[e],Sc=Sc*Cc%wc}function Ac(e){kc(xc.Array);for(let t of e)Gc(t)}function jc(e){kc(xc.BigInt),Dc.setBigInt64(0,e);for(let e of Oc)kc(e)}function Mc(e){kc(xc.Boolean),kc(+!!e)}function Nc(e){kc(xc.Constructor),Gc(e.toString())}function Pc(e){kc(xc.Date),Gc(e.getTime())}function Fc(e){kc(xc.Function),Gc(e.toString())}function Ic(e){kc(xc.Null)}function Lc(e){kc(xc.Number),Dc.setFloat64(0,e,!0);for(let e of Oc)kc(e)}function Rc(e){kc(xc.Object);for(let t of yc(e).sort())Gc(t),Gc(e[t])}function zc(e){kc(xc.RegExp),Vc(e.toString())}const Bc=new TextEncoder;function Vc(e){kc(xc.String);for(let t of Bc.encode(e))kc(t)}function Hc(e){kc(xc.Symbol),Gc(e.toString())}function Uc(e){kc(xc.TypeArray);let t=new Uint8Array(e.buffer);for(let e=0;e<t.length;e++)kc(t[e])}function Wc(e){return kc(xc.Undefined)}function Gc(e){return Qo(e)?Uc(e):es(e)?Pc(e):$o(e)?zc(e):Yo(e)?Mc(e.valueOf()):Zo(e)?Vc(e.valueOf()):Xo(e)?Lc(e.valueOf()):bc(e)?Lc(e):_(e)?Ac(e):ka(e)?Mc(e):Oa(e)?jc(e):Aa(e)?Nc(e):Na(e)?Ic(e):y(e)?Rc(e):b(e)?Vc(e):Fa(e)?Hc(e):x(e)?Wc(e):ja(e)?Fc(e):_c()}function Kc(e){return Sc=BigInt(`14695981039346656037`),Gc(e),Sc}function qc(e){return Kc(e).toString(16).padStart(16,`0`)}function Jc(e){switch(e.keyword){case`additionalProperties`:return`must not have additional properties`;case`anyOf`:return`must match a schema in anyOf`;case`boolean`:return`schema is false`;case`const`:return`must be equal to constant`;case`contains`:return`must contain at least 1 valid item`;case`dependencies`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`dependentRequired`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`enum`:return`must be equal to one of the allowed values`;case`exclusiveMaximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`exclusiveMinimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`format`:return`must match format "${e.params.format}"`;case`if`:return`must match "${e.params.failingKeyword}" schema`;case`maxItems`:return`must not have more than ${e.params.limit} items`;case`maxLength`:return`must not have more than ${e.params.limit} characters`;case`maxProperties`:return`must not have more than ${e.params.limit} properties`;case`maximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`minItems`:return`must not have fewer than ${e.params.limit} items`;case`minLength`:return`must not have fewer than ${e.params.limit} characters`;case`minProperties`:return`must not have fewer than ${e.params.limit} properties`;case`minimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`multipleOf`:return`must be multiple of ${e.params.multipleOf}`;case`not`:return`must not be valid`;case`oneOf`:return`must match exactly one schema in oneOf`;case`pattern`:return`must match pattern "${e.params.pattern}"`;case`propertyNames`:return`property names ${e.params.propertyNames.join(`, `)} are invalid`;case`required`:return`must have required properties ${e.params.requiredProperties.join(`, `)}`;case`type`:return typeof e.params.type==`string`?`must be ${e.params.type}`:`must be either ${e.params.type.join(` or `)}`;case`unevaluatedItems`:return`must not have unevaluated items`;case`unevaluatedProperties`:return`must not have unevaluated properties`;case`uniqueItems`:return`must not have duplicate items`;case`~refine`:return e.params.message;default:return`an unknown validation error occurred`}}let Yc=Jc;function Xc(){return Yc}function Zc(e){return Cs(e)&&w(e,`~codec`)&&y(e[`~codec`])&&w(e[`~codec`],`encode`)&&w(e[`~codec`],`decode`)}function Qc(e){return Cs(e)&&w(e,`~immutable`)}function $c(e,t={}){return Es(e,t)}function el(e){return Cs(e)&&w(e,`~readonly`)}function tl(e){return A({"~kind":`BigInt`},{type:`bigint`},e)}function nl(e){return M(e,`BigInt`)}function rl(e){return M(e,`Boolean`)}const il=`-?(?:0|[1-9][0-9]*)`;function al(e){return A({"~kind":`Integer`},{type:`integer`},e)}function ol(e){return M(e,`Integer`)}var sl=class extends Error{constructor(e){super(`Invalid Literal value`),Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}};function cl(e){return Oa(e)?`bigint`:ka(e)?`boolean`:v(e)?`number`:b(e)?`string`:(()=>{throw new sl(e)})()}function ll(e,t){return A({"~kind":`Literal`},{type:cl(e),const:e},t)}function ul(e){return Oa(e)||ka(e)||v(e)||b(e)}function dl(e){return hl(e)&&Oa(e.const)}function fl(e){return hl(e)&&ka(e.const)}function pl(e){return hl(e)&&v(e.const)}function ml(e){return hl(e)&&b(e.const)}function hl(e){return M(e,`Literal`)}function gl(e){return A({"~kind":`Null`},{type:`null`},e)}function _l(e){return M(e,`Null`)}const vl=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function yl(e){return A({"~kind":`Number`},{type:`number`},e)}function bl(e){return M(e,`Number`)}function xl(e){return A({"~kind":`Symbol`},{type:`symbol`},e)}function Sl(e){return M(e,`Symbol`)}function Cl(e){return A({"~kind":`String`},{type:`string`},e)}function wl(e){return M(e,`String`)}function Tl(e,t={}){return A({"~kind":`Union`},{anyOf:e},t)}function L(e){return M(e,`Union`)}function El(e){return Ss(e,[`~kind`,`anyOf`])}function Dl(e){let t=$d(e);return S(t.length,2)?t[0]:[]}function Ol(e){return!0}function kl(e){return C(e,(e,t)=>jl(e)?kl(t):!1,()=>!0)}function Al(e){return!S(e.length,0)&&kl(e)}function jl(e){return L(e)?Al(e.anyOf):hl(e)?Ol(e.const):!1}function Ml(e){return Al(e)}function Nl(e){return A({"~kind":`TemplateLiteral`},{type:`string`,pattern:e},{})}function Pl(e,t,n=[]){return C(e,(e,r)=>Pl(r,t,[...n,`${e}${t}`]),()=>n)}function Fl(e,t){return S(e.length,0)?[`${t}`]:Pl(e,t)}function Il(e,t,n=[]){return C(t,(t,r)=>Il(e,r,[...n,...Ll(e,t)]),()=>n)}function Ll(e,t){return L(t)?Il(e,t.anyOf):hl(t)?Fl(e,t.const):_c()}function Rl(e,t){return C(t,(t,n)=>Rl(Ll(e,t),n),()=>e)}function zl(e){return e.map(e=>ll(e))}function Bl(e){return Tl(zl(Rl([],e)))}function Vl(e){return S(e.length,0)?_c():S(e.length,1)&&hl(e[0])?e[0]:Bl(e)}function Hl(e){let t=Dl(e);return S(t.length,0)?Cl():Ml(t)?Vl(t):Nl(e)}function Ul(e){let t=Hl(e);return xf(t)?Cl():t}function Wl(e,t){return A({"~kind":`Record`},{type:`object`,patternProperties:{[e]:t}})}function Gl(e){return Wl(Zu,e)}function Kl(e){return P({true:e,false:e})}function ql(e,t={}){let[n,r,i]=[e,e.length,!1];return A({"~kind":`Tuple`},{type:`array`,additionalItems:i,items:n,minItems:r},t)}function Jl(e){return M(e,`Tuple`)}function Yl(e){return Ss(e,[`~kind`,`type`,`items`,`minItems`,`additionalItems`])}function Xl(e){return Ss(e,[`~readonly`])}function Zl(e,t){return j(Xl(e),{},t)}function Ql(e,t,n,r){return Zl(U(e,t,n),r)}function $l(e,t={}){return Zl(e,t)}function eu(e){return Ss(e,[`~optional`])}function tu(e,t){return j(eu(e),{},t)}function nu(e,t,n,r){return tu(U(e,t,n),r)}function ru(e,t={}){return tu(e,t)}function iu(e){return e.reduceRight((e,t,n)=>({[n]:t,...e}),{})}function au(e){return P(iu(e.items))}function ou(e){return F(e)||Jl(e)}function su(e,t){return el(e)?!!el(t):!1}function cu(e,t){return Ys(e)?!!Ys(t):!1}function lu(e,t){let n=su(e,t),r=cu(e,t),i=$l(ru(Du([e,t])));return n&&r?$c(Js(i)):n&&!r?$c(i):!n&&r?Js(i):i}function uu(e,t,n){return n in e?n in t?lu(e[n],t[n]):e[n]:n in t?t[n]:Ks()}function du(e,t){return[.../* @__PURE__ */ new Set([...T(e),...T(t)])].reduce((n,r)=>({...n,[r]:uu(e,t,r)}),{})}function fu(e){return F(e)?e.properties:Jl(e)?iu(e.items):{}}function pu(e,t){return P(du(fu(e),fu(t)))}function mu(e,t){let n=Sm(e,t);return S(n,2)?e:S(n,3)||S(n,0)?t:Ks()}function hu(e,t){let n=ou(e),r=ou(t);return n&&r?pu(e,t):n&&!r?e:!n&&r?t:mu(e,t)}function gu(e,t){return qs(e)||Gs(e)?e:tc(e)||qs(t)||Gs(t)?t:tc(t)?e:hu(e,t)}function _u(e,t){return L(e)||L(t)}function vu(e,t){let n=Au(e),r=Au(t);return _u(n,r)?Du([n,r]):gu(n,r)}function yu(e,t,n=[]){return C(t,(t,r)=>yu(e,r,[...n,vu(t,e)]),()=>S(n.length,0)?[e]:n)}function bu(e,t,n=[]){return C(e,(e,r)=>bu(r,t,[...n,...xu([e],t)]),()=>n)}function xu(e,t=[]){return C(e,(e,n)=>L(e)?xu(n,bu(e.anyOf,t)):xu(n,yu(e,t)),()=>t)}function Su(e,t){return Ef(xm({},e,t))?[]:[e]}function Cu(e,t,n=[]){return C(e,(e,r)=>Cu(r,t,[...n,...Su(e,t)]),()=>n)}function wu(e,t){let n=Au(e);return ku(Cu(L(n)?n.anyOf:[n],t))}function Tu(e,t,n){return ku([Du([e,t]),wu(n,e)])}function Eu(e,t=[]){return C(e,(e,n)=>Eu(n,[...t,ll(e)]),()=>ku(t))}function Du(e){return ku(Em(xu(e)))}function Ou(e){return Au(Ul(e))}function ku(e){return ju(Em(e))}function Au(e){return cc(e)?Tu(e.if,e.then,e.else):uc(e)?Eu(e.enum):I(e)?Du(e.allOf):xf(e)?Ou(e.pattern):L(e)?ku(e.anyOf):e}function ju(e){return S(e.length,1)?e[0]:S(e.length,0)?Ks():Tl(e)}function Mu(e,t){return Ku(Eu(e),t)}function Nu(e,t){return Wl(Yu,t)}function Pu(e,t){return Ku(Du(e),t)}function Fu(e,t){return b(e)||v(e)?P({[e]:t}):S(e,!1)?P({false:t}):S(e,!0)?P({true:t}):P({})}function Iu(e,t){return Wl(Xu,t)}function Lu(e,t){return w(e,`pattern`)&&(b(e.pattern)||e.pattern instanceof RegExp)?Wl(e.pattern.toString(),t):Wl(Zu,t)}function Ru(e,t){return Ml(Dl(e))?Ku(Ou(e),t):Wl(e,t)}function zu(e){return L(e)?Bu(e.anyOf):[e]}function Bu(e,t=[]){return C(e,(e,n)=>Bu(n,[...t,...zu(e)]),()=>t)}function Vu(e){return e.some(e=>wl(e)||bl(e)||ol(e))}function Hu(e,t){return S(Vu(e),!0)?Wl(Zu,t):void 0}function Uu(e,t){return e.reduce((e,n)=>hl(n)&&(b(n.const)||v(n.const))?{...e,[n.const]:t}:e,{})}function Wu(e,t){return P(Uu(e,t))}function Gu(e,t){let n=Bu(e),r=Hu(n,t);return Cs(r)?r:Wu(n,t)}function Ku(e,t){return Gs(e)?Gl(t):rl(e)?Kl(t):uc(e)?Mu(e.enum,t):ol(e)?Nu(e,t):I(e)?Pu(e.allOf,t):hl(e)?Fu(e.const,t):bl(e)?Iu(e,t):L(e)?Gu(e.anyOf,t):wl(e)?Lu(e,t):xf(e)?Ru(e.pattern,t):P({})}function qu(e,t,n){return H([e])?j(Ku(e,t),{},n):Qu(e,t,n)}function Ju(e,t,n,r,i){return qu(U(e,t,n),U(e,t,r),i)}const Yu=`^${il}$`,Xu=`^${vl}$`,Zu=`^.*$`;function Qu(e,t,n={}){return N(`Record`,[e,t],n)}function $u(e,t,n={}){return qu(e,t,n)}function ed(e,t){return Wl(e,t)}function td(e){return S(e,Zu)?Cl():S(e,Yu)?al():S(e,Xu)?yl():Hl(e)}function nd(e){return T(e.patternProperties)[0]}function rd(e){return td(nd(e))}function id(e){return e.patternProperties[nd(e)]}function ad(e){return M(e,`Record`)}function od(e){return A({"~kind":`Rest`},{type:`rest`,items:e},{})}function sd(e){return M(e,`Rest`)}function cd(e){return M(e,`This`)}function ld(e){return A({"~kind":`Undefined`},{type:`undefined`},e)}function ud(e){return M(e,`Undefined`)}function dd(e){return M(e,`Void`)}function fd(e){return tl()}function pd(e){return Cl()}function md(e){return yl()}function hd(e){return al()}function gd(e){return Ks()}function _d(e){return ll(e)}function vd(e){return e}function yd(e){return Tl(e[1])}function bd(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function xd(e){return[e[0],...e[1]]}function Sd(e){return e}function Cd(e){return e[1]}function wd(e){return S(e.length,2)}function Td(e,t,n){return wd(e)?t(e[0],e[1]):n()}function Ed(e,t){return S(t.indexOf(e),0)?[e,t.slice(e.length)]:[]}function Dd(e,t){for(let n=0;n<e.length;n++){let r=Ed(e[n],t);if(wd(r))return r}return[]}function Od(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}const kd=[...Od(97,122),...Od(65,90)],Ad=[`0`,...Od(49,57)];function jd(e){let t=e.indexOf(`*/`);return S(t,-1)?``:e.slice(t+2)}function Md(e){let t=e.indexOf(`
|
|
968
968
|
`);return S(t,-1)?``:e.slice(t)}function Nd(e){return e.replace(/^[ \t\r\f\v]+/,``)}function Pd(e){let t=Nd(e);return t.startsWith(`/*`)?Pd(jd(t.slice(2))):t.startsWith(`//`)?Pd(Md(t.slice(2))):t}function Fd(e){let t=e.trimStart();return t.startsWith(`/*`)?Fd(jd(t.slice(2))):t.startsWith(`//`)?Fd(Md(t.slice(2))):t}[...Ad];function Id(e,t){return Dd([e],t)}function Ld(e,t){return S(e,``)?[``,t]:e.startsWith(`
|
|
969
969
|
`)?Id(e,Pd(t)):e.startsWith(` `)?Id(e,t):Id(e,Fd(t))}[...kd,...Ad],[...Ad];function Rd(e){return S(e,``)?[]:[e.slice(0,1),e.slice(1)]}function zd(e,t){return C(e,(e,n)=>t.startsWith(e)?!0:zd(n,t),()=>!1)}function Bd(e,t,n=``){return Td(Rd(t),(r,i)=>zd(e,t)?[n,t]:Bd(e,i,`${n}${r}`),()=>[])}function Vd(e,t){return Td(Bd(e,t),(e,t)=>S(e,``)?[]:[e,t],()=>[])}const R=(e,t,n=()=>[])=>e.length===2?t(e):n(),Hd=e=>R(Ld(`-?(?:0|[1-9][0-9]*)n`,e),([e,t])=>[fd(e),t]),Ud=e=>R(Ld(`.*`,e),([e,t])=>[pd(e),t]),Wd=e=>R(Ld(`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`,e),([e,t])=>[md(e),t]),Gd=e=>R(Ld(`-?(?:0|[1-9][0-9]*)`,e),([e,t])=>[hd(e),t]),Kd=e=>R(Ld(`(?!)`,e),([e,t])=>[gd(e),t]),qd=e=>R(Vd([`-?(?:0|[1-9][0-9]*)n`,`.*`,`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`,`-?(?:0|[1-9][0-9]*)`,`(?!)`,`(`,`)`,`$`,`|`],e),([e,t])=>[_d(e),t]),Jd=e=>R(R(Hd(e),([e,t])=>[e,t],()=>R(Ud(e),([e,t])=>[e,t],()=>R(Wd(e),([e,t])=>[e,t],()=>R(Gd(e),([e,t])=>[e,t],()=>R(Kd(e),([e,t])=>[e,t],()=>R(Yd(e),([e,t])=>[e,t],()=>R(qd(e),([e,t])=>[e,t],()=>[]))))))),([e,t])=>[vd(e),t]),Yd=e=>R(R(Ld(`(`,e),([e,t])=>R(Qd(t),([t,n])=>R(Ld(`)`,n),([n,r])=>[[e,t,n],r]))),([e,t])=>[yd(e),t]),Xd=e=>R(R(R(Zd(e),([e,t])=>R(Ld(`|`,t),([t,n])=>R(Xd(n),([n,r])=>[[e,t,n],r]))),([e,t])=>[e,t],()=>R(R(Zd(e),([e,t])=>[[e],t]),([e,t])=>[e,t],()=>R([[],e],([e,t])=>[e,t],()=>[]))),([e,t])=>[bd(e),t]),Zd=e=>R(R(Jd(e),([e,t])=>R(Qd(t),([t,n])=>[[e,t],n])),([e,t])=>[xd(e),t]),Qd=e=>R(R(Xd(e),([e,t])=>[e,t],()=>R(Zd(e),([e,t])=>[e,t],()=>[])),([e,t])=>[Sd(e),t]),$d=e=>R(R(Ld(`^`,e),([e,t])=>R(Qd(t),([t,n])=>R(Ld(`$`,n),([n,r])=>[[e,t,n],r]))),([e,t])=>[Cd(e),t]);function ef(e){return e.join(`|`)}function tf(e){return e.slice(1,e.length-1)}function nf(e,t,n){return mf(t,`${n}${e}`)}function rf(e,t){return mf(e,`${t}-?(?:0|[1-9][0-9]*)n`)}function af(e,t){return mf(e,`${t}${il}`)}function of(e,t){return mf(e,`${t}${vl}`)}function sf(e,t){return pf(Tl([ll(`false`),ll(`true`)]),e,t)}function cf(e,t){return mf(e,`${t}.*`)}function lf(e,t,n){return mf(t,`${n}${tf(e)}`)}function uf(e,t,n){return pf(_f(e,{}),t,n)}function df(e,t,n){return pf(Eu(e),t,n)}function ff(e,t,n,r=[]){return C(e,(e,i)=>ff(i,t,n,[...r,pf(e,[],``)]),()=>mf(t,`${n}(${ef(r)})`))}function pf(e,t,n){return uc(e)?df(e.enum,t,n):ol(e)?af(t,n):hl(e)?nf(e.const,t,n):nl(e)?rf(t,n):rl(e)?sf(t,n):bl(e)?of(t,n):wl(e)?cf(t,n):xf(e)?lf(e.pattern,t,n):bf(e)?uf(e.parameters[0],t,n):L(e)?ff(e.anyOf,t,n):`(?!)`}function mf(e,t){return C(e,(e,n)=>pf(e,n,t),()=>t)}function hf(e){return`^${mf(e,``)}$`}function gf(e){return Nl(hf(e))}function _f(e,t){return H(e)?j(gf(e),{},t):yf(e,t)}function vf(e,t,n,r){return _f(Av(e,t,n),r)}function yf(e,t={}){return N(`TemplateLiteral`,[e],t)}function bf(e){return Cs(e)&&w(e,`action`)&&S(e.action,`TemplateLiteral`)}function xf(e){return M(e,`TemplateLiteral`)}function Sf(e){return A({"~kind":`ExtendsUnion`},{inferred:e})}function Cf(e){return y(e)&&w(e,`~kind`)&&w(e,`inferred`)&&S(e[`~kind`],`ExtendsUnion`)&&y(e.inferred)}function z(e){return A({"~kind":`ExtendsTrue`},{inferred:e})}function wf(e){return y(e)&&w(e,`~kind`)&&w(e,`inferred`)&&S(e[`~kind`],`ExtendsTrue`)&&y(e.inferred)}function B(){return A({"~kind":`ExtendsFalse`},{})}function Tf(e){return y(e)&&w(e,`~kind`)&&S(e[`~kind`],`ExtendsFalse`)}function Ef(e){return Cf(e)||wf(e)}function Df(e,t,n){return Ef(e)?t(e.inferred):n()}function Of(e,t,n,r){return Df(V(e,n,r),r=>z(ss(ss(e,r),{[t]:n})),()=>B())}function kf(e,t){return z(e)}function Af(e,t,n,r,i){return Df(V(e,t,n),e=>Df(V(e,t,r),e=>z(e),()=>B()),()=>Df(V(e,t,i),e=>z(e),()=>B()))}function jf(e,t,n){return V(e,t,Eu(n))}function Mf(e,t,n){return C(n,(n,r)=>Df(V(e,t,n),e=>Mf(e,t,r),()=>B()),()=>z(e))}function Nf(e,t,n){return V(e,t,Ou(n))}function Pf(e,t,n){return C(n,(n,r)=>Df(V(e,t,n),e=>z(e),()=>Pf(e,t,r)),()=>B())}function Ff(e,t,n){return Gs(n)?kf(e,t):cc(n)?Af(e,t,n.if,n.then,n.else):uc(n)?jf(e,t,n.enum):oc(n)?Of(e,n.name,t,n.extends):I(n)?Mf(e,t,n.allOf):xf(n)?Nf(e,t,n.pattern):L(n)?Pf(e,t,n.anyOf):tc(n)?z(e):B()}function If(e,t,n){return oc(n)?Ff(e,t,n):Gs(n)||tc(n)?z(e):Sf(e)}function Lf(e,t){let n=Qc(e),r=Qc(t);return n&&r||!n&&r?!0:!(n&&!r)}function Rf(e,t,n,r){return Ms(r)?Lf(t,r)?V(e,n,r.items):B():Ff(e,t,r)}function zf(e,t,n){return nl(n)?z(e):Ff(e,t,n)}function Bf(e,t,n){return rl(n)?z(e):Ff(e,t,n)}function Vf(e,t,n,r,i){let a=oc(r)?t:r,o=oc(r)?r:t,s=Ys(t),c=Ys(r);return!s&&c?B():Df(V(e,a,o),e=>Wf(e,n,i),()=>B())}function Hf(e,t,n,r){return C(r,(r,i)=>Vf(e,t,n,r,i),()=>Ys(t)?z(e):B())}function Uf(e,t,n){return C(t,(t,r)=>Hf(e,t,r,n),()=>z(e))}function Wf(e,t,n){return Uf(e,t,n)}function Gf(e,t,n){return dd(n)?z(e):V(e,t,n)}function Kf(e,t,n,r){return Gs(r)||tc(r)?z(e):Fs(r)?Df(Wf(e,t,r.parameters),e=>Gf(e,n,r.instanceType),()=>B()):B()}function qf(e,t,n,r,i){return Df(V(e,t,i),()=>V(e,n,i),()=>V(e,r,i))}function Jf(e,t,n){return V(e,Eu(t),n)}function Yf(e,t,n,r){return Gs(r)||tc(r)?z(e):Rs(r)?Df(Wf(e,t,r.parameters),e=>Gf(e,n,r.returnType),()=>B()):B()}function Xf(e,t,n){return ol(n)||bl(n)?z(e):Ff(e,t,n)}function Zf(e,t,n){return V(e,Du(t),n)}function Qf(e,t,n){return t===n?z(e):B()}function $f(e,t,n){return hl(n)?Qf(e,t,n.const):nl(n)?z(e):Ff(e,ll(t),n)}function ep(e,t,n){return hl(n)?Qf(e,t,n.const):rl(n)?z(e):Ff(e,ll(t),n)}function tp(e,t,n){return hl(n)?Qf(e,t,n.const):bl(n)?z(e):Ff(e,ll(t),n)}function np(e,t,n){return hl(n)?Qf(e,t,n.const):wl(n)?z(e):Ff(e,ll(t),n)}function rp(e,t,n){return Oa(t.const)?$f(e,t.const,n):ka(t.const)?ep(e,t.const,n):v(t.const)?tp(e,t.const,n):b(t.const)?np(e,t.const,n):_c()}function ip(e,t,n){return oc(n)?Ff(e,t,n):z(e)}function ap(e,t,n){return _l(n)?z(e):Ff(e,t,n)}function op(e,t,n){return bl(n)?z(e):Ff(e,t,n)}function sp(e,t,n){return Ys(t)?Ys(n)?z(e):B():z(e)}function cp(e,t,n){return oc(n)&&qs(n.extends)?B():Df(V(e,t,n),e=>sp(e,t,n),()=>B())}function lp(e,t){return e.reduce((e,n)=>n in t&&Ef(t[n])?{...e,...t[n].inferred}:_c(),{})}function up(e,t,n){let r={};for(let i of T(n))r[i]=i in t?cp({},t[i],n[i]):Ys(n[i])?oc(n[i])?z(ss(e,{[n[i].name]:n[i].extends})):z(e):B();let i=to(r).every(e=>Ef(e)),a=i?lp(T(r),r):{};return i?z(a):B()}function dp(e,t,n){let r=up(e,t,n);return Ef(r)?z(ss(e,r.inferred)):B()}function fp(e,t,n){return dp(e,t,n)}function pp(e,t){return T(t).reduce((n,r)=>({...n,[r]:w(e,r)?L(n[r])?Tl([...n[r].anyOf,t[r]]):Tl([e[r],t[r]]):t[r]}),e)}function mp(e,t,n,r){return C(t,(t,i)=>Df(V({},e[t],n),t=>mp(e,i,n,pp(r,t)),()=>B()),()=>z(r))}function hp(e,t,n,r){return mp(t,T(t),r,e)}function gp(e,t,n){return ad(n)?hp(e,t,nd(n),id(n)):F(n)?fp(e,t,n.properties):Ff(e,P(t),n)}function _p(e,t){return S(T(t).length,0)?z(e):B()}function vp(e,t,n,r,i){return V(e,n,i)}function yp(e,t,n,r){return ad(r)?vp(e,td(t),n,td(nd(r)),id(r)):F(r)?_p(e,r.properties):Gs(r)||tc(r)?z(e):B()}function bp(e,t,n){return wl(n)?z(e):Ff(e,t,n)}function xp(e,t,n){return Sl(n)?z(e):Ff(e,t,n)}function Sp(e,t,n){return V(e,Ou(t),n)}function Cp(e,t){return A({"~kind":`Inferrable`},{name:e,type:t},{})}function wp(e){return y(e)&&w(e,`~kind`)&&w(e,`name`)&&w(e,`type`)&&S(e[`~kind`],`Inferrable`)&&b(e.name)&&y(e.type)}function Tp(e){return sd(e)?oc(e.items)?Ms(e.items.extends)?Cp(e.items.name,e.items.extends.items):tc(e.items.extends)?Cp(e.items.name,e.items.extends):void 0:_c():void 0}function Ep(e){return oc(e)?Cp(e.name,e.extends):void 0}function Dp(e,t,n=[]){return C(e,(e,r)=>Df(V({},e,t),()=>Dp(r,t,[...n,e]),()=>void 0),()=>n)}function Op(e,t,n,r){let i=Dp(n,r);return _(i)?z(ss(e,{[t]:ql(i)})):B()}function kp(e,t,n,r){let i=Dp(n,r);return _(i)?z(ss(e,{[t]:Tl(i)})):B()}function Ap(e){return[...e].reverse()}function jp(e,t){return t?Ap(e):e}function Mp(e){let t=e.length>0?e[0]:void 0;return Cs(Cs(t)?Tp(t):void 0)}function Np(e,t,n,r,i,a){return Df(V(e,n,i),e=>Ip(e,t,r,a),()=>B())}function Pp(e,t,n,r,i){let a=Tp(r);return wp(a)?Op(e,a.name,jp(n,t),a.type):C(n,(n,a)=>Np(e,t,n,a,r,i),()=>B())}function Fp(e,t,n,r){return C(r,(r,i)=>Pp(e,t,n,r,i),()=>S(n.length,0)?z(e):B())}function Ip(e,t,n,r){return Fp(e,t,n,r)}function Lp(e,t,n){let r=kv(e,Dv([],[]),n),i=Mp(r);return Ip(e,i,jp(t,i),jp(r,i))}function Rp(e,t,n){let r=Ep(n);return wp(r)?kp(e,r.name,t,r.type):C(t,(t,r)=>Df(V(e,t,n),e=>Rp(e,r,n),()=>B()),()=>z(e))}function zp(e,t,n){let r=kv(e,Dv([],[]),t);return Jl(n)?Lp(e,r,n.items):Ms(n)?Rp(e,r,n.items):Ff(e,ql(r),n)}function Bp(e,t,n){return dd(n)||ud(n)?z(e):Ff(e,t,n)}function Vp(e,t,n){return C(n,(n,r)=>Df(V(e,t,n),e=>z(e),()=>Vp(e,t,r)),()=>B())}function Hp(e,t,n){return C(t,(t,r)=>Df(Vp(e,t,n),e=>Hp(e,r,n),()=>B()),()=>z(e))}function Up(e,t,n){let r=Ep(n);return wp(r)?kp(e,r.name,t,r.type):L(n)?Hp(e,t,n.anyOf):Hp(e,t,[n])}function Wp(e,t,n){return oc(n)?Ff(e,t,n):Gs(n)||tc(n)?z(e):B()}function Gp(e,t,n){return dd(n)?z(e):Ff(e,t,n)}function V(e,t,n){return Gs(t)?If(e,t,n):Ms(t)?Rf(e,t,t.items,n):nl(t)?zf(e,t,n):rl(t)?Bf(e,t,n):Fs(t)?Kf(e,t.parameters,t.instanceType,n):cc(t)?qf(e,t.if,t.then,t.else,n):uc(t)?Jf(e,t.enum,n):Rs(t)?Yf(e,t.parameters,t.returnType,n):ol(t)?Xf(e,t,n):I(t)?Zf(e,t.allOf,n):hl(t)?rp(e,t,n):qs(t)?ip(e,t,n):_l(t)?ap(e,t,n):bl(t)?op(e,t,n):F(t)?gp(e,t.properties,n):ad(t)?yp(e,nd(t),id(t),n):wl(t)?bp(e,t,n):Sl(t)?xp(e,t,n):xf(t)?Sp(e,t.pattern,n):Jl(t)?zp(e,t.items,n):ud(t)?Bp(e,t,n):L(t)?Up(e,t.anyOf,n):tc(t)?Wp(e,t,n):dd(t)?Gp(e,t,n):B()}function Kp(e,t){return Du([...e,P(t)])}function qp(e,t,n){return H(e)?j(Kp(e,t),{},n):Yp(e,t,n)}function Jp(e,t,n,r,i){return qp(Av(e,t,n),Ov(e,t,r),i)}function Yp(e,t,n={}){return N(`Interface`,[e,t],n)}function Xp(e){return Cs(e)&&w(e,`action`)&&S(e.action,`Interface`)}function Zp(e,t,n){return e.includes(n)?!0:em([...e,n],t,t[n])}function Qp(e,t,n){return $p(e,t,Qs(n))}function $p(e,t,n){return C(n,(n,r)=>em(e,t,n)?!0:$p(e,t,r),()=>!1)}function em(e,t,n){return Vs(n)?Zp(e,t,n.$ref):Ms(n)?em(e,t,n.items):Fs(n)?$p(e,t,[...n.parameters,n.instanceType]):Rs(n)?$p(e,t,[...n.parameters,n.returnType]):Xp(n)?Qp(e,t,n.parameters[1]):I(n)?$p(e,t,n.allOf):F(n)?Qp(e,t,n.properties):L(n)?$p(e,t,n.anyOf):Jl(n)?$p(e,t,n.items):ad(n)?em(e,t,id(n)):!1}function tm(e,t,n){return em(e,t,n)}function nm(e,t){return t.reduce((t,n)=>tm([n],e,e[n])?[...t,n]:t,[])}function rm(e){return nm(e,Zs(e))}function im(e,t,n){return n.includes(t)?n:t in e?sm(e,e[t],[...n,t]):_c()}function am(e,t,n){return om(e,Qs(t),n)}function om(e,t,n){return t.reduce((t,n)=>sm(e,n,t),n)}function sm(e,t,n){return Vs(t)?im(e,t.$ref,n):Ms(t)?sm(e,t.items,n):Fs(t)?om(e,[...t.parameters,t.instanceType],n):Rs(t)?om(e,[...t.parameters,t.returnType],n):Xp(t)?am(e,t.parameters[1],n):I(t)?om(e,t.allOf,n):F(t)?am(e,t.properties,n):L(t)?om(e,t.anyOf,n):Jl(t)?om(e,t.items,n):ad(t)?sm(e,id(t),n):n}function cm(e,t,n){return sm(e,n,[t])}function lm(e){return Ws()}function um(e){return T(e).reduce((t,n)=>({...t,[n]:fm(e[n])}),{})}function dm(e){return e.reduce((e,t)=>[...e,fm(t)],[])}function fm(e){return Vs(e)?lm(e.$ref):Ms(e)?js(fm(e.items),Ns(e)):Fs(e)?Ps(dm(e.parameters),fm(e.instanceType)):Rs(e)?Ls(dm(e.parameters),fm(e.returnType)):I(e)?dc(dm(e.allOf)):F(e)?P(um(e.properties)):ad(e)?$u(rd(e),fm(id(e))):L(e)?Tl(dm(e.anyOf)):Jl(e)?ql(dm(e.items)):e}function pm(e,t){return t in e?fm(e[t]):ec()}function mm(e){return pm(e.$defs,e.$ref)}function hm(e,t,n){let r=Av(e,Dv([],[]),t),i=Ov({},Dv([],[]),n);return Du([...r,P(i)])}function gm(e,t){return T(e).filter(e=>t.includes(e)).reduce((t,n)=>{let r=e[n],i=Xp(r)?hm(e,r.parameters[0],r.parameters[1]):r;return{...t,[n]:i}},{})}function _m(e,t,n){return nc(gm(e,cm(e,t,n)),t)}function vm(e,t){return t in e?Vs(e[t])?vm(e,e[t].$ref):e[t]:Ks()}function ym(e,t){return vm(e,t)}function bm(e){return rc(e)?mm(e):ic(e)?ec():e}function xm(e,t,n){return V(e,bm(t),bm(n))}function Sm(e,t){let n=[xm({},e,t),xm({},t,e)];return Ef(n[0])&&Ef(n[1])?0:Ef(n[0])&&Tf(n[1])?2:Tf(n[0])&&Ef(n[1])?3:1}function Cm(e,t,n=[],r=t){return C(t,(t,i)=>{let a=Sm(e,t);return S(a,2)||S(a,0)?r:S(a,1)?Cm(e,i,[...n,t],r):Cm(e,i,n,r)},()=>[...n,e])}function wm(e,t,n){let r=Au(e);return Gs(r)||tc(r)?[r]:qs(r)?Tm(t,n):F(r)?Tm(t,[...n,r]):Tm(t,Cm(r,n))}function Tm(e,t=[]){return C(e,(e,n)=>wm(e,n,t),()=>t)}function Em(e){return Bu(Tm(e))}function Dm(e,t){return j(Au(e),{},t)}function Om(e,t,n,r){return Dm(U(e,t,n),r)}function km(e,t=[]){return ws(e)&&S(e.action,`Conditional`)?Vs(e.parameters[0])?km(e.parameters[2],km(e.parameters[3],[...t,e.parameters[0].$ref])):km(e.parameters[2],km(e.parameters[3],t)):ws(e)&&S(e.action,`Mapped`)&&ws(e.parameters[1])&&S(e.parameters[1].action,`KeyOf`)&&Vs(e.parameters[1].parameters[0])?[...t,e.parameters[1].parameters[0].$ref]:t}function Am(e,t){return e.reduce((e,n)=>[...e,t.includes(n.name)],[])}function jm(e,t,n=[]){return C(e,(e,r)=>C(t,(t,i)=>jm(r,i,[...n,[t,e]]),()=>n),()=>n)}function Mm(e){return xf(e)?Ou(e.pattern):uc(e)?Eu(e.enum):e}function Nm(e){let t=Mm(e);return L(t)?[...t.anyOf]:[t]}function Pm(e,t){return e.reduce((e,n)=>[...e,[...n,t]],[])}function Fm(e,t){return t.reduce((t,n)=>[...t,...Pm(e,n)],[])}function Im(e){return e.reduce((e,t)=>S(t[0],!0)?Fm(e,Nm(t[1])):Fm(e,[t[1]]),[[]])}function Lm(e,t,n){let r=jm(t,Am(e,km(n)));return ws(n)&&S(n.action,`Conditional`)||ws(n)&&S(n.action,`Mapped`)?Im(r):[t]}function Rm(){return[`(not-resolvable)`,Ks()]}function zm(){return[`(not-generic)`,Ks()]}function Bm(e,t,n){return[e,Hs(t,n)]}function Vm(e,t,n){return t in e?Hm(e,t,e[t],n):Rm()}function Hm(e,t,n,r){return Us(n)?Bm(t,n.parameters,n.expression):Vs(n)?Vm(e,n.$ref,r):zm()}function Um(e,t,n){return Hm(e,`(anonymous)`,t,n)}function Wm(e,t,n){if(oc(t)||sh(t)||Ef(xm({},t,n)))return;let r={parameter:e,expect:n,actual:t};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:r})}function Gm(e,t,n,r,i){let a=U(e,t,i);return Wm(n,a,r),ss(e,{[n]:a})}function Km(e,t,n,r,i){let a=U(e,t,n.extends),o=U(e,t,n.equals);return C(i,(i,o)=>qm(Gm(e,t,n.name,a,i),t,r,o),()=>qm(Gm(e,t,n.name,a,o),t,r,[]))}function qm(e,t,n,r){return C(n,(n,i)=>Km(e,t,n,i,r),()=>e)}function Jm(e,t,n,r){return qm(e,t,n,r)}let Ym=0,Xm=0;function Zm(){if(!La(Xm,as().maxInstantiationCount))throw Error(`Type instantiation is excessively deep and possibly infinite`)}function Qm(){Zm(),Xm++,Ym++}function $m(){Ym--,S(Ym,0)&&(Xm=0)}function eh(e){return Ia(e.callstack.length,0)?e.callstack[e.callstack.length-1]:``}function th(e,t){return S(eh(e),t)}function nh(e,t,n,r,i,a){Qm();try{let o=Jm(e,t,r,a),s=U(o,Dv([...t.callstack,n.$ref],t.visited),i);return U(o,Dv([],[]),s)}finally{$m()}}function rh(e,t,n,r,i,a){return a.reduce((a,o)=>{let s=nh(e,t,n,r,i,o);return[...a,s]},[])}function ih(e,t,n,r,i,a){let o=rh(e,t,n,r,i,Lm(r,a,i));return S(o.length,1)?o[0]:ku(o)}function ah(e,t,n,r){let i=Av(e,t,r),a=Um(e,n,r),o=a[0],s=a[1];return Us(s)?th(t,o)?oh(Bs(o),i):ih(e,t,Bs(o),s.parameters,s.expression,i):oh(n,i)}function oh(e,t){return A({"~kind":`Call`},{type:`call`,target:e,arguments:t},{})}function sh(e){return M(e,`Call`)}function ch(e){return Ss(e,[`~immutable`])}function lh(e,t){return j(ch(e),{},t)}function uh(e,t,n,r){return lh(U(e,t,n),r)}function dh(e,t){return e(t)}function fh(e,t){return b(t)?ll(dh(e,t)):ll(t)}function ph(e,t){return hh(e,Ou(t))}function mh(e,t){return Tl(t.map(t=>hh(e,t)))}function hh(e,t){return hl(t)?fh(e,t.const):xf(t)?ph(e,t.pattern):L(t)?mh(e,t.anyOf):t}function gh(e,t={}){return N(`Capitalize`,[e],t)}function _h(e,t={}){return N(`Lowercase`,[e],t)}function vh(e,t={}){return N(`Uncapitalize`,[e],t)}function yh(e,t={}){return N(`Uppercase`,[e],t)}const bh=e=>e[0].toUpperCase()+e.slice(1),xh=e=>e.toLowerCase(),Sh=e=>e[0].toLowerCase()+e.slice(1),Ch=e=>e.toUpperCase();function wh(e,t){return H([e])?j(hh(bh,e),{},t):gh(e,t)}function Th(e,t){return H([e])?j(hh(xh,e),{},t):_h(e,t)}function Eh(e,t){return H([e])?j(hh(Sh,e),{},t):vh(e,t)}function Dh(e,t){return H([e])?j(hh(Ch,e),{},t):yh(e,t)}function Oh(e,t,n,r){return wh(U(e,t,n),r)}function kh(e,t,n,r){return Th(U(e,t,n),r)}function Ah(e,t,n,r){return Eh(U(e,t,n),r)}function jh(e,t,n,r){return Dh(U(e,t,n),r)}function Mh(e,t,n,r,i={}){return N(`Conditional`,[e,t,n,r],i)}function Nh(e,t,n,r,i,a){let o=xm(e,n,r);return Cf(o)?Tl([U(o.inferred,t,i),U(e,t,a)]):wf(o)?U(o.inferred,t,i):U(e,t,a)}function Ph(e,t,n,r,i,a,o){return H([n,r])?j(Nh(e,t,n,r,i,a),{},o):Mh(n,r,i,a,o)}function Fh(e,t,n,r,i,a,o){return Ph(e,t,U(e,t,n),U(e,t,r),i,a,o)}function Ih(e,t={}){return N(`ConstructorParameters`,[e],t)}function Lh(e){let t=Fs(e)?e.parameters:[];return ql(kv({},Dv([],[]),t))}function Rh(e,t){return H([e])?j(Lh(e),{},t):Ih(e,t)}function zh(e,t,n,r){return Rh(U(e,t,n),r)}function Bh(e,t,n={}){return N(`Exclude`,[e,t],n)}function Vh(e,t,n){return H([e,t])?j(wu(e,t),{},n):Bh(e,t,n)}function Hh(e,t,n,r,i){return Vh(U(e,t,n),U(e,t,r),i)}function Uh(e,t,n={}){return N(`Extract`,[e,t],n)}function Wh(e,t){return Ef(xm({},e,t))?[e]:[]}function Gh(e,t,n=[]){return C(e,(e,r)=>Gh(r,t,[...n,...Wh(e,t)]),()=>n)}function Kh(e,t){let n=Au(e);return ku(Gh(L(n)?n.anyOf:[n],t))}function qh(e,t,n){return H([e,t])?j(Kh(e,t),{},n):Uh(e,t,n)}function Jh(e,t,n,r,i){return qh(U(e,t,n),U(e,t,r),i)}function Yh(e,t,n={}){return N(`Index`,[e,t],n)}function Xh(e,t){return ag(ym(e,t))}function Zh(e,t,n){return ag(Tu(e,t,n))}function Qh(e,t){let n=T(e).filter(e=>!w(t,e)),r=T(t).filter(t=>!w(e,t)),i=T(e).filter(e=>w(t,e)),a=n.reduce((t,n)=>({...t,[n]:e[n]}),{}),o=r.reduce((e,n)=>({...e,[n]:t[n]}),{}),s=i.reduce((n,r)=>({...n,[r]:Du([e[r],t[r]])}),{});return ss(ss(a,o),s)}function $h(e){return e.reduce((e,t)=>Qh(e,ag(t)),{})}function eg(e){return e}function tg(e){return ag(au(ql(e)))}function ng(e,t){return T(e).filter(e=>e in t).reduce((n,r)=>({...n,[r]:ku([e[r],t[r]])}),{})}function rg(e,t){return C(e,(e,n)=>rg(n,ng(t,ag(e))),()=>t)}function ig(e){return C(e,(e,t)=>rg(t,ag(e)),()=>_c())}function ag(e){return rc(e)?Xh(e.$defs,e.$ref):cc(e)?Zh(e.if,e.then,e.else):I(e)?$h(e.allOf):L(e)?ig(e.anyOf):Jl(e)?tg(e.items):F(e)?eg(e.properties):{}}function og(e){return P(ag(e))}const sg=/* @__PURE__ */ RegExp(`^(?:0|[1-9][0-9]*)$`);function cg(e){let t=`${e}`;return sg.test(t)?parseInt(t):e}function lg(e){return ll(cg(e))}function ug(e){return e.map(e=>dg(e))}function dg(e){return I(e)?dc(ug(e.allOf)):L(e)?Tl(ug(e.anyOf)):hl(e)?lg(e.const):e}function fg(e,t){return Ef(xm({},dg(t),yl()))?e:hl(t)&&S(t.const,`length`)?yl():Ks()}function pg(e,t){return bg(ym(e,t))}function mg(e,t,n){return bg(Tu(e,t,n))}function hg(e){return bg(Eu(e))}function gg(e){return bg(Du(e))}function _g(e){return[`${e}`]}function vg(e){return bg(Ou(e))}function yg(e){return e.reduce((e,t)=>[...e,...bg(t)],[])}function bg(e){return rc(e)?pg(e.$defs,e.$ref):cc(e)?mg(e.if,e.then,e.else):uc(e)?hg(e.enum):I(e)?gg(e.allOf):hl(e)?_g(e.const):xf(e)?vg(e.pattern):L(e)?yg(e.anyOf):[]}function xg(e){return bg(e)}function Sg(e,t){return t.map(t=>Cg(e,t))}function Cg(e,t){return Ms(t)?js(Cg(e,t.items)):Fs(t)?Ps(Sg(e,t.parameters),Cg(e,t.instanceType)):Rs(t)?Ls(Sg(e,t.parameters),Cg(e,t.returnType)):Jl(t)?ql(Sg(e,t.items)):L(t)?Tl(Sg(e,t.anyOf)):I(t)?dc(Sg(e,t.allOf)):cd(t)?P(e):t}function wg(e,t){return Cg(e,t)}function Tg(e,t){return wg(e,t in e?e[t]:Ks())}function Eg(e,t){return t.reduce((t,n)=>[...t,Tg(e,n)],[])}function Dg(e,t){return ku(Eg(e,xg(t)))}const Og=new RegExp(Yu);function kg(e){return e.filter(e=>Og.test(e))}function Ag(e){return ku(Eg(e,kg(Zs(e))))}function jg(e,t){return bl(t)?Ag(e):Dg(e,t)}function Mg(e){return ll(cg(e))}function Ng(e){return e.map(e=>Pg(e))}function Pg(e){return I(e)?dc(Ng(e.allOf)):L(e)?Tl(Ng(e.anyOf)):hl(e)?Mg(e.const):e}function Fg(e,t){return e.reduceRight((e,n,r)=>Ef(xm({},ll(r),t))?[n,...e]:e,[])}function Ig(e,t){return ju(Fg(e,Pg(t)))}function Lg(e){return ju(e)}function Rg(e,t){return hl(t)&&S(t.const,`length`)?ll(e.length):bl(t)||ol(t)?Lg(e):Ig(e,t)}function zg(e,t){return Ms(e)?fg(e.items,t):F(e)?jg(e.properties,t):Jl(e)?Rg(e.items,t):Ks()}function Bg(e){return rc(e)||cc(e)||I(e)||L(e)?og(e):e}function Vg(e,t,n){return H([e,t])?j(zg(Bg(e),t),{},n):Yh(e,t,n)}function Hg(e,t,n,r,i){return Vg(U(e,t,n),U(e,t,r),i)}function Ug(e,t={}){return N(`InstanceType`,[e],t)}function Wg(e){return Fs(e)?e.instanceType:Ks()}function Gg(e,t){return H([e])?j(Wg(e),{},t):Ug(e,t)}function Kg(e,t,n,r={}){return Gg(U(e,t,n),r)}function qg(e,t={}){return N(`KeyOf`,[e],t)}function Jg(){return Tl([yl(),Cl(),xl()])}function Yg(e){return yl()}function Xg(e){return e.reduce((e,t)=>ul(t)?[...e,ll(cg(t))]:_c(),[])}function Zg(e){return ju(Xg(T(e)))}function Qg(e){return rd(e)}function $g(e){return ju(e.map((e,t)=>ll(t)))}function e_(e){return Gs(e)?Jg():Ms(e)?Yg(e.items):F(e)?Zg(e.properties):ad(e)?Qg(e):Jl(e)?$g(e.items):Ks()}function t_(e){return rc(e)||cc(e)||I(e)||L(e)?og(e):e}function n_(e,t){return H([e])?j(e_(t_(e)),{},t):qg(e,t)}function r_(e,t,n,r){return n_(U(e,t,n),r)}function i_(e,t,n,r,i={}){return N(`Mapped`,[e,t,n,r],i)}function a_(e){return l_(Ou(e))}function o_(e){return e.reduce((e,t)=>[...e,...l_(t)],[])}function s_(e){return l_(Eu(e))}function c_(e){return v(e)?[ll(`${e}`)]:[ll(e)]}function l_(e){return uc(e)?s_(e.enum):hl(e)?c_(e.const):xf(e)?a_(e.pattern):L(e)?o_(e.anyOf):[e]}function u_(e){return l_(e)}function d_(e){return xf(e)?Ou(e.pattern):e}function f_(e,t,n,r,i,a){let o=ss(e,{[n.name]:r}),s=d_(U(o,t,i)),c=U(o,t,a);return pl(s)||ml(s)?{[s.const]:c}:{}}function p_(e,t,n,r,i,a){return r.reduce((r,o)=>[...r,f_(e,t,n,o,i,a)],[])}function m_(e){return e.reduce((e,t)=>[...e,P(t)],[])}function h_(e,t,n,r,i,a){return Du(m_(p_(e,t,n,u_(r),i,a)))}function g_(e,t,n,r,i,a,o){return H([r])?j(h_(e,t,n,r,i,a),{},o):i_(n,r,i,a,o)}function __(e,t,n,r,i,a,o){return g_(e,t,n,U(e,t,r),i,a,o)}function v_(e,t,n){let r=ss(e,t);return T(t).filter(e=>n.includes(e)).reduce((e,n)=>({...e,[n]:_m(r,n,t[n])}),{})}function y_(e,t,n){let r=ss(e,t);return T(t).filter(e=>!n.includes(e)).reduce((e,n)=>({...e,[n]:U(r,Dv([],[]),t[n])}),{})}function b_(e,t,n){let r=rm(t),i=v_(e,t,r),a=y_(e,t,r);return j({...i,...a},{},n)}function x_(e,t,n,r){return b_(e,n,r)}function S_(e,t={}){return N(`NonNullable`,[e],t)}function C_(e){return Vh(e,Tl([gl(),ld()]),{})}function w_(e,t){return H([e])?j(C_(e),{},t):S_(e,t)}function T_(e,t,n,r){return w_(U(e,t,n),r)}function E_(e,t,n={}){return N(`Omit`,[e,t],n)}function D_(e){let t=og(e);return F(t)?t.properties:_c()}function O_(e,t){return T(e).reduce((n,r)=>t.includes(r)?n:{...n,[r]:e[r]},{})}function k_(e,t){return P(O_(D_(e),xg(t)))}function A_(e,t,n){return H([e,t])?j(k_(e,t),{},n):E_(e,t,n)}function j_(e,t,n,r,i){return A_(U(e,t,n),U(e,t,r),i)}function M_(e,t={}){return N(`Parameters`,[e],t)}function N_(e){let t=Rs(e)?e.parameters:[];return ql(kv({},Dv([],[]),t))}function P_(e,t){return H([e])?j(N_(e),{},t):M_(e,t)}function F_(e,t,n,r){return P_(U(e,t,n),r)}function I_(e,t={}){return N(`Partial`,[e],t)}function L_(e,t){let n=H_(ym(e,t));return nc(ss(e,{[t]:n}),t)}function R_(e,t,n){return H_(Tu(e,t,n))}function z_(e){return H_(Du(e))}function B_(e){return Tl(e.map(e=>H_(e)))}function V_(e){return P(T(e).reduce((t,n)=>({...t,[n]:Js(e[n])}),{}))}function H_(e){return rc(e)?L_(e.$defs,e.$ref):cc(e)?R_(e.if,e.then,e.else):I(e)?z_(e.allOf):L(e)?B_(e.anyOf):F(e)?V_(e.properties):P({})}function U_(e,t){return H([e])?j(H_(e),{},t):I_(e,t)}function W_(e,t,n,r){return U_(U(e,t,n),r)}function G_(e,t,n={}){return N(`Pick`,[e,t],n)}function K_(e,t){return T(e).reduce((n,r)=>t.includes(r)?ss(n,{[r]:e[r]}):n,{})}function q_(e,t){return P(K_(D_(e),xg(t)))}function J_(e,t,n){return H([e,t])?j(q_(e,t),{},n):G_(e,t,n)}function Y_(e,t,n,r,i){return J_(U(e,t,n),U(e,t,r),i)}function X_(e,t={}){return N(`ReadonlyObject`,[e],t)}function Z_(e){return Rv(js(e))}function Q_(e,t){let n=iv(ym(e,t));return nc(ss(e,{[t]:n}),t)}function $_(e,t,n){return iv(Tu(e,t,n))}function ev(e){return iv(Du(e))}function tv(e){return P(T(e).reduce((t,n)=>({...t,[n]:$c(e[n])}),{}))}function nv(e){return Rv(ql(e))}function rv(e){return Tl(e.map(e=>iv(e)))}function iv(e){return Ms(e)?Z_(e.items):rc(e)?Q_(e.$defs,e.$ref):cc(e)?$_(e.if,e.then,e.else):I(e)?ev(e.allOf):F(e)?tv(e.properties):Jl(e)?nv(e.items):L(e)?rv(e.anyOf):e}function av(e,t){return H([e])?j(iv(e),{},t):X_(e)}function ov(e,t,n,r){return av(U(e,t,n),r)}function sv(e,t,n,r){return t.visited.includes(r)?n:r in e?U(e,Dv(t.callstack,[...t.visited,r]),e[r]):n}function cv(e,t){let n=pv(ym(e,t));return nc(ss(e,{[t]:n}),t)}function lv(e,t,n){return pv(Tu(e,t,n))}function uv(e){return pv(Du(e))}function dv(e){return Tl(e.map(e=>pv(e)))}function fv(e){return P(T(e).reduce((t,n)=>({...t,[n]:ru(e[n])}),{}))}function pv(e){return rc(e)?cv(e.$defs,e.$ref):cc(e)?lv(e.if,e.then,e.else):I(e)?uv(e.allOf):L(e)?dv(e.anyOf):F(e)?fv(e.properties):P({})}function mv(e,t={}){return N(`Required`,[e],t)}function hv(e,t){return H([e])?j(pv(e),{},t):mv(e,t)}function gv(e,t,n,r){return hv(U(e,t,n),r)}function _v(e,t={}){return N(`ReturnType`,[e],t)}function vv(e){return Rs(e)?e.returnType:Ks()}function yv(e,t){return H([e])?j(vv(e),{},t):_v(e,t)}function bv(e,t,n,r={}){return yv(U(e,t,n),r)}function xv(e,t){return N(`With`,[e,t],{})}function Sv(e,t){return Cv(e,t)}function Cv(e,t){return H([e])?j(e,{},t):xv(e,t)}function wv(e,t,n,r){return Cv(U(e,t,n),r)}function Tv(e){return sd(e)?Jl(e.items)?Ev(e.items.items):oc(e.items)||Vs(e.items)?[e]:[Ks()]:[e]}function Ev(e){return e.reduce((e,t)=>[...e,...Tv(t)],[])}function Dv(e,t){return{callstack:e,visited:t}}function H(e){return C(e,(e,t)=>!Vs(e)&&H(t),()=>!0)}function Ov(e,t,n){return T(n).reduce((r,i)=>({...r,[i]:U(e,t,n[i])}),{})}function kv(e,t,n){return Ev(Av(e,t,n))}function Av(e,t,n){return n.map(n=>U(e,t,n))}function jv(e,t){let n=Ys(e)?ks(t,{}):t,r=el(e)?Es(n,{}):n;return Qc(e)?Iv(r,{}):r}function Mv(e,t,n,r,i){return S(n,`AddImmutable`)?Lv(e,t,r[0],i):S(n,`RemoveImmutable`)?uh(e,t,r[0],i):S(n,`AddReadonly`)?Ds(e,t,r[0],i):S(n,`RemoveReadonly`)?Ql(e,t,r[0],i):S(n,`AddOptional`)?As(e,t,r[0],i):S(n,`RemoveOptional`)?nu(e,t,r[0],i):S(n,`Capitalize`)?Oh(e,t,r[0],i):S(n,`Conditional`)?Fh(e,t,r[0],r[1],r[2],r[3],i):S(n,`ConstructorParameters`)?zh(e,t,r[0],i):S(n,`Evaluate`)?Om(e,t,r[0],i):S(n,`Exclude`)?Hh(e,t,r[0],r[1],i):S(n,`Extract`)?Jh(e,t,r[0],r[1],i):S(n,`Index`)?Hg(e,t,r[0],r[1],i):S(n,`InstanceType`)?Kg(e,t,r[0],i):S(n,`Interface`)?Jp(e,t,r[0],r[1],i):S(n,`KeyOf`)?r_(e,t,r[0],i):S(n,`Lowercase`)?kh(e,t,r[0],i):S(n,`Mapped`)?__(e,t,r[0],r[1],r[2],r[3],i):S(n,`Module`)?x_(e,t,r[0],i):S(n,`NonNullable`)?T_(e,t,r[0],i):S(n,`Pick`)?Y_(e,t,r[0],r[1],i):S(n,`Parameters`)?F_(e,t,r[0],i):S(n,`Partial`)?W_(e,t,r[0],i):S(n,`Omit`)?j_(e,t,r[0],r[1],i):S(n,`ReadonlyObject`)?ov(e,t,r[0],i):S(n,`Record`)?Ju(e,t,r[0],r[1],i):S(n,`Required`)?gv(e,t,r[0],i):S(n,`ReturnType`)?bv(e,t,r[0],i):S(n,`TemplateLiteral`)?vf(e,t,r[0],i):S(n,`Uncapitalize`)?Ah(e,t,r[0],i):S(n,`Uppercase`)?jh(e,t,r[0],i):S(n,`With`)?wv(e,t,r[0],r[1]):N(n,r,i)}function Nv(e,t,n){return jv(n,Vs(n)?sv(e,t,n,n.$ref):Ms(n)?js(U(e,t,n.items),Ns(n)):sh(n)?ah(e,t,n.target,n.arguments):Fs(n)?Ps(Av(e,t,n.parameters),U(e,t,n.instanceType),Is(n)):Rs(n)?Ls(Av(e,t,n.parameters),U(e,t,n.returnType),zs(n)):cc(n)?sc(U(e,t,n.if),U(e,t,n.then),U(e,t,n.else),lc(n)):I(n)?dc(Av(e,t,n.allOf),fc(n)):F(n)?P(Ov(e,t,n.properties),$s(n)):ad(n)?ed(nd(n),U(e,t,id(n))):sd(n)?od(U(e,t,n.items)):Jl(n)?ql(kv(e,t,n.items),Yl(n)):L(n)?Tl(Av(e,t,n.anyOf),El(n)):n)}function U(e,t,n){return ws(n)?Mv(e,t,n.action,n.parameters,n.options):Nv(e,t,n)}function Pv(e,t){return U(e,Dv([],[]),t)}function Fv(e){return j(e,{"~immutable":!0},{})}function Iv(e,t){return j(Fv(e),{},t)}function Lv(e,t,n,r){return Iv(U(e,t,n),r)}function Rv(e,t={}){return Iv(e,t)}function zv(e,t={}){return Dm(e,t)}function Bv(e,t){let n=Sm(e,t);return S(n,3)?1:+!!S(n,1)}function Vv(e,t,n=[]){return C(t,(r,i)=>S(Bv(e,r),1)?Vv(e,i,[...n,r]):[...n,e,...t],()=>[...n,e])}function Hv(e,t=[]){return C(e,(e,n)=>Hv(n,Vv(e,t)),()=>t)}function Uv(e){return Hv(e)}const Wv=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i],Gv=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,Kv=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function qv(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!Kv.some(t=>t.test(e.errorMessage))&&(Wv.some(t=>t.test(e.errorMessage))||e.provider===`cerebras`&&Gv.test(e.errorMessage))||t&&e.stopReason===`stop`&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason===`length`&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}function Jv(e){return w(e,`~refine`)&&_(e[`~refine`])&&Ka(e[`~refine`],0,e=>y(e)&&w(e,`check`)&&w(e,`error`)&&ja(e.check)&&ja(e.error))}function Yv(e){return y(e)&&!_(e)}function Xv(e){return ka(e)}function W(e){return Yv(e)||Xv(e)}function Zv(e){return w(e,`additionalItems`)&&W(e.additionalItems)}function Qv(e){return w(e,`additionalProperties`)&&W(e.additionalProperties)}function $v(e){return w(e,`allOf`)&&_(e.allOf)&&e.allOf.every(e=>W(e))}function ey(e){return w(e,`$anchor`)&&b(e.$anchor)}function ty(e){return w(e,`anyOf`)&&_(e.anyOf)&&e.anyOf.every(e=>W(e))}function ny(e){return w(e,`const`)}function ry(e){return w(e,`contains`)&&W(e.contains)}function iy(e){return w(e,`default`)}function ay(e){return w(e,`dependencies`)&&y(e.dependencies)&&Object.values(e.dependencies).every(e=>W(e)||_(e)&&e.every(e=>b(e)))}function oy(e){return w(e,`dependentRequired`)&&y(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>_(e)&&e.every(e=>b(e)))}function sy(e){return w(e,`dependentSchemas`)&&y(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>W(e))}function cy(e){return w(e,`$dynamicAnchor`)&&b(e.$dynamicAnchor)}function ly(e){return w(e,`$dynamicRef`)&&b(e.$dynamicRef)}function uy(e){return w(e,`else`)&&W(e.else)}function dy(e){return w(e,`enum`)&&_(e.enum)}function fy(e){return w(e,`exclusiveMaximum`)&&(v(e.exclusiveMaximum)||Oa(e.exclusiveMaximum))}function py(e){return w(e,`exclusiveMinimum`)&&(v(e.exclusiveMinimum)||Oa(e.exclusiveMinimum))}function my(e){return w(e,`format`)&&b(e.format)}function hy(e){return w(e,`$id`)&&b(e.$id)}function gy(e){return w(e,`if`)&&W(e.if)}function _y(e){return w(e,`items`)&&(W(e.items)||_(e.items)&&e.items.every(e=>W(e)))}function vy(e){return _y(e)&&_(e.items)}function yy(e){return w(e,`maximum`)&&(v(e.maximum)||Oa(e.maximum))}function by(e){return w(e,`maxContains`)&&v(e.maxContains)}function xy(e){return w(e,`maxItems`)&&v(e.maxItems)}function Sy(e){return w(e,`maxLength`)&&v(e.maxLength)}function Cy(e){return w(e,`maxProperties`)&&v(e.maxProperties)}function wy(e){return w(e,`minimum`)&&(v(e.minimum)||Oa(e.minimum))}function Ty(e){return w(e,`minContains`)&&v(e.minContains)}function Ey(e){return w(e,`minItems`)&&v(e.minItems)}function Dy(e){return w(e,`minLength`)&&v(e.minLength)}function Oy(e){return w(e,`minProperties`)&&v(e.minProperties)}function ky(e){return w(e,`multipleOf`)&&(v(e.multipleOf)||Oa(e.multipleOf))}function Ay(e){return w(e,`not`)&&W(e.not)}function jy(e){return w(e,`oneOf`)&&_(e.oneOf)&&e.oneOf.every(e=>W(e))}function My(e){return w(e,`pattern`)&&(b(e.pattern)||e.pattern instanceof RegExp)}function Ny(e){return w(e,`patternProperties`)&&y(e.patternProperties)&&Object.values(e.patternProperties).every(e=>W(e))}function Py(e){return w(e,`prefixItems`)&&_(e.prefixItems)&&e.prefixItems.every(e=>W(e))}function Fy(e){return w(e,`properties`)&&y(e.properties)&&Object.values(e.properties).every(e=>W(e))}function Iy(e){return w(e,`propertyNames`)&&(y(e.propertyNames)||W(e.propertyNames))}function Ly(e){return w(e,`$recursiveAnchor`)&&ka(e.$recursiveAnchor)}function Ry(e){return Ly(e)&&S(e.$recursiveAnchor,!0)}function zy(e){return w(e,`$recursiveRef`)&&b(e.$recursiveRef)}function By(e){return w(e,`$ref`)&&b(e.$ref)}function Vy(e){return w(e,`required`)&&_(e.required)&&e.required.every(e=>b(e))}function Hy(e){return w(e,`then`)&&W(e.then)}function Uy(e){return w(e,`type`)&&(b(e.type)||_(e.type)&&e.type.every(e=>b(e)))}function Wy(e){return w(e,`uniqueItems`)&&ka(e.uniqueItems)}function Gy(e){return w(e,`unevaluatedItems`)&&W(e.unevaluatedItems)}function Ky(e){return w(e,`unevaluatedProperties`)&&W(e.unevaluatedProperties)}function qy(e){return Gy(e)||Ky(e)||Ja(T(e),t=>Yy(e[t]))}function Jy(e){return Ja(e,e=>Yy(e))}function Yy(e){return _(e)?Jy(e):y(e)?qy(e):!1}function Xy(e,t){return Yy(t)||Ja(T(e),t=>Yy(e[t]))}var Zy=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return D(O(`context`,`Push`),[])}Pop(){return D(O(`context`,`Pop`),[])}AddIndex(e){return D(O(`context`,`AddIndex`),[e])}AddKey(e){return D(O(`context`,`AddKey`),[e])}Merge(e){return D(O(`context`,`Merge`),[e])}},Qy=class{constructor(){let e=/* @__PURE__ */ new Set,t=/* @__PURE__ */ new Set;this.stack=[{indices:e,keys:t}]}Push(){let e=/* @__PURE__ */ new Set,t=/* @__PURE__ */ new Set;return this.stack.push({indices:e,keys:t}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let t of e)t.GetIndices().forEach(e=>this.GetIndices().add(e)),t.GetKeys().forEach(e=>this.GetKeys().add(e));return!0}},$y=class extends Qy{constructor(){super(),this.errors=[]}AtCapacity(){return this.errors.length>=as().maxErrors}AddError(e){return this.AtCapacity()||this.errors.push(e),!1}GetErrors(){return this.errors}};const eb={identifier:`External`,variables:[]};function tb(e){let t=`External[${eb.variables.length}]`;return eb.variables.push(e),t}function nb(){eb.variables=[]}function rb(){return{...eb}}function ib(e,t,n,r){return Ao(tb(n[`~refine`].map(e=>e)),k(0),[`refinement`,`_`],D(O(`refinement`,`check`),[r]))}function ab(e,t,n,r){return Ka(n[`~refine`],0,(e,t)=>e.check(r))}function ob(e,t,n,r,i,a){return qa(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let sb=0;function cb(){return`var_${sb++}`}function lb(e){return _y(e)&&_(e.items)}function ub(e,t,n,r){let[i,a]=[cb(),cb()],o=xT(e,t,n.additionalItems,i),s=To(a,k(n.items.length)),c=t.AddIndex(a);return Ao(r,k(0),[i,a],E(s,so(o,c)))}function db(e,t,n,r){let[i,a]=[cb(),cb()],o=xT(e,t,n.additionalItems,i),s=To(a,k(n.items.length));return Ao(r,k(0),[i,a],E(s,o))}function fb(e,t,n,r){return lb(n)?t.UseUnevaluated()?ub(e,t,n,r):db(e,t,n,r):k(!0)}function pb(e,t,n,r){return!lb(n)||Ka(r,0,(r,i)=>La(i,n.items.length)||CT(e,t,n.additionalItems,r)&&t.AddIndex(i))}function mb(e,t,n,r,i,a){return!lb(i)||Ka(a,0,(a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return La(o,i.items.length)||TT(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function hb(e){return new RegExp(e,`u`)}function gb(e,t){return!e.UseUnevaluated()&&(S(t,!0)||y(t)&&S(T(t).length,0))}function _b(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function vb(e){let t=[];return Ny(e)&&t.push(...T(e.patternProperties)),Fy(e)&&t.push(...T(e.properties).map(_b)),S(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function yb(e,t,n){return Vy(t)&&Fy(t)&&!Ny(t)&&S(t.additionalProperties,!1)&&S(T(t.properties).length,t.required.length)}function bb(e,t,n){return Co(O(D(O(`Object`,`getOwnPropertyNames`),[n]),`length`),k(t.required.length))}function xb(e,t,n,r){let[i,a]=[cb(),cb()],o=tb(hb(vb(n))),s=xT(e,t,n.additionalProperties,`${r}[${i}]`),c=D(O(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?E(c,so(s,l)):E(c,s);return Ao(Fo(r),k(0),[i,a],u)}function Sb(e,t,n,r){return gb(t,n.additionalProperties)?k(!0):yb(t,n,r)?bb(t,n,r):xb(e,t,n,r)}function Cb(e,t,n,r){let i=hb(vb(n));return Ka(T(r),0,(a,o)=>i.test(a)||CT(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function wb(e,t,n,r,i,a){let o=hb(vb(i)),s=[];return qa(T(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=o.test(c)||TT(e,t,u,d,i.additionalProperties,a[c])&&t.AddKey(c);return f||s.push(c),f})||t.AddError({keyword:`additionalProperties`,schemaPath:n,instancePath:r,params:{additionalProperties:s}})}function Tb(e,t,n,r,i){let a=Uo(`results`,`[]`),o=n.map((e,t)=>Uo(`context_${t}`,Bo(`CheckContext`,[]))),s=n.map((n,i)=>Uo(`condition_${i}`,D(zo([`context`],ST(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>Wo(`condition_${t}`,D(O(`results`,`push`),[`context_${t}`]))),l=Go(so(i,t.Merge(`results`)));return D(zo([],Ho([a,...o,...s,...c,l])),[])}function Eb(e,t,n,r){return Tb(e,t,n.allOf,r,Co(O(`results`,`length`),k(n.allOf.length)))}function Db(e,t,n,r){return Ko(n.allOf.map(n=>ST(e,t,n,r)))}function Ob(e,t,n,r){return t.UseUnevaluated()?Eb(e,t,n,r):Db(e,t,n,r)}function kb(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new Qy;return wT(e,i,n,r)?[...t,i]:t},[]);return S(i.length,n.allOf.length)&&t.Merge(i)}function Ab(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new $y,u=ET(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=S(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function jb(e,t,n,r){return Tb(e,t,n.anyOf,r,wo(O(`results`,`length`),k(0)))}function Mb(e,t,n,r){return qo(n.anyOf.map(n=>ST(e,t,n,r)))}function Nb(e,t,n,r){return t.UseUnevaluated()?jb(e,t,n,r):Mb(e,t,n,r)}function Pb(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new Qy;return wT(e,i,n,r)?[...t,i]:t},[]);return Ia(i.length,0)&&t.Merge(i)}function Fb(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new $y,l=ET(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=Ia(s.length,0)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c||t.AddError({keyword:`anyOf`,schemaPath:n,instancePath:r,params:{}})}function Ib(e,t,n,r){return k(!!n)}function Lb(e,t,n,r){return n}function Rb(e,t,n,r,i,a){return Lb(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function zb(e,t,n,r){return Ha(n.const)?Co(r,k(n.const)):Lo(r,tb(n.const))}function Bb(e,t,n,r){return Ha(n.const)?S(r,n.const):io(r,n.const)}function Vb(e,t,n,r,i,a){return Bb(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Hb(e){return!(Ty(e)&&S(e.minContains,0))}function Ub(e,t,n,r){let[i,a]=[cb(),cb()];return so(co(Co(O(r,`length`),k(0))),Mo(r,[i,a],so(ST(e,t,n.contains,i),t.AddIndex(a))))}function Wb(e,t,n,r){let[i]=[cb()];return so(co(Co(O(r,`length`),k(0))),jo(r,[i,`_`],ST(e,t,n.contains,i)))}function Gb(e,t,n,r){return Hb(n)?t.UseUnevaluated()?Ub(e,t,n,r):Wb(e,t,n,r):k(!0)}function Kb(e,t,n,r){return!Hb(n)||!S(r.length,0)&&Ya(r,(r,i)=>wT(e,t,n.contains,r)&&t.AddIndex(i))}function qb(e,t,n,r,i,a){return Kb(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Jb(e,t,n,r){return E(Co(O(Fo(r),`length`),k(0)),Ko($a(n.dependencies).map(([n,i])=>{let a=co(Io(r,k(n))),o=ST(e,t,i,r);return E(a,_(i)?(e=>Ko(e.map(e=>Io(r,k(e)))))(i):o)})))}function Yb(e,t,n,r){let i=S(T(r).length,0),a=Ka($a(n.dependencies),0,([n,i])=>!w(r,n)||(_(i)?i.every(e=>w(r,e)):wT(e,t,i,r)));return i||a}function Xb(e,t,n,r,i,a){let o=S(T(a).length,0),s=qa($a(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!w(a,i)||(_(o)?o.every(e=>w(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):ET(e,t,s,r,o,a))});return o||s}function Zb(e,t,n,r){return E(Co(O(Fo(r),`length`),k(0)),Ko($a(n.dependentRequired).map(([e,t])=>E(co(Io(r,k(e))),Ko(t.map(e=>Io(r,k(e))))))))}function Qb(e,t,n,r){let i=S(T(r).length,0),a=Ka($a(n.dependentRequired),0,([e,t])=>!w(r,e)||t.every(e=>w(r,e)));return i||a}function $b(e,t,n,r,i,a){let o=S(T(a).length,0),s=qa($a(i.dependentRequired),0,([e,i])=>!w(a,e)||qa(i,0,o=>w(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function ex(e,t,n,r){return E(Co(O(Fo(r),`length`),k(0)),Ko($a(n.dependentSchemas).map(([n,i])=>E(co(Io(r,k(n))),ST(e,t,i,r)))))}function tx(e,t,n,r){let i=S(T(r).length,0),a=Ka($a(n.dependentSchemas),0,([n,i])=>!w(r,n)||wT(e,t,i,r));return i||a}function nx(e,t,n,r,i,a){let o=S(T(a).length,0),s=qa($a(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!w(a,i)||ET(e,t,s,r,o,a)});return o||s}function rx(e,t,n,r){return IT(e,t,e.DynamicRef(n)??!1,r)}function ix(e,t,n,r){let i=e.DynamicRef(n)??!1;return W(i)&&wT(e,t,i,r)}function ax(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return W(o)&&ET(e,t,`#`,r,o,a)}function ox(e,t,n,r){return qo(n.enum.map(e=>Ha(e)?Co(r,k(e)):Lo(r,tb(e))))}function sx(e,t,n,r){return Ja(n.enum,e=>Ha(e)?S(r,e):io(r,e))}function cx(e,t,n,r,i,a){return sx(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function lx(e,t,n,r){return To(r,k(n.exclusiveMaximum))}function ux(e,t,n,r){return La(r,n.exclusiveMaximum)}function dx(e,t,n,r,i,a){return ux(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function fx(e,t,n,r){return wo(r,k(n.exclusiveMinimum))}function px(e,t,n,r){return Ia(r,n.exclusiveMinimum)}function mx(e,t,n,r,i,a){return px(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const hx=[0,31,28,31,30,31,30,31,31,30,31,30,31],gx=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function _x(e){return e%4==0&&(e%100!=0||e%400==0)}function vx(e){let t=gx.exec(e);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r===2&&_x(n)?29:hx[r])}const yx=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function bx(e,t=!0){let n=yx.exec(e);if(!n||t&&!n[4]&&!n[5])return!1;let r=+n[1],i=+n[2],a=+n[3];if(r>23||i>59||a>60)return!1;if(n[5]){let e=+n[6],t=+n[7];if(e>23||t>59)return!1}if(a<60)return!0;let o=n[5]===`-`?-1:1,s=+(n[6]||0),c=+(n[7]||0);return((r*60+i-o*(s*60+c))%1440+1440)%1440==1439}function xx(e){let t=e.split(/T/i);return t.length===2&&vx(t[0])&&bx(t[1])}const Sx=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Cx(e){return Sx.test(e)}const wx=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function Tx(e){return wx.test(e)}const Ex=/^(?!-).*(?<!-)$/,Dx=/^(?!..--)/,Ox=/^[a-zA-Z0-9-]*$/,kx=/[^\p{ASCII}]/u,Ax=/[0-9]/,jx=/[\u{0660}-\u{0669}]/u,Mx=/[\u{06f0}-\u{06f9}]/u,Nx=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,Px=/[\u{002d}\u{002b}]/u,Fx=/\p{Mn}/u,Ix=/\p{Mc}/u,Lx=/[\p{Mn}\p{Mc}\p{Me}]/u,Rx=/\p{L}/u,zx=/\p{Nd}/u,Bx=/\p{Script=Greek}/u,Vx=/\p{Script=Hebrew}/u,Hx=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Ux=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Wx=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,Gx=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,Kx=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,qx=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,Jx=new RegExp([Ax,Mx].map(e=>e.source).join(`|`),`u`),Yx=new RegExp([Rx,Px,Nx,zx,Fx,Ix,Kx,qx].map(e=>e.source).join(`|`),`u`);function Xx(e){return Ex.test(e)&&Dx.test(e)&&Ox.test(e)}function Zx(){throw null}function Qx(e){return e.toLowerCase().startsWith(`xn--`)}function $x(e,t,n){e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let r=0;for(;e>455;)e=Math.floor(e/35),r+=36;return r+Math.floor(36*e/(e+38))}function eS(e){let t=[],n=128,r=0,i=72,a=e.lastIndexOf(`-`);if(a>0)for(let n=0;n<a;n++){let r=e.charCodeAt(n);r>=128&&Zx(),t.push(r)}let o=a<0?0:a+1;for(;o<e.length;){let a=r,s=1,c=36;for(;;){o>=e.length&&Zx();let t=e.charCodeAt(o++),n;t>=97&&t<=122?n=t-97:t>=48&&t<=57?n=t-48+26:Zx(),r+=n*s;let a=c<=i?1:c>=i+26?26:c-i;if(n<a)break;s*=36-a,c+=36}let l=t.length+1;i=$x(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return String.fromCodePoint(...t)}function tS(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}const nS=new RegExp(kx.source,`gu`);function rS(e){let t=e.replace(nS,``),n=t.length,r=n>0?[t,`-`]:[],i=Array.from(e,e=>e.codePointAt(0)),a=128,o=0,s=72,c=n;for(;c<i.length;){let e=1/0;for(let t of i)t>=a&&t<e&&(e=t);o+=(e-a)*(c+1),a=e;for(let e of i)if(e<a&&o++,e===a){let e=o;for(let t=36;;t+=36){let n=t<=s?1:t>=s+26?26:t-s;if(e<n)break;let i=n+(e-n)%(36-n);r.push(tS(i)),e=Math.floor((e-n)/(36-n))}r.push(tS(e)),s=$x(o,c+1,c===n),o=0,c++}o++,a++}return r.join(``)}const iS=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,aS=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,oS=/^(?:R|AL|AN)$/;function sS(e){if(Qx(e))try{return lS(eS(e.slice(4).toLowerCase()))}catch{return!1}return lS(e)}function cS(e){let t=String.fromCodePoint(e);return Jx.test(t)?`EN`:jx.test(t)?`AN`:Fx.test(t)?`NSM`:Vx.test(t)?`R`:Ux.test(t)?`AL`:Rx.test(t)?`L`:`ON`}function lS(e){for(let t of e)if(oS.test(cS(t.codePointAt(0))))return!0;return!1}function uS(e){let t=!1,n=aS,r=!1,i=!1,a=!0;for(let o of e){let e=cS(o.codePointAt(0));if(a){if(e!==`L`&&e!==`R`&&e!==`AL`)return!1;t=e===`R`||e===`AL`,n=t?iS:aS,a=!1}if(!n.test(e))return!1;e===`EN`?r=!0:e===`AN`&&(i=!0)}return!(t&&r&&i)}function dS(e){return kx.test(e)&&rS(e).length+4>63}function fS(e){return e[0]===`-`||e[e.length-1]===`-`||e.slice(2).join(``).startsWith(`--`)}function pS(e){if(dS(e)||lS(e)&&!uS(e))return!1;let t=[...e],n=t.map(e=>e.codePointAt(0)),r=n.length;if(fS(t)||Lx.test(t[0]))return!1;let i=!1;for(let e=0;e<r;e++){let r=n[e],a=t[e];if(Gx.test(a)||!Yx.test(a))return!1;Hx.test(a)&&(i=!0);let o=n[e-1],s=n[e+1];switch(r){case 183:if(o!==108||s!==108)return!1;break;case 885:if(!s||!Bx.test(t[e+1]))return!1;break;case 1523:case 1524:if(!o||!Vx.test(t[e-1]))return!1;break;case 8204:if(!o||o<128&&!Wx.test(t[e-1]))return!1;break;case 8205:if(!o||!Wx.test(t[e-1]))return!1}}return!(e.includes(`・`)&&!i)}function mS(e){if(!Qx(e))return!1;try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=eS(t);return kx.test(n)?pS(n):!1}catch{return!1}}function hS(e){return e.length>0&&e.length<=63}function gS(e){return hS(e)&&(mS(e)||Xx(e))}function _S(e){return e.length===0||e.length>253||e.charCodeAt(e.length-1)===46?!1:e.split(`.`).every(e=>gS(e))}function vS(e){return e.length>0&&e.length<=63}function yS(e){return vS(e)&&(mS(e)||pS(e))}function bS(e){return e.replace(/[\uff01-\uff5e]/g,e=>String.fromCharCode(e.charCodeAt(0)-65248)).normalize(`NFC`).replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,``).replace(/[\u002E\u3002\uFF0E\uFF61]/g,`.`)}function xS(e){if(e.length===0||e.includes(` `))return!1;let t=bS(e);if(t.length>253)return!1;let n=t.split(`.`),r=n.some(e=>sS(e));return n.every(e=>yS(e)&&(!r||uS(e)))}function SS(e){return _S(e)}const CS=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function wS(e){return CS.test(e.normalize(`NFC`))}function TS(e){return xS(e)}const ES=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function DS(e){return ES.test(e)}const OS=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function kS(e){return OS.test(e)}const AS=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,jS=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function MS(e){return!AS.test(e)&&!jS.test(e)&&URL.canParse(e,`http://example.com`)}const NS=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,PS=/[\x00-\x20<>\^`{|}\\]/,FS=/%(?![0-9a-fA-F]{2})/;function IS(e){return e.length<2048?e.replace(NS,`[::1]`):e}function LS(e){return PS.test(e)||FS.test(e)?!1:URL.canParse(IS(e))}const RS=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function zS(e){return RS.test(e)}const BS=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function VS(e){return BS.test(e)}function HS(e){try{return new RegExp(e,`u`),!0}catch{return!1}}const US=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function WS(e){return US.test(e)}const GS=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function KS(e){return GS.test(e)}const qS=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function JS(e){return qS.test(e)}const YS=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function XS(e){return YS.test(e)}function ZS(e){return URL.canParse(e)}const QS=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function $S(e){return QS.test(e)}const G=/* @__PURE__ */ new Map;function eC(){G.clear()}function tC(){return[...G.entries()]}function nC(e,t){G.set(e,t)}function rC(e){return G.has(e)}function iC(e){return G.get(e)}function aC(e,t){return G.get(e)?.(t)??!0}function oC(){eC(),G.set(`date-time`,xx),G.set(`date`,vx),G.set(`duration`,Cx),G.set(`email`,Tx),G.set(`hostname`,SS),G.set(`idn-email`,wS),G.set(`idn-hostname`,TS),G.set(`ipv4`,DS),G.set(`ipv6`,kS),G.set(`iri-reference`,MS),G.set(`iri`,LS),G.set(`json-pointer-uri-fragment`,zS),G.set(`json-pointer`,VS),G.set(`regex`,HS),G.set(`relative-json-pointer`,WS),G.set(`time`,bx),G.set(`uri-reference`,KS),G.set(`uri-template`,JS),G.set(`uri`,XS),G.set(`url`,ZS),G.set(`uuid`,$S)}oC();var sC=/* @__PURE__ */ e({Clear:()=>eC,Entries:()=>tC,Get:()=>iC,Has:()=>rC,IsDate:()=>vx,IsDateTime:()=>xx,IsDuration:()=>Cx,IsEmail:()=>Tx,IsHostname:()=>SS,IsIPv4:()=>DS,IsIPv6:()=>kS,IsIdnEmail:()=>wS,IsIdnHostname:()=>TS,IsIri:()=>LS,IsIriReference:()=>MS,IsJsonPointer:()=>VS,IsJsonPointerUriFragment:()=>zS,IsRegex:()=>HS,IsRelativeJsonPointer:()=>WS,IsTime:()=>bx,IsUri:()=>XS,IsUriReference:()=>KS,IsUriTemplate:()=>JS,IsUrl:()=>ZS,IsUuid:()=>$S,Reset:()=>oC,Set:()=>nC,Test:()=>aC});function cC(e,t,n,r){return D(O(`Format`,`Test`),[k(n.format),r])}function lC(e,t,n,r){return aC(n.format,r)}function uC(e,t,n,r,i,a){return lC(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function dC(e,t,n,r){let i=!Hy(n)||n.then,a=!uy(n)||n.else;return Vo(ST(e,t,n.if,r),ST(e,t,i,r),ST(e,t,a,r))}function fC(e,t,n,r){let i=!Hy(n)||n.then,a=!uy(n)||n.else;return wT(e,t,n.if,r)?wT(e,t,i,r):wT(e,t,a,r)}function pC(e,t,n,r,i,a){let o=!Hy(i)||i.then,s=!uy(i)||i.else,c=new $y,l=ET(e,c,`${n}/if`,r,i.if,a)?ET(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):ET(e,t,`${n}/else`,r,s,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`else`}});return l&&t.Merge([c]),l}function mC(e,t,n,r){return Ko(n.items.map((n,i)=>E(Eo(O(r,`length`),k(i)),so(xT(e,t,n,`${r}[${i}]`),t.AddIndex(k(i))))))}function hC(e,t,n,r){return Ko(n.items.map((n,i)=>E(Eo(O(r,`length`),k(i)),xT(e,t,n,`${r}[${i}]`))))}function gC(e,t,n,r){return t.UseUnevaluated()?mC(e,t,n,r):hC(e,t,n,r)}function _C(e,t,n,r){return Ka(n.items,0,(n,i)=>Ra(r.length,i)||CT(e,t,n,r[i])&&t.AddIndex(i))}function vC(e,t,n,r,i,a){return qa(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return Ra(a.length,o)||TT(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function yC(e,t,n,r){let i=Py(n)?n.prefixItems.length:0,a=xT(e,t,n.items,`element`),o=t.AddIndex(`index`);return Ao(r,k(i),[`element`,`index`],so(a,o))}function bC(e,t,n,r){let i=Py(n)?n.prefixItems.length:0,a=xT(e,t,n.items,`element`);return Ao(r,k(i),[`element`,`index`],a)}function xC(e,t,n,r){return t.UseUnevaluated()?yC(e,t,n,r):bC(e,t,n,r)}function SC(e,t,n,r){return Ka(r,Py(n)?n.prefixItems.length:0,(r,i)=>CT(e,t,n.items,r)&&t.AddIndex(i))}function CC(e,t,n,r,i,a){return qa(a,Py(i)?i.prefixItems.length:0,(a,o)=>TT(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function wC(e,t,n,r){return vy(n)?gC(e,t,n,r):xC(e,t,n,r)}function TC(e,t,n,r){return vy(n)?_C(e,t,n,r):SC(e,t,n,r)}function EC(e,t,n,r,i,a){return vy(i)?vC(e,t,n,r,i,a):CC(e,t,n,r,i,a)}function DC(e){return ry(e)}function OC(e,t,n,r){if(!DC(n))return k(!0);let[i]=[cb()];return Eo(No(r,[i,`_`],ST(e,t,n.contains,i)),k(n.maxContains))}function kC(e,t,n,r){return!DC(n)||Ra(Xa(r,r=>wT(e,t,n.contains,r)),n.maxContains)}function AC(e,t,n,r,i,a){let o=Ty(i)?i.minContains:1;return kC(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function jC(e,t,n,r){return Eo(r,k(n.maximum))}function MC(e,t,n,r){return Ra(r,n.maximum)}function NC(e,t,n,r,i,a){return MC(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function PC(e,t,n,r){return Eo(O(r,`length`),k(n.maxItems))}function FC(e,t,n,r){return Ra(r.length,n.maxItems)}function IC(e,t,n,r,i,a){return FC(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function LC(e,t,n,r){return ko(r,k(n.maxLength))}function RC(e,t,n,r){return Wa(r,n.maxLength)}function zC(e,t,n,r,i,a){return RC(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function BC(e,t,n,r){return Eo(O(Fo(r),`length`),k(n.maxProperties))}function VC(e,t,n,r){return Ra(T(r).length,n.maxProperties)}function HC(e,t,n,r,i,a){return VC(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function UC(e){return ry(e)}function WC(e,t,n,r){let[i,a]=[cb(),cb()];return Do(No(r,[i,a],so(ST(e,t,n.contains,i),t.AddIndex(a))),k(n.minContains))}function GC(e,t,n,r){let[i]=[cb()];return Do(No(r,[i,`_`],ST(e,t,n.contains,i)),k(n.minContains))}function KC(e,t,n,r){return UC(n)?t.UseUnevaluated()?WC(e,t,n,r):GC(e,t,n,r):k(!0)}function qC(e,t,n,r){return!UC(n)||za(Xa(r,(r,i)=>wT(e,t,n.contains,r)&&t.AddIndex(i)),n.minContains)}function JC(e,t,n,r,i,a){return qC(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function YC(e,t,n,r){return Do(r,k(n.minimum))}function XC(e,t,n,r){return za(r,n.minimum)}function ZC(e,t,n,r,i,a){return XC(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function QC(e,t,n,r){return Do(O(r,`length`),k(n.minItems))}function $C(e,t,n,r){return za(r.length,n.minItems)}function ew(e,t,n,r,i,a){return $C(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function tw(e,t,n,r){return Oo(r,k(n.minLength))}function nw(e,t,n,r){return Ga(r,n.minLength)}function rw(e,t,n,r,i,a){return nw(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function iw(e,t,n,r){return Do(O(Fo(r),`length`),k(n.minProperties))}function aw(e,t,n,r){return za(T(r).length,n.minProperties)}function ow(e,t,n,r,i,a){return aw(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function sw(e,t,n,r){return Jo(r,k(n.multipleOf))}function cw(e,t,n,r){return Ba(r,n.multipleOf)}function lw(e,t,n,r,i,a){return cw(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function uw(e,t,n,r){return Tb(e,t,[n.not],r,co(Co(O(`results`,`length`),k(1))))}function dw(e,t,n,r){return co(ST(e,t,n.not,r))}function fw(e,t,n,r){return t.UseUnevaluated()?uw(e,t,n,r):dw(e,t,n,r)}function pw(e,t,n,r){let i=new Qy;return!wT(e,i,n.not,r)&&t.Merge([i])}function mw(e,t,n,r,i,a){return pw(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function hw(e,t,n,r){return Tb(e,t,n.oneOf,r,Co(O(`results`,`length`),k(1)))}function gw(e,t,n,r){let[i]=[cb()];return Co(No(Ro(n.oneOf.map(n=>ST(e,t,n,r))),[i,`_`],Co(i,k(!0))),k(1))}function _w(e,t,n,r){return t.UseUnevaluated()?hw(e,t,n,r):gw(e,t,n,r)}function vw(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new Qy;return wT(e,i,n,r)?[...t,i]:t},[]);return S(i.length,1)&&t.Merge(i)}function yw(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new $y,u=ET(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=S(c.length,1)&&t.Merge(c);return!l&&S(s.length,0)&&o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),l||t.AddError({keyword:`oneOf`,schemaPath:n,instancePath:r,params:{passingSchemas:s}})}function bw(e,t,n,r){return D(O(tb(b(n.pattern)?hb(n.pattern):n.pattern),`test`),[r])}function xw(e,t,n,r){return(b(n.pattern)?hb(n.pattern):n.pattern).test(r)}function Sw(e,t,n,r,i,a){return xw(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function Cw(e,t,n,r){return Ko($a(n.patternProperties).map(([n,i])=>{let[a,o]=[cb(),cb()],s=co(D(O(tb(hb(n)),`test`),[a])),c=xT(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?E(s,so(c,l)):E(s,c);return Ao(Po(r),k(0),[`[${a}, ${o}]`,`_`],u)}))}function ww(e,t,n,r){return Ka($a(n.patternProperties),0,([n,i])=>{let a=hb(n);return Ka($a(r),0,([n,r])=>!a.test(n)||CT(e,t,i,r)&&t.AddKey(n))})}function Tw(e,t,n,r,i,a){return qa($a(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=hb(i);return qa($a(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||TT(e,t,s,a,o,i)&&t.AddKey(n)})})}function Ew(e,t,n,r){return Ko(n.prefixItems.map((n,i)=>{let a=Eo(O(r,`length`),k(i)),o=xT(e,t,n,`${r}[${i}]`),s=t.AddIndex(k(i));return E(a,t.UseUnevaluated()?so(o,s):o)}))}function Dw(e,t,n,r){return S(r.length,0)||Ka(n.prefixItems,0,(n,i)=>Ra(r.length,i)||CT(e,t,n,r[i])&&t.AddIndex(i))}function Ow(e,t,n,r,i,a){return S(a.length,0)||qa(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return Ra(a.length,o)||TT(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function kw(e,t){return e.includes(t)||as().exactOptionalPropertyTypes}function Aw(e,t){return bo(O(e,t))}function jw(e,t){return x(e[t])}function Mw(e,t,n,r){let i=Vy(n)?n.required:[];return Ko($a(n.properties).map(([n,a])=>{let o=co(Io(r,k(n))),s=xT(e,t,a,O(r,n)),c=t.AddKey(k(n)),l=t.UseUnevaluated()?so(s,c):s,u=i.includes(n)?l:E(o,l);return kw(i,n)?u:E(Aw(r,n),u)}))}function Nw(e,t,n,r){let i=Vy(n)?n.required:[];return Ka($a(n.properties),0,([n,a])=>{let o=!w(r,n)||CT(e,t,a,r[n])&&t.AddKey(n);return kw(i,n)?o:jw(r,n)||o})}function Pw(e,t,n,r,i,a){let o=Vy(i)?i.required:[];return qa($a(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!w(a,i)||TT(e,t,c,l,s,a[i])&&t.AddKey(i);return kw(o,i)?u():jw(a,i)||u()})}function Fw(e,t,n,r){let[i,a]=[cb(),cb()];return Ao(Fo(r),k(0),[i,a],ST(e,t,n.propertyNames,i))}function Iw(e,t,n,r){return Ka(T(r),0,(r,i)=>wT(e,t,n.propertyNames,r))}function Lw(e,t,n,r,i,a){let o=[];return qa(T(a),0,(a,s)=>{let c=`${r}/${a}`,l=ET(e,t,`${n}/propertyNames`,c,i.propertyNames,a);return l||o.push(a),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Rw(e,t,n,r){return IT(e,t,e.RecursiveRef(n)??!1,r)}function zw(e,t,n,r){let i=e.RecursiveRef(n)??!1;return W(i)&&wT(e,t,i,r)}function Bw(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return W(o)&&ET(e,t,`#`,r,o,a)}function Vw(e,t,n,r){let i=zo([`context`,`value`],IT(e,t,n,`value`));return D(zo([`context`,`value`],Ho([Uo(`nextContext`,Bo(`CheckContext`,[])),Uo(`result`,D(i,[`nextContext`,`value`])),Wo(`result`,t.Merge(`[nextContext]`)),Go(`result`)])),[`context`,r])}function Hw(e,t,n,r){return IT(e,t,n,r)}function Uw(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?Vw(e,t,i,r):Hw(e,t,i,r)}function Ww(e,t,n,r){let i=e.Ref(n)??!1,a=new Qy,o=W(i)&&wT(e,a,i,r);return o&&t.Merge([a]),o}function Gw(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new $y,c=W(o)&&ET(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function Kw(e,t,n,r){return Ko(n.required.map(e=>Io(r,k(e))))}function qw(e,t,n,r){return Ka(n.required,0,e=>w(r,e))}function Jw(e,t,n,r,i,a){let o=[];return qa(i.required,0,e=>{let t=w(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function Yw(e,t,n,r){return S(n,`object`)?go(r):S(n,`array`)?lo(r):S(n,`boolean`)?fo(r):S(n,`integer`)?po(r):S(n,`number`)?ho(r):S(n,`null`)?mo(r):S(n,`string`)?vo(r):S(n,`bigint`)?uo(r):S(n,`constructor`)?So(r):S(n,`function`)?xo(r):S(n,`symbol`)?yo(r):S(n,`undefined`)||S(n,`void`)?bo(r):k(!0)}function Xw(e,t,n,r,i){return S(n,`object`)?Pa(i):S(n,`array`)?_(i):S(n,`boolean`)?ka(i):S(n,`integer`)?Ma(i):S(n,`number`)?v(i):S(n,`null`)?Na(i):S(n,`string`)?b(i):S(n,`bigint`)?Oa(i):S(n,`constructor`)?Aa(i):S(n,`function`)?ja(i):S(n,`symbol`)?Fa(i):S(n,`undefined`)?x(i):!S(n,`void`)||x(i)}function Zw(e,t,n,r){return qo(n.map(n=>Yw(e,t,n,r)))}function Qw(e,t,n,r,i){return Ja(n,n=>Xw(e,t,n,r,i))}function $w(e,t,n,r){return _(n.type)?Zw(e,t,n.type,r):Yw(e,t,n.type,r)}function eT(e,t,n,r){return _(n.type)?Qw(e,t,n.type,n,r):Xw(e,t,n.type,n,r)}function tT(e,t,n,r,i,a){return(_(i.type)?Qw(e,t,i.type,i,a):Xw(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function nT(e,t,n,r){let[i,a]=[cb(),cb()],o=D(O(`context`,`GetIndices`),[]),s=D(O(`indices`,`has`),[i]),c=ST(e,t,n.unevaluatedItems,a),l=D(O(`context`,`AddIndex`),[i]),u=Ao(r,k(0),[a,i],so(E(s,c),l));return D(zo([`context`],Ho([Uo(`indices`,o),Go(u)])),[`context`])}function rT(e,t,n,r){let i=t.GetIndices();return Ka(r,0,(r,a)=>(i.has(a)||wT(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function iT(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return qa(a,0,(a,c)=>{let l=new $y,u=(o.has(c)||ET(e,l,n,r,i.unevaluatedItems,a))&&t.AddIndex(c);return u||s.push(c),u})||t.AddError({keyword:`unevaluatedItems`,schemaPath:n,instancePath:r,params:{unevaluatedItems:s}})}function aT(e,t,n,r){let[i,a]=[cb(),cb()],o=D(O(`context`,`GetKeys`),[]),s=D(O(`keys`,`has`),[i]),c=D(O(`context`,`AddKey`),[i]),l=ST(e,t,n.unevaluatedProperties,a),u=Ao(Po(r),k(0),[`[${i}, ${a}]`,`_`],E(s,so(l,c)));return D(zo([`context`],Ho([Uo(`keys`,o),Go(u)])),[`context`])}function oT(e,t,n,r){let i=t.GetKeys();return Ka($a(r),0,([r,a])=>i.has(r)||wT(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function sT(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return qa($a(a),0,([a,c])=>{let l=new $y,u=o.has(a)||ET(e,l,n,r,i.unevaluatedProperties,c)&&t.AddKey(a);return u||s.push(a),u})||t.AddError({keyword:`unevaluatedProperties`,schemaPath:n,instancePath:r,params:{unevaluatedProperties:s}})}function cT(e){return!S(e.uniqueItems,!1)}function lT(e,t,n,r){return cT(n)?Co(O(Bo(`Set`,[D(O(r,`map`),[O(`Hashing`,`Hash`)])]),`size`),O(r,`length`)):k(!0)}function uT(e,t,n,r){if(!cT(n))return!0;let i=new Set(r.map(qc)).size,a=r.length;return S(i,a)}function dT(e,t,n,r,i,a){if(!cT(i))return!0;let o=/* @__PURE__ */ new Set,s=a.reduce((e,t,n)=>{let r=qc(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return S(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function fT(e,t){return Uy(e)&&(_(e.type)&&Ia(e.type.length,0)&&Ka(e.type,0,e=>S(e,t))||S(e.type,t))}function pT(e){return fT(e,`object`)}function mT(e){return Yv(e)&&(Qv(e)||ay(e)||oy(e)||sy(e)||Fy(e)||Ny(e)||Iy(e)||Oy(e)||Cy(e)||Vy(e)||Ky(e))}function hT(e){return fT(e,`array`)}function gT(e){return Yv(e)&&(Zv(e)||_y(e)||ry(e)||by(e)||xy(e)||Ty(e)||Ey(e)||Py(e)||Gy(e)||Wy(e))}function _T(e){return fT(e,`string`)}function vT(e){return Yv(e)&&(Dy(e)||Sy(e)||my(e)||My(e))}function yT(e){return fT(e,`number`)||fT(e,`bigint`)}function bT(e){return Yv(e)&&(wy(e)||yy(e)||fy(e)||py(e)||ky(e))}function xT(e,t,n,r){return t.UseUnevaluated()?so(so(t.Push(),ST(e,t,n,r)),t.Pop()):ST(e,t,n,r)}function ST(e,t,n,r){e.Push(n);let i=[];if(Xv(n))return Ib(e,t,n,r);if(Uy(n)&&i.push($w(e,t,n,r)),mT(n)){let a=[];Vy(n)&&a.push(Kw(e,t,n,r)),Qv(n)&&a.push(Sb(e,t,n,r)),ay(n)&&a.push(Jb(e,t,n,r)),oy(n)&&a.push(Zb(e,t,n,r)),sy(n)&&a.push(ex(e,t,n,r)),Ny(n)&&a.push(Cw(e,t,n,r)),Fy(n)&&a.push(Mw(e,t,n,r)),Iy(n)&&a.push(Fw(e,t,n,r)),Oy(n)&&a.push(iw(e,t,n,r)),Cy(n)&&a.push(BC(e,t,n,r));let o=Ko(a),s=E(co(go(r)),o);i.push(pT(n)?o:s)}if(gT(n)){let a=[];Zv(n)&&a.push(fb(e,t,n,r)),ry(n)&&a.push(Gb(e,t,n,r)),_y(n)&&a.push(wC(e,t,n,r)),by(n)&&a.push(OC(e,t,n,r)),xy(n)&&a.push(PC(e,t,n,r)),Ty(n)&&a.push(KC(e,t,n,r)),Ey(n)&&a.push(QC(e,t,n,r)),Py(n)&&a.push(Ew(e,t,n,r)),Wy(n)&&a.push(lT(e,t,n,r));let o=Ko(a),s=E(co(lo(r)),o);i.push(hT(n)?o:s)}if(vT(n)){let a=[];Sy(n)&&a.push(LC(e,t,n,r)),Dy(n)&&a.push(tw(e,t,n,r)),my(n)&&a.push(cC(e,t,n,r)),My(n)&&a.push(bw(e,t,n,r));let o=Ko(a),s=E(co(vo(r)),o);i.push(_T(n)?o:s)}if(bT(n)){let a=[];fy(n)&&a.push(lx(e,t,n,r)),py(n)&&a.push(fx(e,t,n,r)),yy(n)&&a.push(jC(e,t,n,r)),wy(n)&&a.push(YC(e,t,n,r)),ky(n)&&a.push(sw(e,t,n,r));let o=Ko(a),s=E(co(E(ho(r),uo(r))),o);i.push(yT(n)?o:s)}By(n)&&i.push(Uw(e,t,n,r)),zy(n)&&i.push(Rw(e,t,n,r)),ly(n)&&i.push(rx(e,t,n,r)),ny(n)&&i.push(zb(e,t,n,r)),dy(n)&&i.push(ox(e,t,n,r)),gy(n)&&i.push(dC(e,t,n,r)),Ay(n)&&i.push(fw(e,t,n,r)),$v(n)&&i.push(Ob(e,t,n,r)),ty(n)&&i.push(Nb(e,t,n,r)),jy(n)&&i.push(_w(e,t,n,r)),Gy(n)&&i.push(E(co(lo(r)),nT(e,t,n,r))),Ky(n)&&i.push(E(co(_o(r)),aT(e,t,n,r))),Jv(n)&&i.push(ib(e,t,n,r));let a=Ko(i);return e.Pop(n),a}function CT(e,t,n,r){return t.Push()&&wT(e,t,n,r)&&t.Pop()}function wT(e,t,n,r){e.Push(n);let i=Xv(n)?Lb(e,t,n,r):(!Uy(n)||eT(e,t,n,r))&&(!(y(r)&&!_(r))||(!Vy(n)||qw(e,t,n,r))&&(!Qv(n)||Cb(e,t,n,r))&&(!ay(n)||Yb(e,t,n,r))&&(!oy(n)||Qb(e,t,n,r))&&(!sy(n)||tx(e,t,n,r))&&(!Ny(n)||ww(e,t,n,r))&&(!Fy(n)||Nw(e,t,n,r))&&(!Iy(n)||Iw(e,t,n,r))&&(!Oy(n)||aw(e,t,n,r))&&(!Cy(n)||VC(e,t,n,r)))&&(!_(r)||(!Zv(n)||pb(e,t,n,r))&&(!ry(n)||Kb(e,t,n,r))&&(!_y(n)||TC(e,t,n,r))&&(!by(n)||kC(e,t,n,r))&&(!xy(n)||FC(e,t,n,r))&&(!Ty(n)||qC(e,t,n,r))&&(!Ey(n)||$C(e,t,n,r))&&(!Py(n)||Dw(e,t,n,r))&&(!Wy(n)||uT(e,t,n,r)))&&(!b(r)||(!Sy(n)||RC(e,t,n,r))&&(!Dy(n)||nw(e,t,n,r))&&(!my(n)||lC(e,t,n,r))&&(!My(n)||xw(e,t,n,r)))&&(!(v(r)||Oa(r))||(!fy(n)||ux(e,t,n,r))&&(!py(n)||px(e,t,n,r))&&(!yy(n)||MC(e,t,n,r))&&(!wy(n)||XC(e,t,n,r))&&(!ky(n)||cw(e,t,n,r)))&&(!By(n)||Ww(e,t,n,r))&&(!zy(n)||zw(e,t,n,r))&&(!ly(n)||ix(e,t,n,r))&&(!ny(n)||Bb(e,t,n,r))&&(!dy(n)||sx(e,t,n,r))&&(!gy(n)||fC(e,t,n,r))&&(!Ay(n)||pw(e,t,n,r))&&(!$v(n)||kb(e,t,n,r))&&(!ty(n)||Pb(e,t,n,r))&&(!jy(n)||vw(e,t,n,r))&&(!Gy(n)||!_(r)||rT(e,t,n,r))&&(!Ky(n)||!y(r)||oT(e,t,n,r))&&(!Jv(n)||ab(e,t,n,r));return e.Pop(n),i}function TT(e,t,n,r,i,a){return t.Push()&&ET(e,t,n,r,i,a)&&t.Pop()}function ET(e,t,n,r,i,a){if(t.AtCapacity())return!1;e.Push(i);let o=Xv(i)?Rb(e,t,n,r,i,a):!!(+(!Uy(i)||tT(e,t,n,r,i,a))&(!(y(a)&&!_(a))||!!(+(!Vy(i)||Jw(e,t,n,r,i,a))&(!Qv(i)||wb(e,t,n,r,i,a))&(!ay(i)||Xb(e,t,n,r,i,a))&(!oy(i)||$b(e,t,n,r,i,a))&(!sy(i)||nx(e,t,n,r,i,a))&(!Ny(i)||Tw(e,t,n,r,i,a))&(!Fy(i)||Pw(e,t,n,r,i,a))&(!Iy(i)||Lw(e,t,n,r,i,a))&(!Oy(i)||ow(e,t,n,r,i,a))&(!Cy(i)||HC(e,t,n,r,i,a))))&(!_(a)||!!(+(!Zv(i)||mb(e,t,n,r,i,a))&(!ry(i)||qb(e,t,n,r,i,a))&(!_y(i)||EC(e,t,n,r,i,a))&(!by(i)||AC(e,t,n,r,i,a))&(!xy(i)||IC(e,t,n,r,i,a))&(!Ty(i)||JC(e,t,n,r,i,a))&(!Ey(i)||ew(e,t,n,r,i,a))&(!Py(i)||Ow(e,t,n,r,i,a))&(!Wy(i)||dT(e,t,n,r,i,a))))&(!b(a)||!!(+(!Sy(i)||zC(e,t,n,r,i,a))&(!Dy(i)||rw(e,t,n,r,i,a))&(!my(i)||uC(e,t,n,r,i,a))&(!My(i)||Sw(e,t,n,r,i,a))))&(!(v(a)||Oa(a))||!!(+(!fy(i)||dx(e,t,n,r,i,a))&(!py(i)||mx(e,t,n,r,i,a))&(!yy(i)||NC(e,t,n,r,i,a))&(!wy(i)||ZC(e,t,n,r,i,a))&(!ky(i)||lw(e,t,n,r,i,a))))&(!By(i)||Gw(e,t,n,r,i,a))&(!zy(i)||Bw(e,t,n,r,i,a))&(!ly(i)||ax(e,t,n,r,i,a))&(!ny(i)||Vb(e,t,n,r,i,a))&(!dy(i)||cx(e,t,n,r,i,a))&(!gy(i)||pC(e,t,n,r,i,a))&(!Ay(i)||mw(e,t,n,r,i,a))&(!$v(i)||Ab(e,t,n,r,i,a))&(!ty(i)||Fb(e,t,n,r,i,a))&(!jy(i)||yw(e,t,n,r,i,a))&(!Gy(i)||!_(a)||iT(e,t,n,r,i,a))&(!Ky(i)||!y(a)||sT(e,t,n,r,i,a)))&&(!Jv(i)||ob(e,t,n,r,i,a));return e.Pop(i),o}const DT=[0],OT=/* @__PURE__ */ new Map,kT=/* @__PURE__ */ new Map;function AT(){return`${DT[0]++}`}function jT(e,t){OT.has(e)||OT.set(e,/* @__PURE__ */ new Map);let n=OT.get(e);if(n.has(t))return n.get(t);let r=AT();return n.set(t,r),r}function MT(e,t,n,r){return e.UseUnevaluated()?D(`check_${n}`,[`context`,r]):D(`check_${n}`,[r])}function NT(e,t,n,r){let i=ST(e,t,n,`value`);return t.UseUnevaluated()?Uo(`check_${r}`,zo([`context`,`value`],i)):Uo(`check_${r}`,zo([`value`],i))}function PT(){DT[0]=0,OT.clear(),kT.clear()}function FT(){return[...kT.values()]}function IT(e,t,n,r){let i=jT(n,e.LexicalBaseURL()),a=MT(t,n,i,r);return kT.has(i)?a:(kT.set(i,``),kT.set(i,NT(e,t,n,i)),a)}function LT(e,t){return y(t)&&!Za(e)?t[e]:void 0}function RT(e,t){return e.reduce((e,t)=>LT(t,e),t)}function zT(e){if(S(e.length,0))return[];let t=e.split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`));return t.length>0&&t[0]===``?t.slice(1):t}function BT(e,t){return RT(zT(t),e)}const VT=`https://json-schema.org`;function HT(e,t){if(y(e)&&cy(e)&&S(e.$dynamicAnchor,t))return e;if(y(e))for(let n of T(e)){let r=HT(e[n],t);if(r)return r}}function UT(e,t,n){if(S(e,n))return t.href;let r=Yv(e)&&hy(e)?new URL(e.$id,t.href):t;if(_(e))for(let t of e){let e=UT(t,r,n);if(!x(e))return e}else if(y(e))for(let t of T(e)){let i=UT(e[t],r,n);if(!x(i))return i}}function WT(e,t,n){if(S(e.$id,n.hash))return e;let r=new URL(n.href,t.href);if(S(t.pathname,r.pathname))return n.hash.startsWith(`#`)?qT(e,n):e}function GT(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return S(r.href,i.href)?e:void 0}function KT(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return S(r.href,i.href)?e:void 0}function qT(e,t){if(t.href.endsWith(`#`))return e;if(!t.hash.startsWith(`#`))return;let n=decodeURIComponent(t.hash.slice(1));if(n.startsWith(`/`))return BT(e,n)}function JT(e,t,n){if(hy(e)){let r=WT(e,t,n);if(!x(r))return r}if(ey(e)){let r=GT(e,t,n);if(!x(r))return r}if(cy(e)){let r=KT(e,t,n);if(!x(r))return r}return qT(e,n)}function YT(e,t,n){return e.reduce((e,r)=>{let i=QT(r,t,n);return x(i)?e:i},void 0)}function XT(e){return S(e,`const`)||S(e,`enum`)}function ZT(e,t,n){return T(e).reduce((r,i)=>{if(XT(i))return r;let a=QT(e[i],t,n);return x(a)?r:a},void 0)}function QT(e,t,n){let r=Yv(e)&&hy(e)?new URL(e.$id,t.href):t;if(Yv(e)){let t=JT(e,r,n);if(!x(t))return t}if(_(e))return YT(e,r,n);if(y(e))return ZT(e,r,n)}function $T(e,t,n){return UT(e,new URL(t||`.`,VT),n)}function eE(e,t,n,r){let i=lE(e,t,n,r,!1);return Yv(i)&&hy(i)?i:void 0}function tE(e){return e.href.split(`#`)[0]}function nE(e,t){return w(e,t)?e[t]:void 0}function rE(e,t,n){return QT(e,t,n)}function iE(e,t,n){let r=tE(n);if(S(r,tE(t))||!w(e,r))return;let i=e[r],a=Yv(i)&&hy(i)?new URL(i.$id,r):new URL(r);return S(n.hash,``)?i:QT(i,a,n)}function aE(e,t,n,r,i){if(!r.$ref.startsWith(`#`)||w(e,`$schema`))return;let a=$T(t,n,i);if(!(x(a)||S(a,n)))return{target:i,base:a,root:t}}function oE(e,t,n){let r=e[t];if(Yv(r))return{target:n,base:t,root:r}}function sE(e,t,n,r,i){let a=i?oE(e.context,r,n):void 0;return x(a)?aE(e.root,e.lexicalSchema,e.referenceBase,t,n):a}function cE(e,t,n,r,i,a){if(hy(i))return;let o=eE(e,t,n,r);if(o&&!a.includes(o))return{target:i,resource:o}}function lE(e,t,n,r,i=!0){let a=new URL(n||`.`,VT),o=i&&hy(t)?new URL(t.$id,a):a,s=new URL(r,o.href);return nE(e,r)??rE(t,o,s)??iE(e,o,s)}function uE(e,t,n,r,i,a){let o=new URL(n||`.`,VT),s=lE(e,i.$dynamicRef.startsWith(`#`)?r:t,n,i.$dynamicRef,!1);if(x(s)){let e=new URL(i.$dynamicRef,o).hash;if(!e.startsWith(`#/`)&&e.startsWith(`#`)){let n=decodeURIComponent(e.slice(1));return a.find(e=>S(e.$dynamicAnchor,n))??HT(t,n)}return}return!Yv(s)||!cy(s)||new URL(i.$dynamicRef,o).hash.startsWith(`#/`)?s:a.find(e=>S(e.$dynamicAnchor,s.$dynamicAnchor))??s}function dE(e,t){let n=e.inRetrievedFrame?e.lexicalSchema:e.root,r=t.$ref.startsWith(`#`)?e.lexicalSchema:n,i=lE(e.context,r,e.referenceBase,t.$ref,!1);if(!i||!Yv(i))return{schema:i};let a=new URL(t.$ref,e.referenceBase).href.split(`#`)[0],o=!S(a,e.resourceBase);return{schema:i,retrievedResource:sE(e,t,i,a,o),resolvedResource:o?cE(e.context,e.root,e.referenceBase,a,i,e.ids):void 0}}function fE(e,t){let n=Ry(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return lE(e.context,n,e.lexicalBase,t.$recursiveRef,!1)}function pE(e,t){return uE(e.context,e.root,e.lexicalBase,e.lexicalSchema,t,e.dynamicAnchors)}var K=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},q,mE,hE,gE,_E,vE,yE,bE,xE,SE,CE,wE,TE,EE,DE,OE=class{constructor(e,t){q.add(this),this.context=e,this.schema=t,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=/* @__PURE__ */ new Map,this.retrievedFrames=[],this.resolvedResources=/* @__PURE__ */ new Map,this.pendingResource=!0}LexicalBaseURL(){return K(this,q,`m`,gE).call(this,this.ids)}Push(e){if(!Yv(e))return;hy(e)&&K(this,q,`m`,wE).call(this,e),ey(e)&&this.anchors.push(e),Ry(e)&&this.recursiveAnchors.push(e),cy(e)&&this.dynamicAnchors.push(e);let t=this.retrievedResources.get(e);t&&this.retrievedFrames.push({schema:t.root,base:t.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){Yv(e)&&(hy(e)&&K(this,q,`m`,TE).call(this,e),ey(e)&&this.anchors.pop(),Ry(e)&&this.recursiveAnchors.pop(),cy(e)&&this.dynamicAnchors.pop(),this.retrievedResources.has(e)&&this.retrievedFrames.pop(),K(this,q,`m`,DE).call(this,e))}Ref(e){let t=dE(K(this,q,`m`,mE).call(this),e);return K(this,q,`m`,hE).call(this,t),t.schema}RecursiveRef(e){let t=fE(K(this,q,`m`,mE).call(this),e);return t&&(this.pendingResource=!0),t}DynamicRef(e){let t=pE(K(this,q,`m`,mE).call(this),e);return t&&(this.pendingResource=!0),t}};q=/* @__PURE__ */ new WeakSet,mE=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:K(this,q,`m`,yE).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:K(this,q,`m`,vE).call(this),resourceBase:K(this,q,`m`,_E).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},hE=function(e){x(e.schema)||(this.pendingResource=!0),x(e.resolvedResource)||K(this,q,`m`,EE).call(this,e.resolvedResource.target,e.resolvedResource.resource),x(e.retrievedResource)||this.retrievedResources.set(e.retrievedResource.target,{base:e.retrievedResource.base,root:e.retrievedResource.root})},gE=function(e){let t=this.retrievedFrames[this.retrievedFrames.length-1],n=t?new URL(t.base):new URL(VT);return(t?e.slice(t.idDepth):e).reduce((e,t)=>new URL(t.$id,e),n).href},_E=function(){let e=this.retrievedFrames[this.retrievedFrames.length-1];return e?this.resourceIds.slice(e.resourceDepth).reduce((e,t)=>new URL(t.$id,e),new URL(e.base)).href:K(this,q,`m`,gE).call(this,this.resourceIds)},vE=function(){if(this.retrievedFrames.length>0)return K(this,q,`m`,_E).call(this);let e=this.ids[this.ids.length-1];return e&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e.$id)?this.LexicalBaseURL():K(this,q,`m`,_E).call(this)},yE=function(){let e=this.retrievedFrames[this.retrievedFrames.length-1];return e?this.ids.length>e.idDepth?this.ids[this.ids.length-1]:e.schema:this.ids.length>0?this.ids[this.ids.length-1]:this.schema},bE=function(e){e.forEach(e=>K(this,q,`m`,SE).call(this,e,!1))},xE=function(e){e.forEach(e=>K(this,q,`m`,CE).call(this,e,!1))},SE=function e(t,n=!0){if(Xv(t))return;if(_(t))return K(this,q,`m`,bE).call(this,t);if(!Yv(t))return;let r=t;if(n||!hy(r)){!n&&cy(r)&&this.dynamicAnchors.push(r);for(let t of T(r))K(this,q,`m`,e).call(this,r[t],!1)}},CE=function e(t,n=!0){if(Xv(t))return;if(_(t))return K(this,q,`m`,xE).call(this,t);if(!Yv(t))return;let r=t;if(n||!hy(r)){!n&&cy(r)&&this.dynamicAnchors.pop();for(let t of T(r))K(this,q,`m`,e).call(this,r[t],!1)}},wE=function(e){this.ids.push(e);let t=this.pendingResource;this.pendingResource=!1,t&&this.resourceIds.push(e),K(this,q,`m`,SE).call(this,e,!0)},TE=function(e){this.ids.pop(),this.resourceIds.length>0&&S(this.resourceIds[this.resourceIds.length-1],e)&&this.resourceIds.pop(),K(this,q,`m`,CE).call(this,e,!0)},EE=function(e,t){K(this,q,`m`,wE).call(this,t),this.resolvedResources.set(e,t)},DE=function(e){if(!this.resolvedResources.has(e))return;let t=this.resolvedResources.get(e);K(this,q,`m`,TE).call(this,t),this.resolvedResources.delete(e)};function kE(e){return`${e.Functions().join(`;
|
|
970
970
|
`)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function AE(e,t){return gc(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(Qy,Da,sC,vc,e.External().variables)}function jE(e){let t=new OE(e.Context(),e.Schema()),n=new Qy;return r=>wT(t,n,e.Schema(),r)}function ME(e,t){return hc()?AE(e,t):jE(e)}var NE=class{constructor(e,t,n){this.isAccelerated=e,this.code=t,this.check=n}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}},PE=class{constructor(e,t,n,r,i,a){this.context=e,this.schema=t,this.external=n,this.functions=r,this.entry=i,this.useUnevaluated=a}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=kE(this),t=ME(this,e);return new NE(hc(),e,t)}};function FE(...e){let[t,n]=ac(e,{2:(e,t)=>[e,t],1:e=>[{},e]});nb(),PT();let r=new OE(t,n),i=new Zy(Xy(t,n)),a=IT(r,i,n,`value`),o=FT();return new PE(t,n,rb(),o,a,i.UseUnevaluated())}function IE(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=new OE(t,n),a=new $y,o=ET(i,a,`#`,``,n,r),s=a.GetErrors(),c=Xc();return[o,s.map(e=>({...e,message:c(e)}))]}function LE(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return wT(new OE(t,n),new Qy,n,r)}function RE(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return LE(t,n,r)}function zE(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=IE(t,n,r);return a}var BE=class extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"cause",{value:{source:e,errors:n,value:t},writable:!1,configurable:!1,enumerable:!1})}};function VE(e,t,n){return _(n)?n.map(n=>QE(e,t.items,n)):n}function HE(e,t,n){return QE({...e,...t.$defs},Bs(t.$ref),n)}function UE(e,t){let n=w(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=zv(Pv(e,t));return F(r)?Sv(r,n):r}function WE(e,t,n){return QE(e,UE(e,t),n)}function GE(e){return w(e,`additionalProperties`)?e.additionalProperties:void 0}function KE(e,t,n){if(!y(n)||_(n))return n;let r=GE(t);for(let i of T(n)){if(w(t.properties,i)){n[i]=QE(e,t.properties[i],n[i]);continue}if(ka(r)&&S(r,!0)||Cs(r)&&RE(e,r,n[i])){n[i]=QE(e,r,n[i]);continue}delete n[i]}return n}function qE(e,t,n){if(!y(n))return n;let r=GE(t),[i,a]=[new RegExp(nd(t)),id(t)];for(let t of T(n)){if(i.test(t)){n[t]=QE(e,a,n[t]);continue}if(ka(r)&&S(r,!0)||Cs(r)&&RE(e,r,n[t])){n[t]=QE(e,r,n[t]);continue}delete n[t]}return n}function JE(e,t,n){return w(e,t.$ref)?QE(e,e[t.$ref],n):n}function YE(e,t,n){if(!_(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;i<r;i++)n[i]=QE(e,t.items[i],n[i]);return Ia(n.length,r)?n.slice(0,r):n}function XE(e){return ys(e)}function ZE(e,t,n){for(let r of t.anyOf){let t=QE(e,r,XE(n));if(RE(e,r,t))return t}return n}function QE(e,t,n){return Ms(t)?VE(e,t,n):rc(t)?HE(e,t,n):I(t)?WE(e,t,n):F(t)?KE(e,t,n):ad(t)?qE(e,t,n):Vs(t)?JE(e,t,n):Jl(t)?YE(e,t,n):L(t)?ZE(e,t,n):n}function $E(e,t){for(let n of rs.Keys(e))rs.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function eD(e){let t={};for(let n of rs.Keys(e))t[n]=rD(e[n]);return t}function tD(e){return nD(Uv(e))}function nD(e){return e.map(e=>rD(e))}function rD(e){return $E(e,Ms(e)?js(rD(e.items),Ns(e)):I(e)?dc(nD(e.allOf)):L(e)?Tl(tD(e.anyOf)):F(e)?P(eD(e.properties)):ad(e)?$u(rd(e),rD(id(e))):Jl(e)?ql(nD(e.items)):e)}function iD(e){return rD(e)}function aD(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return QE(t,as().unionPrioritySort?iD(n):n,r)}function oD(e){return y(e)&&w(e,`value`)}function J(e){return{value:e}}function sD(e){return _(e)?J(e):J([e])}function cD(e){return S(e,!0)?J(BigInt(1)):J(BigInt(0))}const lD=/^-?(0|[1-9]\d*)n$/,uD=/^-?(0|[1-9]\d*)\.\d+$/,dD=/^-?(0|[1-9]\d*)$/;function fD(e){return lD.test(e)}function pD(e){return uD.test(e)}function mD(e){return dD.test(e)}function hD(e){let t=e.toLowerCase();return fD(e)?J(BigInt(e.slice(0,e.length-1))):pD(e)?J(BigInt(e.split(`.`)[0])):mD(e)?J(BigInt(e)):S(t,`false`)?J(BigInt(0)):S(t,`true`)?J(BigInt(1)):void 0}function gD(e){return Oa(e)?J(e):ka(e)?cD(e):v(e)?J(BigInt(Math.trunc(e))):Na(e)?J(BigInt(0)):b(e)?hD(e):x(e)?J(BigInt(0)):void 0}function _D(e){return S(e,BigInt(0))?J(!1):S(e,BigInt(1))?J(!0):void 0}function vD(e){return S(e,0)?J(!1):S(e,1)?J(!0):void 0}function yD(e){return S(e.toLowerCase(),`false`)?J(!1):S(e.toLowerCase(),`true`)?J(!0):S(e,`0`)?J(!1):S(e,`1`)?J(!0):void 0}function bD(e){return Oa(e)?_D(e):ka(e)?J(e):v(e)?vD(e):Na(e)?J(!1):b(e)?yD(e):x(e)?J(!1):void 0}function xD(e){return S(e,BigInt(0))?J(null):void 0}function SD(e){return S(e,!1)?J(null):void 0}function CD(e){return S(e,0)?J(null):void 0}function wD(e){let t=e.toLowerCase();return S(t,`undefined`)||S(t,`null`)||S(e,``)||S(e,`0`)?J(null):void 0}function TD(e){return Oa(e)?xD(e):ka(e)?SD(e):v(e)?CD(e):Na(e)?J(null):b(e)?wD(e):x(e)?J(null):void 0}const ED=BigInt(2**53-1),DD=BigInt(-(2**53-1));function OD(e){return e<=ED&&e>=DD?J(Number(e)):void 0}function kD(e){return J(+!!e)}function AD(e){let t=+e;if(v(t))return J(t);let n=e.toLowerCase();if(S(n,`false`))return J(0);if(S(n,`true`))return J(1);let r=gD(e);if(oD(r))return r.value<=ED&&r.value>=DD?J(Number(r.value)):void 0}function jD(e){return Oa(e)?OD(e):ka(e)?kD(e):v(e)?J(e):Na(e)?J(0):b(e)?AD(e):x(e)?J(0):void 0}function MD(e){return Oa(e)||ka(e)||v(e)?J(e.toString()):Na(e)?J(`null`):b(e)?J(e):x(e)?J(``):void 0}function ND(e){return S(e,BigInt(0))?J(void 0):void 0}function PD(e){return S(e,!1)?J(void 0):void 0}function FD(e){return S(e,0)?J(void 0):void 0}function ID(e){let t=e.toLowerCase();return S(t,`undefined`)||S(t,`null`)||S(e,``)||S(e,`0`)?J(void 0):void 0}function LD(e){return Oa(e)?ND(e):ka(e)?PD(e):v(e)?FD(e):Na(e)?J(void 0):b(e)?ID(e):x(e)?J(e):void 0}function RD(e,t,n){return sD(n).value.map(n=>dO(e,t.items,n))}function zD(e,t,n){let r=gD(n);return oD(r)?r.value:n}function BD(e,t,n){let r=bD(n);return oD(r)?r.value:n}function VD(e,t,n){return dO({...e,...t.$defs},Bs(t.$ref),n)}function HD(e,t,n){return dO(e,zv(t),n)}function UD(e,t,n){let r=jD(n);return oD(r)?Math.trunc(r.value):n}function WD(e,t,n){return dO(e,zv(Pv(e,t)),n)}function GD(e,t,n){let r=gD(n);return oD(r)&&S(t.const,r.value)?r.value:n}function KD(e,t,n){let r=bD(n);return oD(r)&&S(t.const,r.value)?r.value:n}function qD(e,t,n){let r=jD(n);return oD(r)&&S(t.const,r.value)?r.value:n}function JD(e,t,n){let r=MD(n);return oD(r)&&S(t.const,r.value)?r.value:n}function YD(e,t,n){return S(t.const,n)?n:dl(t)?GD(e,t,n):fl(t)?KD(e,t,n):pl(t)?qD(e,t,n):ml(t)?JD(e,t,n):_c()}function XD(e,t,n){let r=TD(n);return oD(r)?r.value:n}function ZD(e,t,n){let r=jD(n);return oD(r)?r.value:n}function QD(e,t,n,r){let i=T(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=dO(e,n,r[t]));return r}function $D(e,t,n){return Ys(e)&&x(n[t])}function eO(e,t,n){let r=Qa(t.properties),i=T(n);for(let[t,a]of r)for(let r of i)t.test(r)&&!$D(a,r,n)&&(n[r]=dO(e,a,n[r]));return w(t,`additionalProperties`)&&y(t.additionalProperties)?QD(e,r,t.additionalProperties,n):n}function tO(e,t,n){return Pa(n)?eO(e,t,n):n}function nO(e,t,n){let r=Qa(t.patternProperties),i=T(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=dO(e,a,n[r]));return w(t,`additionalProperties`)&&y(t.additionalProperties)?QD(e,r,t.additionalProperties,n):n}function rO(e,t,n){return Pa(n)?nO(e,t,n):n}function iO(e,t,n){return w(e,t.$ref)?dO(e,e[t.$ref],n):n}function aO(e,t,n){let r=MD(n);return oD(r)?r.value:n}function oO(e,t,n){return dO(e,zv(t),n)}function sO(e,t,n){if(!_(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=dO(e,t.items[r],n[r]);return n}function cO(e,t,n){let r=LD(n);return oD(r)?r.value:n}function lO(e,t,n){if(t.anyOf.some(t=>RE(e,t,n)))return n;let r=t.anyOf.map(t=>dO(e,t,XE(n))).find(n=>RE(e,t,n));return x(r)?n:r}function uO(e,t,n){return oD(LD(n))?void 0:n}function dO(e,t,n){return Ms(t)?RD(e,t,n):nl(t)?zD(e,t,n):rl(t)?BD(e,t,n):rc(t)?VD(e,t,n):uc(t)?HD(e,t,n):ol(t)?UD(e,t,n):I(t)?WD(e,t,n):hl(t)?YD(e,t,n):_l(t)?XD(e,t,n):bl(t)?ZD(e,t,n):F(t)?tO(e,t,n):ad(t)?rO(e,t,n):Vs(t)?iO(e,t,n):wl(t)?aO(e,t,n):xf(t)?oO(e,t,n):Jl(t)?sO(e,t,n):ud(t)?cO(e,t,n):L(t)?lO(e,t,n):dd(t)?uO(e,t,n):n}function fO(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return dO(t,n,r)}function pO(e,t,n){if(!_(n))return n;for(let r=0;r<n.length;r++)n[r]=SO(e,t.items,n[r]);return n}function mO(e,t,n){return SO({...e,...t.$defs},Bs(t.$ref),n)}function hO(e,t){return x(t)?ja(e.default)?e.default():XE(e.default):t}function gO(e,t,n){return SO(e,zv(Pv(e,t)),n)}function _O(e,t,n){if(!y(n))return n;let r=T(t.properties);for(let i of r){let r=SO(e,t.properties[i],n[i]);(!x(r)||!Ys(t.properties[i])&&w(t.properties[i],`default`))&&(n[i]=r)}if(!Qv(t)||ka(t.additionalProperties))return n;for(let i of T(n))r.includes(i)||(n[i]=SO(e,t.additionalProperties,n[i]));return n}function vO(e,t,n){if(!y(n))return n;let[r,i]=[new RegExp(nd(t)),id(t)];for(let t of T(n))r.test(t)&&iy(i)&&(n[t]=SO(e,i,n[t]));if(!Qv(t))return n;for(let i of T(n))r.test(i)||(n[i]=SO(e,t.additionalProperties,n[i]));return n}function yO(e,t,n){return w(e,t.$ref)?SO(e,e[t.$ref],n):n}function bO(e,t,n){if(!_(n))return n;let[r,i]=[t.items,Math.max(t.items.length,n.length)];for(let t=0;t<i;t++)t<r.length&&(n[t]=SO(e,r[t],n[t]));return n}function xO(e,t,n){for(let r of t.anyOf){let t=SO(e,r,XE(n));if(RE(e,r,t))return t}return n}function SO(e,t,n){let r=iy(t)?hO(t,n):n;return Ms(t)?pO(e,t,r):rc(t)?mO(e,t,r):I(t)?gO(e,t,r):F(t)?_O(e,t,r):ad(t)?vO(e,t,r):Vs(t)?yO(e,t,r):Jl(t)?bO(e,t,r):L(t)?xO(e,t,r):r}function CO(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return SO(t,n,r)}function wO(e){return(...t)=>{let[n,r,i]=ac(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function TO(e,t,n){return t[`~codec`].decode(n)}function EO(e,t,n){return t[`~codec`].encode(n)}function DO(e,t,n,r){return Zc(n)?S(e,`Decode`)?TO(t,n,r):EO(t,n,r):r}function OO(e,t,n,r){if(!_(r))return r;for(let i=0;i<r.length;i++)r[i]=ZO(e,t,n.items,r[i]);return DO(e,t,n,r)}function kO(e,t,n,r){let i=DO(e,t,n,r);if(!_(i))return i;for(let r=0;r<i.length;r++)i[r]=ZO(e,t,n.items,i[r]);return i}function AO(e,t,n,r){return S(e,`Decode`)?OO(e,t,n,r):kO(e,t,n,r)}function jO(e,t,n,r){return r=ZO(e,{...t,...n.$defs},Bs(n.$ref),r),DO(e,t,n,r)}function MO(e){return e.reduce((e,t)=>({...e,...t}),{})}function NO(e,t){for(let n of t)if(!io(e,n))return n;return e}function PO(e,t,n,r){if(S(n.allOf.length,0))return DO(e,t,n,r);let i=n.allOf.map(n=>ZO(e,t,n,aD(n,XE(r))));return DO(e,t,n,i.every(e=>y(e))?MO(i):NO(r,i))}function FO(e,t,n,r){if(S(n.allOf.length,0))return DO(e,t,n,r);let i=DO(e,t,n,r),a=n.allOf.map(n=>ZO(e,t,n,aD(n,XE(i))));return a.every(e=>y(e))?MO(a):NO(i,a)}function IO(e,t,n,r){return S(e,`Decode`)?PO(e,t,n,r):FO(e,t,n,r)}function LO(e,t,n,r){if(!Pa(r))return r;for(let i of T(n.properties))w(r,i)&&!$D(n.properties[i],i,r)&&(r[i]=ZO(e,t,n.properties[i],r[i]));return DO(e,t,n,r)}function RO(e,t,n,r){let i=DO(e,t,n,r);if(!Pa(i))return i;for(let r of T(n.properties))w(i,r)&&!$D(n.properties[r],r,i)&&(i[r]=ZO(e,t,n.properties[r],i[r]));return i}function zO(e,t,n,r){return S(e,`Decode`)?LO(e,t,n,r):RO(e,t,n,r)}function BO(e,t,n,r){if(!Pa(r))return r;let i=new RegExp(nd(n));for(let a of T(r))i.test(a)&&(r[a]=ZO(e,t,id(n),r[a]));return DO(e,t,n,r)}function VO(e,t,n,r){let i=DO(e,t,n,r);if(!Pa(i))return i;let a=new RegExp(nd(n));for(let r of T(i))a.test(r)&&(i[r]=ZO(e,t,id(n),i[r]));return i}function HO(e,t,n,r){return S(e,`Decode`)?BO(e,t,n,r):VO(e,t,n,r)}function UO(e,t,n,r){return w(t,n.$ref)?ZO(e,t,t[n.$ref],r):r}function WO(e,t,n,r){return S(e,`Decode`)?DO(e,t,n,UO(e,t,n,r)):UO(e,t,n,DO(e,t,n,r))}function GO(e,t,n,r){if(!_(r))return r;for(let i=0;i<Math.min(n.items.length,r.length);i++)r[i]=ZO(e,t,n.items[i],r[i]);return DO(e,t,n,r)}function KO(e,t,n,r){let i=DO(e,t,n,r);if(!_(i))return r;for(let r=0;r<Math.min(n.items.length,i.length);r++)i[r]=ZO(e,t,n.items[r],i[r]);return i}function qO(e,t,n,r){return S(e,`Decode`)?GO(e,t,n,r):KO(e,t,n,r)}function JO(e,t,n,r){for(let i of n.anyOf)if(RE(t,i,r))return DO(e,t,n,ZO(e,t,i,r));return r}function YO(e,t,n,r){let i=DO(e,t,n,r);for(let r of n.anyOf){let n=ZO(e,t,r,XE(i));if(RE(t,r,n))return n}return i}function XO(e,t,n,r){return S(e,`Decode`)?JO(e,t,n,r):YO(e,t,n,r)}function ZO(e,t,n,r){return Ms(n)?AO(e,t,n,r):rc(n)?jO(e,t,n,r):I(n)?IO(e,t,n,r):F(n)?zO(e,t,n,r):ad(n)?HO(e,t,n,r):Vs(n)?WO(e,t,n,r):Jl(n)?qO(e,t,n,r):L(n)?XO(e,t,n,r):DO(e,t,n,r)}var QO=class extends BE{constructor(e,t){super(`Decode`,e,t)}};function $O(e,t,n){if(!RE(e,t,n))throw new QO(n,zE(e,t,n));return n}function ek(e,t,n){return ZO(`Decode`,e,as().unionPrioritySort?iD(t):t,n)}const tk=wO([(e,t,n)=>XE(n),(e,t,n)=>CO(e,t,n),(e,t,n)=>fO(e,t,n),(e,t,n)=>aD(e,t,n),(e,t,n)=>$O(e,t,n),(e,t,n)=>ek(e,t,n)]);function nk(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return tk(t,n,r)}var rk=class extends BE{constructor(e,t){super(`Encode`,e,t)}};function ik(e,t,n){if(!RE(e,t,n))throw new rk(n,zE(e,t,n));return n}function ak(e,t,n){return ZO(`Encode`,e,as().unionPrioritySort?iD(t):t,n)}const ok=wO([(e,t,n)=>XE(n),(e,t,n)=>ak(e,t,n),(e,t,n)=>CO(e,t,n),(e,t,n)=>fO(e,t,n),(e,t,n)=>aD(e,t,n),(e,t,n)=>ik(e,t,n)]);function sk(...e){let[t,n,r]=ac(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return ok(t,n,r)}function ck(e,t){return Zc(t)||gk(e,t.items)}function lk(e,t){return Zc(t)||pk({...e,...t.$defs},Bs(t.$ref))}function uk(e,t){return Zc(t)||t.allOf.some(t=>gk(e,t))}function dk(e,t){return Zc(t)||T(t.properties).some(n=>gk(e,t.properties[n]))}function fk(e,t){return Zc(t)||gk(e,id(t))}function pk(e,t){return!_k.has(t.$ref)&&(_k.add(t.$ref),Zc(t)||w(e,t.$ref)&&gk(e,e[t.$ref]))}function mk(e,t){return Zc(t)||t.items.some(t=>gk(e,t))}function hk(e,t){return Zc(t)||t.anyOf.some(t=>gk(e,t))}function gk(e,t){return Ms(t)?ck(e,t):rc(t)?lk(e,t):I(t)?uk(e,t):F(t)?dk(e,t):ad(t)?fk(e,t):Vs(t)?pk(e,t):Jl(t)?mk(e,t):L(t)?hk(e,t):Zc(t)}const _k=/* @__PURE__ */ new Set;function vk(...e){let[t,n]=ac(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return _k.clear(),gk(t,n)}var yk=class extends Error{constructor(e,t){super(t),this.type=e}};function bk(e,t){return ja(t.default)?t.default(t):y(t.default)?XE(t.default):t.default}function xk(e,t){if(Wy(t)&&!iy(t))throw new yk(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=Ey(t)?t.minItems:0;return Array.from({length:n},()=>Hk(e,t.items))}function Sk(e,t){return py(t)?BigInt(t.exclusiveMinimum)+BigInt(1):wy(t)?BigInt(t.minimum):BigInt(0)}function Ck(e,t){return!1}function wk(e,t){let n=Hk(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function Tk(e,t){return Hk({...e,...t.$defs},Bs(t.$ref))}function Ek(e,t){return Hk(e,zv(t))}function Dk(e,t){let n=Hk(e,t.returnType);return()=>n}function Ok(e,t){return py(t)&&v(t.exclusiveMinimum)?t.exclusiveMinimum+1:wy(t)?t.minimum:0}function kk(e,t){return Hk(e,zv(Pv(e,t)))}function Ak(e,t){return t.const}function jk(e,t){throw new yk(t,`Cannot create TNever types`)}function Mk(e,t){return null}function Nk(e,t){return py(t)&&v(t.exclusiveMinimum)?t.exclusiveMinimum+1:wy(t)?t.minimum:0}function Pk(e,t){return(x(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:Hk(e,t.properties[r])}),{})}function Fk(e,t){if(Oy(t)&&!iy(t))throw new yk(t,`Record with the minProperties constraint must have a default annotation`);return{}}function Ik(e,t){return w(e,t.$ref)?Hk(e,e[t.$ref]):(()=>{throw new yk(t,`Unable to deref Ref`)})()}function Lk(e,t){if((My(t)||my(t))&&!iy(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=Dy(t)?t.minLength:0;return``.padEnd(n)}function Rk(e,t){return Symbol()}function zk(e,t){let n=Ul(t.pattern);if(wl(n))throw new yk(t,`Unable to create TemplateLiteral due to infinite type expansion`);return Hk(e,n)}function Bk(e,t){return Array.from({length:t.minItems},(n,r)=>Hk(e,t.items[r]))}function Vk(e,t){if(S(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return Hk(e,t.anyOf[0])}function Hk(e,t){return iy(t)?bk(e,t):Ms(t)?xk(e,t):nl(t)?Sk(e,t):rl(t)?Ck(e,t):Fs(t)?wk(e,t):rc(t)?Tk(e,t):uc(t)?Ek(e,t):Rs(t)?Dk(e,t):ol(t)?Ok(e,t):I(t)?kk(e,t):hl(t)?Ak(e,t):qs(t)?jk(e,t):_l(t)?Mk(e,t):bl(t)?Nk(e,t):F(t)?Pk(e,t):ad(t)?Fk(e,t):Vs(t)?Ik(e,t):wl(t)?Lk(e,t):Sl(t)?Rk(e,t):xf(t)?zk(e,t):Jl(t)?Bk(e,t):ud(t)?void 0:L(t)?Vk(e,t):(dd(t),void 0)}function Uk(...e){let[t,n]=ac(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Hk(t,n)}var Wk=class extends BE{constructor(e,t){super(`Parse`,e,t)}};function Gk(e,t,n){if(!RE(e,t,n))throw new Wk(n,zE(e,t,n));return n}const Kk=wO([(e,t,n)=>XE(n),(e,t,n)=>CO(e,t,n),(e,t,n)=>fO(e,t,n),(e,t,n)=>aD(e,t,n),(e,t,n)=>Gk(e,t,n)]);Tl([P({type:ll(`insert`),path:Cl(),value:ec()}),Object({type:ll(`update`),path:Cl(),value:ec()}),P({type:ll(`delete`),path:Cl()})]);var qk=class{constructor(e,t){this.hasCodec=vk(e,t),this.buildResult=FE(e,t),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(as().correctiveParse)return Kk(this.Context(),this.Type(),e);throw new Wk(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:zE(this.Context(),this.Type(),e)}Clean(e){return aD(this.Context(),this.Type(),e)}Convert(e){return fO(this.Context(),this.Type(),e)}Create(){return Uk(this.Context(),this.Type())}Default(e){return CO(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?nk(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?sk(this.Context(),this.Type(),e):this.Parse(e)}};function Jk(...e){let[t,n]=ac(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new qk(t,n)}const Yk=/* @__PURE__ */ new WeakMap,Xk=Symbol.for(`TypeBox.Kind`);function Zk(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function Qk(e,t){switch(t){case`number`:return typeof e==`number`;case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`string`:return typeof e==`string`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!1}}function $k(e){try{return oA(e)}catch{return}}function eA(e,t){switch(t){case`number`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return typeof e==`boolean`?+!!e:e;case`integer`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isInteger(t))return t}return typeof e==`boolean`?+!!e:e;case`boolean`:if(e===null)return!1;if(typeof e==`string`){if(e===`true`)return!0;if(e===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return e;case`string`:return e===null?``:typeof e==`number`||typeof e==`boolean`?String(e):e;case`null`:return e===``||e===0||e===!1?null:e;default:return e}}function tA(e,t){let n=t.properties,r=new Set(n?Object.keys(n):[]);if(n)for(let[t,r]of Object.entries(n))t in e&&(e[t]=iA(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=iA(i,t.additionalProperties))}function nA(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=iA(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=iA(e[n],t.items)}function rA(e,t){for(let n of t)if($k(n)?.Check(e))return e;for(let n of t){let t=iA(structuredClone(e),n);if($k(n)?.Check(t))return t}return e}function iA(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=iA(n,e);Array.isArray(t.anyOf)&&(n=rA(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=rA(n,t.oneOf));let r=Zk(t),i=r.length>1&&r.some(e=>Qk(n,e));if(r.length>0&&!i)for(let e of r){let t=eA(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&tA(n,t),r.includes(`array`)&&Array.isArray(n)&&nA(n,t),n}function aA(e,t){if(Array.isArray(e)){if(Array.isArray(t.items))for(let n=0;n<e.length;n++){let r=t.items[n];r&&aA(e[n],r)}else if(t.items)for(let n of e)aA(n,t.items);return}if(typeof e!=`object`||!e||!t.properties)return;let n=e,r=new Set(t.required??[]);for(let[e,i]of Object.entries(t.properties))e in n&&(n[e]===null&&!r.has(e)&&typeof i.$ref!=`string`&&$k(i)?.Check(null)===!1?delete n[e]:aA(n[e],i))}function oA(e){let t=e,n=Yk.get(t);if(n)return n;let r=Jk(e);return Yk.set(t,r),r}function sA(e){if(e.keyword===`required`){let t=e.params.requiredProperties?.[0];if(t){let n=e.instancePath.replace(/^\//,``).replace(/\//g,`.`);return n?`${n}.${t}`:t}}return e.instancePath.replace(/^\//,``).replace(/\//g,`.`)||`root`}function cA(e,t){let n=structuredClone(t.arguments);aA(n,e.parameters),fO(e.parameters,n);let r=oA(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Xk)){let t=iA(n,e.parameters);if(t!==n){if(typeof n==`object`&&n&&typeof t==`object`&&t){for(let e of Object.keys(n))delete n[e];Object.assign(n,t)}else return r.Check(t)?t:n}}if(r.Check(n))return n;let i=r.Errors(n).map(e=>` - ${sA(e)}: ${e.message}`).join(`
|
|
@@ -1080,7 +1080,7 @@ Write /etc/models
|
|
|
1080
1080
|
`)}\n`}var vF=class{fs;watcher;broker;onPolicyReload;policy=Pn();unwatch=null;reloadChain=Promise.resolve();scoopPolicies=/* @__PURE__ */ new Map;scoopConfigPolicies=/* @__PURE__ */ new Map;scoopReloadChains=/* @__PURE__ */ new Map;constructor(e){this.fs=e.fs,this.watcher=e.watcher??null,this.broker=e.broker??l(e.capabilityBroker??null),this.onPolicyReload=e.onPolicyReload??(()=>{})}async init(){await this.ensureDefaults(),await this.reload(),this.startWatching()}getBroker(){return this.broker}async approve(e){if(e.kind===`export`&&In(this.policy,e.detail)===`nopasswd-allow`)return fF.info(`Export pre-granted by sudoers`,{subject:e.detail}),{decision:`allow`};let t=await this.broker.requestApproval(e);if(t.decision===`always`){if(e.kind===`guest-message`||e.kind===`guest-tool`)return fF.info(`Downgrading "Always" on a guest message to a one-shot allow`),{decision:`allow`,attestation:t.attestation};let n=t.pattern?.trim()||e.suggestedPattern?.trim()||e.detail;try{await this.persistGrant(Wn(e.kind),n)}catch(n){return fF.warn(`Failed to persist "Always" grant; honouring as one-shot allow`,{kind:e.kind,error:n instanceof Error?n.message:String(n)}),{decision:`allow`,attestation:t.attestation}}}return t}getPolicy(){return this.policy}getPolicyForScoop(e){let t=this.scoopPolicies.get(e),n=this.scoopConfigPolicies.get(e),r=[Nn(),this.policy];return n&&r.push(n),t&&r.push(t),Bn(...r)}getConfiguredPolicyForScoop(e){let t=this.scoopConfigPolicies.get(e);return t?Bn(Nn(),t):Nn()}registerScoopConfig(e,t){this.scoopConfigPolicies.set(e,Rn(_F(t??void 0))),this.onPolicyReload(e)}async initScoopPolicy(e,t){this.registerScoopConfig(e,t);let n=Kn(e);if(await this.fs.exists(n).catch(()=>!1)){let{migrateLegacyScoopSudoers:t}=await import(`./migrate-scoop-sudoers-CiGKeg93.js`);await t(e,{fs:this.fs})}await this.reloadScoopPolicy(e)}async appendScoopRule(e,t,n){let r=Ln(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=qn(e);if(!a)return fF.warn(`Unspellable scoop folder; not persisting`,{folder:e}),null;let o=await this.readTextOrEmpty(a),s=`NOPASSWD ${i} ${r}`;if(o.split(`
|
|
1081
1081
|
`).some(e=>e.trim()===s))return fF.info(`Per-scoop grant already present; skipping duplicate append`,{folder:e,kind:t,pattern:r}),r;try{await this.fs.mkdir(Vn,{recursive:!0})}catch{}let c=o?o.endsWith(`
|
|
1082
1082
|
`)?o:`${o}\n`:gF;return await this.fs.writeFile(a,`${c}${s}\n`),await this.reloadScoopPolicy(e),fF.info(`Appended per-scoop grant`,{folder:e,path:a,kind:t,pattern:r}),r}async readTextOrEmpty(e){try{if(!await this.fs.exists(e))return``;let t=await this.fs.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:new TextDecoder().decode(t)}catch(e){if(e instanceof g&&e.code===`ENOENT`)return``;throw e}}getShellConfig(e={}){return{getPolicy:()=>this.policy,broker:this.broker,persistCommandGrant:e=>this.persistCommandGrant(e),transparentGating:e.transparentGating??!0}}reload(){return this.reloadChain=this.reloadChain.then(()=>this.doReload()),this.reloadChain}forgetScoopPolicies(e){this.scoopConfigPolicies.delete(e),this.scoopPolicies.delete(e),this.scoopReloadChains.delete(e),this.onPolicyReload(e)}reloadScoopPolicyByFolder(e){return this.reloadScoopPolicy(e)}dispose(){this.unwatch?.(),this.unwatch=null}reloadScoopPolicy(e){let t=(this.scoopReloadChains.get(e)??Promise.resolve()).then(()=>this.doReloadScoopPolicy(e));return this.scoopReloadChains.set(e,t),t}async doReloadScoopPolicy(e){let t=qn(e);if(!t){this.scoopPolicies.delete(e),this.onPolicyReload(e);return}try{if(!await this.fs.exists(t)){this.scoopPolicies.delete(e),this.onPolicyReload(e);return}}catch{this.scoopPolicies.delete(e),this.onPolicyReload(e);return}this.scoopPolicies.set(e,await this.readPolicyFile(t)),this.onPolicyReload(e)}async doReload(){let e=[await this.readPolicyFile(Un)];try{let t=(await this.fs.readDir(Vn)).filter(e=>e.type===`file`).filter(e=>Mn(e.name)===null).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${Vn}/${n}`))}catch{}this.policy=Bn(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return Pn();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return Rn(n)}catch(t){return fF.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),Pn()}}async ensureDefaults(){try{await this.fs.mkdir(Vn,{recursive:!0})}catch{}await this.seedWhenAbsent(Un,()=>dF),await this.seedWhenAbsent(Gn,async()=>(await import(`./approver-agent-Dd-dJT-g.js`)).DEFAULT_APPROVALS_MD)}async seedWhenAbsent(e,t){try{if(await this.fs.exists(e))return;await this.fs.writeFile(e,await t()),fF.info(`Seeded bundled policy default`,{path:e})}catch(t){fF.warn(`Failed to seed bundled policy default`,{path:e,error:t instanceof Error?t.message:String(t)})}}persistCommandGrant(e){return this.persistGrant(`Cmnd`,e)}async persistGrant(e,t){let n=Ln(t);if(!n)return;let r=``;try{if(await this.fs.exists(Xn)){let e=await this.fs.readFile(Xn,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof g&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(Vn,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
|
|
1083
|
-
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(Xn,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,pF,e=>{let t=/* @__PURE__ */ new Set,n=!1,r=!1;for(let i of e){if(i.path===`/etc/sudoers.d`){r=!0;continue}let e=mF(i.path);e?t.add(e):n=!0}if(r){this.reload();for(let e of[...this.scoopPolicies.keys()])this.reloadScoopPolicy(e);return}n&&this.reload();for(let e of t)this.reloadScoopPolicy(e)}))}};function yF(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function bF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xF(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)xF(e[r],`${t}/${r}`,n);return}if(bF(e))for(let[r,i]of Object.entries(e))xF(i,`${t}/${yF(r)}`,n)}function SF(e,t,n){if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=SF(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(bF(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=SF(o,`${t}/${yF(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function CF(e,t,n){if(bF(e))return SF(e,t,n);if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=CF(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function wF(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function TF(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new o(`redaction-unavailable`);let a=0,s=i;for(;s<e.length;){let t=e[s].length;if(s>i&&a+t>1048576)break;a+=t,s++}let c=e.slice(i,s),l;try{l=await t.redact(c,n)}catch{throw new o(`redaction-unavailable`)}if(l.length!==c.length)throw new o(`redaction-unavailable`);r.push(...l),i=s}return r}function EF(e,t,n,r){let i=[],a=wF(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=wF(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=Se(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function DF(e,t,n){for(let{redactions:r}of e)for(let e of r)t.push(e),n[e.category]=(n[e.category]??0)+1}async function OF(e,n,r,i){if(i?.aborted)throw new o(`redaction-unavailable`);let{privacy:a,...s}=e,c=[];xF(s,``,c);let l=c.filter(e=>!t(e.pointer)),u=[...n.entries()],d=await TF([...l.map(e=>e.value),...u.map(([,e])=>e)],r,i),f=[],p={},m=1,ee=/* @__PURE__ */ new Map,te=[];for(let e=0;e<l.length;e++){let t=l[e],n=EF(t.value,d[e],{kind:`json`,pointer:t.pointer},m);m=n.nextId,n.finalText!==t.value&&ee.set(t.pointer,n.finalText),te.push(n)}DF(te,f,p);let ne=/* @__PURE__ */ new Map,h=l.length,re=[];for(let e=0;e<u.length;e++){let[t,n]=u[e],r=EF(n,d[h+e],{kind:`attachment`,attachmentId:t},m);m=r.nextId,ne.set(t,r.finalText),re.push(r)}DF(re,f,p);let ie=CF(e,``,ee);return{document:{...ie,privacy:{...ie.privacy,redactionCounts:p,redactions:f}},textAttachments:ne}}function kF(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}const AF={"image/png":`.png`,"image/jpeg":`.jpg`,"image/gif":`.gif`,"image/webp":`.webp`,"image/svg+xml":`.svg`,"image/bmp":`.bmp`,"application/pdf":`.pdf`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/json":`.json`,"text/plain":`.txt`,"text/markdown":`.md`,"text/csv":`.csv`,"text/html":`.html`,"text/xml":`.xml`,"application/xml":`.xml`};function jF(e,t){return AF[e]??(t===`text-redacted`?`.txt`:`.bin`)}function MF(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${jF(t,n)}`}function NF(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function PF(e){let t=[];for(let n of e.conversations){let e=0;for(let r of n.messages){let i=r.role;if(i!==`user`&&i!==`assistant`&&i!==`tool-result`)continue;let a=0;for(let o of r.content)o.type===`attachment-ref`&&(t.push({attachmentId:o.attachmentId,conversationId:n.id,messageId:r.id,role:i,userOrdinal:e,imgIndex:a}),a++);i===`user`&&e++}}return t}async function FF(e,t,n,r,i){let a=kF(e.mimeType,e.name),o={attachmentId:t,originalName:e.name,mimeType:e.mimeType,handling:a,present:!0,sourceConversationId:n,sourceMessageId:r};if(a===`text-redacted`){let t;if(e.text!==void 0)t=e.text;else if(e.data!==void 0)t=new TextDecoder().decode(NF(e.data));else if(e.path!==void 0&&i!==void 0)try{t=new TextDecoder().decode(await i(e.path))}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return t===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawText:t}}let s;if(e.data!==void 0)s=NF(e.data);else if(e.path!==void 0&&i!==void 0)try{s=await i(e.path)}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return s===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawBytes:s}}function IF(e,t,n,r){let i=[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:NF(e.data),present:!0,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let e=(t.get(s.conversationId)??[]).filter(e=>e.role===`user`)[s.userOrdinal];if(e===void 0){a.add(s.conversationId),i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-association-unavailable`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let c=(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:e})=>e.kind===`image`||e.kind===`file`&&e.data!==void 0)[s.imgIndex];if(c===void 0){i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}o.add(`${s.conversationId}:${e.id}:${c.i}`),i.push(FF(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function LF(e,t,n){return(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:r,i})=>(r.kind===`text`||r.kind===`file`&&(r.data!==void 0||r.path!==void 0))&&!n.has(`${t}:${e.id}:${i}`))}function RF(e,t,n,r,i,a,o){let s=LF(t,n,i),c=[];for(let t=0;t<s.length;t++){let{a:i}=s[t],l=`${e.id}-file-${t}`;r.has(l)||(a.push(FF(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function zF(e,t,n,r,i){let a=/* @__PURE__ */ new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=RF(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,/* @__PURE__ */ new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function BF(e,t){let n=/* @__PURE__ */ new Map,r=0,i=/* @__PURE__ */ new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,MF(r++,t.mimeType,t.handling));for(let n of e)!n.present&&n.missingReason!==void 0&&t.add(n.missingReason);return{rawAttachments:e.map(e=>e.present?{id:e.attachmentId,path:i.get(e.attachmentId),originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!0}:{id:e.attachmentId,path:``,originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!1,missingReason:e.missingReason??`attachment-file-missing`}),textMap:n}}async function VF(e,t,n,r,i){let{rawAttachments:a,textMap:s}=BF(e,n),c,l;try{let e=await OF({...t,attachments:a},s,r,i);c=e.document,l=e.textAttachments}catch(e){throw e instanceof o?e:new o(`attachment-unreadable`)}let u=/* @__PURE__ */ new Map;for(let t of e){if(u.has(t.attachmentId))throw new o(`schema-invalid`);u.set(t.attachmentId,t)}let d=/* @__PURE__ */ new Map,f=await Promise.all(c.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=u.get(e.id);if(t===void 0)throw new o(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(l.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await be(n);return d.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...c,attachments:f},bundleFiles:d}}async function HF(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??/* @__PURE__ */ new Map,o=e.vfsReader,s=/* @__PURE__ */ new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=IF(PF(t),n,a,o);l.size>0&&s.add(`attachment-association-unavailable`);for(let e of t.conversations)e.messages.filter(e=>e.role===`user`).length>(n.get(e.id)??[]).filter(e=>e.role===`user`).length&&s.add(`attachment-association-unavailable`);let d=await Promise.all(c),{updates:f,additionalPendingPromises:p}=zF(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),ee=[...d,...m],te=t;f.size>0&&(te={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:ne,bundleFiles:h}=await VF(ee,te,s,r,i),re=[...ne.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{...ne,session:{...ne.session,completeness:{status:re.length>0?`partial`:ne.session.completeness.status,missing:re}}},bundleFiles:h}}function UF(e){return Ft(e)}function WF(e,t){return e.map(e=>{let n=t.isProcessing(e.jid)?`1`:`0`,r=t.getAgentMessages(e.jid);if(r===null)return`${e.jid}:${n}:null`;let i=r.length,a=r[i-1],o=a?.role??``,s=a&&`timestamp`in a?a.timestamp:-1,c=a&&`toolCallId`in a?a.toolCallId:``;return`${e.jid}:${n}:${i}:${o}:${s}:${c}`}).join(`,`)}function GF(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let e of t)i.set(e.id,e);let a=/* @__PURE__ */ new Map;for(let e of n)a.set(e.id,e);let o=[],s=/* @__PURE__ */ new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:bt(t)?`cone`:`scoop`,name:t.name,...t.folder&&!bt(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=UF(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function KF(e,t,n={}){let r=e=>n.rootJid===void 0?e:Ct(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new o(`transfer-aborted`);let i=WF(n,e),[a,s]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new o(`transfer-aborted`);let c=r(e.listScoops());if(i===WF(c,e))return GF(c,a,s,e)}}function qF(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function JF(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function YF(e,t){if(typeof e==`string`)return e?[{type:`text`,text:e}]:[];let n=[],r=0;for(let i of e)i.type===`text`?i.text&&n.push({type:`text`,text:i.text}):i.type===`image`&&n.push(JF(t,r++));return n}function XF(e,t){let n=[],r=/* @__PURE__ */ new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=JF(t,a++);n.push(e),o.data&&o.mimeType&&r.set(e.attachmentId,{data:o.data,mimeType:o.mimeType})}return{blocks:n,excluded:i,images:r}}function ZF(e,t){let n=[],r=/* @__PURE__ */ new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=JF(t,i++);n.push(e),a.data&&a.mimeType&&r.set(e.attachmentId,{data:a.data,mimeType:a.mimeType})}return{blocks:n,images:r}}function QF(e,t,n){let r=qF(t,n),i=YF(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:/* @__PURE__ */ new Map}}function $F(e,t,n){let r=qF(t,n),{blocks:i,excluded:a,images:o}=XF(e.content,r);return{message:{id:r,sequence:n,role:`assistant`,timestamp:new Date(e.timestamp).toISOString(),content:i,model:{provider:e.provider,id:e.model,api:e.api},usage:e.usage,stopReason:e.stopReason,...e.errorMessage?{error:e.errorMessage}:{}},excludedReasoningBlocks:a,images:o}}function eI(e,t,n){let r=qF(t,n),{blocks:i,images:a}=ZF(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function tI(e,t,n){return e.role===`user`?QF(e,t,n):e.role===`assistant`?$F(e,t,n):e.role===`toolResult`?eI(e,t,n):{message:null,excludedReasoningBlocks:0,images:/* @__PURE__ */ new Map}}function nI(e){let t=[];for(let n of e){if(!n.parentConversationId)continue;let e={sourceConversationId:n.parentConversationId,targetConversationId:n.id};n.originToolCallId&&(e.toolCallId=n.originToolCallId),t.push(e)}return t}function rI(e){let t=0,n=/* @__PURE__ */ new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=tI(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:nI(e),excludedReasoningBlocks:t,canonicalImages:n}}const iI=(()=>{let e=/* @__PURE__ */ new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function aI(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^iI[(t^e[n])&255];return~t>>>0}const oI=new TextEncoder;function sI(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function cI(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function lI(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,sI(r,4,20),sI(r,6,2048),sI(r,8,0),sI(r,10,0),sI(r,12,0),cI(r,14,n),cI(r,18,t),cI(r,22,t),sI(r,26,e.length),sI(r,28,0),r.set(e,30),r}function uI(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,sI(i,4,20),sI(i,6,20),sI(i,8,2048),sI(i,10,0),sI(i,12,0),sI(i,14,0),cI(i,16,n),cI(i,20,t),cI(i,24,t),sI(i,28,e.length),sI(i,30,0),sI(i,32,0),sI(i,34,0),sI(i,36,0),cI(i,38,0),cI(i,42,r),i.set(e,46),i}function dI(e,t,n){let r=/* @__PURE__ */ new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,sI(r,4,0),sI(r,6,0),sI(r,8,e),sI(r,10,e),cI(r,12,t),cI(r,16,n),sI(r,20,0),r}function fI(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function pI(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${xe(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*mI(e,t,n,r){if(t?.aborted)throw r(new o(`transfer-aborted`)),new o(`transfer-aborted`);let i=()=>r(new o(`transfer-aborted`));t?.addEventListener(`abort`,i,{once:!0});let a=Qn.create(),s=0,c=0,l=[],u=!1;function*d(e){a.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{for(let n of e){if(t?.aborted)throw new o(`transfer-aborted`);let e=await n.load();if(t?.aborted)throw new o(`transfer-aborted`);if(e.byteLength>hI)throw new o(`schema-invalid`);let r=oI.encode(n.path),i=aI(e),a=lI(r,e.length,i);if(c+a.length+e.length>hI)throw new o(`schema-invalid`,`archive exceeds ZIP32 offsets`);if(l.push({nameBytes:r,size:e.length,crc:i,localOffset:c}),yield*d(a),t?.aborted)throw new o(`transfer-aborted`);yield*d(e)}if(l.length>gI)throw new o(`schema-invalid`);let r=c;for(let e of l){if(t?.aborted)throw new o(`transfer-aborted`);yield*d(uI(e.nameBytes,e.size,e.crc,e.localOffset))}if(t?.aborted)throw new o(`transfer-aborted`);yield*d(dI(l.length,c-r,r)),u=!0,n({byteLength:s,sha256:a.hex()})}catch(e){throw u=!0,r(e),e}finally{t?.removeEventListener(`abort`,i),u||(u=!0,r(new o(`transfer-aborted`)))}}const hI=4294967295,gI=65535;function _I(e,t){let n=/* @__PURE__ */ new Set;for(let{path:t}of e){if(!fI(t)||n.has(t))throw new o(`schema-invalid`);n.add(t)}if(e.length>gI)throw new o(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return a.catch(()=>void 0),{chunks:mI(e,t,r,i),completion:a}}function vI(e,t,n){for(let e of t.keys())if(!fI(e))throw new o(`schema-invalid`);if(t.size+1>gI)throw new o(`schema-invalid`);for(let e of t.values())if(e.byteLength>hI)throw new o(`schema-invalid`);let r=[{path:`transcript.json`,load:()=>new TextEncoder().encode(JSON.stringify(e,null,2))},...[...t].map(([e,t])=>({path:e,load:()=>t}))];return{filename:pI(e),..._I(r,n)}}function yI(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:(/* @__PURE__ */ new Date()).toISOString(),producer:{application:`slicc`,version:i},format:s},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function bI(e,t){let n=[],r=1;for(let i of e){if(i.role!==`user`&&i.role!==`assistant`)continue;let e=`${t}-msg-${String(r).padStart(6,`0`)}`;n.push({id:e,sequence:r++,role:i.role,timestamp:new Date(i.timestamp||0).toISOString(),content:i.content?[{type:`text`,text:i.content}]:[]})}return n}function xI(e){let t=te(e);if(!t.ok)throw new o(`schema-invalid`,t.error)}function SI(e,t,n){let r=/* @__PURE__ */ new Map;for(let i of e)if(i.present&&i.path){if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}}return r}async function CI(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);return n?{...e,byteLength:n.length,sha256:await be(n)}:e}))}function wI(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return{};let n=t[1],r={},i=n.match(/^createdAt:\s*(\d+)\s*$/m),a=n.match(/^updatedAt:\s*(\d+)\s*$/m);return i&&(r.createdAt=new Date(Number(i[1])).toISOString()),a&&(r.updatedAt=new Date(Number(a[1])).toISOString()),r}var TI=class{deps;constructor(e){this.deps=e}async export(e,t={}){let{signal:n,onProgress:r}=t,i;return i=e.kind===`active`?await this.buildActiveSnapshot(n,r):await this.buildFrozenSnapshot(e.sessionId,n,r),xI(i.document),r?.({phase:`packaging`}),vI(i.document,i.bundleFiles,n)}async snapshotCone(e,t){let n=await KF(this.deps.collection,t,{rootJid:e.jid}),r=rI(n.sources),i=await HF({document:yI(e.jid,e.name,`active`,r,this.deps.version),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});return xI(i.document),i}async snapshotFrozen(e,t){let n=await this.buildFrozenSnapshot(e,t);return xI(n.document),n}async captureFrozen(e,t){let n=await KF(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=rI(n.sources),{document:i,bundleFiles:a}=await HF({document:yI(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});if(xI(i),t?.aborted)throw new o(`transfer-aborted`);try{await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a},t)}finally{this.deps.snapshotStore.discardIfUnindexed?.(e.sessionId)?.catch(()=>void 0)}}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await KF(this.deps.collection,e),r=rI(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=yI(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),HF({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r;try{r=await this.deps.snapshotStore.read(e)}catch(e){if(!(e instanceof o)||e.code!==`session-not-found`)throw e;r=null}return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=/* @__PURE__ */ new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await OF(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new o(`redaction-unavailable`)}let a=SI(r.attachments,i,e.attachments),s=await CI(r.attachments,a);return{document:{...r,attachments:s},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await nn(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new o(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new o(`session-not-found`)}let{loadFrozenArchive:a}=await import(`./session-jsonl-BwJt_n1u.js`),{title:c,messages:l}=await a(this.deps.vfs,i,r.filename),u=`legacy-cone`,d=bI(l,u),f=wI(i),p={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:(/* @__PURE__ */ new Date()).toISOString(),producer:{application:`slicc`,version:this.deps.version},format:s},session:{id:e,title:c,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...f,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:u,kind:`cone`,name:c,messages:d}],delegations:[],attachments:[]},m=/* @__PURE__ */ new Map([[u,l]]);return n?.({phase:`redacting`}),HF({document:p,chatMessagesByConversation:m,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new o(`attachment-unreadable`);return t}};const EI=`/sessions/data`,DI=`document.json`,OI=`.publishing`;function kI(e){if(e?.aborted)throw new o(`transfer-aborted`)}function AI(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new o(`session-not-found`)}function jI(e){return`${EI}/${e}`}function MI(e){return`${EI}/.tmp-${e}`}async function NI(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function PI(e,t){let n;try{n=await e.readDir(t)}catch{return}for(let r of n){let n=`${t}/${r.name}`;r.type===`directory`&&await PI(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function FI(e,t){let n=await e.readDir(t);for(let r of n){if(r.name===OI)continue;let n=`${t}/${r.name}`;r.type===`directory`?await PI(e,n):await e.rm(n)}}async function II(e,t,n,r){kI(r),await NI(e,n);let i=await e.readDir(t);for(let a of i){kI(r);let i=`${t}/${a.name}`,o=`${n}/${a.name}`;if(a.type===`directory`)await II(e,i,o,r);else{let t=await e.readFile(i,{encoding:`binary`});await e.writeFile(o,t)}}}async function LI(e,t,n,r){AI(t);let i=MI(t),a=jI(t),s=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!s.has(e))throw new o(`schema-invalid`);kI(r),await NI(e,i);let c=!1;try{let t=[...n.document.attachments];for(let[e,i]of n.attachments){kI(r);let n=await be(i),a=s.get(e);if(a!==void 0){let e=t.indexOf(a);e!==-1&&(t[e]={...a,sha256:n,byteLength:i.length})}}let o={...n.document,attachments:t},l=JSON.stringify(o,null,2);if(await e.writeFile(`${i}/${DI}`,l),n.attachments.size>0)for(let[t,r]of n.attachments){let n=`${i}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await NI(e,`${i}/${t.slice(0,a)}`),await e.writeFile(n,r)}await e.flush(),kI(r),await NI(e,a),c=!0,await e.writeFile(`${a}/${OI}`,`in-progress`),await FI(e,a),kI(r),await II(e,i,a,r),await e.flush(),kI(r),await e.rm(`${a}/${OI}`)}catch(t){if(c)try{await FI(e,a)}catch{}throw await PI(e,i),t}await PI(e,i)}async function RI(e,t){AI(t);for(let n of[jI(t),MI(t)])try{await e.rm(n,{recursive:!0})}catch(e){if(e?.code!==`ENOENT`)throw e}}async function zI(e,t){let[{serializeIndexWrite:n},{readIndexForPresence:r}]=await Promise.all([import(`./frozen-archive-writer-CXRaBKpe.js`).then(e=>e.i),import(`./frozen-session-identity-XzcVW8UL.js`)]);return n(async()=>{let n=await r(e);return n===null||n.some(e=>e.sessionId===t)?!1:(await RI(e,t),!0)})}async function BI(e,t){AI(t);let n=jI(t),r=`${n}/${DI}`;try{throw await e.stat(`${n}/${OI}`),new o(`session-not-found`)}catch(e){if(e instanceof o||e.code!==`ENOENT`)throw e}let i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new o(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new o(`schema-invalid`)}if(!te(a).ok)throw new o(`schema-invalid`);let s=/* @__PURE__ */ new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new o(`transfer-corrupt`)}if(await be(i)!==t.sha256)throw new o(`transfer-corrupt`);s.set(t.path,i)}return{document:a,attachments:s}}function VI(e){return`error`in e}function HI(){throw new o(`redaction-unavailable`)}function UI(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&HI(),e.texts}function WI(){return{async redact(e){let t;try{t=await fetch(ze(`/api/secrets/redact-export`),{method:`POST`,headers:Be({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{HI()}t.ok||HI();let n;try{n=await t.json()}catch{HI()}return UI(n,e.length)}}}function GI(){return{async redact(e){let t;try{t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.redact-export`,texts:e},e=>{chrome.runtime.lastError,t(e??null)})})}catch{HI()}return typeof t==`object`&&t&&VI(t)&&HI(),UI(t,e.length)}}}function KI(){return{async redact(e){let t;try{t=await ot(`secrets.redact-export`,{texts:e})}catch{HI()}return t??HI(),typeof t==`object`&&t&&VI(t)&&HI(),UI(t,e.length)}}}function qI(){return{async redact(e){HI()}}}function JI(){let e=at();return e===`connect`?qI():e===`extension-direct`?GI():e===`extension-delegate`?KI():WI()}const YI=/* @__PURE__ */ new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function XI(e){return`e${e}`}function ZI(e){let t=[];for(let n of e){let e=eL(n),r=nL(n);if(e===`assistant`){let e=t.length,i=XI(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:aL(n),message:n,model:iL(n)});for(let e of oL(n)){let n=t.length;t.push({id:XI(n),seq:n,kind:`tool-call`,timestamp:r,toolCallId:e.id,name:e.name,assistantEntryId:i})}continue}if(e===`toolResult`){let e=n,i=t.length;t.push({id:XI(i),seq:i,kind:`tool-result`,timestamp:r,text:aL(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=aL(n),a=e===`user`?$I(i):null,o=t.length,s=XI(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):YI.has(a)?t.push({id:s,seq:o,kind:`child-result`,timestamp:r,text:i,message:n,channel:a}):t.push({id:s,seq:o,kind:`external-event`,timestamp:r,text:i,message:n,channel:a})}return t}function QI(e){let t=[];for(let n of e){let e=t.length,r=XI(e),i=rL(n),a=typeof n.content==`string`?n.content:``;if(n.role===`assistant`){t.push({id:r,seq:e,kind:`assistant`,timestamp:i,text:a,chat:n,model:n.model});for(let e of n.toolCalls??[]){let n=t.length;t.push({id:XI(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&uj(n.channel)?n.channel:$I(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):YI.has(o)?t.push({id:r,seq:e,kind:`child-result`,timestamp:i,text:a,chat:n,channel:o}):t.push({id:r,seq:e,kind:`external-event`,timestamp:i,text:a,chat:n,channel:o})}return t}function $I(e){for(let t of fj(e)){let e=(t.sender?pj(t.sender):null)??mj(t.body);if(e)return e}return null}function eL(e){return e.role??``}function tL(e){if(typeof e==`number`)return e;if(typeof e==`string`){let t=Date.parse(e);return Number.isNaN(t)?0:t}return e instanceof Date?e.getTime():0}function nL(e){return tL(e.timestamp)}function rL(e){return tL(e.timestamp)}function iL(e){let t=e.model;return typeof t==`string`?t:void 0}function aL(e){let t=e.content;if(typeof t==`string`)return t;if(!Array.isArray(t))return``;let n=[];for(let e of t)e?.type===`text`&&n.push(e.text);return n.join(``)}function oL(e){let t=e.content;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(e?.type!==`toolCall`)continue;let t=e;n.push({id:t.id??``,name:t.name??``})}return n}function sL(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function cL(e){return e!==null&&e.version<=2}const lL=h(`work-unit-conversation`);var uL=class extends Error{};const dL=`conversations`;async function fL(e){let t=e.now??(()=>Date.now()),n=await mL(e.store,t()),r={migrated:0,alreadyDone:0,empty:0,skipped:0};if(n.done)return r.alreadyDone=e.units.length,r;let i=new Set(n.completedKeys),a=!1;for(let o of e.units){let s={...o,parentJid:o.parentJid??null},c=xn(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await pL(e,s,c,t());n===`migrated`?r.migrated++:n===`already`?r.alreadyDone++:r.empty++}catch(i){let o=i instanceof Error?i.message:String(i);if(r.skipped++,n.skipped=[...n.skipped.filter(e=>e.key!==c),{key:c,reason:o}],lL.warn(`Skipping a unit whose conversation could not be migrated`,{key:c,folder:s.folder,error:o}),i instanceof uL){a=!0,n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${s.jid}`);continue}}i.add(c),n.completedKeys=[...i],n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${s.jid}`)}return n.done=!a,n.updatedAt=t(),await e.store.putMigrationState(n),lL.info(`Canonical conversation migration complete`,{...r}),r}async function pL(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return lL.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw new uL(`canonical record unreadable: ${i.reason}`);let a=Sn(t),o=await e.loadAgentSession(t.jid);if(o&&!Array.isArray(o.messages))throw Error(`agent-sessions record has no message list`);if(o&&o.messages.length>0){let t={...a,version:2,origin:`agent-history`,entries:ZI(o.messages),createdAt:o.createdAt??r,updatedAt:r,migratedFrom:`agent-sessions`};return await e.store.save(t),`migrated`}let s=await e.loadChatSession(a.legacyKeys.chatSessionId);if(s&&!Array.isArray(s.messages))throw Error(`browser-coding-agent record has no message list`);if(s&&s.messages.length>0){let t={...a,version:2,origin:`ui-projection`,entries:QI(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function mL(e,t){let n=await e.getMigrationState(dL);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:dL,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var hL=/* @__PURE__ */ e({applyAttachmentOverlays:()=>yL,interleaveMarkers:()=>bL,toAgentMessages:()=>_L,toChatMessages:()=>vL});const gL=/* @__PURE__ */ new Set([`summarized`,`fallback`]);function _L(e){if(!cL(e)||e===null||e.origin!==`agent-history`)return[];let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.message&&t.push(n.message);return t}async function vL(e,t={}){if(!cL(e)||e===null)return[];if(e.origin===`ui-projection`){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return bL(t,e.markers)}let n=e.projectionPrefix??[],r=_L(e);if(r.length===0)return bL([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>Cj),a=yL(i(r,t),e.attachments);return bL([...n,...a],e.markers)}function yL(e,t){if(!t?.length)return e;let n=[...t].sort((e,t)=>e.timestamp-t.timestamp),r=/* @__PURE__ */ new Set;return e.map(e=>{if(e.role!==`user`||e.attachments?.length)return e;let t=e.content.trim(),i=n.findIndex((e,n)=>!r.has(n)&&e.body.trim()===t);return i<0?e:(r.add(i),{...e,attachments:n[i].attachments})})}function bL(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||gL.has(e.compaction.state));if(n.length===0)return e;let r=[...n].sort((e,t)=>e.timestamp-t.timestamp),i=[],a=0;for(let t of e){let e=xL(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(SL(r[a++]));i.push(t)}for(;a<r.length;)i.push(SL(r[a++]));return i}function xL(e){let t=e.timestamp;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Date.parse(t);if(!Number.isNaN(e))return e}return-1/0}function SL(e){return e.kind===`error`?{id:e.id,role:`assistant`,content:e.text,timestamp:e.timestamp,error:!0}:{id:e.id,role:`assistant`,content:``,timestamp:e.timestamp,compaction:e.compaction}}async function CL(e){return{id:e.legacyKeys.chatSessionId,messages:await vL(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function wL(e){return{id:e.workUnitId,messages:_L(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var TL=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(wL)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(CL))}async latestPerUnit(){let e=/* @__PURE__ */ new Map;for(let t of await this.store.loadAll()){let n=e.get(t.workUnitId);(!n||t.updatedAt>n.updatedAt)&&e.set(t.workUnitId,t)}return[...e.values()]}async loadRootChatSession(e){let t=await this.store.loadLatestInWorkspace(en({parentJid:null,folder:e}).root);return t?CL(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const EL=h(`work-unit-conversation`),DL=`conversations`,OL=`migrations`;var kL=class{dbPromise=null;dbName;writeChains=/* @__PURE__ */ new Map;constructor(e={}){this.dbName=e.dbName??`slicc-work-units`}async load(e){let t=await this.read(e);return t.status===`ok`?t.record:null}async read(e){try{let t=await IL((await this.getDb()).transaction(DL,`readonly`).objectStore(DL).get(e));return t?cL(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(EL.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(EL.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return EL.warn(`Conversation record read failed`,{key:e,error:RL(t)}),{status:`error`,reason:RL(t)}}}async save(e){let t=e.version>2?e.version:sL(e),n={...e,version:t},r=(await this.getDb()).transaction(DL,`readwrite`);return r.objectStore(DL).put(n),await LL(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(DL,`readwrite`);t.objectStore(DL).delete(e),await LL(t)}catch(t){EL.warn(`Conversation record delete failed`,{key:e,error:RL(t)})}})}async rekey(e,t){if(e!==t.key)try{let n=await this.read(e);if(n.status!==`ok`)return;let r=await this.read(t.key);if(r.status===`incompatible`||r.status===`error`){EL.warn(`Conversation rekey refused: target is not writable`,{fromKey:e,toKey:t.key,status:r.status});return}let i=Date.now();await this.save({...n.record,key:t.key,workUnitId:t.workUnitId,workspaceId:t.workspaceId,folder:t.folder,legacyKeys:t.legacyKeys,updatedAt:i}),await this.delete(e)}catch(n){EL.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:RL(n)})}}async loadAll(){try{return(await IL((await this.getDb()).transaction(DL,`readonly`).objectStore(DL).getAll())).filter(e=>cL(e)&&Array.isArray(e.entries))}catch(e){return EL.warn(`Conversation record listing failed`,{error:RL(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await IL((await this.getDb()).transaction(DL,`readonly`).objectStore(DL).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)cL(e)&&Array.isArray(e.entries)&&(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return EL.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:RL(t)}),null}}async listKeys(){try{return(await IL((await this.getDb()).transaction(DL,`readonly`).objectStore(DL).getAllKeys())).map(String)}catch(e){return EL.warn(`Conversation key listing failed`,{error:RL(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=ZI(t);return this.serialize(e.key,()=>this.ingestEntries(e,i,n,r))}async ingestEntries(e,t,n,r){try{let i=await this.read(e.key);if(i.status===`incompatible`||i.status===`error`)return null;let a=i.status===`ok`?i.record:null,o=AL(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return EL.warn(`Conversation record write failed`,{key:e.key,error:RL(t)}),null}}async putMarker(e,t,n={}){return this.withRecord(e,n.createWith,e=>{let n=(e.markers??[]).filter(e=>e.id!==t.id);return n.push(t),n.sort((e,t)=>e.timestamp-t.timestamp),{...e,markers:n.slice(-64)}})}async putAttachments(e,t){if(t.length===0)return!1;let n=new Set(t.map(e=>e.id));return this.withRecord(e.key,e,e=>({...e,attachments:[...(e.attachments??[]).filter(e=>!n.has(e.id)),...t].sort((e,t)=>e.timestamp-t.timestamp).slice(-256)}))}async deleteMarker(e,t){return this.withRecord(e,void 0,e=>{let n=(e.markers??[]).filter(e=>e.id!==t);return n.length===(e.markers?.length??0)?null:{...e,markers:n}})}withRecord(e,t,n){return this.serialize(e,()=>this.mutateRecord(e,t,n))}async mutateRecord(e,t,n){try{let r=await this.read(e),i=r.status===`ok`?r.record:r.status===`absent`&&t?jL(t,Date.now()):null;if(!i)return!1;let a=n(i);return a?(await this.save({...a,updatedAt:Date.now()}),!0):!1}catch(t){return EL.warn(`Conversation marker write failed`,{key:e,error:RL(t)}),!1}}serialize(e,t){let n=(this.writeChains.get(e)??Promise.resolve()).then(t,t),r=n.then(()=>void 0,()=>void 0);return this.writeChains.set(e,r),r.then(()=>{this.writeChains.get(e)===r&&this.writeChains.delete(e)}),n}async getMigrationState(e){try{return await IL((await this.getDb()).transaction(OL,`readonly`).objectStore(OL).get(e))??null}catch(t){return EL.warn(`Migration state read failed`,{id:e,error:RL(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(OL,`readwrite`);t.objectStore(OL).put(e),await LL(t)}catch(t){EL.warn(`Migration state write failed`,{id:e.id,error:RL(t)})}}async clearAll(){let e=(await this.getDb()).transaction([DL,OL],`readwrite`);e.objectStore(DL).clear(),e.objectStore(OL).clear(),await LL(e)}getDb(){return this.dbPromise||(this.dbPromise=FL(this.dbName).then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}};function AL(e,t,n,r,i){if(!e)return t.length===0?null:{key:n.key,version:2,workUnitId:n.workUnitId,workspaceId:n.workspaceId,folder:n.folder,origin:r,entries:t,createdAt:i.createdAt,updatedAt:i.now,legacyKeys:n.legacyKeys};if(e.origin===`ui-projection`&&r===`agent-history`)return t.length===0?null:{...e,version:2,origin:r,entries:t,projectionPrefix:[...e.projectionPrefix??[],...ML(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&NL(a,t))return null;let o=t.length>a.length&&NL(a,t);return{...e,version:2,origin:r,entries:t,updatedAt:i.now,rewrites:o?e.rewrites:(e.rewrites??0)+1,legacyKeys:n.legacyKeys}}function jL(e,t){return{key:e.key,version:2,workUnitId:e.workUnitId,workspaceId:e.workspaceId,folder:e.folder,origin:`agent-history`,entries:[],createdAt:t,updatedAt:t,legacyKeys:e.legacyKeys}}function ML(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function NL(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!PL(e[n],t[n]))return!1;return!0}function PL(e,t){return e.kind!==t.kind||e.seq!==t.seq?!1:e.kind===`tool-call`&&t.kind===`tool-call`?e.toolCallId===t.toolCallId&&e.name===t.name:(`text`in e?e.text:``)===(`text`in t?t.text:``)}function FL(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(DL)||e.createObjectStore(DL,{keyPath:`key`}),e.objectStoreNames.contains(OL)||e.createObjectStore(OL,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function IL(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function LL(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function RL(e){return e instanceof Error?e.message:String(e)}var zL=/* @__PURE__ */ e({CONE_MEMORY_PATH:()=>HL,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>VL,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>UL,applyConeMemoryBudget:()=>JL,readSessionCount:()=>KL,restructureConeMemory:()=>qL,splitConeMemory:()=>GL});const BL=h(`cone-memory-budget`),VL=1.25,HL=Xt.memoryPath,UL=`/sessions/index.json`,WL=/^## Auto-extracted/m;function GL(e){let t=WL.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function KL(e){try{let t=await e.readFile(UL,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?tn(r).length:0}catch{return 0}}async function qL(e){let{header:t,autoExtracted:n}=GL(e.currentContent);if(!n.trim())return e.currentContent;let r=nt(`You are a memory consolidation assistant. You are given a markdown file's "auto-extracted" section — a list of memory bullets accumulated across sessions of an AI coding assistant. Your job is to rewrite that section as a tighter, deduplicated set of durable memories that fits well within ${e.budget} characters.
|
|
1083
|
+
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(Xn,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,pF,e=>{let t=/* @__PURE__ */ new Set,n=!1,r=!1;for(let i of e){if(i.path===`/etc/sudoers.d`){r=!0;continue}let e=mF(i.path);e?t.add(e):n=!0}if(r){this.reload();for(let e of[...this.scoopPolicies.keys()])this.reloadScoopPolicy(e);return}n&&this.reload();for(let e of t)this.reloadScoopPolicy(e)}))}};function yF(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function bF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xF(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)xF(e[r],`${t}/${r}`,n);return}if(bF(e))for(let[r,i]of Object.entries(e))xF(i,`${t}/${yF(r)}`,n)}function SF(e,t,n){if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=SF(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(bF(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=SF(o,`${t}/${yF(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function CF(e,t,n){if(bF(e))return SF(e,t,n);if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=CF(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function wF(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function TF(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new o(`redaction-unavailable`);let a=0,s=i;for(;s<e.length;){let t=e[s].length;if(s>i&&a+t>1048576)break;a+=t,s++}let c=e.slice(i,s),l;try{l=await t.redact(c,n)}catch{throw new o(`redaction-unavailable`)}if(l.length!==c.length)throw new o(`redaction-unavailable`);r.push(...l),i=s}return r}function EF(e,t,n,r){let i=[],a=wF(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=wF(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=Se(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function DF(e,t,n){for(let{redactions:r}of e)for(let e of r)t.push(e),n[e.category]=(n[e.category]??0)+1}async function OF(e,n,r,i){if(i?.aborted)throw new o(`redaction-unavailable`);let{privacy:a,...s}=e,c=[];xF(s,``,c);let l=c.filter(e=>!t(e.pointer)),u=[...n.entries()],d=await TF([...l.map(e=>e.value),...u.map(([,e])=>e)],r,i),f=[],p={},m=1,ee=/* @__PURE__ */ new Map,te=[];for(let e=0;e<l.length;e++){let t=l[e],n=EF(t.value,d[e],{kind:`json`,pointer:t.pointer},m);m=n.nextId,n.finalText!==t.value&&ee.set(t.pointer,n.finalText),te.push(n)}DF(te,f,p);let ne=/* @__PURE__ */ new Map,h=l.length,re=[];for(let e=0;e<u.length;e++){let[t,n]=u[e],r=EF(n,d[h+e],{kind:`attachment`,attachmentId:t},m);m=r.nextId,ne.set(t,r.finalText),re.push(r)}DF(re,f,p);let ie=CF(e,``,ee);return{document:{...ie,privacy:{...ie.privacy,redactionCounts:p,redactions:f}},textAttachments:ne}}function kF(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}const AF={"image/png":`.png`,"image/jpeg":`.jpg`,"image/gif":`.gif`,"image/webp":`.webp`,"image/svg+xml":`.svg`,"image/bmp":`.bmp`,"application/pdf":`.pdf`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/json":`.json`,"text/plain":`.txt`,"text/markdown":`.md`,"text/csv":`.csv`,"text/html":`.html`,"text/xml":`.xml`,"application/xml":`.xml`};function jF(e,t){return AF[e]??(t===`text-redacted`?`.txt`:`.bin`)}function MF(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${jF(t,n)}`}function NF(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function PF(e){let t=[];for(let n of e.conversations){let e=0;for(let r of n.messages){let i=r.role;if(i!==`user`&&i!==`assistant`&&i!==`tool-result`)continue;let a=0;for(let o of r.content)o.type===`attachment-ref`&&(t.push({attachmentId:o.attachmentId,conversationId:n.id,messageId:r.id,role:i,userOrdinal:e,imgIndex:a}),a++);i===`user`&&e++}}return t}async function FF(e,t,n,r,i){let a=kF(e.mimeType,e.name),o={attachmentId:t,originalName:e.name,mimeType:e.mimeType,handling:a,present:!0,sourceConversationId:n,sourceMessageId:r};if(a===`text-redacted`){let t;if(e.text!==void 0)t=e.text;else if(e.data!==void 0)t=new TextDecoder().decode(NF(e.data));else if(e.path!==void 0&&i!==void 0)try{t=new TextDecoder().decode(await i(e.path))}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return t===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawText:t}}let s;if(e.data!==void 0)s=NF(e.data);else if(e.path!==void 0&&i!==void 0)try{s=await i(e.path)}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return s===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawBytes:s}}function IF(e,t,n,r){let i=[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:NF(e.data),present:!0,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let e=(t.get(s.conversationId)??[]).filter(e=>e.role===`user`)[s.userOrdinal];if(e===void 0){a.add(s.conversationId),i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-association-unavailable`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let c=(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:e})=>e.kind===`image`||e.kind===`file`&&e.data!==void 0)[s.imgIndex];if(c===void 0){i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}o.add(`${s.conversationId}:${e.id}:${c.i}`),i.push(FF(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function LF(e,t,n){return(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:r,i})=>(r.kind===`text`||r.kind===`file`&&(r.data!==void 0||r.path!==void 0))&&!n.has(`${t}:${e.id}:${i}`))}function RF(e,t,n,r,i,a,o){let s=LF(t,n,i),c=[];for(let t=0;t<s.length;t++){let{a:i}=s[t],l=`${e.id}-file-${t}`;r.has(l)||(a.push(FF(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function zF(e,t,n,r,i){let a=/* @__PURE__ */ new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=RF(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,/* @__PURE__ */ new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function BF(e,t){let n=/* @__PURE__ */ new Map,r=0,i=/* @__PURE__ */ new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,MF(r++,t.mimeType,t.handling));for(let n of e)!n.present&&n.missingReason!==void 0&&t.add(n.missingReason);return{rawAttachments:e.map(e=>e.present?{id:e.attachmentId,path:i.get(e.attachmentId),originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!0}:{id:e.attachmentId,path:``,originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!1,missingReason:e.missingReason??`attachment-file-missing`}),textMap:n}}async function VF(e,t,n,r,i){let{rawAttachments:a,textMap:s}=BF(e,n),c,l;try{let e=await OF({...t,attachments:a},s,r,i);c=e.document,l=e.textAttachments}catch(e){throw e instanceof o?e:new o(`attachment-unreadable`)}let u=/* @__PURE__ */ new Map;for(let t of e){if(u.has(t.attachmentId))throw new o(`schema-invalid`);u.set(t.attachmentId,t)}let d=/* @__PURE__ */ new Map,f=await Promise.all(c.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=u.get(e.id);if(t===void 0)throw new o(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(l.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await be(n);return d.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...c,attachments:f},bundleFiles:d}}async function HF(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??/* @__PURE__ */ new Map,o=e.vfsReader,s=/* @__PURE__ */ new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=IF(PF(t),n,a,o);l.size>0&&s.add(`attachment-association-unavailable`);for(let e of t.conversations)e.messages.filter(e=>e.role===`user`).length>(n.get(e.id)??[]).filter(e=>e.role===`user`).length&&s.add(`attachment-association-unavailable`);let d=await Promise.all(c),{updates:f,additionalPendingPromises:p}=zF(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),ee=[...d,...m],te=t;f.size>0&&(te={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:ne,bundleFiles:h}=await VF(ee,te,s,r,i),re=[...ne.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{...ne,session:{...ne.session,completeness:{status:re.length>0?`partial`:ne.session.completeness.status,missing:re}}},bundleFiles:h}}function UF(e){return Ft(e)}function WF(e,t){return e.map(e=>{let n=t.isProcessing(e.jid)?`1`:`0`,r=t.getAgentMessages(e.jid);if(r===null)return`${e.jid}:${n}:null`;let i=r.length,a=r[i-1],o=a?.role??``,s=a&&`timestamp`in a?a.timestamp:-1,c=a&&`toolCallId`in a?a.toolCallId:``;return`${e.jid}:${n}:${i}:${o}:${s}:${c}`}).join(`,`)}function GF(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let e of t)i.set(e.id,e);let a=/* @__PURE__ */ new Map;for(let e of n)a.set(e.id,e);let o=[],s=/* @__PURE__ */ new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:bt(t)?`cone`:`scoop`,name:t.name,...t.folder&&!bt(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=UF(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function KF(e,t,n={}){let r=e=>n.rootJid===void 0?e:Ct(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new o(`transfer-aborted`);let i=WF(n,e),[a,s]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new o(`transfer-aborted`);let c=r(e.listScoops());if(i===WF(c,e))return GF(c,a,s,e)}}function qF(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function JF(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function YF(e,t){if(typeof e==`string`)return e?[{type:`text`,text:e}]:[];let n=[],r=0;for(let i of e)i.type===`text`?i.text&&n.push({type:`text`,text:i.text}):i.type===`image`&&n.push(JF(t,r++));return n}function XF(e,t){let n=[],r=/* @__PURE__ */ new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=JF(t,a++);n.push(e),o.data&&o.mimeType&&r.set(e.attachmentId,{data:o.data,mimeType:o.mimeType})}return{blocks:n,excluded:i,images:r}}function ZF(e,t){let n=[],r=/* @__PURE__ */ new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=JF(t,i++);n.push(e),a.data&&a.mimeType&&r.set(e.attachmentId,{data:a.data,mimeType:a.mimeType})}return{blocks:n,images:r}}function QF(e,t,n){let r=qF(t,n),i=YF(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:/* @__PURE__ */ new Map}}function $F(e,t,n){let r=qF(t,n),{blocks:i,excluded:a,images:o}=XF(e.content,r);return{message:{id:r,sequence:n,role:`assistant`,timestamp:new Date(e.timestamp).toISOString(),content:i,model:{provider:e.provider,id:e.model,api:e.api},usage:e.usage,stopReason:e.stopReason,...e.errorMessage?{error:e.errorMessage}:{}},excludedReasoningBlocks:a,images:o}}function eI(e,t,n){let r=qF(t,n),{blocks:i,images:a}=ZF(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function tI(e,t,n){return e.role===`user`?QF(e,t,n):e.role===`assistant`?$F(e,t,n):e.role===`toolResult`?eI(e,t,n):{message:null,excludedReasoningBlocks:0,images:/* @__PURE__ */ new Map}}function nI(e){let t=[];for(let n of e){if(!n.parentConversationId)continue;let e={sourceConversationId:n.parentConversationId,targetConversationId:n.id};n.originToolCallId&&(e.toolCallId=n.originToolCallId),t.push(e)}return t}function rI(e){let t=0,n=/* @__PURE__ */ new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=tI(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:nI(e),excludedReasoningBlocks:t,canonicalImages:n}}const iI=(()=>{let e=/* @__PURE__ */ new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function aI(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^iI[(t^e[n])&255];return~t>>>0}const oI=new TextEncoder;function sI(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function cI(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function lI(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,sI(r,4,20),sI(r,6,2048),sI(r,8,0),sI(r,10,0),sI(r,12,0),cI(r,14,n),cI(r,18,t),cI(r,22,t),sI(r,26,e.length),sI(r,28,0),r.set(e,30),r}function uI(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,sI(i,4,20),sI(i,6,20),sI(i,8,2048),sI(i,10,0),sI(i,12,0),sI(i,14,0),cI(i,16,n),cI(i,20,t),cI(i,24,t),sI(i,28,e.length),sI(i,30,0),sI(i,32,0),sI(i,34,0),sI(i,36,0),cI(i,38,0),cI(i,42,r),i.set(e,46),i}function dI(e,t,n){let r=/* @__PURE__ */ new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,sI(r,4,0),sI(r,6,0),sI(r,8,e),sI(r,10,e),cI(r,12,t),cI(r,16,n),sI(r,20,0),r}function fI(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function pI(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${xe(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*mI(e,t,n,r){if(t?.aborted)throw r(new o(`transfer-aborted`)),new o(`transfer-aborted`);let i=()=>r(new o(`transfer-aborted`));t?.addEventListener(`abort`,i,{once:!0});let a=Qn.create(),s=0,c=0,l=[],u=!1;function*d(e){a.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{for(let n of e){if(t?.aborted)throw new o(`transfer-aborted`);let e=await n.load();if(t?.aborted)throw new o(`transfer-aborted`);if(e.byteLength>hI)throw new o(`schema-invalid`);let r=oI.encode(n.path),i=aI(e),a=lI(r,e.length,i);if(c+a.length+e.length>hI)throw new o(`schema-invalid`,`archive exceeds ZIP32 offsets`);if(l.push({nameBytes:r,size:e.length,crc:i,localOffset:c}),yield*d(a),t?.aborted)throw new o(`transfer-aborted`);yield*d(e)}if(l.length>gI)throw new o(`schema-invalid`);let r=c;for(let e of l){if(t?.aborted)throw new o(`transfer-aborted`);yield*d(uI(e.nameBytes,e.size,e.crc,e.localOffset))}if(t?.aborted)throw new o(`transfer-aborted`);yield*d(dI(l.length,c-r,r)),u=!0,n({byteLength:s,sha256:a.hex()})}catch(e){throw u=!0,r(e),e}finally{t?.removeEventListener(`abort`,i),u||(u=!0,r(new o(`transfer-aborted`)))}}const hI=4294967295,gI=65535;function _I(e,t){let n=/* @__PURE__ */ new Set;for(let{path:t}of e){if(!fI(t)||n.has(t))throw new o(`schema-invalid`);n.add(t)}if(e.length>gI)throw new o(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return a.catch(()=>void 0),{chunks:mI(e,t,r,i),completion:a}}function vI(e,t,n){for(let e of t.keys())if(!fI(e))throw new o(`schema-invalid`);if(t.size+1>gI)throw new o(`schema-invalid`);for(let e of t.values())if(e.byteLength>hI)throw new o(`schema-invalid`);let r=[{path:`transcript.json`,load:()=>new TextEncoder().encode(JSON.stringify(e,null,2))},...[...t].map(([e,t])=>({path:e,load:()=>t}))];return{filename:pI(e),..._I(r,n)}}function yI(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:(/* @__PURE__ */ new Date()).toISOString(),producer:{application:`slicc`,version:i},format:s},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function bI(e,t){let n=[],r=1;for(let i of e){if(i.role!==`user`&&i.role!==`assistant`)continue;let e=`${t}-msg-${String(r).padStart(6,`0`)}`;n.push({id:e,sequence:r++,role:i.role,timestamp:new Date(i.timestamp||0).toISOString(),content:i.content?[{type:`text`,text:i.content}]:[]})}return n}function xI(e){let t=te(e);if(!t.ok)throw new o(`schema-invalid`,t.error)}function SI(e,t,n){let r=/* @__PURE__ */ new Map;for(let i of e)if(i.present&&i.path){if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}}return r}async function CI(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);return n?{...e,byteLength:n.length,sha256:await be(n)}:e}))}function wI(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return{};let n=t[1],r={},i=n.match(/^createdAt:\s*(\d+)\s*$/m),a=n.match(/^updatedAt:\s*(\d+)\s*$/m);return i&&(r.createdAt=new Date(Number(i[1])).toISOString()),a&&(r.updatedAt=new Date(Number(a[1])).toISOString()),r}var TI=class{deps;constructor(e){this.deps=e}async export(e,t={}){let{signal:n,onProgress:r}=t,i;return i=e.kind===`active`?await this.buildActiveSnapshot(n,r):await this.buildFrozenSnapshot(e.sessionId,n,r),xI(i.document),r?.({phase:`packaging`}),vI(i.document,i.bundleFiles,n)}async snapshotCone(e,t){let n=await KF(this.deps.collection,t,{rootJid:e.jid}),r=rI(n.sources),i=await HF({document:yI(e.jid,e.name,`active`,r,this.deps.version),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});return xI(i.document),i}async snapshotFrozen(e,t){let n=await this.buildFrozenSnapshot(e,t);return xI(n.document),n}async captureFrozen(e,t){let n=await KF(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=rI(n.sources),{document:i,bundleFiles:a}=await HF({document:yI(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});if(xI(i),t?.aborted)throw new o(`transfer-aborted`);try{await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a},t)}finally{this.deps.snapshotStore.discardIfUnindexed?.(e.sessionId)?.catch(()=>void 0)}}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await KF(this.deps.collection,e),r=rI(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=yI(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),HF({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r;try{r=await this.deps.snapshotStore.read(e)}catch(e){if(!(e instanceof o)||e.code!==`session-not-found`)throw e;r=null}return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=/* @__PURE__ */ new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await OF(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new o(`redaction-unavailable`)}let a=SI(r.attachments,i,e.attachments),s=await CI(r.attachments,a);return{document:{...r,attachments:s},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await nn(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new o(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new o(`session-not-found`)}let{loadFrozenArchive:a}=await import(`./session-jsonl-eXAElh6W.js`),{title:c,messages:l}=await a(this.deps.vfs,i,r.filename),u=`legacy-cone`,d=bI(l,u),f=wI(i),p={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:(/* @__PURE__ */ new Date()).toISOString(),producer:{application:`slicc`,version:this.deps.version},format:s},session:{id:e,title:c,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...f,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:u,kind:`cone`,name:c,messages:d}],delegations:[],attachments:[]},m=/* @__PURE__ */ new Map([[u,l]]);return n?.({phase:`redacting`}),HF({document:p,chatMessagesByConversation:m,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new o(`attachment-unreadable`);return t}};const EI=`/sessions/data`,DI=`document.json`,OI=`.publishing`;function kI(e){if(e?.aborted)throw new o(`transfer-aborted`)}function AI(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new o(`session-not-found`)}function jI(e){return`${EI}/${e}`}function MI(e){return`${EI}/.tmp-${e}`}async function NI(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function PI(e,t){let n;try{n=await e.readDir(t)}catch{return}for(let r of n){let n=`${t}/${r.name}`;r.type===`directory`&&await PI(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function FI(e,t){let n=await e.readDir(t);for(let r of n){if(r.name===OI)continue;let n=`${t}/${r.name}`;r.type===`directory`?await PI(e,n):await e.rm(n)}}async function II(e,t,n,r){kI(r),await NI(e,n);let i=await e.readDir(t);for(let a of i){kI(r);let i=`${t}/${a.name}`,o=`${n}/${a.name}`;if(a.type===`directory`)await II(e,i,o,r);else{let t=await e.readFile(i,{encoding:`binary`});await e.writeFile(o,t)}}}async function LI(e,t,n,r){AI(t);let i=MI(t),a=jI(t),s=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!s.has(e))throw new o(`schema-invalid`);kI(r),await NI(e,i);let c=!1;try{let t=[...n.document.attachments];for(let[e,i]of n.attachments){kI(r);let n=await be(i),a=s.get(e);if(a!==void 0){let e=t.indexOf(a);e!==-1&&(t[e]={...a,sha256:n,byteLength:i.length})}}let o={...n.document,attachments:t},l=JSON.stringify(o,null,2);if(await e.writeFile(`${i}/${DI}`,l),n.attachments.size>0)for(let[t,r]of n.attachments){let n=`${i}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await NI(e,`${i}/${t.slice(0,a)}`),await e.writeFile(n,r)}await e.flush(),kI(r),await NI(e,a),c=!0,await e.writeFile(`${a}/${OI}`,`in-progress`),await FI(e,a),kI(r),await II(e,i,a,r),await e.flush(),kI(r),await e.rm(`${a}/${OI}`)}catch(t){if(c)try{await FI(e,a)}catch{}throw await PI(e,i),t}await PI(e,i)}async function RI(e,t){AI(t);for(let n of[jI(t),MI(t)])try{await e.rm(n,{recursive:!0})}catch(e){if(e?.code!==`ENOENT`)throw e}}async function zI(e,t){let[{serializeIndexWrite:n},{readIndexForPresence:r}]=await Promise.all([import(`./frozen-archive-writer-Cixi7_NJ.js`).then(e=>e.i),import(`./frozen-session-identity-DoWKIEpR.js`)]);return n(async()=>{let n=await r(e);return n===null||n.some(e=>e.sessionId===t)?!1:(await RI(e,t),!0)})}async function BI(e,t){AI(t);let n=jI(t),r=`${n}/${DI}`;try{throw await e.stat(`${n}/${OI}`),new o(`session-not-found`)}catch(e){if(e instanceof o||e.code!==`ENOENT`)throw e}let i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new o(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new o(`schema-invalid`)}if(!te(a).ok)throw new o(`schema-invalid`);let s=/* @__PURE__ */ new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new o(`transfer-corrupt`)}if(await be(i)!==t.sha256)throw new o(`transfer-corrupt`);s.set(t.path,i)}return{document:a,attachments:s}}function VI(e){return`error`in e}function HI(){throw new o(`redaction-unavailable`)}function UI(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&HI(),e.texts}function WI(){return{async redact(e){let t;try{t=await fetch(ze(`/api/secrets/redact-export`),{method:`POST`,headers:Be({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{HI()}t.ok||HI();let n;try{n=await t.json()}catch{HI()}return UI(n,e.length)}}}function GI(){return{async redact(e){let t;try{t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.redact-export`,texts:e},e=>{chrome.runtime.lastError,t(e??null)})})}catch{HI()}return typeof t==`object`&&t&&VI(t)&&HI(),UI(t,e.length)}}}function KI(){return{async redact(e){let t;try{t=await ot(`secrets.redact-export`,{texts:e})}catch{HI()}return t??HI(),typeof t==`object`&&t&&VI(t)&&HI(),UI(t,e.length)}}}function qI(){return{async redact(e){HI()}}}function JI(){let e=at();return e===`connect`?qI():e===`extension-direct`?GI():e===`extension-delegate`?KI():WI()}const YI=/* @__PURE__ */ new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function XI(e){return`e${e}`}function ZI(e){let t=[];for(let n of e){let e=eL(n),r=nL(n);if(e===`assistant`){let e=t.length,i=XI(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:aL(n),message:n,model:iL(n)});for(let e of oL(n)){let n=t.length;t.push({id:XI(n),seq:n,kind:`tool-call`,timestamp:r,toolCallId:e.id,name:e.name,assistantEntryId:i})}continue}if(e===`toolResult`){let e=n,i=t.length;t.push({id:XI(i),seq:i,kind:`tool-result`,timestamp:r,text:aL(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=aL(n),a=e===`user`?$I(i):null,o=t.length,s=XI(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):YI.has(a)?t.push({id:s,seq:o,kind:`child-result`,timestamp:r,text:i,message:n,channel:a}):t.push({id:s,seq:o,kind:`external-event`,timestamp:r,text:i,message:n,channel:a})}return t}function QI(e){let t=[];for(let n of e){let e=t.length,r=XI(e),i=rL(n),a=typeof n.content==`string`?n.content:``;if(n.role===`assistant`){t.push({id:r,seq:e,kind:`assistant`,timestamp:i,text:a,chat:n,model:n.model});for(let e of n.toolCalls??[]){let n=t.length;t.push({id:XI(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&uj(n.channel)?n.channel:$I(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):YI.has(o)?t.push({id:r,seq:e,kind:`child-result`,timestamp:i,text:a,chat:n,channel:o}):t.push({id:r,seq:e,kind:`external-event`,timestamp:i,text:a,chat:n,channel:o})}return t}function $I(e){for(let t of fj(e)){let e=(t.sender?pj(t.sender):null)??mj(t.body);if(e)return e}return null}function eL(e){return e.role??``}function tL(e){if(typeof e==`number`)return e;if(typeof e==`string`){let t=Date.parse(e);return Number.isNaN(t)?0:t}return e instanceof Date?e.getTime():0}function nL(e){return tL(e.timestamp)}function rL(e){return tL(e.timestamp)}function iL(e){let t=e.model;return typeof t==`string`?t:void 0}function aL(e){let t=e.content;if(typeof t==`string`)return t;if(!Array.isArray(t))return``;let n=[];for(let e of t)e?.type===`text`&&n.push(e.text);return n.join(``)}function oL(e){let t=e.content;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(e?.type!==`toolCall`)continue;let t=e;n.push({id:t.id??``,name:t.name??``})}return n}function sL(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function cL(e){return e!==null&&e.version<=2}const lL=h(`work-unit-conversation`);var uL=class extends Error{};const dL=`conversations`;async function fL(e){let t=e.now??(()=>Date.now()),n=await mL(e.store,t()),r={migrated:0,alreadyDone:0,empty:0,skipped:0};if(n.done)return r.alreadyDone=e.units.length,r;let i=new Set(n.completedKeys),a=!1;for(let o of e.units){let s={...o,parentJid:o.parentJid??null},c=xn(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await pL(e,s,c,t());n===`migrated`?r.migrated++:n===`already`?r.alreadyDone++:r.empty++}catch(i){let o=i instanceof Error?i.message:String(i);if(r.skipped++,n.skipped=[...n.skipped.filter(e=>e.key!==c),{key:c,reason:o}],lL.warn(`Skipping a unit whose conversation could not be migrated`,{key:c,folder:s.folder,error:o}),i instanceof uL){a=!0,n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${s.jid}`);continue}}i.add(c),n.completedKeys=[...i],n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${s.jid}`)}return n.done=!a,n.updatedAt=t(),await e.store.putMigrationState(n),lL.info(`Canonical conversation migration complete`,{...r}),r}async function pL(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return lL.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw new uL(`canonical record unreadable: ${i.reason}`);let a=Sn(t),o=await e.loadAgentSession(t.jid);if(o&&!Array.isArray(o.messages))throw Error(`agent-sessions record has no message list`);if(o&&o.messages.length>0){let t={...a,version:2,origin:`agent-history`,entries:ZI(o.messages),createdAt:o.createdAt??r,updatedAt:r,migratedFrom:`agent-sessions`};return await e.store.save(t),`migrated`}let s=await e.loadChatSession(a.legacyKeys.chatSessionId);if(s&&!Array.isArray(s.messages))throw Error(`browser-coding-agent record has no message list`);if(s&&s.messages.length>0){let t={...a,version:2,origin:`ui-projection`,entries:QI(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function mL(e,t){let n=await e.getMigrationState(dL);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:dL,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var hL=/* @__PURE__ */ e({applyAttachmentOverlays:()=>yL,interleaveMarkers:()=>bL,toAgentMessages:()=>_L,toChatMessages:()=>vL});const gL=/* @__PURE__ */ new Set([`summarized`,`fallback`]);function _L(e){if(!cL(e)||e===null||e.origin!==`agent-history`)return[];let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.message&&t.push(n.message);return t}async function vL(e,t={}){if(!cL(e)||e===null)return[];if(e.origin===`ui-projection`){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return bL(t,e.markers)}let n=e.projectionPrefix??[],r=_L(e);if(r.length===0)return bL([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>Cj),a=yL(i(r,t),e.attachments);return bL([...n,...a],e.markers)}function yL(e,t){if(!t?.length)return e;let n=[...t].sort((e,t)=>e.timestamp-t.timestamp),r=/* @__PURE__ */ new Set;return e.map(e=>{if(e.role!==`user`||e.attachments?.length)return e;let t=e.content.trim(),i=n.findIndex((e,n)=>!r.has(n)&&e.body.trim()===t);return i<0?e:(r.add(i),{...e,attachments:n[i].attachments})})}function bL(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||gL.has(e.compaction.state));if(n.length===0)return e;let r=[...n].sort((e,t)=>e.timestamp-t.timestamp),i=[],a=0;for(let t of e){let e=xL(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(SL(r[a++]));i.push(t)}for(;a<r.length;)i.push(SL(r[a++]));return i}function xL(e){let t=e.timestamp;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Date.parse(t);if(!Number.isNaN(e))return e}return-1/0}function SL(e){return e.kind===`error`?{id:e.id,role:`assistant`,content:e.text,timestamp:e.timestamp,error:!0}:{id:e.id,role:`assistant`,content:``,timestamp:e.timestamp,compaction:e.compaction}}async function CL(e){return{id:e.legacyKeys.chatSessionId,messages:await vL(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function wL(e){return{id:e.workUnitId,messages:_L(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var TL=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(wL)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(CL))}async latestPerUnit(){let e=/* @__PURE__ */ new Map;for(let t of await this.store.loadAll()){let n=e.get(t.workUnitId);(!n||t.updatedAt>n.updatedAt)&&e.set(t.workUnitId,t)}return[...e.values()]}async loadRootChatSession(e){let t=await this.store.loadLatestInWorkspace(en({parentJid:null,folder:e}).root);return t?CL(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const EL=h(`work-unit-conversation`),DL=`conversations`,OL=`migrations`;var kL=class{dbPromise=null;dbName;writeChains=/* @__PURE__ */ new Map;constructor(e={}){this.dbName=e.dbName??`slicc-work-units`}async load(e){let t=await this.read(e);return t.status===`ok`?t.record:null}async read(e){try{let t=await IL((await this.getDb()).transaction(DL,`readonly`).objectStore(DL).get(e));return t?cL(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(EL.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(EL.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return EL.warn(`Conversation record read failed`,{key:e,error:RL(t)}),{status:`error`,reason:RL(t)}}}async save(e){let t=e.version>2?e.version:sL(e),n={...e,version:t},r=(await this.getDb()).transaction(DL,`readwrite`);return r.objectStore(DL).put(n),await LL(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(DL,`readwrite`);t.objectStore(DL).delete(e),await LL(t)}catch(t){EL.warn(`Conversation record delete failed`,{key:e,error:RL(t)})}})}async rekey(e,t){if(e!==t.key)try{let n=await this.read(e);if(n.status!==`ok`)return;let r=await this.read(t.key);if(r.status===`incompatible`||r.status===`error`){EL.warn(`Conversation rekey refused: target is not writable`,{fromKey:e,toKey:t.key,status:r.status});return}let i=Date.now();await this.save({...n.record,key:t.key,workUnitId:t.workUnitId,workspaceId:t.workspaceId,folder:t.folder,legacyKeys:t.legacyKeys,updatedAt:i}),await this.delete(e)}catch(n){EL.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:RL(n)})}}async loadAll(){try{return(await IL((await this.getDb()).transaction(DL,`readonly`).objectStore(DL).getAll())).filter(e=>cL(e)&&Array.isArray(e.entries))}catch(e){return EL.warn(`Conversation record listing failed`,{error:RL(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await IL((await this.getDb()).transaction(DL,`readonly`).objectStore(DL).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)cL(e)&&Array.isArray(e.entries)&&(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return EL.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:RL(t)}),null}}async listKeys(){try{return(await IL((await this.getDb()).transaction(DL,`readonly`).objectStore(DL).getAllKeys())).map(String)}catch(e){return EL.warn(`Conversation key listing failed`,{error:RL(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=ZI(t);return this.serialize(e.key,()=>this.ingestEntries(e,i,n,r))}async ingestEntries(e,t,n,r){try{let i=await this.read(e.key);if(i.status===`incompatible`||i.status===`error`)return null;let a=i.status===`ok`?i.record:null,o=AL(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return EL.warn(`Conversation record write failed`,{key:e.key,error:RL(t)}),null}}async putMarker(e,t,n={}){return this.withRecord(e,n.createWith,e=>{let n=(e.markers??[]).filter(e=>e.id!==t.id);return n.push(t),n.sort((e,t)=>e.timestamp-t.timestamp),{...e,markers:n.slice(-64)}})}async putAttachments(e,t){if(t.length===0)return!1;let n=new Set(t.map(e=>e.id));return this.withRecord(e.key,e,e=>({...e,attachments:[...(e.attachments??[]).filter(e=>!n.has(e.id)),...t].sort((e,t)=>e.timestamp-t.timestamp).slice(-256)}))}async deleteMarker(e,t){return this.withRecord(e,void 0,e=>{let n=(e.markers??[]).filter(e=>e.id!==t);return n.length===(e.markers?.length??0)?null:{...e,markers:n}})}withRecord(e,t,n){return this.serialize(e,()=>this.mutateRecord(e,t,n))}async mutateRecord(e,t,n){try{let r=await this.read(e),i=r.status===`ok`?r.record:r.status===`absent`&&t?jL(t,Date.now()):null;if(!i)return!1;let a=n(i);return a?(await this.save({...a,updatedAt:Date.now()}),!0):!1}catch(t){return EL.warn(`Conversation marker write failed`,{key:e,error:RL(t)}),!1}}serialize(e,t){let n=(this.writeChains.get(e)??Promise.resolve()).then(t,t),r=n.then(()=>void 0,()=>void 0);return this.writeChains.set(e,r),r.then(()=>{this.writeChains.get(e)===r&&this.writeChains.delete(e)}),n}async getMigrationState(e){try{return await IL((await this.getDb()).transaction(OL,`readonly`).objectStore(OL).get(e))??null}catch(t){return EL.warn(`Migration state read failed`,{id:e,error:RL(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(OL,`readwrite`);t.objectStore(OL).put(e),await LL(t)}catch(t){EL.warn(`Migration state write failed`,{id:e.id,error:RL(t)})}}async clearAll(){let e=(await this.getDb()).transaction([DL,OL],`readwrite`);e.objectStore(DL).clear(),e.objectStore(OL).clear(),await LL(e)}getDb(){return this.dbPromise||(this.dbPromise=FL(this.dbName).then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}};function AL(e,t,n,r,i){if(!e)return t.length===0?null:{key:n.key,version:2,workUnitId:n.workUnitId,workspaceId:n.workspaceId,folder:n.folder,origin:r,entries:t,createdAt:i.createdAt,updatedAt:i.now,legacyKeys:n.legacyKeys};if(e.origin===`ui-projection`&&r===`agent-history`)return t.length===0?null:{...e,version:2,origin:r,entries:t,projectionPrefix:[...e.projectionPrefix??[],...ML(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&NL(a,t))return null;let o=t.length>a.length&&NL(a,t);return{...e,version:2,origin:r,entries:t,updatedAt:i.now,rewrites:o?e.rewrites:(e.rewrites??0)+1,legacyKeys:n.legacyKeys}}function jL(e,t){return{key:e.key,version:2,workUnitId:e.workUnitId,workspaceId:e.workspaceId,folder:e.folder,origin:`agent-history`,entries:[],createdAt:t,updatedAt:t,legacyKeys:e.legacyKeys}}function ML(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function NL(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!PL(e[n],t[n]))return!1;return!0}function PL(e,t){return e.kind!==t.kind||e.seq!==t.seq?!1:e.kind===`tool-call`&&t.kind===`tool-call`?e.toolCallId===t.toolCallId&&e.name===t.name:(`text`in e?e.text:``)===(`text`in t?t.text:``)}function FL(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(DL)||e.createObjectStore(DL,{keyPath:`key`}),e.objectStoreNames.contains(OL)||e.createObjectStore(OL,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function IL(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function LL(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function RL(e){return e instanceof Error?e.message:String(e)}var zL=/* @__PURE__ */ e({CONE_MEMORY_PATH:()=>HL,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>VL,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>UL,applyConeMemoryBudget:()=>JL,readSessionCount:()=>KL,restructureConeMemory:()=>qL,splitConeMemory:()=>GL});const BL=h(`cone-memory-budget`),VL=1.25,HL=Xt.memoryPath,UL=`/sessions/index.json`,WL=/^## Auto-extracted/m;function GL(e){let t=WL.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function KL(e){try{let t=await e.readFile(UL,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?tn(r).length:0}catch{return 0}}async function qL(e){let{header:t,autoExtracted:n}=GL(e.currentContent);if(!n.trim())return e.currentContent;let r=nt(`You are a memory consolidation assistant. You are given a markdown file's "auto-extracted" section — a list of memory bullets accumulated across sessions of an AI coding assistant. Your job is to rewrite that section as a tighter, deduplicated set of durable memories that fits well within ${e.budget} characters.
|
|
1084
1084
|
|
|
1085
1085
|
<auto-extracted>
|
|
1086
1086
|
${n}
|
|
@@ -1258,15 +1258,15 @@ Created: ${(/* @__PURE__ */ new Date()).toISOString()}
|
|
|
1258
1258
|
`),f=Buffer.byteLength(d,`utf-8`);return{content:d,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:f,lastLinePartial:u,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function fH(e,t){let n=Buffer.from(e,`utf-8`);if(n.length<=t)return e;let r=n.length-t;for(;r<n.length&&(n[r]&192)==128;)r++;return n.slice(r).toString(`utf-8`)}const pH=h(`tool:bash`),mH=40960,hH=1048576,gH=`\0slicc-img:`;function _H(e){let t=ct(e).filter(e=>e.kind===`image`);if(t.length===0)return{text:e,markers:/* @__PURE__ */ new Map};let n=/* @__PURE__ */ new Set,r=hH;for(let e=t.length-1;e>=0;e--){let i=t[e].marker.length;if(i>r&&n.size>0)break;r-=i,n.add(e)}let i=/* @__PURE__ */ new Map,a=``,o=0;return t.forEach((t,r)=>{if(a+=e.slice(o,t.index),n.has(r)){let e=`${gH}${r}`;i.set(e,t.marker),a+=e}else a+=`[image dropped: a newer image in this command used up the ${hH/1024}KB image budget. View it on its own to see it.]`;o=t.index+t.marker.length}),a+=e.slice(o),{text:a,markers:i}}function vH(e){let t=ct(e).filter(e=>e.kind===`image`);if(t.length===0)return e;let n=``,r=0;for(let i of t)n+=`${e.slice(r,i.index)}[image]`,r=i.index+i.marker.length;return n+e.slice(r)}function yH(e){return e.replaceAll(RegExp(`${gH}\\d+`,`g`),`[image]`)}function bH(e,t){if(t.size===0)return e;let n=e;for(let[e,r]of t)n.includes(e)&&(n=n.replace(e,()=>r));return n}async function xH(e,t,n,r){let{text:i,markers:a}=_H(e),o=dH(i,{maxBytes:mH});if(!o.truncated)return bH(i,a);let s=`showing the last ${lH(o.outputBytes)} of ${lH(o.totalBytes)} (${o.totalLines} lines)`,c=`${n}/bash-output-${r()}.txt`;try{return await t.writeFile(c,yH(i)),bH(`${o.content}\n\n[Output truncated: ${s}. Full output written to ${c} — read specific ranges with \`sed -n 'START,ENDp' ${c}\`, \`tail -n +N ${c}\`, or \`grep\`.]`,a)}catch(e){return pH.warn(`Failed to persist full bash output`,{error:e instanceof Error?e.message:String(e)}),bH(`${o.content}\n\n[Output truncated: ${s}. Re-run piping through \`head\`/\`tail\`/\`grep\`/\`sed -n\` to narrow the output.]`,a)}}const SH=/* @__PURE__ */ new Set([`grep`,`egrep`,`fgrep`,`rg`]);function CH(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:case`SingleQuoted`:case`Escaped`:t+=n.value;break;case`DoubleQuoted`:for(let e of n.parts){if(e.type!==`Literal`&&e.type!==`Escaped`)return null;t+=e.value}break;default:return null}return t}function wH(e){let t=e.statements[e.statements.length-1],n=t?.pipelines[t.pipelines.length-1];if(!n||n.negated)return null;let r=n.commands[n.commands.length-1];if(r?.type!==`SimpleCommand`||!r.name)return null;let i=CH(r.name);if(i!==`command`)return i;let a=r.args[0];return a?CH(a):null}function TH(e,t,n,r){if(n!==1||r.trim())return!1;let i;try{i=wH(e.getBash().transform(t).ast)}catch{return!1}return i!==null&&SH.has(i)}function EH(e,t){let n=e.options.annotateResult?.();return n?`${t.endsWith(`
|
|
1259
1259
|
`)||t.length===0?t:`${t}\n`}${n}\n`:t}function DH(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return e}function OH(e){return`Execute a bash command. Full shell with pipes, redirects, chaining, control flow. Includes: grep, rg, sed, awk, jq, find, curl, git, node, python3, sqlite3, open (--view for vision), playwright-cli (browser automation). Run \`commands\` for full list. Output is capped at ${mH/1024}KB (the tail is kept); when truncated the full output is written to a temp file named in the result so you can page it. Inline images (\`open --view\`) do not count against that cap — up to ${hH/1024}KB of images per command reaches you as pictures, not base64. A command still running after background_after seconds (default ${e}) is detached: you get a job id at once and a Background Command lick delivers its exit code and output later, so a stuck command never wedges the turn. A pipeline reports the last stage's exit (bash default); when any stage is non-zero the result includes \`pipeline: 1 0\` with each stage's code.`}function kH(e){return{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`},timeout:{type:`number`,description:`Hard ceiling in seconds: the command is killed and this call returns an error — no job, no lick. Omit for no ceiling (the default), which detaches a slow command instead of killing it.`},background_after:{type:`number`,description:`Seconds to wait before detaching the command. Defaults to ${e}. Use 0 to detach immediately (dev servers, watchers), or a large value when you must have the output in this turn. A smaller timeout wins: the command is killed, not detached.`}},required:[`command`]}}function AH(e){return{content:`Command timed out after ${e}s and was killed; no output was captured. Re-run it with a larger timeout, a larger background_after so it detaches instead of dying, or narrow the command so it finishes sooner.`,isError:!0}}function jH(e,t,n){let r=new AbortController,i=e.options.jobHost?.spawn(t)??null,a=()=>r.abort();n?.aborted?r.abort():n?.addEventListener(`abort`,a,{once:!0}),i&&(i.signal.aborted?r.abort():i.signal.addEventListener(`abort`,()=>r.abort(),{once:!0}));let o=[],s,c,l=Promise.resolve(),u=()=>{if(s===void 0||c===void 0)return;let t=s,n=c,r=o.join(``);l=l.then(async()=>{let i=await LH(e,n,r);await e.fs.writeFile(t,i)}).catch(e=>pH.warn(`Failed to tee background bash output`,{jobId:n,outputPath:t,error:e instanceof Error?e.message:String(e)}))};return{job:i,controller:r,settled:e.shell.executeCommand(t,r.signal,i?.pid,void 0,{capturePipeStatus:!0,onOutput:e=>{o.push(e),u()}}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e instanceof Error?e.message:String(e)})),releaseTurnSignal:()=>n?.removeEventListener(`abort`,a),getTeedOutput:()=>o.join(``),startPersisting:(t,n)=>{s=t,c=n,l=l.then(()=>e.swept).then(()=>void 0),u()},flushPersist:()=>l,killedByTimeout:!1}}function MH(e,t){t===`timeout`&&(e.killedByTimeout=!0),e.job?.kill(),e.controller.abort(),e.job?.exit(null)}function NH(e,t){e.job?.exit(e.job.signal.aborted?null:t)}function PH(e,t,n,r,i){let a=i===void 0?``:` Its ${i}s timeout still applies.`;return{content:`Still running after ${n}s — detached as background job ${e}. This turn is NOT blocked on it: continue with other work, and do not re-run the command. A "Background Command" lick will arrive with the exit code and a preview once it finishes, and its full output is being written to ${r} as it runs.${t===void 0?``:` Pid ${t}: \`ps\` lists it, \`kill ${t}\` stops it.`}${a}`}}function FH(e,t,n,r={}){let i=0,a=0,o=import(`./bash-job-journal-DEe5YuRn.js`),s=o.then(({createBashJobJournal:e})=>e(t,n,void 0,(e,t)=>pH.warn(e,{tempDir:n,error:t instanceof Error?t.message:String(t)}))),c={shell:e,fs:t,tempDir:n,options:r,defaultBackgroundAfter:DH(r.defaultBackgroundAfterSeconds)??600,nextOutputSeq:()=>i+=1,nextJobId:()=>`bg-${a+=1}`,journal:s,swept:Promise.resolve()};return c.swept=Promise.all([o,s]).then(([{KERNEL_RESTART_EXIT_CODE:e},t])=>t.sweep((t,n)=>IH(c,t,n,e))).catch(e=>pH.warn(`Could not sweep orphaned bash jobs`,{tempDir:n,error:e})),{name:`bash`,description:OH(c.defaultBackgroundAfter),inputSchema:kH(c.defaultBackgroundAfter),execute:(e,t)=>UH(c,e,t)}}function IH(e,t,n,r){let i={type:`bash`,bashJobId:t.jobId,bashCommand:t.command,bashExitCode:r,...t.pid===void 0?{}:{bashJobPid:t.pid},resultPath:t.outputPath,preview:n,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{jobId:t.jobId,pid:t.pid??null,command:t.command,exitCode:r,resultPath:t.outputPath,killedByKernelRestart:!0}};pH.warn(`Background bash job was killed by a kernel restart`,{jobId:t.jobId,command:t.command,startedAt:t.startedAt});let a=n=>{if(e.options.fireLick?.(i)===!1){if(n<=1){pH.warn(`No lick sink for a kernel-restart job report; output file still has it`,{jobId:t.jobId,outputPath:t.outputPath});return}setTimeout(()=>a(n-1),2e3)}};a(30)}async function LH(e,t,n){let r=e.options.scrubOutput;if(!r||!n)return n;try{return await r(n)}catch(e){return pH.warn(`Background bash output scrub failed; withholding output`,{jobId:t,error:e instanceof Error?e.message:String(e)}),`[output withheld: secret scrub unavailable]`}}function RH(e){return e.ok?e.result.exitCode===124&&/execution aborted/i.test(e.result.stderr):/execution aborted/i.test(e.error)}function zH(e,t){return e===void 0?`--- killed (exit ${t}) ---\n`:`--- killed after ${e}s (exit ${t}) ---\n`}async function BH(e,t,n,r,i,a,o,s){await o.flushPersist();let c=o.killedByTimeout||RH(a),l,u;if(c){let e=o.getTeedOutput();u=124,l=`${e.endsWith(`
|
|
1260
1260
|
`)||e.length===0?e:`${e}\n`}${zH(s,u)}`}else if(a.ok)l=ur([a.result.stdout,a.result.stderr].filter(Boolean).join(``)||`(exit code: ${a.result.exitCode})`,a.result.pipeStatus),u=a.result.exitCode;else{let e=o.getTeedOutput();u=1,l=e?`${e.endsWith(`
|
|
1261
|
-
`)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await LH(e,t,EH(e,l)),f;try{await e.fs.writeFile(i,d),f=i}catch(e){pH.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){pH.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=dH(vH(d),{maxBytes:2048});e.options.fireLick({type:`bash`,bashJobId:t,bashCommand:r,bashExitCode:u,...n===void 0?{}:{bashJobPid:n},resultPath:f,preview:p.content,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:u,resultPath:f??null}})}function VH(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=Promise.all([e.journal,e.swept]).then(([e])=>e.record({jobId:o,pid:s,command:n,outputPath:c,startedAt:(/* @__PURE__ */ new Date()).toISOString()})),u=()=>l.then(()=>e.journal).then(e=>e.clear(o)).catch(e=>pH.warn(`Could not journal a detached bash job`,{jobId:o,error:e})),d=i===void 0?void 0:i-a,f=d===void 0?void 0:setTimeout(()=>MH(t,`timeout`),d*1e3);return t.settled.then(r=>(f!==void 0&&clearTimeout(f),NH(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),BH(e,o,s,n,c,r,t,i))).catch(e=>pH.error(`Background bash delivery failed`,{jobId:o,error:e})).then(u),pH.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:d}),PH(o,s,r,c,i)}async function HH(e,t,n){pH.debug(`Result`,{exitCode:n.exitCode,stdoutLength:n.stdout.length,stderrLength:n.stderr.length});let r=``;return n.stdout&&(r+=n.stdout),n.stderr&&(r+=n.stderr),r||=`(exit code: ${n.exitCode})`,r=EH(e,ur(r,n.pipeStatus)),{content:await xH(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!TH(e.shell,t,n.exitCode,n.stderr)}}async function UH(e,t,n){let r=t.command,i=DH(t.timeout),a=DH(t.background_after)??e.defaultBackgroundAfter;pH.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=jH(e,r,n),s=i!==void 0&&i<=a,c=s?i:a,l,u=new Promise(e=>{l=setTimeout(()=>e(`elapsed`),c*1e3)});try{let t=await Promise.race([o.settled,u]);return t===`elapsed`&&s?(MH(o,`timeout`),pH.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),AH(c)):t===`elapsed`?VH(e,o,r,c,i,a):(NH(o,t.ok?t.result.exitCode:1),t.ok?await HH(e,r,t.result):(pH.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const WH={type:`object`,required:[`path`,`edits`],properties:{path:{type:`string`},edits:{type:`array`,items:{type:`object`,required:[`oldText`,`newText`],properties:{oldText:{type:`string`},newText:{type:`string`}}}}}};function GH(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function KH(e){if(!e||typeof e!=`object`)return e;let t=e;if(typeof t.edits==`string`)try{let e=JSON.parse(t.edits);Array.isArray(e)?t.edits=e:GH(e)&&(t.edits=[e])}catch{}else GH(t.edits)&&(t.edits=[t.edits]);if(typeof t.oldText!=`string`||typeof t.newText!=`string`)return t;let n=Array.isArray(t.edits)?[...t.edits]:[];n.push({oldText:t.oldText,newText:t.newText});let{oldText:r,newText:i,...a}=t;return{...a,edits:n}}function qH(e,t=`/workspace`){return{name:`edit`,description:`Edit one file using exact replacements. Each oldText must be unique in the original file; edits must not overlap. Combine changes to the same block in one edit.`,inputSchema:WH,prepareArguments:KH,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-
|
|
1261
|
+
`)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await LH(e,t,EH(e,l)),f;try{await e.fs.writeFile(i,d),f=i}catch(e){pH.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){pH.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=dH(vH(d),{maxBytes:2048});e.options.fireLick({type:`bash`,bashJobId:t,bashCommand:r,bashExitCode:u,...n===void 0?{}:{bashJobPid:n},resultPath:f,preview:p.content,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:u,resultPath:f??null}})}function VH(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=Promise.all([e.journal,e.swept]).then(([e])=>e.record({jobId:o,pid:s,command:n,outputPath:c,startedAt:(/* @__PURE__ */ new Date()).toISOString()})),u=()=>l.then(()=>e.journal).then(e=>e.clear(o)).catch(e=>pH.warn(`Could not journal a detached bash job`,{jobId:o,error:e})),d=i===void 0?void 0:i-a,f=d===void 0?void 0:setTimeout(()=>MH(t,`timeout`),d*1e3);return t.settled.then(r=>(f!==void 0&&clearTimeout(f),NH(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),BH(e,o,s,n,c,r,t,i))).catch(e=>pH.error(`Background bash delivery failed`,{jobId:o,error:e})).then(u),pH.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:d}),PH(o,s,r,c,i)}async function HH(e,t,n){pH.debug(`Result`,{exitCode:n.exitCode,stdoutLength:n.stdout.length,stderrLength:n.stderr.length});let r=``;return n.stdout&&(r+=n.stdout),n.stderr&&(r+=n.stderr),r||=`(exit code: ${n.exitCode})`,r=EH(e,ur(r,n.pipeStatus)),{content:await xH(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!TH(e.shell,t,n.exitCode,n.stderr)}}async function UH(e,t,n){let r=t.command,i=DH(t.timeout),a=DH(t.background_after)??e.defaultBackgroundAfter;pH.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=jH(e,r,n),s=i!==void 0&&i<=a,c=s?i:a,l,u=new Promise(e=>{l=setTimeout(()=>e(`elapsed`),c*1e3)});try{let t=await Promise.race([o.settled,u]);return t===`elapsed`&&s?(MH(o,`timeout`),pH.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),AH(c)):t===`elapsed`?VH(e,o,r,c,i,a):(NH(o,t.ok?t.result.exitCode:1),t.ok?await HH(e,r,t.result):(pH.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const WH={type:`object`,required:[`path`,`edits`],properties:{path:{type:`string`},edits:{type:`array`,items:{type:`object`,required:[`oldText`,`newText`],properties:{oldText:{type:`string`},newText:{type:`string`}}}}}};function GH(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function KH(e){if(!e||typeof e!=`object`)return e;let t=e;if(typeof t.edits==`string`)try{let e=JSON.parse(t.edits);Array.isArray(e)?t.edits=e:GH(e)&&(t.edits=[e])}catch{}else GH(t.edits)&&(t.edits=[t.edits]);if(typeof t.oldText!=`string`||typeof t.newText!=`string`)return t;let n=Array.isArray(t.edits)?[...t.edits]:[];n.push({oldText:t.oldText,newText:t.newText});let{oldText:r,newText:i,...a}=t;return{...a,edits:n}}function qH(e,t=`/workspace`){return{name:`edit`,description:`Edit one file using exact replacements. Each oldText must be unique in the original file; edits must not overlap. Combine changes to the same block in one edit.`,inputSchema:WH,prepareArguments:KH,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-iaL4Mz3u.js`);return i(e,t,n,r)}}}async function JH(e,t,n){if(Dn(pt(t)))return null;try{let r=await e.readTextFile(t);if(n.length<=262144)return r===n?null:`Write did not land: ${t} content mismatch (expected ${n.length} chars, got ${r.length})`;if(r.length!==n.length)return`Write did not land: ${t} content mismatch (expected ${n.length} chars, got ${r.length})`;let i=4096;return r.slice(0,i)!==n.slice(0,i)||r.slice(-4096)!==n.slice(-4096)?`Write did not land: ${t} content mismatch (head/tail sample)`:null}catch(e){return`Write did not land: ${t} is not readable (${e instanceof Error?e.message:String(e)})`}}const YH=h(`tool:fs`);function XH(e,t=`/workspace`){return[ZH(e),QH(e),qH(e,t)]}function ZH(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${sH/1024}KB (whichever is hit first); use offset/limit for large files and the \`offset=N\` in the footer to page through the rest.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to read.`},offset:{type:`number`,description:`Line number to start reading from (1-based). Optional.`},limit:{type:`number`,description:`Maximum number of lines to read. Optional.`}},required:[`path`]},async execute(t){let n=t.path,r=t.offset??1,i=t.limit;YH.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
|
|
1262
1262
|
`),a=t.length,o=Math.max(0,r-1),s=o+1;if(o>=t.length)return{content:`Offset ${r} is beyond end of file (${a} lines total)`,isError:!0};let c=i===void 0?t.slice(o):t.slice(o,Math.min(o+i,t.length)),l=i===void 0?void 0:c.length,u=uH(c.join(`
|
|
1263
|
-
`));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${lH(new TextEncoder().encode(t[o]??``).length)}, exceeds ${lH(sH)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${sH}]`};let d=u.content,f=``;if(u.truncated){let e=s+u.outputLines-1,t=e+1;f=u.truncatedBy===`lines`?`\n\n[Showing lines ${s}-${e} of ${a}. Use offset=${t} to continue.]`:`\n\n[Showing lines ${s}-${e} of ${a} (${lH(sH)} limit). Use offset=${t} to continue.]`}else l!==void 0&&o+l<t.length&&(f=`\n\n[${t.length-(o+l)} more lines in file. Use offset=${o+l+1} to continue.]`);return{content:d+f}}catch(e){let t=e instanceof Error?e.message:String(e);return YH.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function QH(e){return{name:`write_file`,description:`Write content to a file. Creates the file if it does not exist, or overwrites it if it does. Parent directories are created automatically.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to write.`},content:{type:`string`,description:`The content to write to the file.`}},required:[`path`,`content`]},async execute(t){let n=t.path,r=t.content;YH.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await JH(e,n,r);return t?(YH.error(`Write durability check failed`,{path:n,error:t}),{content:t,isError:!0}):{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return YH.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const $H={type:`object`,properties:{path:{type:`string`,description:`Absolute path of the memory file (a CLAUDE.md memory or a curation draft).`},content:{type:`string`,description:"Complete new file content (whole-file rewrite). Exclusive with `edits`."},edits:{type:`array`,description:"Exact replacements applied in order; each oldText must occur exactly once. Exclusive with `content`.",items:{type:`object`,required:[`oldText`,`newText`],properties:{oldText:{type:`string`},newText:{type:`string`}}}}},required:[`path`]};function eU(e,t){return{name:er,description:"Write a memory file — the only tool that may. Enforces the memory budget (over budget, a write must shrink the file) and reports the size that landed plus the remaining room or overage, so no `wc -c` turn is needed. Pass `content` for a rewrite or `edits` for exact replacements.",inputSchema:$H,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-
|
|
1263
|
+
`));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${lH(new TextEncoder().encode(t[o]??``).length)}, exceeds ${lH(sH)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${sH}]`};let d=u.content,f=``;if(u.truncated){let e=s+u.outputLines-1,t=e+1;f=u.truncatedBy===`lines`?`\n\n[Showing lines ${s}-${e} of ${a}. Use offset=${t} to continue.]`:`\n\n[Showing lines ${s}-${e} of ${a} (${lH(sH)} limit). Use offset=${t} to continue.]`}else l!==void 0&&o+l<t.length&&(f=`\n\n[${t.length-(o+l)} more lines in file. Use offset=${o+l+1} to continue.]`);return{content:d+f}}catch(e){let t=e instanceof Error?e.message:String(e);return YH.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function QH(e){return{name:`write_file`,description:`Write content to a file. Creates the file if it does not exist, or overwrites it if it does. Parent directories are created automatically.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to write.`},content:{type:`string`,description:`The content to write to the file.`}},required:[`path`,`content`]},async execute(t){let n=t.path,r=t.content;YH.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await JH(e,n,r);return t?(YH.error(`Write durability check failed`,{path:n,error:t}),{content:t,isError:!0}):{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return YH.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const $H={type:`object`,properties:{path:{type:`string`,description:`Absolute path of the memory file (a CLAUDE.md memory or a curation draft).`},content:{type:`string`,description:"Complete new file content (whole-file rewrite). Exclusive with `edits`."},edits:{type:`array`,description:"Exact replacements applied in order; each oldText must occur exactly once. Exclusive with `content`.",items:{type:`object`,required:[`oldText`,`newText`],properties:{oldText:{type:`string`},newText:{type:`string`}}}}},required:[`path`]};function eU(e,t){return{name:er,description:"Write a memory file — the only tool that may. Enforces the memory budget (over budget, a write must shrink the file) and reports the size that landed plus the remaining room or overage, so no `wc -c` turn is needed. Pass `content` for a rewrite or `edits` for exact replacements.",inputSchema:$H,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-C_0rryC9.js`);return r(e,t,n)}}}function tU(){return null}const nU=h(`tool:request-secret`);async function rU(e,t){let n=tU();if(n)return n(e);let r=t.callPanelRpc??await iU();return r?r(e):{stored:!1,reason:`unavailable`}}async function iU(){let{getPanelRpcClient:e}=await import(`./panel-rpc-BJU93e51.js`).then(e=>e.r),t=e();return t?e=>t.call(`secret-request`,e,{timeoutMs:3e5}):null}function aU(e){try{return e.getProvider?.()||void 0}catch(e){nU.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function oU(e){if(!Array.isArray(e))return;let t=e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:void 0}function sU(e,t){let n=[`The user stored the secret "${e.name}".`,`Scope: ${e.domains.join(`, `)} — it is only unmasked for requests to these hosts.`,e.persisted?`Lifetime: saved (survives this session).`:`Lifetime: this session only (held in memory).`];return e.maskedValue?(n.push(`Masked value: ${e.maskedValue}`,`Use the masked value wherever the credential goes (headers, request bodies). SLICC substitutes the real value at the network boundary. You will never see the real value.`),t&&n.push(`It is also available as $${e.name} in bash.`)):n.push(`The store did not report a masked value; run \`secret get ${e.name}\` to read it.`),n.join(`
|
|
1264
1264
|
`)}function cU(e){switch(e.reason){case`cancelled`:return`The user dismissed the secret prompt — nothing was stored. Do not retry; ask what to do instead.`;case`unavailable`:return"This float cannot prompt for a secret (no secret-entry surface). Ask the user to add it from the leader UI or with `secret set`.";default:return`The secret could not be stored${e.detail?`: ${e.detail}`:``}.`}}function lU(e={}){return{name:`request_secret`,description:`Ask the user for a credential (API key, token, password) through a secure prompt. You never receive the real value: the result carries only the secret name, a masked stand-in to use in requests, and the domains it may be sent to. Use this instead of asking for a credential in chat, which would put it in the transcript.`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Suggested secret name, e.g. GITHUB_TOKEN. Use an uppercase POSIX identifier so it is also available as $NAME in bash. The user can change it.`},reason:{type:`string`,description:`One plain sentence saying what the credential is for. Shown verbatim to the user.`},domains:{type:`array`,items:{type:`string`},description:`Suggested hosts the value may be sent to, e.g. ["api.github.com", "*.github.com"]. Be as narrow as the task allows; the user reviews and can edit this.`},persist:{type:`boolean`,description:`Suggest keeping the secret beyond this session. Defaults to false (session-only).`}},required:[`name`,`reason`]},async execute(t){let n=typeof t.name==`string`?t.name.trim():``,r=typeof t.reason==`string`?t.reason.trim():``;if(!n||!r)return{content:"request_secret needs both `name` and `reason`.",isError:!0};let i={name:n,reason:r,domains:oU(t.domains),persist:t.persist===!0,requester:e.requester,provider:aU(e)},a;try{a=await rU(i,e)}catch(e){let t=e instanceof Error?e.message:String(e);return nU.error(`secret request failed`,{name:n,error:t}),{content:`The secret prompt failed: ${t}`,isError:!0}}if(!a.stored)return{content:cU(a),isError:!0};let o=uU(a.name,a.maskedValue,e);return nU.info(`secret stored via request_secret`,{name:a.name,persisted:a.persisted}),{content:sU(a,o)}}}}function uU(e,t,n){if(!n.setEnv||!t||!lr(e))return!1;try{return n.setEnv(e,t),!0}catch(t){return nU.warn(`could not inject the masked value into the shell env`,{name:e,error:t instanceof Error?t.message:String(t)}),!1}}const dU=/* @__PURE__ */ new Set([`true`,`false`,`:`]);function fU(e){return!e||e.length===0||e.some(e=>e.trim()===`*`)?!1:e.every(e=>dU.has(e.trim()))}function pU(e){let t=e?.toolSurface??`full`;return t===`full`?`full`:t===`output`||fU(e?.allowedCommands)?e?.structuredOutputSchema?`output`:`none`:`full`}const mU=h(`scoop-management-tools`),hU=`cross_cone`;function gU(e){return Ct(e.getScoops(),e.scoop.jid)}function _U(e){let t=/* @__PURE__ */ new Set;for(let n of gU(e))n.jid!==e.scoop.jid&&n.parentJid!==null&&t.add(n.jid);return t}function vU(e){let t=Dt(e.getScoops());return t!==void 0&&t.jid===e.scoop.jid}function yU(e){let t=e.getScoops(),n=_U(e),r=vU(e),i=[];for(let e of t){if(e.parentJid===null)continue;if(n.has(e.jid)){i.push({scoop:e,relation:`own`});continue}if(!r)continue;let a=Ut(t,e);a.kind!==`cycle`&&i.push({scoop:e,relation:a.kind===`root`?`foreign`:`inherited`})}return i}function bU(e){return t=>t.folder===e||t.name===e}function xU(e,t){let n=yU(t);return n.find(t=>t.scoop.folder===e)??n.find(t=>t.relation===`own`&&t.scoop.name===e)??n.find(t=>t.scoop.name===e)}function SU(e,t){let n=[],r=[];for(let i of e){let e=xU(i,t);e?n.push(e):r.push(i)}return{resolved:n,unknown:r}}function CU(e,t){return Tt(e.getScoops(),t.scoop)?.folder??`unknown`}function wU(e,t){return t.relation===`inherited`?`inherited (its owning cone is gone)`:`owned by cone "${CU(e,t)}"`}function TU(e,t,n,r){let i=e.filter(e=>e.relation!==`own`);return i.length===0||t===!0?null:{content:`Refusing to ${n}: ${i.map(e=>`"${e.scoop.folder}" is ${wU(r,e)}`).join(`; `)}. Pass ${hU}: true to act on it anyway.`,isError:!0}}function EU(e){return{type:`boolean`,description:`Set true to ${e} a scoop you do not own — inherited (its cone is gone) or another cone's. Default false; omitting it on such a scoop is an error, so the choice stays deliberate.`}}const DU=[`command`,`read`,`write`,`secret`];function OU(e){return`${xe(e,{maxLen:50})}-scoop`}function kU(e){return e===void 0?{ok:!0}:an(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${on.join(`, `)}.`,isError:!0}}function AU(e){return e===void 0?{ok:!0}:typeof e!=`number`||!Number.isFinite(e)||e<0?{ok:!1,content:`Invalid background_after "${String(e)}". Must be a number of seconds >= 0.`}:{ok:!0,seconds:e}}function jU(e,t){if(e===void 0||!t)return{ok:!0,modelId:e};let n=t(e);return n.ok?{ok:!0,modelId:n.selection.modelId,providerId:n.selection.providerId}:{ok:!1,content:`Unknown model "${e}": ${n.error}. Run the "models" shell command to list available model IDs.`,isError:!0}}function MU(e,t){let n=yU(t).map(e=>e.scoop.folder).join(`, `)||`(none)`;return{content:`Not found in the scoops you can manage (${t.scoop.folder}): ${e.join(`, `)}. Available: ${n}`,isError:!0}}function NU(e,t,n=``){let r=t?.(e.jid),i=r?.status??`unknown`,a=r?.lastActivity?new Date(r.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,o=a?` — ${i} (since ${a})`:` — ${i}`;return e.parentJid===null?`- ${e.assistantLabel} (${e.folder}) [CONE]${o}`:`- ${e.name} (${e.folder})${n}${o}`}async function PU(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),mU.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function FU(e){let{kind:t,detail:n,suggested_pattern:r,reason:i}=e;if(!DU.includes(t))return{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${DU.join(`, `)}.`,isError:!0}};if(typeof n!=`string`||n.trim().length===0)return{ok:!1,result:{content:`detail must be a non-empty string.`,isError:!0}};let a=typeof i==`string`?dr(i):``;return{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{},...a?{reason:a}:{}}}}function IU(e){let t=[`Cone decision: ${e.decision}.`];return e.decision===`always`&&e.pattern&&t.push(`Persisted pattern: ${e.pattern}`),e.note&&t.push(`Approver's reason: ${e.note}`),e.decision===`deny`&&t.push(e.note?`Not approved. Address the reason above before asking again; do not retry as-is and do not route around it.`:`Not approved, and no reason was given. Do not retry as-is; ask the cone what would make it acceptable, or move on.`),t.join(`
|
|
1265
1265
|
`)}async function LU(e,t){let n=FU(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return mU.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:IU(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function RU(e,t){let{scoop_name:n,prompt:r,cross_cone:i}=e;if(bU(n)(t.scoop))return{content:`Cannot feed yourself.`,isError:!0};let a=xU(n,t);if(!a)return MU([n],t);let o=TU([a],i,`feed "${n}"`,t);if(o)return o;try{await t.onFeedScoop(a.scoop.jid,r),mU.info(`Fed scoop`,{target:a.scoop.folder,relation:a.relation,promptLength:r.length});let e=a.relation===`own`?`You will be notified when it completes.`:`Its completion notice goes to its owner; use scoop_wait (${hU}: true) for the result.`;return{content:`Task sent to ${a.scoop.folder}. ${e}`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function zU(e,t){return t.relation===`own`?``:t.relation===`inherited`?` [INHERITED]`:` [FOREIGN: ${CU(e,t)}]`}async function BU(e){let t=new Map(yU(e).map(e=>[e.scoop.jid,e])),n=e.getScoops().filter(n=>n.jid===e.scoop.jid||t.has(n.jid));return n.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${n.map(n=>{let r=t.get(n.jid);return NU(n,e.getScoopTabState,r?zU(e,r):``)}).join(`
|
|
1266
1266
|
`)}`}}function VU({name:e,folder:t,model:n,modelProviderId:r,visiblePaths:i,writablePaths:a,workspaceMode:o,allowedCommands:s,thinkingLevel:c,backgroundAfterSeconds:l,parentJid:u,defaultVisibleRoots:d,canCreateChildren:f}){return{name:e,folder:t,trigger:`@${t}`,requiresTrigger:!0,assistantLabel:t,addedAt:(/* @__PURE__ */ new Date()).toISOString(),config:{...n?{modelId:n}:{},...n&&r?{modelProviderId:r}:{},...HU(o,t,d,i,a),workspaceMode:o,...s?{allowedCommands:s}:{},...c?{thinkingLevel:c}:{},...l===void 0?{}:{backgroundAfterSeconds:l},...f===!0?{canCreateChildren:!0}:{}},configSchemaVersion:3,parentJid:u}}function HU(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function UU(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return mU.error(`Auto-feed failed`,{name:n,error:t}),{content:`Scoop "${n}" created as "${r}" but the initial task could not be sent: ${t}. Use feed_scoop to retry.`,isError:!0}}return{content:`Scoop "${n}" created as "${r}" and task sent. It is now working on it.`}}async function WU(e,t){let n=t.getTurnSignal?.();if(n?.aborted)return{content:`The parent turn was stopped.`,isError:!0};let{name:r,model:i,prompt:a,visiblePaths:o,writablePaths:s,workspaceMode:c,allowedCommands:l,thinking:u,background_after:d,canCreateChildren:f}=e,p=vt(c);if(!p.ok)return{content:p.error,isError:!0};let m=kU(u);if(!m.ok)return{content:m.content,isError:m.isError};let ee=AU(d);if(!ee.ok)return{content:ee.content,isError:!0};let te=jU(i,t.resolveModelSelection);if(!te.ok)return{content:te.content,isError:te.isError};let ne=OU(r),h=gU(t).find(e=>e.jid!==t.scoop.jid&&e.parentJid!==null&&(e.name===r||e.folder===ne));if(h)return{content:`A scoop named "${h.name}" (${h.folder}) already exists in your scoops. Use feed_scoop to give it another task, or drop_scoop first.`,isError:!0};let re=jt(ne,t.getScoops().map(e=>e.folder));try{let e=VU({name:r,folder:re,model:te.modelId,modelProviderId:te.providerId,visiblePaths:o,writablePaths:s,workspaceMode:p.mode,allowedCommands:l,thinkingLevel:m.level,backgroundAfterSeconds:ee.seconds,parentJid:t.scoop.jid,defaultVisibleRoots:Zt(en(t.scoop)),canCreateChildren:f===!0}),i=await t.onScoopScoop(e);if(n?.aborted)return await t.onDropScoop?.(i.jid),{content:`The parent turn was stopped before the scoop could start.`,isError:!0};if(mU.info(`Scoop created`,{name:r,folder:re}),a&&t.onFeedScoop){let e=await UU(i,a,r,re,t.onFeedScoop);return n?.aborted?(await t.onDropScoop?.(i.jid),{content:`The parent turn was stopped while starting the scoop.`,isError:!0}):e}return{content:`Scoop "${r}" created as "${re}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function GU(e,t){let{scoop_name:n,cross_cone:r}=e;if(bU(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=xU(n,t);if(!i)return MU([n],t);let a=TU([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),mU.info(`Scoop dropped`,{name:i.scoop.name,folder:i.scoop.folder,relation:i.relation}),{content:`Scoop "${i.scoop.name}" (${i.scoop.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function KU(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function qU(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return KU();let{resolved:i,unknown:a}=SU(n,t);return i.length===0?MU(a,t):TU(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),mU.info(`Scoops muted`,{names:i.map(e=>e.scoop.folder)}),{content:`Muted: ${i.map(e=>e.scoop.folder).join(`, `)}${a.length>0?` (unknown: ${a.join(`, `)})`:``}`})}function JU(e,t){if(e.length===0)return[`No stashed completions.`];let n=[``,`Stashed completions:`];for(let r of e){let e=t.get(r.jid)??r.jid;n.push(`--- ${e} ---`),r.notificationPath&&n.push(`VFS path: ${r.notificationPath}`),n.push(r.summary)}return n}async function YU(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return KU();let{resolved:i,unknown:a}=SU(n,t);if(i.length===0)return MU(a,t);let o=TU(i,r,`unmute these scoops`,t);if(o)return o;let s=i.map(e=>e.scoop.jid),c=new Map(i.map(e=>[e.scoop.jid,e.scoop.folder])),l=await t.onUnmuteScoops(s);mU.info(`Scoops unmuted`,{names:i.map(e=>e.scoop.folder),stashedCount:l.length});let u=[`Unmuted: ${i.map(e=>e.scoop.folder).join(`, `)}${a.length>0?` (unknown: ${a.join(`, `)})`:``}`];return u.push(...JU(l,c)),{content:u.join(`
|
|
1267
1267
|
`)}}function XU(e,t){return!Array.isArray(e)||e.length===0?KU():t!==void 0&&(typeof t!=`number`||!Number.isFinite(t)||t<0)?{content:`timeout_ms must be a non-negative finite number (or omitted).`,isError:!0}:null}function ZU(e,t,n,r){return`scoop_wait scheduled for: ${e}${r===void 0?` (no timeout)`:` (timeout: ${r}ms)`}.${t.length>0?` Unknown (skipped): ${t.join(`, `)}.`:``}${n?` Dropped before schedule (skipped): ${n}.`:``} Continue with other work — a 'scoop-wait' lick will be delivered when all listed scoops complete or the timeout fires.`}async function QU(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=XU(n,r);if(a)return a;let{resolved:o,unknown:s}=SU(n,t);if(o.length===0)return MU(s,t);let c=TU(o,i,`wait on these scoops`,t);if(c)return c;let l=o.map(e=>e.scoop.jid),u=t.onScheduleScoopWait(l,r),d=new Map(o.map(e=>[e.scoop.jid,e.scoop.folder])),f=u.scheduled.map(e=>d.get(e)??e).join(`, `),p=u.unknown.map(e=>d.get(e)??e).join(`, `);return mU.info(`Wait scheduled`,{scheduled:u.scheduled.map(e=>d.get(e)??e),droppedAtSchedule:p?p.split(`, `):[],unknownNames:s,timeout_ms:r}),u.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${p||u.unknown.join(`, `)}).${s.length>0?` Unknown names: ${s.join(`, `)}.`:``}`,isError:!0}:{content:ZU(f,s,p,r)}}function $U(e,t){return t?e.persisted?`Approved (always) — persisted NOPASSWD rule for ${e.kind??`unknown`} pattern "${e.persistedPattern}" in /etc/sudoers.d/scoop-${e.scoopFolder??`<unknown>`}.`:e.persistError?`Approved (always) but could NOT persist a rule (${e.persistError}). The current action is allowed; future occurrences will prompt again.`:`Approved (always) — no persistable rule applied for this request.`:`Approved (once) — the current action proceeds; future ones will prompt again.`}async function eW(e,t){let{lick_id:n,always:r,pattern:i,reason:a}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let o=typeof a==`string`?dr(a):``,s={...r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`},...o?{note:o}:{}};try{let e=await t.onSudoResolve(n,s);return e.settled?(mU.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:$U(e,!!r)}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_confirm failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function tW(e,t){let{lick_id:n,reason:r}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let i=typeof r==`string`?dr(r):``;try{let e=await t.onSudoResolve(n,{decision:`deny`,...i?{note:i}:{}});return e.settled?(mU.info(`Lick dismissed`,{id:n,hasReason:!!i}),e.message?{content:e.message}:{content:i?`Denied, and the scoop was told why: "${i}"`:"Denied with NO reason, so the scoop cannot tell refusal from misunderstanding. Pass `reason` next time."}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_dismiss failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function nW(e){let t=e.onListSudoRequests();return t.length===0?{content:`No pending sudo requests.`}:{content:`Pending sudo requests:\n${t.map(t=>{let n=e.getScoops().find(e=>e.jid===t.scoopJid)?.folder??t.scoopJid,r=t.request.suggestedPattern?` (suggested: ${t.request.suggestedPattern})`:``,i=t.request.reason?`\n reason: ${t.request.reason}`:``;return`- ${t.id} — ${n} — ${t.request.kind}: ${t.request.detail}${r}${i}`}).join(`
|
|
1268
|
-
`)}`}}async function rW(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),mU.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function iW(e){return{name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:t=>PU(t,e)}}function aW(e){return{name:`sudo_request`,description:`Ask the cone for an explicit sudo escalation before running a sensitive action. Use this when you know up-front that a command, read, or write will be gated and you want a clean approval round-trip instead of letting the gate fire mid-action. Resolves with the cone's decision (allow / always / deny). If your sudoers already grants the subject with NOPASSWD, this resolves allow immediately without prompting the cone. 'always' durably widens your sandbox by appending a NOPASSWD rule to the cone-owned /etc/sudoers.d/scoop-<folder> drop-in (you cannot write it yourself). 'deny' (or a timeout / dropped cone) resolves fail-closed. Always pass 'reason': the approver sees only what you ask for, never why.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...DU],description:`The kind of sensitive action being requested. command = a shell command; read/write = a VFS path; secret = a credential read. Only command/read/write can be persisted with "always" (no sudoers Secret directive).`},detail:{type:`string`,description:`The concrete subject of the request (e.g., the command line "git push origin main" or the VFS path "/workspace/.git/config"). The cone sees this verbatim.`},suggested_pattern:{type:`string`,description:`Optional pre-filled glob pattern for an "always" grant (e.g., "git push*" for a command or "/workspace/.git/**" for a path). The cone may override this.`},reason:{type:`string`,description:`Why you need this, in one sentence. Name the goal it unblocks, not the action restated: "the build writes its output there", not "I need to write there". Truncated at 300 characters.`}},required:[`kind`,`detail`]},execute:t=>LU(t,e)}}function oW(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop") — any name list_scoops shows you.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`},[hU]:EU(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>RU(t,e)}}function sW(e){return{name:`list_scoops`,description:`List the scoops you can manage: your own subtree, plus — leading cone only — ones tagged [INHERITED] (owning cone gone) or [FOREIGN: <cone>] (another cone owns it). These names are the only ones feed_scoop / drop_scoop / scoop_mute / scoop_unmute / scoop_wait resolve; a tagged one also needs cross_cone: true.`,inputSchema:{type:`object`,properties:{}},execute:()=>BU(e)}}function cW(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, a workspace isolation mode (private | shared-readonly), and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default for workspaceMode: shared-readonly (the default) is YOUR OWN workspace plus the shared skills tree — ["/workspace/"] for the primary cone, ["/cones/<folder>/workspace/", "/workspace/skills/"] for any other; private is []. Prefer omitting it over naming "/workspace/" explicitly, which would point the scoop at a different cone's files. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable in shared-readonly; private does not auto-include them. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes — note that /tmp stays readable and writable regardless, as shared scratch space every scoop gets (so nothing secret belongs there). Trailing slash recommended.`},workspaceMode:{type:`string`,enum:[`private`,`shared-readonly`,`snapshot`,`shared-live`],description:`Workspace isolation mode. Default "shared-readonly" is today's scoop: parent workspace + skills are visible, own sandbox + /shared/ are writable, mounts stay readable. "private" is an isolated sandbox (own /scoops/<folder>/ only — no parent workspace, no implicit /shared/, mounts are NOT auto-visible). "snapshot" and "shared-live" are not implemented and are rejected. Explicit visiblePaths / writablePaths still replace the mode's path defaults.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...on],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`},background_after:{type:`number`,description:`Seconds this scoop's bash tool waits for a command before detaching it to the background and continuing (default 600). Lower it for a scoop that must never stall on a slow command — nobody can cancel a scoop's turn, and its detached commands report back via a Background Command lick. Use 0 to detach every command immediately.`},canCreateChildren:{type:`boolean`,description:`Explicit nested-delegation grant. When true, the new scoop may create and manage its own children (grandchildren of you). Omit or false (the default) keeps it a leaf. The grant is refused when you do not hold canCreateChildren yourself.`}},required:[`name`]},execute:t=>WU(t,e)}}function lW(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop") — any name list_scoops shows you.`},[hU]:EU(`drop`)},required:[`scoop_name`]},execute:t=>GU(t,e)}}function uW(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`},[hU]:EU(`mute`)},required:[`scoop_names`]},execute:t=>qU(t,e)}}function dW(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`},[hU]:EU(`unmute`)},required:[`scoop_names`]},execute:t=>YU(t,e)}}function fW(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops list_scoops shows you (e.g., ["writer-scoop", "reviewer-scoop"]).`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."},[hU]:EU(`wait on`)},required:[`scoop_names`]},execute:t=>QU(t,e)}}function pW(e){return{name:`lick_confirm`,description:`Confirm (approve) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. With always=true, the orchestrator additionally appends a NOPASSWD <directive> <pattern> rule to the requesting scoop's /etc/sudoers.d/scoop-<folder> drop-in so the same action won't prompt again. always=false (the default) is allow-once.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification, e.g. "lick-…"). Use list_sudo_requests to see outstanding ids.`},always:{type:`boolean`,description:`If true, persist a NOPASSWD rule into the requesting scoop's per-scoop sudoers so the action won't prompt again. Defaults to false (allow-once).`},pattern:{type:`string`,description:`Optional glob pattern to persist when always=true (e.g., "git push*" or "/workspace/.git/**"). Defaults to the request's suggestedPattern, then to the exact detail. Ignored when always=false.`},reason:{type:`string`,description:`Optional note for the requester — a caveat on the approval. Only reaches a scoop that asked via sudo_request; an implicit filesystem gate has no channel to report it on success. Truncated at 300 characters.`}},required:[`lick_id`]},execute:t=>eW(t,e)}}function mW(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action — pass a reason, or the scoop just retries. For llms.txt discovery this silently appends the advertising host to /etc/llmstxtignore.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in a sudo-request or llms.txt discovery notification).`},reason:{type:`string`,description:`Why you are refusing, in one sentence; the scoop sees it verbatim. Always give one for a sudo denial — without it the scoop cannot tell refusal from misunderstanding, and retries or works around it. Truncated at 300 characters.`}},required:[`lick_id`]},execute:t=>tW(t,e)}}function hW(e){return{name:`list_sudo_requests`,description:`List all pending cone-mediated sudo requests (lick id, requesting scoop, kind, detail). Use to find a lick_id for lick_confirm / lick_dismiss.`,inputSchema:{type:`object`,properties:{}},execute:()=>nW(e)}}function gW(e){return{name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:t=>rW(t,e)}}function _W(e){let t=[],n=wt(e.scoop);return bt(e.scoop)||(t.push(iW(e)),e.onSudoRequest&&t.push(aW(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(cW(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(oW(e)),t.push(sW(e)),e.onDropScoop&&t.push(lW(e)),e.onMuteScoops&&t.push(uW(e)),e.onUnmuteScoops&&t.push(dW(e)),e.onScheduleScoopWait&&t.push(fW(e)),e.onSudoResolve&&(t.push(pW(e)),t.push(mW(e))),e.onListSudoRequests&&t.push(hW(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(gW(e))),t}var vW=/* @__PURE__ */ e({buildScoopTools:()=>CW,getOrCreateConnectionManager:()=>jW});const yW=h(`scoop-context`);function bW(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-BHK4U4e6.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function xW(e){let t=e.scoop.config?.structuredOutputSchema;if(pU(e.scoop.config)!==`output`||!t)return SW(e,[]);let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BrnZ-LJ8.js`);return SW(e,[n(t,e.onStructuredOutput)])}function SW(e,t){let n={scrubToolResult:rt()},r=bW(e);return e.processManager?it(t,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},n,r):it(t,void 0,n,r)}async function CW(e){if(pU(e.scoop.config)!==`full`)return xW(e);let{scoop:t,unit:n,callbacks:r}=e,i=_W({scoop:t,getTurnSignal:e.getTurnSignal,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:de,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:e.onSudoRequest??r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=XH(e.gatedFs,n.workspace.root),o=e.blindReads??null,s=eU(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>zL);return t(e.fs)},...o?{blindPaths:()=>o.outsidePaths()}:{}}),c=[...a,s,FH(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:rt(),...o?{annotateResult:()=>o.takeNote()}:{},fireLick:e=>{let n=globalThis.__slicc_lick_handler;return n?(n(e),!0):(yW.warn(`No lick handler for background bash completion`,{folder:t.folder}),!1)}}),...i,lU({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>se(dV(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BrnZ-LJ8.js`);c.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let l={scrubToolResult:rt()},u=bW(e),d=e.processManager?it(c,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},l,u):it(c,void 0,l,u),f=OW(await wW(e.fs,t),u,l);return[...d,...f]}async function wW(e,t){try{if(t.parentJid!==null)return[];let{listServers:n}=await import(`./store-BRq0dNJo.js`).then(e=>e.r),r=await n(e),i=Object.entries(r);if(i.length===0)return[];let a=i.filter(([,e])=>{let t=e.exposure??`codemode`;return t===`direct`||t===`codemode`||t===`codemode-deferred`||kW(e)});if(a.length===0)return[];let{toAgentTools:o}=await import(`./agent-tools-ENaFAaxk.js`),s=await jW(),c=[];for(let[t,n]of a)try{let{connection:r,transport:i}=await s.connect(t,n);i!==n.transport&&(n.transport=i,import(`./store-BRq0dNJo.js`).then(e=>e.r).then(({setServer:r})=>r(t,n,e)).catch(()=>{}));let a=n.tools??await r.listTools()??[],l=o({serverName:t,tools:a,connection:r,exposure:n.exposure,toolExposure:n.toolExposure,writeOverflow:async(t,n)=>{try{await e.mkdir(`/tmp/mcp`,{recursive:!0}),await e.writeFile(`/tmp/mcp/${t}.txt`,n)}catch{}}});c.push(...l);let u=await TW(t,a,r,n);u&&c.push(u)}catch(e){yW.warn(`failed to load MCP tools for agent`,{server:t,error:e instanceof Error?e.message:String(e)})}return c}catch(e){return yW.debug(`MCP agent tools unavailable`,{error:e instanceof Error?e.message:String(e)}),[]}}async function TW(e,t,n,r){try{let{createCodemodeAgentTool:i}=await import(`./codemode-tool-BvKukYUa.js`);return i({serverName:e,tools:t,connection:n,exposure:r.exposure,toolExposure:r.toolExposure})}catch(t){return yW.debug(`codemode tool unavailable for server`,{server:e,error:t instanceof Error?t.message:String(t)}),null}}async function EW(e,t,n,r){let i=n.currentGate();if(!i)return null;if(r?.aborted)return{content:[{type:`text`,text:`${e}: not approved (guest-caused turn).`}],details:void 0};let a;try{a=await i.approve(e,t)}catch{a=!1}return!a||r?.aborted?{content:[{type:`text`,text:`${e}: not approved (guest-caused turn).`}],details:void 0}:null}async function DW(e,t){if(t)for(let n=0;n<e.content.length;n++){let r=e.content[n];if(r.type===`text`&&`text`in r&&typeof r.text==`string`)try{let i=await t(r.text);i!==r.text&&(e.content[n]={type:`text`,text:i})}catch{}}}function OW(e,t,n){return e.map(e=>({...e,async execute(r,i,a,o){let s=await EW(e.name,i,t,a);if(s)return s;let c=await e.execute(r,i,a,o);return await DW(c,n.scrubToolResult),c}}))}function kW(e){return e.toolExposure?Object.values(e.toolExposure).some(e=>e===`direct`||e===`codemode`||e===`codemode-deferred`):!1}let AW=null;async function jW(){if(AW)return AW;let{McpConnectionManager:e}=await import(`./connection-manager-Dj5JSkDt.js`);return AW=new e({getAuthHeader:async e=>{try{let{getOAuthAccountInfo:t}=await import(`./account-store-CuQyRnib.js`).then(e=>e.t),n=t(`mcp:${e}`);return n?`Bearer ${n.token}`:null}catch{return null}}}),AW}const MW=h(`scoop-context`);async function NW(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();MW.info(`Filesystem ready`,{folder:t.folder}),await NV(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,blindReads:l,sudoBroker:u,skills:d}=await oH({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,...e.escalations?{escalations:e.escalations}:{},processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),mcpConnectionManager:e.mcpConnectionManager});e.onShellReady(o);let f=await CW({getTurnGuestGates:e.getTurnGuestGates,getTurnSignal:e.getTurnSignal,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,blindReads:l,...i.onSudoRequest&&u?{onSudoRequest:e=>u.requestApproval(e)}:{},processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:p,globalMemory:m}=await cV(r,n,()=>i.getGlobalMemory());if(!uV(t))return MW.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let ee=fV(t,n),te=_V(t,n,m,p,d),ne=await e.sessions.restore(),{streamWithSessionId:h,compactFn:re,getCompactionApiKey:ie}=await FV(ee,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>uV(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let ae=Mt(t);return{kind:`ready`,agent:AV({model:ee,tools:f,systemPrompt:te,messages:ne,thinkingLevel:yV(bV()??ae.level,ee),getApiKey:()=>uV(t)??void 0,transformContext:re,streamFn:h,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:re,getCompactionApiKey:ie,effortOverride:ae.effortOverride,toolCount:f.length}}const PW=h(`scoop-context`);var FW=class{deps;timer=null;createdAt=0;constructor(e){this.deps=e}get sessionId(){return this.deps.sessionId}async restore(){let e=this.deps.canonical;if(!e)return[];let t=null;try{t=await e.store.load(e.identity.key)}catch(e){return PW.error(`Failed to restore the conversation`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.deps.onRestoreError(`Conversation history could not be restored. Starting fresh.`),[]}let n=_L(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=Qe(n);return PW.info(`Restored conversation from the canonical work-unit record`,{folder:this.deps.folder,messageCount:r.length,droppedOrphans:n.length-r.length}),r}persistNow(e){this.flush(e)}flush(e){return this.flushChecked(e).then(()=>void 0)}flushChecked(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return Promise.resolve(!0);let n=this.deps.canonical;return n?(this.createdAt||=Date.now(),n.store.syncAgentMessages(n.identity,t,{createdAt:this.createdAt}).then(e=>e!==null,e=>(PW.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),!1))):Promise.resolve(!0)}async clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.createdAt=0;let e=this.deps.canonical;e&&await e.store.delete(e.identity.key);try{await this.deps.store?.delete(this.deps.sessionId)}catch(e){PW.warn(`Failed to clear the legacy agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})}}schedule(){this.deps.isDisposed()||this.deps.canonical&&this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.isDisposed()||this.persistNow()},1e3))}};function IW(e,t){if(!e)return null;let{text:n}=t,r=n.length>200?`${n.slice(0,197)}…`:n;return e.spawn({kind:`scoop-turn`,argv:[`prompt`,r],cwd:t.cwd,owner:t.owner,adoptAbort:t.abortController})}function LW(e,t,n){t&&e&&(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function RW(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const zW=h(`scoop-context`);var BW=class{deps;constructor(e){this.deps=e}async run(e,t){let n=null;for(let r=1;r<=3;r++){if(this.deps.isDisposed()||t.aborted)return null;let i=await this.tryAttempt(e,t);if(!i||this.deps.isDisposed()||t.aborted||(n=i,await this.handleAttemptError(i,r,t)))return null}return n}reportExhausted(e){let t=e.message;zW.error(`Agent error after retries exhausted`,{folder:this.deps.folder,error:t,maxRetries:3}),this.fail(`Scoop "${this.deps.scoopName}" failed after 3 attempts: ${t}`,t)}async tryAttempt(e,t){this.deps.beginAttempt();try{if(await e(),this.deps.isDisposed()||t.aborted)return null;let n=this.deps.overflow.pendingRecovery;if(n!==null&&(await n,this.deps.overflow.clearPendingRecovery(n),this.deps.isDisposed()||t.aborted))return null;let r=this.deps.getStreamError();return r?Error(r):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handleAttemptError(e,t,n){let r=e.message;return this.handleStaleAssetError(r)||this.handleNonRetryableError(r)?!0:!await this.handleRetryableError(r,t,n)&&(zW.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:YB(r)}),!!(t<3&&(await XB(VW(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return JB(e)?(zW.error(`Non-retryable agent error`,{folder:this.deps.folder,error:e}),this.fail(`Scoop "${this.deps.scoopName}" failed with unrecoverable error: ${e}`,e),!0):!1}handleStaleAssetError(e){return Zi(e)?(zW.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),ea(this.deps.isInteractive),this.fail(`Scoop "${this.deps.scoopName}" hit a stale build after a deploy; reloading to recover.`,e),!0):!1}async handleRetryableError(e,t,n){if(!YB(e)||t>=3)return!1;let r=VW(t);return zW.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await XB(r,n)&&!this.deps.isDisposed()}fail(e,t){zB(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function VW(e){return Fr({attempt:e-1,baseMs:1e3})}function HW(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){zW.info(`Queueing prompt via ${r.steer?`steer`:`followUp`} while processing`,{folder:r.folder,isProcessing:r.isProcessing,agentIsStreaming:i});let a={role:`user`,content:[{type:`text`,text:t},...n],timestamp:Date.now()};return r.steer?e.steer(a):e.followUp(a),!0}return!1}const UW=h(`scoop-context`);var WW=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;escalations={asked:0,allowed:0,denied:0};promptAbortController=null;forceReleaseTimer=null;turnEpoch=0;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;mcpConnectionManager;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;turnJournal;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>(this.callbacks.onToolStart?.(e,t,n),this.makeToolCallDurable(e,t,n)),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:e=>this.checkpoint(e),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s,c,l,u){this.scoop=e,this.unit=Yt(e),this.owner={kind:kt(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.capabilityBroker=l??null,this.turnJournal=u??null,this.sessions=new FW({store:r??null,canonical:c?{store:c,identity:Sn(e)}:null,sessionId:e.jid,folder:e.folder,getMessages:()=>this.agent?.state?.messages,isDisposed:()=>this.disposed,onRestoreError:e=>this.callbacks.onError(e)}),this.runBounds=new DV({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new rV({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new aV({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new EV({getAgent:()=>this.agent,isDisposed:()=>this.disposed,getTurnSignal:()=>this.promptAbortController?.signal,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),isImageRecoveryActive:()=>this.imageRecovery.isActive,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onExhausted:e=>this.reportExhaustedOverflow(e),setStatus:e=>this.setStatus(e),scoopName:e.name,folder:e.folder}),this.turnRunner=new BW({isDisposed:()=>this.disposed,overflow:this.overflow,beginAttempt:()=>{this.didStreamDeltas=!1,this.promptStreamErrorMessage=null},getStreamError:()=>this.promptStreamErrorMessage,setStatus:e=>this.setStatus(e),onError:e=>this.callbacks.onError(e),onFatalError:t.onFatalError?e=>this.callbacks.onFatalError?.(e):void 0,isInteractive:this.unit.completion.mode===`interactive`,scoopName:e.name,folder:e.folder})}ownLickTarget(){return QV(this.unit,this.scoop,St(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Kt(this.callbacks.getScoops(),this.scoop)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}resetStructuredOutput(){this.structuredOutputCaptured=!1,this.structuredOutputValue=void 0}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);if(!this.mcpConnectionManager){let{getOrCreateConnectionManager:e}=await Promise.resolve().then(()=>vW);this.mcpConnectionManager=await e()}let e=await NW({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,escalations:this.escalations,capabilityBroker:this.capabilityBroker,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getTurnGuestGates:()=>this.turnGuestGates,getTurnSignal:()=>this.promptAbortController?.signal,getLickTarget:()=>this.ownLickTarget(),getTmpDir:()=>this.ownTmpDir(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputCaptured||=(this.structuredOutputValue=e,!0)},mcpConnectionManager:this.mcpConnectionManager,spawnBashJob:e=>this.bashJobs.spawn(e),onBeforeCompaction:(e,t)=>this.maybeSnapshotBeforeCompaction(e,t)});if(e.kind===`abandoned`)return;if(e.kind===`deferred`){this.setStatus(`ready`);return}this.compactFn=e.compactFn,this.getCompactionApiKey=e.getCompactionApiKey,this.activeEffortOverride=e.effortOverride,this.agent=e.agent,this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),UW.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:e.toolCount})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);UW.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){return this.agent||(await this.init(),this.agent)?!0:(this.callbacks.onError(mV(this.scoop)),!1)}cleanupPromptState(e,t,n,r,i){if(i!==void 0&&i!==this.turnEpoch){this.currentTurnProcess!==t&&LW(this.processManager,t,{lastError:n,aborted:!0});return}this.runBounds.disarm();let a=this.runBounds.takeExceededNote();a!==null&&this.callbacks.onError(`agent run terminated: ${a}`),(n||r.aborted)&&this.sessions.persistNow(),this.disarmForceRelease(),this.isProcessing=!1,this.turnJournal?.end(this.scoop.jid),!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),LW(this.processManager,t,{lastError:n,aborted:r.aborted}),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}turnGuestGates=[];async prompt(e,t=[],n){if(!await this.ensureAgentReady())return;let r=n?.guestGates??[];if(HW(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder})){for(let e of r)this.addTurnGuestGate(e);return}this.turnGuestGates=[...r];let i=this.agent;await this.runTurn(e,0,()=>i.prompt(e,t))}async resumeTurn(e,t=[]){if(!await this.ensureAgentReady()||this.isBusy)return;this.turnGuestGates=[...t];let n=this.agent;await this.runTurn(`(resumed after reload)`,e,()=>{let e=n.state.messages,t=e[e.length-1];return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)&&(n.state.messages=e.slice(0,-1)),n.continue()})}settleInterruptedToolCalls(e){let t=this.agent;if(!t||e.length===0)return;let n=Date.now(),r=e.map(e=>({role:`toolResult`,toolCallId:e.toolCallId,toolName:e.toolName,content:[{type:`text`,text:e.text}],isError:!0,timestamp:n}));t.state.messages=[...t.state.messages,...r],this.sessions.persistNow();for(let t of e)this.callbacks.onToolEnd?.(t.toolName,t.text,!0,t.toolCallId)}reportError(e){this.callbacks.onError(e)}hasAgent(){return this.agent!==null}async runTurn(e,t,n){this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal,a=++this.turnEpoch;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let o=IW(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:r});this.currentTurnProcess=o,this.runBounds.arm(),this.turnJournal?.begin(this.scoop.jid,this.scoop.folder,t,this.turnGuestGates);let s=null;try{if(s=await this.turnRunner.run(n,i),s&&!this.disposed&&!i.aborted){this.turnRunner.reportExhausted(s);return}a===this.turnEpoch&&!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,o,s,i,a)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||(this.turnGuestGates.push(e),this.turnJournal?.setGuestGates(this.scoop.jid,this.turnGuestGates))}stop(){RW(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.armForceRelease()}disarmForceRelease(){this.forceReleaseTimer!==null&&(clearTimeout(this.forceReleaseTimer),this.forceReleaseTimer=null)}armForceRelease(){this.disarmForceRelease();let e=this.turnEpoch,t=this.currentTurnProcess;this.forceReleaseTimer=setTimeout(()=>{this.forceReleaseTimer=null,!this.disposed&&this.turnEpoch===e&&this.isProcessing&&(t&&this.processManager&&(this.processManager.signal(t.pid,`SIGKILL`),this.processManager.exit(t.pid,null)),this.bashJobs.reapAll(),this.shell?.cancelActiveCommand(),this.agent?.abort?.(),this.turnEpoch===e&&this.isProcessing&&(this.isProcessing=!1,this.status===`processing`&&this.setStatus(`ready`)))},2e3)}clearMessages(){if(this.agent){let e=We(this.agent.state.messages);this.agent.state.messages=e?[e]:[]}}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0);try{await this.reloadSkills()}catch(e){UW.warn(`clearSession: could not rebuild system prompt from memory`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})}}idleCompactionEnabled(){return On(this.scoop)?!0:this.unit.parentId===null&&Ae(`compact-on-idle`)}armIdleCompaction(){if(!this.idleCompactionEnabled()){this.idleCompaction?.disarm();return}if(this.idleCompaction){this.idleCompaction.arm();return}this.idleCompactionLoading??=this.loadIdleCompaction(),this.idleCompactionLoading.then(e=>{!this.disposed&&this.status===`ready`&&e.arm()})}async loadIdleCompaction(){let[{IdleCompaction:e},{readIdleCompactionSettings:t}]=await Promise.all([import(`./idle-compaction-CkyuBvDI.js`),import(`./idle-compaction-settings-1yyApSsQ.js`)]),n=new e({isEnabled:()=>this.idleCompactionEnabled(),getSettings:t,getAgent:()=>this.agent,isDisposed:()=>this.disposed,isBusy:()=>this.isBusy,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),estimateTokens:$e,onCompacted:()=>this.sessions.persistNow(),onDiscarded:e=>this.callbacks.onCompactionStateChange?.(`cancelled`,{trigger:`idle`,roundId:e}),folder:this.scoop.folder});return this.idleCompaction=n,n}async maybeSnapshotBeforeCompaction(e,t){if(this.unit.parentId===null||Ae(`memory-v2`))return this.snapshotBeforeCompaction(e,t)}async snapshotBeforeCompaction(e,t){if(!this.fs||this.disposed)return;let n=this.sessionGeneration,{scoopSessionsDir:r,snapshotLiveSession:i}=await import(`./live-session-snapshot-3Eb9FMGE.js`),a=this.unit.parentId===null,o=await i({vfs:this.fs,cone:{folder:this.scoop.folder,label:this.scoop.assistantLabel},messages:e,trigger:t,...a?{}:{sessionsDir:r(this.scoop.folder,this.scoop.jid)},stillValid:()=>!this.disposed&&n===this.sessionGeneration});return o&&a&&this.scheduleLiveDeltaCuration(),o?{transcriptPath:o.transcriptPath}:void 0}scheduleLiveDeltaCuration(){let e=this.fs;if(!e)return;let t={folder:this.scoop.folder,...this.scoop.jid?{jid:this.scoop.jid}:{}};import(`./live-session-curation-CLbx1I_X.js`).then(n=>n.scheduleLiveDeltaCuration({vfs:e,cone:t})).catch(e=>{UW.warn(`Live delta curation failed to start`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}async settleLiveSnapshot(e){if(this.unit.parentId===null&&this.fs)try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-3Eb9FMGE.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){UW.warn(`Live snapshot settle failed (archive stays live)`,{folder:this.scoop.folder,discard:e,error:t instanceof Error?t.message:String(t)})}}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getEscalations(){return{...this.escalations}}getContextFill(){return pV(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=SV(this.agent,this.scoop))}async reloadSkills(){this.agent&&await wV(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){if(!this.agent)return UW.info(`Thinking level stored for a deferred agent`,{requested:e}),`off`;if(bV())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=CV(this.agent,e);return UW.info(`Thinking level applied`,{requested:e,resolved:n,model:this.agent.state.model?.id,provider:this.agent.state.model?.provider,reasoning:this.agent.state.model?.reasoning===!0}),n}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}streamThinking(){if(!this.agent)return null;let e=this.agent.state.thinkingLevel;return{level:e,...e!==`off`&&this.activeEffortOverride===`max`?{effortOverride:`max`}:{}}}flushConversation(){return this.sessions.flushChecked()}dispose(){this.sessions.persistNow(),this.turnJournal?.end(this.scoop.jid),this.disposed=!0,this.disarmForceRelease(),this.idleCompaction?.cancel(),this.runBounds.disarm(),RW(this.processManager,this.currentTurnProcess,`SIGTERM`,this.promptAbortController),this.bashJobs.reapAll(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}handleAgentEvent(e,t){if(!this.disposed)return $B(e,this.eventSink,t)}async makeToolCallDurable(e,t,n){let r=Promise.all([this.sessions.flush(),n?this.turnJournal?.toolStarted(this.scoop.jid,n,e,t):null]),i,a=new Promise(e=>{i=setTimeout(()=>e(`timeout`),2e3)});try{await Promise.race([r,a])===`timeout`&&UW.warn(`Tool call not yet durable; running it anyway`,{folder:this.scoop.folder,toolName:e})}finally{clearTimeout(i)}}checkpoint(e){let t=e?.role;if(t===`user`)this.sessions.persistNow();else if(t===`toolResult`){let{toolCallId:t}=e;this.sessions.flush().then(()=>this.turnJournal?.toolEnded(this.scoop.jid,t))}else this.sessions.schedule()}setStatus(e){this.disposed||(this.status=e,e===`ready`?this.armIdleCompaction():this.idleCompaction?.cancel(),this.callbacks.onStatusChange(e))}handleAssistantMessageEnd(e){e.errorMessage||this.overflow.markAssistantSucceeded();let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}handleAgentEndEvent(e,t){this.disposed||t?.aborted||ZB(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const Q=h(`scoop-lifecycle-manager`);var GW=class{deps;units=/* @__PURE__ */ new Map;tabCreates=/* @__PURE__ */ new Map;gelatiereModelSync=Promise.resolve();constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new IB(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}displayJidFor(e){let t=this.deps.approverFor(e)?.jid;return t&&t!==e?t:void 0}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??St(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Tt(t.values(),e)??St(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Q.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof yn))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}createTab(e){let t=this.tabCreates.get(e);if(t!=null)return t;let n;return n=this.openTab(e).finally(()=>{this.tabCreates.get(e)===n&&this.tabCreates.delete(e)}),this.tabCreates.set(e,n),n}async openTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Q.debug(`Context already exists`,{jid:e});return}}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Yt(t).policy.filesystem;if(a.kind===`restricted`){let e=vt(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new yn(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:_t(a.mode)});a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new WW(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0,this.deps.getTurnJournal?.()??void 0);if(n.attachContext(l,i),await l.init(),this.units.get(e)!==n||n.context!==l)return;n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{Q.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),Q.info(`Scoop context created`,{jid:e,contextId:i})}async reinitAfterPromote(e){let t=this.units.get(e);if(t?.context){t.disposeContext();try{await this.createTab(e)}catch(n){let r=n instanceof Error?n.message:String(n);Q.warn(`Failed to re-init promoted unit; next prompt will retry`,{jid:e,error:r}),t.disposeContext(),this.markTabError(e,r)}}}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.deps.getScoops().get(e);if(o&&On(o)&&(await this.syncGelatiereModel(),!zt(o)))throw Error(`The gelatiere cannot run until the leading cone has a model`);let s=this.getContext(e);s||=(await this.createTab(e),this.getContext(e));let c=this.units.get(e);if(c?.tab?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}s=this.getContext(e)}if(!s||!c){Q.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),c.tab&&c.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await s.prompt(t,i,a)}async resumeTurn(e,t,n){let r=this.getContext(e),i=this.units.get(e);r&&i&&!r.isBusy&&(this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),i.tab&&i.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),await r.resumeTurn(t,n))}async register(e){let t=this.deps.getScoops(),n=Dt(t.values())?.jid;if(Vt(e),this.inheritModel(e),e.parentJid!==null){let n=[];for(let r of t.values())r.jid!==e.jid&&n.push(r.folder);let r=jt(e.folder,n);r!==e.folder&&(Q.warn(`Scoop folder already taken — registering under a free variant`,{jid:e.jid,requested:e.folder,folder:r}),e.folder=r,e.trigger=`@${r}`,e.assistantLabel=r)}t.set(e.jid,e);try{await this.deps.db.saveScoop(e)}catch(n){throw t.delete(e.jid),n}this.deps.messageRouter.ensureQueue(e.jid),Q.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&uB(`spawn`,e.folder)}catch(n){Q.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){Q.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{Q.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}Dt(t.values())?.jid!==n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the new leading cone after registration`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}inheritModel(e){if(On(e)){let t=Dt(this.deps.getScoops().values());At(e,t?zt(t):void 0);return}if(Ot(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?zt(t):void 0)??$z();n&&At(e,n)}async unregister(e){let t=this.deps.getScoops(),n=Dt(t.values())?.jid===e;for(let n of Wt(t.values(),e))await this.unregister(n.jid);let r=t.get(e);if(r&&r.parentJid===null&&St(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let i=this.deps.getLickManager();if(r&&i){let{webhooks:e,cronTasks:t}=await i.getLicksForScoopFromDb(r.name,r.folder),n=this.deps.buildActiveLicksError(r.folder,e,t);if(n)throw n}this.deps.costTracker.snapshot(e);let a=globalThis.__slicc_wsSubscribers;a&&a.dropForScoop(e).catch(t=>{Q.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),await Promise.all([r?this.deps.getConversationStore()?.delete(xn(r)):void 0,this.deps.getSessionStore()?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})})]),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let o=this.deps.approvalRouter.failScoop(e);if(o>0&&Q.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:o}),r&&this.deps.getSudoManager()?.forgetScoopPolicies(r.folder),Q.info(`Scoop unregistered`,{jid:e}),r)try{this.deps.callbacks.onScoopUnregistered?.(r)}catch(t){Q.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the replacement leading cone after root removal`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;if(On(n))return await this.syncGelatiereModel(),!1;let r=Dt(this.deps.getScoops().values())?.jid===e,i=n.model;At(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return At(n,i),this.getContext(e)?.updateModel(),Q.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return r&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to synchronize gelatiere after leading model change`,{jid:e,error:t instanceof Error?t.message:String(t)})}),!0}syncGelatiereModel(){let e=this.gelatiereModelSync.then(()=>this.applyGelatiereModel());return this.gelatiereModelSync=e.then(()=>void 0,()=>void 0),e}async applyGelatiereModel(){let e=this.deps.getScoops(),t=[...e.values()].find(On);if(!t)return!1;let n=Dt(e.values()),r=n?zt(n):void 0,i=zt(t),a=r?i?.provider===r.provider&&i.id===r.id:Ot(t)===void 0;if(!a){let e=t.model?{...t.model}:void 0,i=t.config?{...t.config}:void 0;At(t,r);try{await this.deps.db.saveScoop(t)}catch(n){throw t.model=e,t.config=i,n}Q.info(`Gelatiere model synchronized with leading cone`,{jid:t.jid,leadingJid:n?.jid,model:r?`${r.provider}:${r.id}`:void 0})}return r&&this.getContext(t.jid)?.updateModel(),!a}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();Q.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Lt(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Q.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}streamThinking(e){return this.getContext(e)?.streamThinking()??null}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Yt(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:n=>this.handleScoopTurnError(e,t,n),onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Et(n,t),await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(t,n)=>i.scheduleScoopWait(t,n,e):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:en(t).memoryPath}):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),approveGuestToolCall:e=>i.approveDirectedOrUser(e),onSudoResolve:o.canResolveApprovals?(n,r)=>i.resolveActionableLick(n,r,bt(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(bt(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleScoopTurnError(e,t,n){this.deps.getScoops().has(e)&&(this.deps.completionService.recordFailure(e,n),this.units.get(e)?.transition(`error`,{error:n}),uB(`error`,t.folder,n),this.deps.callbacks.onError(e,n),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,n),this.dispatch(e,`onStatusChange`,`error`))}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(Q.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),uB(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Yt(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(i)try{this.deps.callbacks.onError(i.jid,`[@${r.assistantLabel} FAILED]: ${t}`,{endTurn:!1})}catch(e){Q.error(`Failed to record fatal error for scoop owner`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}}};const $=h(`scoop-message-router`);var KW=class{deps;messageQueues=/* @__PURE__ */ new Map;lastAgentTimestamp=/* @__PURE__ */ new Map;pollInterval=null;debounceStates=/* @__PURE__ */ new Map;processing=/* @__PURE__ */ new Map;busyDeferrals=/* @__PURE__ */ new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if($.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){$.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);uB(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),$.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){$.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){$.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if($.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){$.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{$.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`||t.channel===`scoop-notify`||t.channel===`scoop-idle`||t.channel===`scoop-wait`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);$.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;n.reported||r<3e5||(n.reported=!0,$.warn(`Busy lick queue may be starved`,{jid:e,error:`Lick queue remained deferred while scoop was busy for 300s`}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r}))}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){$.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){$.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){$.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if($.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){$.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){$.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=aP(sP(iP(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){$.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=[],l=s.map(e=>{let t=new Date(e.timestamp),n=t.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}),r=BA(e.content,e.attachments);return e.attachments?.length&&c.push({id:e.id,timestamp:t.getTime(),body:r,attachments:[...e.attachments]}),`[${n}] ${e.senderName}: ${r}`}).join(`
|
|
1269
|
-
`);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>VA(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=aP(sP(iP(a),o));this.lastAgentTimestamp.set(e,f),await this.deps.db.setState(`lastAgentTs_${e}`,f);let p=s.some(e=>e.steer),m=/* @__PURE__ */ new Set,ee=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);m.has(t)||(m.add(t),ee.push(e.guestGate))}await this.deps.sendPrompt(e,l,d.senderId,d.senderName,u,{steer:p,...ee.length>0?{guestGates:ee}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);$.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),await this.deps.settleFoldedCost?.(e),t&&await t.clearSession(n).catch(t=>{$.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{$.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),$.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{$.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{$.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),$.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const qW=h(`orchestrator`),JW={decision:`deny`};var YW=class{scoops=/* @__PURE__ */ new Map;workUnits=new TN(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new _z({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;onConversationsReady=null;turnJournal=null;interruptedTurns=null;bootRestoreTail=Promise.resolve();fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new NB({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),findParent:e=>this.parentOrDefaultRoot(e),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new jB({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts(),mergeFoldedIntoFrozen:(e,t)=>this.mergeFoldedCostIntoFrozen(e,t)});completionService=new _B({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findParent:e=>this.parentOrDefaultRoot(e),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new iB({getScoops:()=>this.scoops,findApprover:e=>this.capableApproverOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>nP(e),saveMessage:e=>eP(e)});lickRegistry=new Yz({getConeShell:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new KW({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),recordSentAttachments:(e,t)=>this.recordSentAttachments(e,t),onError:(e,t,n)=>this.callbacks.onError(e,t,n),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),settleFoldedCost:e=>this.costTracker.settleFolded(e),db:{saveMessage:e=>eP(e),deleteMessage:e=>tP(e),clearMessagesForScoop:e=>$N(e),clearAllMessages:()=>QN(),getMessagesSince:(e,t,n)=>cP(e,t,n),setState:(e,t)=>mP(e,t)},isExternalLickChannel:iN});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new GW({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getConversationStore:()=>this.conversationStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,getCapabilityBroker:()=>this.capabilityBroker,getTurnJournal:()=>this.turnJournal,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>YN(e),deleteScoop:e=>ZN(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Wz(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t,n)=>this.scheduleScoopWait(e,t,n),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t,n)=>this.resolveActionableLick(e,t,n),approveDirectedOrUser:e=>this.approveDirectedOrUser(e),listPendingSudoRequests:e=>this.listPendingSudoRequests(e)}})}setProcessManager(e){this.processManager=e}setCapabilityBroker(e){this.capabilityBroker=e}getCapabilityBroker(){return this.capabilityBroker}getProcessManager(){return this.processManager}async initPolicyLayerAndLoadRecords(e,t,n){return eB(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new vF({fs:e,watcher:t,capabilityBroker:this.capabilityBroker,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),n(),this.llmsTxtIgnorePolicy=new uF(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new Qz(e,t),await this.modelPolicyFile.init(),n(),XN()),n,{stagePrefix:`orchestrator-init`})}setOnConversationsReady(e){this.onConversationsReady=e}async openSharedFilesystem(e,t){let n=await eB(e=>vn.create({dbName:`slicc-fs`,onRepairProgress:e}),e);this.sharedFs=n,this.sessionStore=new WA,this.conversationStore=new kL;let{TurnJournal:r}=await import(`./turn-journal-B8tRUgnH.js`);this.turnJournal=new r,this.interruptedTurns=await this.turnJournal.readAll();let i=new _n;return this.fsWatcher=i,n.setWatcher(i),globalThis.__slicc_fs_watcher=i,t?.onSharedFsReady&&await t.onSharedFsReady(n),{sharedFs:n,fsWatcher:i}}async init(e,t){await hP();let{sharedFs:n,fsWatcher:i}=await this.openSharedFilesystem(e,t),a=await this.initPolicyLayerAndLoadRecords(n,i,e),o=Object.values(a).find(e=>It(e))?.jid;for(let e of Object.values(a)){await this.backfillParent(e,o),Vt(e),this.migrateScoopConfig(e,Object.values(a)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await pP(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.backfillModels(),await this.migrateConversations(e),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new nB({onTaskRun:async(e,t)=>{qW.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),qW.info(`Orchestrator initialized`,{scoopCount:this.scoops.size}),e?.(`conversations-ready`),await this.onConversationsReady?.(),await this.restoreScoopContexts(e),kn(e=>this.getSessionCostsForCommand(e)),An(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>KA);return e()}),this.unregisterExportService=r(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}whenBootRestoresSettled(){return this.bootRestoreTail}async restoreScoopContexts(e){let t=[],n=[];for(let e of this.scoops.values())e.parentJid===null?t.push(e):n.push(e);await sB(t,4,t=>this.restoreScoopContext(t,e));let r=sB(n,4,t=>this.restoreScoopContext(t,e)).catch(e=>{qW.warn(`Background scoop restore failed`,{error:e instanceof Error?e.message:String(e)})});this.bootRestoreTail=this.bootRestoreTail.then(()=>r)}async restoreScoopContext(e,t){try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);qW.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,root:e.parentJid===null,error:n}),e.parentJid!==null&&this.lifecycle.markTabError(e.jid,n)}finally{t?.(`scoop-restored:${e.jid}`)}}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new KM;try{await fL({store:t,units:[...this.scoops.values()],loadAgentSession:async e=>{let t=await this.sessionStore?.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},loadChatSession:async e=>{let t=await n.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},onProgress:e})}catch(e){qW.warn(`Canonical conversation migration failed; it will retry on the next boot`,{error:e instanceof Error?e.message:String(e)})}}recordSentAttachments(e,t){let n=this.conversationStore,r=this.scoops.get(e);n&&r&&n.putAttachments(Sn(r),t).catch(t=>{qW.warn(`Failed to record sent attachments`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=It(e)?null:t??null;try{await YN(e)}catch(t){qW.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!Ot(e)&&!On(e));if(e.length>0){let t=$z(),n=[...e].sort((e,t)=>Number(e.parentJid!==null)-Number(t.parentJid!==null));for(let e of n){let n=e.parentJid?this.scoops.get(e.parentJid):void 0,r=(n?zt(n):void 0)??t;if(r){At(e,r);try{await YN(e)}catch(t){qW.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}try{await this.lifecycle.syncGelatiereModel()}catch(e){qW.warn(`Failed to repair gelatiere model on boot; will retry next boot`,{error:e instanceof Error?e.message:String(e)})}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Xt.root}/`,r=Zt($t(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:(/* @__PURE__ */ new Date()).toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}notifyScoopOutcome(e,t){return this.completionService.notifyWithOutcome(e,t)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-Ch4rtrAp.js`);return t(e,{scoops:this.scoops,ownerRootOf:e=>this.ownerRootOrDefault(e),enqueue:(e,t,n)=>this.approvalRouter.enqueueSudoRequest(e,t,n),getSharedFs:()=>this.sharedFs,workspaceFor:en,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(qW.warn(`Guest approval before SudoManager init — failing closed`),JW)}})}async enqueueDirectedApproval(e,t){return this.approveDirectedOrUser({...t,approver:e})}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t,n){return this.approvalRouter.resolveSudoRequestAndPersist(e,t,n)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}getDefaultConeFs(){let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}registerDiscoveryLick(e){return this.lickRegistry.registerDiscovery(e)}async resolveActionableLick(e,t,n){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t,n)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(e){return this.approvalRouter.listPendingSudoRequests(e)}registerScoop(e){return this.lifecycle.register(e)}async persistScoop(e){this.scoops.set(e.jid,e),await YN(e),e.parentJid===null&&await this.lifecycle.syncGelatiereModel().catch(t=>{qW.warn(`Failed to follow a persisted root leadership change`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}reinitLiveUnit(e){return this.lifecycle.reinitAfterPromote(e)}async rekeyConversation(e,t){await this.conversationStore?.rekey(e,t)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return St(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}capableApproverOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return Ht(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Tt(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){await this.bootRestoreTail,this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await vn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await uz(this.sharedFs).catch(e=>{qW.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new vF({fs:this.sharedFs,watcher:this.fsWatcher,capabilityBroker:this.capabilityBroker,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new uF(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Qz(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),qW.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e,t={}){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e),t)}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}getQueuedMessageIds(e){return this.messageRouter.getQueuedMessageIds(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return nP(e)}async recoverInterruptedWork(e){await this.bootRestoreTail;let t=this.interruptedTurns;this.interruptedTurns=null;let n=this.turnJournal;if(!t||t.length===0||!n)return[];let{recoverInterruptedWork:r}=await import(`./interrupted-work-recovery-BolgIHkM.js`);return r(t,{journal:n,getScoop:e=>this.scoops.get(e),getUnit:e=>this.lifecycle.getContext(e),resumeTurn:(e,t,n)=>this.lifecycle.resumeTurn(e,t,n),emitLick:e})}sendPrompt(e,t,n,r,i=[],a){return this.completionService.allowCompletion(e),this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}syncGelatiereModel(){return this.lifecycle.syncGelatiereModel()}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}streamThinking(e){return this.lifecycle.streamThinking(e)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){for(let t of xt(this.scoops.values(),e))this.completionService.cancelScheduledWaits(t),this.completionService.suppressCompletionUntilNextPrompt(t),this.lifecycle.getContext(t)?.stop(),this.clearQueuedMessages(t).catch(e=>{qW.warn(`Failed to clear queued messages on stop`,{jid:t,error:e instanceof Error?e.message:String(e)})})}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async mergeFoldedCostIntoFrozen(e,t){let n=this.scoops.get(e);if(!n||!this.sharedFs)return!1;try{let{mergeFoldedCostIntoLatestFrozen:e}=await import(`./merge-folded-cost-into-frozen-C24isZFN.js`);return await e(this.sharedFs,n,t)}catch(t){return qW.warn(`Failed to merge folded agent spend into frozen session`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await import(`./frozen-archive-format-7wcOWvsT.js`).then(e=>e.s),r=await n(this.sharedFs);return[...t,...r.map(jn)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async flushConversations(){let e=[...this.lifecycle.getContexts().values()];return(await Promise.allSettled(e.map(e=>e.flushConversation()))).every(e=>e.status===`fulfilled`&&e.value===!0)}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&qW.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.bootRestoreTail,await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,qW.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new TL(this.conversationStore):null,t=this.sharedFs;return new TI({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:async()=>await e?.loadAgentSessions()??[],loadUiChatSessions:async()=>await e?.loadChatSessions()??[],wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:JI(),snapshotStore:{read:e=>BI(t,e),write:(e,n,r)=>LI(t,e,n,r),discardIfUnindexed:e=>zI(t,e)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.256.20`})}};const XW=h(`workflow-run-manager`),ZW=`/shared/workflow-runs`,QW=1e3;function $W(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function eG(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){XW.warn(`observeRun handler threw`,e)}},i=(e,n)=>aG(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=$W(e,a.parentJid),d={id:c,name:a.name,source:a.source,origin:u.origin,lickTarget:u.lickTarget,status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:(/* @__PURE__ */ new Date()).toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(c,d),rG(t,n);let f=i(a.ctx,c),p=iG(e.processManager,d,c,()=>r(c));return e.runRealm(a.code,[`workflow`,a.filename,c],f).then(e=>o(c,l,e)).catch(e=>s(c,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>XW.warn(`workflow run lifecycle error`,e)),{runId:c}}async function o(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?c(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?c(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):c(t,`done`,i,null)}function s(e,t){return c(e,`error`,null,t)}async function c(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${ZW}/${n}.json`,u=(/* @__PURE__ */ new Date()).toISOString();try{await e.sharedFs.mkdir(ZW,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:u},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);XW.error(`failed to write run result file`,{runId:n,resultPath:c,error:t}),o=`result file write failed: ${t}`,i===`done`&&(i=`error`)}s.status=i,s.error=o,s.finishedAt=u,s.preview=i===`done`?nG(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=/* @__PURE__ */ new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){XW.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function tG(e){let t=eG(e);return globalThis[d]=t,XW.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function nG(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function rG(e,t,n=100){if(e.size<=n)return;let r=[...e.values()].filter(e=>e.status!==`running`&&e.status!==`paused`).sort((e,t)=>(e.finishedAt??e.startedAt).localeCompare(t.finishedAt??t.startedAt)),i=e.size-n;for(let n of r){if(i<=0)break;e.delete(n.id),t.delete(n.id),i--}}function iG(e,t,n,r){let i=e.on(`spawn`,e=>{t.pid===null&&e.argv.includes(n)&&(t.pid=e.pid,r(),i())});return i}function aG(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?oG(n,t,a?.args??[],r):e===`agent`?sG(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function oG(e,t,n,r){let i=e.get(t);if(i&&i.status===`running`){let[e,t=``]=n;e===`phase`?(i.currentPhase=t,i.logs.push(t)):e===`log`&&i.logs.push(t),i.logs.length>QW&&i.logs.splice(0,i.logs.length-QW),r()}return{stdout:``,stderr:``,exitCode:0}}async function sG(e,t,n,r){let i=e.get(t);i&&i.status===`running`&&(i.agentsStarted++,r());try{return await n()}finally{let n=e.get(t);n&&n.status===`running`&&(n.agentsDone++,r())}}const cG=/* @__PURE__ */ new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function lG(e,t,n){let r=uG(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=pG(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function uG(e){let t=/* @__PURE__ */ new Map;return dG(t,e.discoveryOrigin),dG(t,e.discoveryUrl),[...t.values()]}function dG(e,t){if(t){fG(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);fG(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!cG.has(e)))fG(e,t,1,`substring`)}catch{}}}function fG(e,t,n,r){if(t.length===0)return;let i=`${r}:${t}`,a=e.get(i);(!a||n>a.weight)&&e.set(i,{text:t,weight:n,match:r})}function pG(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=hG(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)mG(a,e)&&(r+=e.weight*o)}return r}function mG(e,t){if(t.match===`substring`)return e.includes(t.text);let n=t.text.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(^|[^a-z0-9.-])(?:www\\.)?${n}($|[^a-z0-9.-])`).test(e)}function hG(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}function gG(e,t,n=e=>console.warn(`Early conversation hydration failed`,e)){e.setOnConversationsReady(async()=>{try{await t.hydrateBuffersFromRecords(),t.publishHydratedTranscripts()}catch(e){n(e)}})}var _G=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=bG(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name)),t.push({name:yG,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===yG)throw new g(`ENOTDIR`,`not a directory`,e);let n=xG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);return vG.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new g(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=bG(e);if(t.length===1&&t[0]===yG)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new g(`EISDIR`,`is a directory`,e);let n=xG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!vG.includes(r))throw new g(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new g(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=bG(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===yG)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=xG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=xG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!vG.includes(r))throw new g(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new g(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new g(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new g(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new g(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderTable(){let e={stats:this.pm.stats(),processes:this.pm.list().map(e=>({pid:e.pid,ppid:e.ppid,kind:e.kind,state:EG(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:DG(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
1268
|
+
`)}`}}async function rW(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),mU.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function iW(e){return{name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:t=>PU(t,e)}}function aW(e){return{name:`sudo_request`,description:`Ask the cone for an explicit sudo escalation before running a sensitive action. Use this when you know up-front that a command, read, or write will be gated and you want a clean approval round-trip instead of letting the gate fire mid-action. Resolves with the cone's decision (allow / always / deny). If your sudoers already grants the subject with NOPASSWD, this resolves allow immediately without prompting the cone. 'always' durably widens your sandbox by appending a NOPASSWD rule to the cone-owned /etc/sudoers.d/scoop-<folder> drop-in (you cannot write it yourself). 'deny' (or a timeout / dropped cone) resolves fail-closed. Always pass 'reason': the approver sees only what you ask for, never why.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...DU],description:`The kind of sensitive action being requested. command = a shell command; read/write = a VFS path; secret = a credential read. Only command/read/write can be persisted with "always" (no sudoers Secret directive).`},detail:{type:`string`,description:`The concrete subject of the request (e.g., the command line "git push origin main" or the VFS path "/workspace/.git/config"). The cone sees this verbatim.`},suggested_pattern:{type:`string`,description:`Optional pre-filled glob pattern for an "always" grant (e.g., "git push*" for a command or "/workspace/.git/**" for a path). The cone may override this.`},reason:{type:`string`,description:`Why you need this, in one sentence. Name the goal it unblocks, not the action restated: "the build writes its output there", not "I need to write there". Truncated at 300 characters.`}},required:[`kind`,`detail`]},execute:t=>LU(t,e)}}function oW(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop") — any name list_scoops shows you.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`},[hU]:EU(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>RU(t,e)}}function sW(e){return{name:`list_scoops`,description:`List the scoops you can manage: your own subtree, plus — leading cone only — ones tagged [INHERITED] (owning cone gone) or [FOREIGN: <cone>] (another cone owns it). These names are the only ones feed_scoop / drop_scoop / scoop_mute / scoop_unmute / scoop_wait resolve; a tagged one also needs cross_cone: true.`,inputSchema:{type:`object`,properties:{}},execute:()=>BU(e)}}function cW(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, a workspace isolation mode (private | shared-readonly), and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default for workspaceMode: shared-readonly (the default) is YOUR OWN workspace plus the shared skills tree — ["/workspace/"] for the primary cone, ["/cones/<folder>/workspace/", "/workspace/skills/"] for any other; private is []. Prefer omitting it over naming "/workspace/" explicitly, which would point the scoop at a different cone's files. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable in shared-readonly; private does not auto-include them. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes — note that /tmp stays readable and writable regardless, as shared scratch space every scoop gets (so nothing secret belongs there). Trailing slash recommended.`},workspaceMode:{type:`string`,enum:[`private`,`shared-readonly`,`snapshot`,`shared-live`],description:`Workspace isolation mode. Default "shared-readonly" is today's scoop: parent workspace + skills are visible, own sandbox + /shared/ are writable, mounts stay readable. "private" is an isolated sandbox (own /scoops/<folder>/ only — no parent workspace, no implicit /shared/, mounts are NOT auto-visible). "snapshot" and "shared-live" are not implemented and are rejected. Explicit visiblePaths / writablePaths still replace the mode's path defaults.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...on],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`},background_after:{type:`number`,description:`Seconds this scoop's bash tool waits for a command before detaching it to the background and continuing (default 600). Lower it for a scoop that must never stall on a slow command — nobody can cancel a scoop's turn, and its detached commands report back via a Background Command lick. Use 0 to detach every command immediately.`},canCreateChildren:{type:`boolean`,description:`Explicit nested-delegation grant. When true, the new scoop may create and manage its own children (grandchildren of you). Omit or false (the default) keeps it a leaf. The grant is refused when you do not hold canCreateChildren yourself.`}},required:[`name`]},execute:t=>WU(t,e)}}function lW(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop") — any name list_scoops shows you.`},[hU]:EU(`drop`)},required:[`scoop_name`]},execute:t=>GU(t,e)}}function uW(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`},[hU]:EU(`mute`)},required:[`scoop_names`]},execute:t=>qU(t,e)}}function dW(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`},[hU]:EU(`unmute`)},required:[`scoop_names`]},execute:t=>YU(t,e)}}function fW(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops list_scoops shows you (e.g., ["writer-scoop", "reviewer-scoop"]).`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."},[hU]:EU(`wait on`)},required:[`scoop_names`]},execute:t=>QU(t,e)}}function pW(e){return{name:`lick_confirm`,description:`Confirm (approve) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. With always=true, the orchestrator additionally appends a NOPASSWD <directive> <pattern> rule to the requesting scoop's /etc/sudoers.d/scoop-<folder> drop-in so the same action won't prompt again. always=false (the default) is allow-once.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification, e.g. "lick-…"). Use list_sudo_requests to see outstanding ids.`},always:{type:`boolean`,description:`If true, persist a NOPASSWD rule into the requesting scoop's per-scoop sudoers so the action won't prompt again. Defaults to false (allow-once).`},pattern:{type:`string`,description:`Optional glob pattern to persist when always=true (e.g., "git push*" or "/workspace/.git/**"). Defaults to the request's suggestedPattern, then to the exact detail. Ignored when always=false.`},reason:{type:`string`,description:`Optional note for the requester — a caveat on the approval. Only reaches a scoop that asked via sudo_request; an implicit filesystem gate has no channel to report it on success. Truncated at 300 characters.`}},required:[`lick_id`]},execute:t=>eW(t,e)}}function mW(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action — pass a reason, or the scoop just retries. For llms.txt discovery this silently appends the advertising host to /etc/llmstxtignore.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in a sudo-request or llms.txt discovery notification).`},reason:{type:`string`,description:`Why you are refusing, in one sentence; the scoop sees it verbatim. Always give one for a sudo denial — without it the scoop cannot tell refusal from misunderstanding, and retries or works around it. Truncated at 300 characters.`}},required:[`lick_id`]},execute:t=>tW(t,e)}}function hW(e){return{name:`list_sudo_requests`,description:`List all pending cone-mediated sudo requests (lick id, requesting scoop, kind, detail). Use to find a lick_id for lick_confirm / lick_dismiss.`,inputSchema:{type:`object`,properties:{}},execute:()=>nW(e)}}function gW(e){return{name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:t=>rW(t,e)}}function _W(e){let t=[],n=wt(e.scoop);return bt(e.scoop)||(t.push(iW(e)),e.onSudoRequest&&t.push(aW(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(cW(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(oW(e)),t.push(sW(e)),e.onDropScoop&&t.push(lW(e)),e.onMuteScoops&&t.push(uW(e)),e.onUnmuteScoops&&t.push(dW(e)),e.onScheduleScoopWait&&t.push(fW(e)),e.onSudoResolve&&(t.push(pW(e)),t.push(mW(e))),e.onListSudoRequests&&t.push(hW(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(gW(e))),t}var vW=/* @__PURE__ */ e({buildScoopTools:()=>CW,getOrCreateConnectionManager:()=>jW});const yW=h(`scoop-context`);function bW(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-BHK4U4e6.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function xW(e){let t=e.scoop.config?.structuredOutputSchema;if(pU(e.scoop.config)!==`output`||!t)return SW(e,[]);let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BrnZ-LJ8.js`);return SW(e,[n(t,e.onStructuredOutput)])}function SW(e,t){let n={scrubToolResult:rt()},r=bW(e);return e.processManager?it(t,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},n,r):it(t,void 0,n,r)}async function CW(e){if(pU(e.scoop.config)!==`full`)return xW(e);let{scoop:t,unit:n,callbacks:r}=e,i=_W({scoop:t,getTurnSignal:e.getTurnSignal,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:de,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:e.onSudoRequest??r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=XH(e.gatedFs,n.workspace.root),o=e.blindReads??null,s=eU(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>zL);return t(e.fs)},...o?{blindPaths:()=>o.outsidePaths()}:{}}),c=[...a,s,FH(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:rt(),...o?{annotateResult:()=>o.takeNote()}:{},fireLick:e=>{let n=globalThis.__slicc_lick_handler;return n?(n(e),!0):(yW.warn(`No lick handler for background bash completion`,{folder:t.folder}),!1)}}),...i,lU({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>se(dV(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BrnZ-LJ8.js`);c.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let l={scrubToolResult:rt()},u=bW(e),d=e.processManager?it(c,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},l,u):it(c,void 0,l,u),f=OW(await wW(e.fs,t),u,l);return[...d,...f]}async function wW(e,t){try{if(t.parentJid!==null)return[];let{listServers:n}=await import(`./store-BRq0dNJo.js`).then(e=>e.r),r=await n(e),i=Object.entries(r);if(i.length===0)return[];let a=i.filter(([,e])=>{let t=e.exposure??`codemode`;return t===`direct`||t===`codemode`||t===`codemode-deferred`||kW(e)});if(a.length===0)return[];let{toAgentTools:o}=await import(`./agent-tools-ENaFAaxk.js`),s=await jW(),c=[];for(let[t,n]of a)try{let{connection:r,transport:i}=await s.connect(t,n);i!==n.transport&&(n.transport=i,import(`./store-BRq0dNJo.js`).then(e=>e.r).then(({setServer:r})=>r(t,n,e)).catch(()=>{}));let a=n.tools??await r.listTools()??[],l=o({serverName:t,tools:a,connection:r,exposure:n.exposure,toolExposure:n.toolExposure,writeOverflow:async(t,n)=>{try{await e.mkdir(`/tmp/mcp`,{recursive:!0}),await e.writeFile(`/tmp/mcp/${t}.txt`,n)}catch{}}});c.push(...l);let u=await TW(t,a,r,n);u&&c.push(u)}catch(e){yW.warn(`failed to load MCP tools for agent`,{server:t,error:e instanceof Error?e.message:String(e)})}return c}catch(e){return yW.debug(`MCP agent tools unavailable`,{error:e instanceof Error?e.message:String(e)}),[]}}async function TW(e,t,n,r){try{let{createCodemodeAgentTool:i}=await import(`./codemode-tool-BvKukYUa.js`);return i({serverName:e,tools:t,connection:n,exposure:r.exposure,toolExposure:r.toolExposure})}catch(t){return yW.debug(`codemode tool unavailable for server`,{server:e,error:t instanceof Error?t.message:String(t)}),null}}async function EW(e,t,n,r){let i=n.currentGate();if(!i)return null;if(r?.aborted)return{content:[{type:`text`,text:`${e}: not approved (guest-caused turn).`}],details:void 0};let a;try{a=await i.approve(e,t)}catch{a=!1}return!a||r?.aborted?{content:[{type:`text`,text:`${e}: not approved (guest-caused turn).`}],details:void 0}:null}async function DW(e,t){if(t)for(let n=0;n<e.content.length;n++){let r=e.content[n];if(r.type===`text`&&`text`in r&&typeof r.text==`string`)try{let i=await t(r.text);i!==r.text&&(e.content[n]={type:`text`,text:i})}catch{}}}function OW(e,t,n){return e.map(e=>({...e,async execute(r,i,a,o){let s=await EW(e.name,i,t,a);if(s)return s;let c=await e.execute(r,i,a,o);return await DW(c,n.scrubToolResult),c}}))}function kW(e){return e.toolExposure?Object.values(e.toolExposure).some(e=>e===`direct`||e===`codemode`||e===`codemode-deferred`):!1}let AW=null;async function jW(){if(AW)return AW;let{McpConnectionManager:e}=await import(`./connection-manager-Dj5JSkDt.js`);return AW=new e({getAuthHeader:async e=>{try{let{getOAuthAccountInfo:t}=await import(`./account-store--QH_gRlz.js`).then(e=>e.t),n=t(`mcp:${e}`);return n?`Bearer ${n.token}`:null}catch{return null}}}),AW}const MW=h(`scoop-context`);async function NW(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();MW.info(`Filesystem ready`,{folder:t.folder}),await NV(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,blindReads:l,sudoBroker:u,skills:d}=await oH({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,...e.escalations?{escalations:e.escalations}:{},processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),mcpConnectionManager:e.mcpConnectionManager});e.onShellReady(o);let f=await CW({getTurnGuestGates:e.getTurnGuestGates,getTurnSignal:e.getTurnSignal,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,blindReads:l,...i.onSudoRequest&&u?{onSudoRequest:e=>u.requestApproval(e)}:{},processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:p,globalMemory:m}=await cV(r,n,()=>i.getGlobalMemory());if(!uV(t))return MW.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let ee=fV(t,n),te=_V(t,n,m,p,d),ne=await e.sessions.restore(),{streamWithSessionId:h,compactFn:re,getCompactionApiKey:ie}=await FV(ee,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>uV(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let ae=Mt(t);return{kind:`ready`,agent:AV({model:ee,tools:f,systemPrompt:te,messages:ne,thinkingLevel:yV(bV()??ae.level,ee),getApiKey:()=>uV(t)??void 0,transformContext:re,streamFn:h,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:re,getCompactionApiKey:ie,effortOverride:ae.effortOverride,toolCount:f.length}}const PW=h(`scoop-context`);var FW=class{deps;timer=null;createdAt=0;constructor(e){this.deps=e}get sessionId(){return this.deps.sessionId}async restore(){let e=this.deps.canonical;if(!e)return[];let t=null;try{t=await e.store.load(e.identity.key)}catch(e){return PW.error(`Failed to restore the conversation`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.deps.onRestoreError(`Conversation history could not be restored. Starting fresh.`),[]}let n=_L(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=Qe(n);return PW.info(`Restored conversation from the canonical work-unit record`,{folder:this.deps.folder,messageCount:r.length,droppedOrphans:n.length-r.length}),r}persistNow(e){this.flush(e)}flush(e){return this.flushChecked(e).then(()=>void 0)}flushChecked(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return Promise.resolve(!0);let n=this.deps.canonical;return n?(this.createdAt||=Date.now(),n.store.syncAgentMessages(n.identity,t,{createdAt:this.createdAt}).then(e=>e!==null,e=>(PW.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),!1))):Promise.resolve(!0)}async clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.createdAt=0;let e=this.deps.canonical;e&&await e.store.delete(e.identity.key);try{await this.deps.store?.delete(this.deps.sessionId)}catch(e){PW.warn(`Failed to clear the legacy agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})}}schedule(){this.deps.isDisposed()||this.deps.canonical&&this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.isDisposed()||this.persistNow()},1e3))}};function IW(e,t){if(!e)return null;let{text:n}=t,r=n.length>200?`${n.slice(0,197)}…`:n;return e.spawn({kind:`scoop-turn`,argv:[`prompt`,r],cwd:t.cwd,owner:t.owner,adoptAbort:t.abortController})}function LW(e,t,n){t&&e&&(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function RW(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const zW=h(`scoop-context`);var BW=class{deps;constructor(e){this.deps=e}async run(e,t){let n=null;for(let r=1;r<=3;r++){if(this.deps.isDisposed()||t.aborted)return null;let i=await this.tryAttempt(e,t);if(!i||this.deps.isDisposed()||t.aborted||(n=i,await this.handleAttemptError(i,r,t)))return null}return n}reportExhausted(e){let t=e.message;zW.error(`Agent error after retries exhausted`,{folder:this.deps.folder,error:t,maxRetries:3}),this.fail(`Scoop "${this.deps.scoopName}" failed after 3 attempts: ${t}`,t)}async tryAttempt(e,t){this.deps.beginAttempt();try{if(await e(),this.deps.isDisposed()||t.aborted)return null;let n=this.deps.overflow.pendingRecovery;if(n!==null&&(await n,this.deps.overflow.clearPendingRecovery(n),this.deps.isDisposed()||t.aborted))return null;let r=this.deps.getStreamError();return r?Error(r):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handleAttemptError(e,t,n){let r=e.message;return this.handleStaleAssetError(r)||this.handleNonRetryableError(r)?!0:!await this.handleRetryableError(r,t,n)&&(zW.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:YB(r)}),!!(t<3&&(await XB(VW(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return JB(e)?(zW.error(`Non-retryable agent error`,{folder:this.deps.folder,error:e}),this.fail(`Scoop "${this.deps.scoopName}" failed with unrecoverable error: ${e}`,e),!0):!1}handleStaleAssetError(e){return Zi(e)?(zW.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),ea(this.deps.isInteractive),this.fail(`Scoop "${this.deps.scoopName}" hit a stale build after a deploy; reloading to recover.`,e),!0):!1}async handleRetryableError(e,t,n){if(!YB(e)||t>=3)return!1;let r=VW(t);return zW.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await XB(r,n)&&!this.deps.isDisposed()}fail(e,t){zB(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function VW(e){return Fr({attempt:e-1,baseMs:1e3})}function HW(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){zW.info(`Queueing prompt via ${r.steer?`steer`:`followUp`} while processing`,{folder:r.folder,isProcessing:r.isProcessing,agentIsStreaming:i});let a={role:`user`,content:[{type:`text`,text:t},...n],timestamp:Date.now()};return r.steer?e.steer(a):e.followUp(a),!0}return!1}const UW=h(`scoop-context`);var WW=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;escalations={asked:0,allowed:0,denied:0};promptAbortController=null;forceReleaseTimer=null;turnEpoch=0;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;mcpConnectionManager;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;turnJournal;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>(this.callbacks.onToolStart?.(e,t,n),this.makeToolCallDurable(e,t,n)),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:e=>this.checkpoint(e),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s,c,l,u){this.scoop=e,this.unit=Yt(e),this.owner={kind:kt(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.capabilityBroker=l??null,this.turnJournal=u??null,this.sessions=new FW({store:r??null,canonical:c?{store:c,identity:Sn(e)}:null,sessionId:e.jid,folder:e.folder,getMessages:()=>this.agent?.state?.messages,isDisposed:()=>this.disposed,onRestoreError:e=>this.callbacks.onError(e)}),this.runBounds=new DV({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new rV({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new aV({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new EV({getAgent:()=>this.agent,isDisposed:()=>this.disposed,getTurnSignal:()=>this.promptAbortController?.signal,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),isImageRecoveryActive:()=>this.imageRecovery.isActive,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onExhausted:e=>this.reportExhaustedOverflow(e),setStatus:e=>this.setStatus(e),scoopName:e.name,folder:e.folder}),this.turnRunner=new BW({isDisposed:()=>this.disposed,overflow:this.overflow,beginAttempt:()=>{this.didStreamDeltas=!1,this.promptStreamErrorMessage=null},getStreamError:()=>this.promptStreamErrorMessage,setStatus:e=>this.setStatus(e),onError:e=>this.callbacks.onError(e),onFatalError:t.onFatalError?e=>this.callbacks.onFatalError?.(e):void 0,isInteractive:this.unit.completion.mode===`interactive`,scoopName:e.name,folder:e.folder})}ownLickTarget(){return QV(this.unit,this.scoop,St(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Kt(this.callbacks.getScoops(),this.scoop)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}resetStructuredOutput(){this.structuredOutputCaptured=!1,this.structuredOutputValue=void 0}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);if(!this.mcpConnectionManager){let{getOrCreateConnectionManager:e}=await Promise.resolve().then(()=>vW);this.mcpConnectionManager=await e()}let e=await NW({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,escalations:this.escalations,capabilityBroker:this.capabilityBroker,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getTurnGuestGates:()=>this.turnGuestGates,getTurnSignal:()=>this.promptAbortController?.signal,getLickTarget:()=>this.ownLickTarget(),getTmpDir:()=>this.ownTmpDir(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputCaptured||=(this.structuredOutputValue=e,!0)},mcpConnectionManager:this.mcpConnectionManager,spawnBashJob:e=>this.bashJobs.spawn(e),onBeforeCompaction:(e,t)=>this.maybeSnapshotBeforeCompaction(e,t)});if(e.kind===`abandoned`)return;if(e.kind===`deferred`){this.setStatus(`ready`);return}this.compactFn=e.compactFn,this.getCompactionApiKey=e.getCompactionApiKey,this.activeEffortOverride=e.effortOverride,this.agent=e.agent,this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),UW.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:e.toolCount})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);UW.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){return this.agent||(await this.init(),this.agent)?!0:(this.callbacks.onError(mV(this.scoop)),!1)}cleanupPromptState(e,t,n,r,i){if(i!==void 0&&i!==this.turnEpoch){this.currentTurnProcess!==t&&LW(this.processManager,t,{lastError:n,aborted:!0});return}this.runBounds.disarm();let a=this.runBounds.takeExceededNote();a!==null&&this.callbacks.onError(`agent run terminated: ${a}`),(n||r.aborted)&&this.sessions.persistNow(),this.disarmForceRelease(),this.isProcessing=!1,this.turnJournal?.end(this.scoop.jid),!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),LW(this.processManager,t,{lastError:n,aborted:r.aborted}),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}turnGuestGates=[];async prompt(e,t=[],n){if(!await this.ensureAgentReady())return;let r=n?.guestGates??[];if(HW(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder})){for(let e of r)this.addTurnGuestGate(e);return}this.turnGuestGates=[...r];let i=this.agent;await this.runTurn(e,0,()=>i.prompt(e,t))}async resumeTurn(e,t=[]){if(!await this.ensureAgentReady()||this.isBusy)return;this.turnGuestGates=[...t];let n=this.agent;await this.runTurn(`(resumed after reload)`,e,()=>{let e=n.state.messages,t=e[e.length-1];return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)&&(n.state.messages=e.slice(0,-1)),n.continue()})}settleInterruptedToolCalls(e){let t=this.agent;if(!t||e.length===0)return;let n=Date.now(),r=e.map(e=>({role:`toolResult`,toolCallId:e.toolCallId,toolName:e.toolName,content:[{type:`text`,text:e.text}],isError:!0,timestamp:n}));t.state.messages=[...t.state.messages,...r],this.sessions.persistNow();for(let t of e)this.callbacks.onToolEnd?.(t.toolName,t.text,!0,t.toolCallId)}reportError(e){this.callbacks.onError(e)}hasAgent(){return this.agent!==null}async runTurn(e,t,n){this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal,a=++this.turnEpoch;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let o=IW(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:r});this.currentTurnProcess=o,this.runBounds.arm(),this.turnJournal?.begin(this.scoop.jid,this.scoop.folder,t,this.turnGuestGates);let s=null;try{if(s=await this.turnRunner.run(n,i),s&&!this.disposed&&!i.aborted){this.turnRunner.reportExhausted(s);return}a===this.turnEpoch&&!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,o,s,i,a)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||(this.turnGuestGates.push(e),this.turnJournal?.setGuestGates(this.scoop.jid,this.turnGuestGates))}stop(){RW(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.armForceRelease()}disarmForceRelease(){this.forceReleaseTimer!==null&&(clearTimeout(this.forceReleaseTimer),this.forceReleaseTimer=null)}armForceRelease(){this.disarmForceRelease();let e=this.turnEpoch,t=this.currentTurnProcess;this.forceReleaseTimer=setTimeout(()=>{this.forceReleaseTimer=null,!this.disposed&&this.turnEpoch===e&&this.isProcessing&&(t&&this.processManager&&(this.processManager.signal(t.pid,`SIGKILL`),this.processManager.exit(t.pid,null)),this.bashJobs.reapAll(),this.shell?.cancelActiveCommand(),this.agent?.abort?.(),this.turnEpoch===e&&this.isProcessing&&(this.isProcessing=!1,this.status===`processing`&&this.setStatus(`ready`)))},2e3)}clearMessages(){if(this.agent){let e=We(this.agent.state.messages);this.agent.state.messages=e?[e]:[]}}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0);try{await this.reloadSkills()}catch(e){UW.warn(`clearSession: could not rebuild system prompt from memory`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})}}idleCompactionEnabled(){return On(this.scoop)?!0:this.unit.parentId===null&&Ae(`compact-on-idle`)}armIdleCompaction(){if(!this.idleCompactionEnabled()){this.idleCompaction?.disarm();return}if(this.idleCompaction){this.idleCompaction.arm();return}this.idleCompactionLoading??=this.loadIdleCompaction(),this.idleCompactionLoading.then(e=>{!this.disposed&&this.status===`ready`&&e.arm()})}async loadIdleCompaction(){let[{IdleCompaction:e},{readIdleCompactionSettings:t}]=await Promise.all([import(`./idle-compaction-CkyuBvDI.js`),import(`./idle-compaction-settings-1yyApSsQ.js`)]),n=new e({isEnabled:()=>this.idleCompactionEnabled(),getSettings:t,getAgent:()=>this.agent,isDisposed:()=>this.disposed,isBusy:()=>this.isBusy,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),estimateTokens:$e,onCompacted:()=>this.sessions.persistNow(),onDiscarded:e=>this.callbacks.onCompactionStateChange?.(`cancelled`,{trigger:`idle`,roundId:e}),folder:this.scoop.folder});return this.idleCompaction=n,n}async maybeSnapshotBeforeCompaction(e,t){if(this.unit.parentId===null||Ae(`memory-v2`))return this.snapshotBeforeCompaction(e,t)}async snapshotBeforeCompaction(e,t){if(!this.fs||this.disposed)return;let n=this.sessionGeneration,{scoopSessionsDir:r,snapshotLiveSession:i}=await import(`./live-session-snapshot-BDyBgtvN.js`),a=this.unit.parentId===null,o=await i({vfs:this.fs,cone:{folder:this.scoop.folder,label:this.scoop.assistantLabel},messages:e,trigger:t,...a?{}:{sessionsDir:r(this.scoop.folder,this.scoop.jid)},stillValid:()=>!this.disposed&&n===this.sessionGeneration});return o&&a&&this.scheduleLiveDeltaCuration(),o?{transcriptPath:o.transcriptPath}:void 0}scheduleLiveDeltaCuration(){let e=this.fs;if(!e)return;let t={folder:this.scoop.folder,...this.scoop.jid?{jid:this.scoop.jid}:{}};import(`./live-session-curation-CGxamyw3.js`).then(n=>n.scheduleLiveDeltaCuration({vfs:e,cone:t})).catch(e=>{UW.warn(`Live delta curation failed to start`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}async settleLiveSnapshot(e){if(this.unit.parentId===null&&this.fs)try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-BDyBgtvN.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){UW.warn(`Live snapshot settle failed (archive stays live)`,{folder:this.scoop.folder,discard:e,error:t instanceof Error?t.message:String(t)})}}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getEscalations(){return{...this.escalations}}getContextFill(){return pV(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=SV(this.agent,this.scoop))}async reloadSkills(){this.agent&&await wV(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){if(!this.agent)return UW.info(`Thinking level stored for a deferred agent`,{requested:e}),`off`;if(bV())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=CV(this.agent,e);return UW.info(`Thinking level applied`,{requested:e,resolved:n,model:this.agent.state.model?.id,provider:this.agent.state.model?.provider,reasoning:this.agent.state.model?.reasoning===!0}),n}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}streamThinking(){if(!this.agent)return null;let e=this.agent.state.thinkingLevel;return{level:e,...e!==`off`&&this.activeEffortOverride===`max`?{effortOverride:`max`}:{}}}flushConversation(){return this.sessions.flushChecked()}dispose(){this.sessions.persistNow(),this.turnJournal?.end(this.scoop.jid),this.disposed=!0,this.disarmForceRelease(),this.idleCompaction?.cancel(),this.runBounds.disarm(),RW(this.processManager,this.currentTurnProcess,`SIGTERM`,this.promptAbortController),this.bashJobs.reapAll(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}handleAgentEvent(e,t){if(!this.disposed)return $B(e,this.eventSink,t)}async makeToolCallDurable(e,t,n){let r=Promise.all([this.sessions.flush(),n?this.turnJournal?.toolStarted(this.scoop.jid,n,e,t):null]),i,a=new Promise(e=>{i=setTimeout(()=>e(`timeout`),2e3)});try{await Promise.race([r,a])===`timeout`&&UW.warn(`Tool call not yet durable; running it anyway`,{folder:this.scoop.folder,toolName:e})}finally{clearTimeout(i)}}checkpoint(e){let t=e?.role;if(t===`user`)this.sessions.persistNow();else if(t===`toolResult`){let{toolCallId:t}=e;this.sessions.flush().then(()=>this.turnJournal?.toolEnded(this.scoop.jid,t))}else this.sessions.schedule()}setStatus(e){this.disposed||(this.status=e,e===`ready`?this.armIdleCompaction():this.idleCompaction?.cancel(),this.callbacks.onStatusChange(e))}handleAssistantMessageEnd(e){e.errorMessage||this.overflow.markAssistantSucceeded();let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}handleAgentEndEvent(e,t){this.disposed||t?.aborted||ZB(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const Q=h(`scoop-lifecycle-manager`);var GW=class{deps;units=/* @__PURE__ */ new Map;tabCreates=/* @__PURE__ */ new Map;gelatiereModelSync=Promise.resolve();constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new IB(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}displayJidFor(e){let t=this.deps.approverFor(e)?.jid;return t&&t!==e?t:void 0}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??St(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Tt(t.values(),e)??St(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Q.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof yn))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}createTab(e){let t=this.tabCreates.get(e);if(t!=null)return t;let n;return n=this.openTab(e).finally(()=>{this.tabCreates.get(e)===n&&this.tabCreates.delete(e)}),this.tabCreates.set(e,n),n}async openTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Q.debug(`Context already exists`,{jid:e});return}}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Yt(t).policy.filesystem;if(a.kind===`restricted`){let e=vt(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new yn(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:_t(a.mode)});a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new WW(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0,this.deps.getTurnJournal?.()??void 0);if(n.attachContext(l,i),await l.init(),this.units.get(e)!==n||n.context!==l)return;n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{Q.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),Q.info(`Scoop context created`,{jid:e,contextId:i})}async reinitAfterPromote(e){let t=this.units.get(e);if(t?.context){t.disposeContext();try{await this.createTab(e)}catch(n){let r=n instanceof Error?n.message:String(n);Q.warn(`Failed to re-init promoted unit; next prompt will retry`,{jid:e,error:r}),t.disposeContext(),this.markTabError(e,r)}}}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.deps.getScoops().get(e);if(o&&On(o)&&(await this.syncGelatiereModel(),!zt(o)))throw Error(`The gelatiere cannot run until the leading cone has a model`);let s=this.getContext(e);s||=(await this.createTab(e),this.getContext(e));let c=this.units.get(e);if(c?.tab?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}s=this.getContext(e)}if(!s||!c){Q.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),c.tab&&c.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await s.prompt(t,i,a)}async resumeTurn(e,t,n){let r=this.getContext(e),i=this.units.get(e);r&&i&&!r.isBusy&&(this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),i.tab&&i.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),await r.resumeTurn(t,n))}async register(e){let t=this.deps.getScoops(),n=Dt(t.values())?.jid;if(Vt(e),this.inheritModel(e),e.parentJid!==null){let n=[];for(let r of t.values())r.jid!==e.jid&&n.push(r.folder);let r=jt(e.folder,n);r!==e.folder&&(Q.warn(`Scoop folder already taken — registering under a free variant`,{jid:e.jid,requested:e.folder,folder:r}),e.folder=r,e.trigger=`@${r}`,e.assistantLabel=r)}t.set(e.jid,e);try{await this.deps.db.saveScoop(e)}catch(n){throw t.delete(e.jid),n}this.deps.messageRouter.ensureQueue(e.jid),Q.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&uB(`spawn`,e.folder)}catch(n){Q.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){Q.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{Q.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}Dt(t.values())?.jid!==n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the new leading cone after registration`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}inheritModel(e){if(On(e)){let t=Dt(this.deps.getScoops().values());At(e,t?zt(t):void 0);return}if(Ot(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?zt(t):void 0)??$z();n&&At(e,n)}async unregister(e){let t=this.deps.getScoops(),n=Dt(t.values())?.jid===e;for(let n of Wt(t.values(),e))await this.unregister(n.jid);let r=t.get(e);if(r&&r.parentJid===null&&St(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let i=this.deps.getLickManager();if(r&&i){let{webhooks:e,cronTasks:t}=await i.getLicksForScoopFromDb(r.name,r.folder),n=this.deps.buildActiveLicksError(r.folder,e,t);if(n)throw n}this.deps.costTracker.snapshot(e);let a=globalThis.__slicc_wsSubscribers;a&&a.dropForScoop(e).catch(t=>{Q.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),await Promise.all([r?this.deps.getConversationStore()?.delete(xn(r)):void 0,this.deps.getSessionStore()?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})})]),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let o=this.deps.approvalRouter.failScoop(e);if(o>0&&Q.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:o}),r&&this.deps.getSudoManager()?.forgetScoopPolicies(r.folder),Q.info(`Scoop unregistered`,{jid:e}),r)try{this.deps.callbacks.onScoopUnregistered?.(r)}catch(t){Q.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the replacement leading cone after root removal`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;if(On(n))return await this.syncGelatiereModel(),!1;let r=Dt(this.deps.getScoops().values())?.jid===e,i=n.model;At(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return At(n,i),this.getContext(e)?.updateModel(),Q.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return r&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to synchronize gelatiere after leading model change`,{jid:e,error:t instanceof Error?t.message:String(t)})}),!0}syncGelatiereModel(){let e=this.gelatiereModelSync.then(()=>this.applyGelatiereModel());return this.gelatiereModelSync=e.then(()=>void 0,()=>void 0),e}async applyGelatiereModel(){let e=this.deps.getScoops(),t=[...e.values()].find(On);if(!t)return!1;let n=Dt(e.values()),r=n?zt(n):void 0,i=zt(t),a=r?i?.provider===r.provider&&i.id===r.id:Ot(t)===void 0;if(!a){let e=t.model?{...t.model}:void 0,i=t.config?{...t.config}:void 0;At(t,r);try{await this.deps.db.saveScoop(t)}catch(n){throw t.model=e,t.config=i,n}Q.info(`Gelatiere model synchronized with leading cone`,{jid:t.jid,leadingJid:n?.jid,model:r?`${r.provider}:${r.id}`:void 0})}return r&&this.getContext(t.jid)?.updateModel(),!a}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();Q.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Lt(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Q.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}streamThinking(e){return this.getContext(e)?.streamThinking()??null}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Yt(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:n=>this.handleScoopTurnError(e,t,n),onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Et(n,t),await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(t,n)=>i.scheduleScoopWait(t,n,e):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:en(t).memoryPath}):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),approveGuestToolCall:e=>i.approveDirectedOrUser(e),onSudoResolve:o.canResolveApprovals?(n,r)=>i.resolveActionableLick(n,r,bt(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(bt(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleScoopTurnError(e,t,n){this.deps.getScoops().has(e)&&(this.deps.completionService.recordFailure(e,n),this.units.get(e)?.transition(`error`,{error:n}),uB(`error`,t.folder,n),this.deps.callbacks.onError(e,n),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,n),this.dispatch(e,`onStatusChange`,`error`))}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(Q.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),uB(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Yt(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(i)try{this.deps.callbacks.onError(i.jid,`[@${r.assistantLabel} FAILED]: ${t}`,{endTurn:!1})}catch(e){Q.error(`Failed to record fatal error for scoop owner`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}}};const $=h(`scoop-message-router`);var KW=class{deps;messageQueues=/* @__PURE__ */ new Map;lastAgentTimestamp=/* @__PURE__ */ new Map;pollInterval=null;debounceStates=/* @__PURE__ */ new Map;processing=/* @__PURE__ */ new Map;busyDeferrals=/* @__PURE__ */ new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if($.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){$.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);uB(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),$.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){$.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){$.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if($.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){$.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{$.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`||t.channel===`scoop-notify`||t.channel===`scoop-idle`||t.channel===`scoop-wait`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);$.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;n.reported||r<3e5||(n.reported=!0,$.warn(`Busy lick queue may be starved`,{jid:e,error:`Lick queue remained deferred while scoop was busy for 300s`}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r}))}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){$.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){$.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){$.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if($.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){$.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){$.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=aP(sP(iP(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){$.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=[],l=s.map(e=>{let t=new Date(e.timestamp),n=t.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}),r=BA(e.content,e.attachments);return e.attachments?.length&&c.push({id:e.id,timestamp:t.getTime(),body:r,attachments:[...e.attachments]}),`[${n}] ${e.senderName}: ${r}`}).join(`
|
|
1269
|
+
`);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>VA(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=aP(sP(iP(a),o));this.lastAgentTimestamp.set(e,f),await this.deps.db.setState(`lastAgentTs_${e}`,f);let p=s.some(e=>e.steer),m=/* @__PURE__ */ new Set,ee=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);m.has(t)||(m.add(t),ee.push(e.guestGate))}await this.deps.sendPrompt(e,l,d.senderId,d.senderName,u,{steer:p,...ee.length>0?{guestGates:ee}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);$.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),await this.deps.settleFoldedCost?.(e),t&&await t.clearSession(n).catch(t=>{$.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{$.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),$.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{$.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{$.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),$.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const qW=h(`orchestrator`),JW={decision:`deny`};var YW=class{scoops=/* @__PURE__ */ new Map;workUnits=new TN(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new _z({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;onConversationsReady=null;turnJournal=null;interruptedTurns=null;bootRestoreTail=Promise.resolve();fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new NB({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),findParent:e=>this.parentOrDefaultRoot(e),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new jB({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts(),mergeFoldedIntoFrozen:(e,t)=>this.mergeFoldedCostIntoFrozen(e,t)});completionService=new _B({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findParent:e=>this.parentOrDefaultRoot(e),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new iB({getScoops:()=>this.scoops,findApprover:e=>this.capableApproverOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>nP(e),saveMessage:e=>eP(e)});lickRegistry=new Yz({getConeShell:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new KW({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),recordSentAttachments:(e,t)=>this.recordSentAttachments(e,t),onError:(e,t,n)=>this.callbacks.onError(e,t,n),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),settleFoldedCost:e=>this.costTracker.settleFolded(e),db:{saveMessage:e=>eP(e),deleteMessage:e=>tP(e),clearMessagesForScoop:e=>$N(e),clearAllMessages:()=>QN(),getMessagesSince:(e,t,n)=>cP(e,t,n),setState:(e,t)=>mP(e,t)},isExternalLickChannel:iN});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new GW({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getConversationStore:()=>this.conversationStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,getCapabilityBroker:()=>this.capabilityBroker,getTurnJournal:()=>this.turnJournal,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>YN(e),deleteScoop:e=>ZN(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Wz(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t,n)=>this.scheduleScoopWait(e,t,n),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t,n)=>this.resolveActionableLick(e,t,n),approveDirectedOrUser:e=>this.approveDirectedOrUser(e),listPendingSudoRequests:e=>this.listPendingSudoRequests(e)}})}setProcessManager(e){this.processManager=e}setCapabilityBroker(e){this.capabilityBroker=e}getCapabilityBroker(){return this.capabilityBroker}getProcessManager(){return this.processManager}async initPolicyLayerAndLoadRecords(e,t,n){return eB(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new vF({fs:e,watcher:t,capabilityBroker:this.capabilityBroker,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),n(),this.llmsTxtIgnorePolicy=new uF(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new Qz(e,t),await this.modelPolicyFile.init(),n(),XN()),n,{stagePrefix:`orchestrator-init`})}setOnConversationsReady(e){this.onConversationsReady=e}async openSharedFilesystem(e,t){let n=await eB(e=>vn.create({dbName:`slicc-fs`,onRepairProgress:e}),e);this.sharedFs=n,this.sessionStore=new WA,this.conversationStore=new kL;let{TurnJournal:r}=await import(`./turn-journal-B8tRUgnH.js`);this.turnJournal=new r,this.interruptedTurns=await this.turnJournal.readAll();let i=new _n;return this.fsWatcher=i,n.setWatcher(i),globalThis.__slicc_fs_watcher=i,t?.onSharedFsReady&&await t.onSharedFsReady(n),{sharedFs:n,fsWatcher:i}}async init(e,t){await hP();let{sharedFs:n,fsWatcher:i}=await this.openSharedFilesystem(e,t),a=await this.initPolicyLayerAndLoadRecords(n,i,e),o=Object.values(a).find(e=>It(e))?.jid;for(let e of Object.values(a)){await this.backfillParent(e,o),Vt(e),this.migrateScoopConfig(e,Object.values(a)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await pP(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.backfillModels(),await this.migrateConversations(e),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new nB({onTaskRun:async(e,t)=>{qW.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),qW.info(`Orchestrator initialized`,{scoopCount:this.scoops.size}),e?.(`conversations-ready`),await this.onConversationsReady?.(),await this.restoreScoopContexts(e),kn(e=>this.getSessionCostsForCommand(e)),An(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>KA);return e()}),this.unregisterExportService=r(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}whenBootRestoresSettled(){return this.bootRestoreTail}async restoreScoopContexts(e){let t=[],n=[];for(let e of this.scoops.values())e.parentJid===null?t.push(e):n.push(e);await sB(t,4,t=>this.restoreScoopContext(t,e));let r=sB(n,4,t=>this.restoreScoopContext(t,e)).catch(e=>{qW.warn(`Background scoop restore failed`,{error:e instanceof Error?e.message:String(e)})});this.bootRestoreTail=this.bootRestoreTail.then(()=>r)}async restoreScoopContext(e,t){try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);qW.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,root:e.parentJid===null,error:n}),e.parentJid!==null&&this.lifecycle.markTabError(e.jid,n)}finally{t?.(`scoop-restored:${e.jid}`)}}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new KM;try{await fL({store:t,units:[...this.scoops.values()],loadAgentSession:async e=>{let t=await this.sessionStore?.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},loadChatSession:async e=>{let t=await n.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},onProgress:e})}catch(e){qW.warn(`Canonical conversation migration failed; it will retry on the next boot`,{error:e instanceof Error?e.message:String(e)})}}recordSentAttachments(e,t){let n=this.conversationStore,r=this.scoops.get(e);n&&r&&n.putAttachments(Sn(r),t).catch(t=>{qW.warn(`Failed to record sent attachments`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=It(e)?null:t??null;try{await YN(e)}catch(t){qW.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!Ot(e)&&!On(e));if(e.length>0){let t=$z(),n=[...e].sort((e,t)=>Number(e.parentJid!==null)-Number(t.parentJid!==null));for(let e of n){let n=e.parentJid?this.scoops.get(e.parentJid):void 0,r=(n?zt(n):void 0)??t;if(r){At(e,r);try{await YN(e)}catch(t){qW.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}try{await this.lifecycle.syncGelatiereModel()}catch(e){qW.warn(`Failed to repair gelatiere model on boot; will retry next boot`,{error:e instanceof Error?e.message:String(e)})}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Xt.root}/`,r=Zt($t(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:(/* @__PURE__ */ new Date()).toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}notifyScoopOutcome(e,t){return this.completionService.notifyWithOutcome(e,t)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-BHC1QE2R.js`);return t(e,{scoops:this.scoops,ownerRootOf:e=>this.ownerRootOrDefault(e),enqueue:(e,t,n)=>this.approvalRouter.enqueueSudoRequest(e,t,n),getSharedFs:()=>this.sharedFs,workspaceFor:en,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(qW.warn(`Guest approval before SudoManager init — failing closed`),JW)}})}async enqueueDirectedApproval(e,t){return this.approveDirectedOrUser({...t,approver:e})}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t,n){return this.approvalRouter.resolveSudoRequestAndPersist(e,t,n)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}getDefaultConeFs(){let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}registerDiscoveryLick(e){return this.lickRegistry.registerDiscovery(e)}async resolveActionableLick(e,t,n){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t,n)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(e){return this.approvalRouter.listPendingSudoRequests(e)}registerScoop(e){return this.lifecycle.register(e)}async persistScoop(e){this.scoops.set(e.jid,e),await YN(e),e.parentJid===null&&await this.lifecycle.syncGelatiereModel().catch(t=>{qW.warn(`Failed to follow a persisted root leadership change`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}reinitLiveUnit(e){return this.lifecycle.reinitAfterPromote(e)}async rekeyConversation(e,t){await this.conversationStore?.rekey(e,t)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return St(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}capableApproverOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return Ht(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Tt(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){await this.bootRestoreTail,this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await vn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await uz(this.sharedFs).catch(e=>{qW.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new vF({fs:this.sharedFs,watcher:this.fsWatcher,capabilityBroker:this.capabilityBroker,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new uF(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Qz(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),qW.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e,t={}){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e),t)}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}getQueuedMessageIds(e){return this.messageRouter.getQueuedMessageIds(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return nP(e)}async recoverInterruptedWork(e){await this.bootRestoreTail;let t=this.interruptedTurns;this.interruptedTurns=null;let n=this.turnJournal;if(!t||t.length===0||!n)return[];let{recoverInterruptedWork:r}=await import(`./interrupted-work-recovery-BolgIHkM.js`);return r(t,{journal:n,getScoop:e=>this.scoops.get(e),getUnit:e=>this.lifecycle.getContext(e),resumeTurn:(e,t,n)=>this.lifecycle.resumeTurn(e,t,n),emitLick:e})}sendPrompt(e,t,n,r,i=[],a){return this.completionService.allowCompletion(e),this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}syncGelatiereModel(){return this.lifecycle.syncGelatiereModel()}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}streamThinking(e){return this.lifecycle.streamThinking(e)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){for(let t of xt(this.scoops.values(),e))this.completionService.cancelScheduledWaits(t),this.completionService.suppressCompletionUntilNextPrompt(t),this.lifecycle.getContext(t)?.stop(),this.clearQueuedMessages(t).catch(e=>{qW.warn(`Failed to clear queued messages on stop`,{jid:t,error:e instanceof Error?e.message:String(e)})})}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async mergeFoldedCostIntoFrozen(e,t){let n=this.scoops.get(e);if(!n||!this.sharedFs)return!1;try{let{mergeFoldedCostIntoLatestFrozen:e}=await import(`./merge-folded-cost-into-frozen-C9I1ykhe.js`);return await e(this.sharedFs,n,t)}catch(t){return qW.warn(`Failed to merge folded agent spend into frozen session`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await import(`./frozen-archive-format-7wcOWvsT.js`).then(e=>e.s),r=await n(this.sharedFs);return[...t,...r.map(jn)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async flushConversations(){let e=[...this.lifecycle.getContexts().values()];return(await Promise.allSettled(e.map(e=>e.flushConversation()))).every(e=>e.status===`fulfilled`&&e.value===!0)}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&qW.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.bootRestoreTail,await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,qW.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new TL(this.conversationStore):null,t=this.sharedFs;return new TI({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:async()=>await e?.loadAgentSessions()??[],loadUiChatSessions:async()=>await e?.loadChatSessions()??[],wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:JI(),snapshotStore:{read:e=>BI(t,e),write:(e,n,r)=>LI(t,e,n,r),discardIfUnindexed:e=>zI(t,e)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.256.21`})}};const XW=h(`workflow-run-manager`),ZW=`/shared/workflow-runs`,QW=1e3;function $W(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function eG(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){XW.warn(`observeRun handler threw`,e)}},i=(e,n)=>aG(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=$W(e,a.parentJid),d={id:c,name:a.name,source:a.source,origin:u.origin,lickTarget:u.lickTarget,status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:(/* @__PURE__ */ new Date()).toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(c,d),rG(t,n);let f=i(a.ctx,c),p=iG(e.processManager,d,c,()=>r(c));return e.runRealm(a.code,[`workflow`,a.filename,c],f).then(e=>o(c,l,e)).catch(e=>s(c,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>XW.warn(`workflow run lifecycle error`,e)),{runId:c}}async function o(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?c(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?c(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):c(t,`done`,i,null)}function s(e,t){return c(e,`error`,null,t)}async function c(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${ZW}/${n}.json`,u=(/* @__PURE__ */ new Date()).toISOString();try{await e.sharedFs.mkdir(ZW,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:u},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);XW.error(`failed to write run result file`,{runId:n,resultPath:c,error:t}),o=`result file write failed: ${t}`,i===`done`&&(i=`error`)}s.status=i,s.error=o,s.finishedAt=u,s.preview=i===`done`?nG(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=/* @__PURE__ */ new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){XW.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function tG(e){let t=eG(e);return globalThis[d]=t,XW.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function nG(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function rG(e,t,n=100){if(e.size<=n)return;let r=[...e.values()].filter(e=>e.status!==`running`&&e.status!==`paused`).sort((e,t)=>(e.finishedAt??e.startedAt).localeCompare(t.finishedAt??t.startedAt)),i=e.size-n;for(let n of r){if(i<=0)break;e.delete(n.id),t.delete(n.id),i--}}function iG(e,t,n,r){let i=e.on(`spawn`,e=>{t.pid===null&&e.argv.includes(n)&&(t.pid=e.pid,r(),i())});return i}function aG(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?oG(n,t,a?.args??[],r):e===`agent`?sG(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function oG(e,t,n,r){let i=e.get(t);if(i&&i.status===`running`){let[e,t=``]=n;e===`phase`?(i.currentPhase=t,i.logs.push(t)):e===`log`&&i.logs.push(t),i.logs.length>QW&&i.logs.splice(0,i.logs.length-QW),r()}return{stdout:``,stderr:``,exitCode:0}}async function sG(e,t,n,r){let i=e.get(t);i&&i.status===`running`&&(i.agentsStarted++,r());try{return await n()}finally{let n=e.get(t);n&&n.status===`running`&&(n.agentsDone++,r())}}const cG=/* @__PURE__ */ new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function lG(e,t,n){let r=uG(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=pG(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function uG(e){let t=/* @__PURE__ */ new Map;return dG(t,e.discoveryOrigin),dG(t,e.discoveryUrl),[...t.values()]}function dG(e,t){if(t){fG(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);fG(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!cG.has(e)))fG(e,t,1,`substring`)}catch{}}}function fG(e,t,n,r){if(t.length===0)return;let i=`${r}:${t}`,a=e.get(i);(!a||n>a.weight)&&e.set(i,{text:t,weight:n,match:r})}function pG(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=hG(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)mG(a,e)&&(r+=e.weight*o)}return r}function mG(e,t){if(t.match===`substring`)return e.includes(t.text);let n=t.text.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(^|[^a-z0-9.-])(?:www\\.)?${n}($|[^a-z0-9.-])`).test(e)}function hG(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}function gG(e,t,n=e=>console.warn(`Early conversation hydration failed`,e)){e.setOnConversationsReady(async()=>{try{await t.hydrateBuffersFromRecords(),t.publishHydratedTranscripts()}catch(e){n(e)}})}var _G=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=bG(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name)),t.push({name:yG,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===yG)throw new g(`ENOTDIR`,`not a directory`,e);let n=xG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);return vG.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new g(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=bG(e);if(t.length===1&&t[0]===yG)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new g(`EISDIR`,`is a directory`,e);let n=xG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!vG.includes(r))throw new g(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new g(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=bG(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===yG)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=xG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=xG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!vG.includes(r))throw new g(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new g(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new g(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new g(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new g(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderTable(){let e={stats:this.pm.stats(),processes:this.pm.list().map(e=>({pid:e.pid,ppid:e.ppid,kind:e.kind,state:EG(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:DG(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
1270
1270
|
`}renderProcFile(e,t){if(e===1)return OG(t);let n=this.pm.get(e);switch(t){case`status`:return SG(n);case`cmdline`:return CG(n);case`cwd`:return wG(n);case`stat`:return TG(n)}}};const vG=[`status`,`cmdline`,`cwd`,`stat`],yG=`table`;function bG(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function xG(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function SG(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${EG(e.status)} (${e.status})`,`Owner:\t${DG(e)}`,`StartedAt:\t${new Date(e.startedAt).toISOString()}`];return e.finishedAt!==null&&t.push(`FinishedAt:\t${new Date(e.finishedAt).toISOString()}`),e.terminatedBy!==null&&t.push(`TerminatedBy:\t${e.terminatedBy}`),e.exitCode!==null&&t.push(`ExitCode:\t${e.exitCode}`),t.push(`Cmdline:\t${e.argv.join(` `)}`),t.join(`
|
|
1271
1271
|
`)+`
|
|
1272
1272
|
`}function CG(e){return e.argv.join(`\0`)+`\0`}function wG(e){return e.cwd+`
|
|
@@ -1276,6 +1276,6 @@ Created: ${(/* @__PURE__ */ new Date()).toISOString()}
|
|
|
1276
1276
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
1277
1277
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
1278
1278
|
`}}const kG=Math.max(Cr,wr)+5e3;function AG(e={}){let t=e.channel===void 0;if(t&&!e.nonce)throw Error(`installSyncFsResponder: a nonce (or a test channel) is required`);let n=e.channel??new BroadcastChannel(xr(e.nonce)),r=e=>n.postMessage(e),i=/* @__PURE__ */ new Map,a=e=>{let t=e.data;if(t?.type!==`sync-fs-req`||typeof t.id!=`string`)return;let n=t;if(!yr(n.token))return;let a=i.get(n.id);if(a){r({type:Sr,id:n.id}),a.result&&r({type:br,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:Sr,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),kG),r({type:br,id:n.id,...e})};(Er(n)?Tr(n):Dr(n)).then(s).catch(e=>s({ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return n.addEventListener(`message`,a),{dispose:()=>{n.removeEventListener(`message`,a);for(let e of i.values())e.timer&&clearTimeout(e.timer);i.clear(),t&&n.close?.()}}}function jG(){return globalThis}function MG(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return sN(e);case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`bash`:return e.bashJobId??`bash`;case`jshd`:return e.jshdName??`jshd`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function NG(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`bash`:return`bash-${e.bashJobId??`unknown`}`;case`jshd`:return`jshd-${e.jshdName??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function PG(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}FG(e,t)}async function FG(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=St(r),a=e.type===`discovery`&&!e.targetScoop?lG(e,i.filter(sF),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?ua(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!sF(o)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:o.folder});return}if(e.type===`navigate`){try{let{shouldSkipNavigateUpskill:r}=await import(`./upskill-lick-skip-m-4-PedH.js`);if(await r(e,typeof t.getDefaultConeFs==`function`?()=>t.getDefaultConeFs():()=>null)){n.debug?.(`dropping navigate·upskill lick; advertised skill already installed at that commit`);return}}catch(e){n.warn(`navigate·upskill skip check failed; raising card`,e)}e.lickId=t.registerNavigateLick(e)}else e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`?e.lickId=t.registerUpgradeLick(e):e.type===`discovery`&&(e.lickId=t.registerDiscoveryLick(e)??void 0);let s=xN(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=MG(e),l=NG(e),u=e.type,d={id:`${u}-${l}-${Date.now()}`,chatJid:o.jid,senderId:u,senderName:`${u}:${c}`,content:s.content,timestamp:e.timestamp,fromAssistant:!1,channel:u,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(d).catch(e=>{n.warn(`Lick message routing failed`,{channel:u,eventName:c,error:String(e)})})}async function IG(e,t,n,r,i){let o=new mr,s=new YW(e,{...r,getBrowserAPI:()=>t});s.setProcessManager(o);let c=at(),l=i.capabilityBroker??a(c,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});s.setCapabilityBroker(l),fn(l),jG().__slicc_pm=o,hr(gr()),jG().__slicc_browser=t,await n.bind(s,t);let u=wn(()=>n.emitTrayRuntimeStatus()),d=Ee(()=>n.emitTrayRuntimeStatus());gG(s,n);let f=i.logger??console;return await s.init(i.onBootProgress,{onSharedFsReady:async e=>{try{let{applyConfiguredHostMounts:t}=await import(`./auto-mount-table-B2A2zm7m.js`);await t(e,f)}catch(e){f.warn(`Configured host mounts failed`,e)}i.onBootProgress?.(`host-mounts-applied`)}}),await n.hydrateBuffersFromRecords(),n.publishHydratedTranscripts(),{processManager:o,orchestrator:s,unsubLeader:u,unsubFollower:d,sharedFs:s.getSharedFS(),capabilityBroker:l}}async function LG(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-CG3mKA1r.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await Promise.resolve().then(()=>KA);r(()=>a());let{getLickManager:o}=await Promise.resolve().then(()=>Lz),s=o();await s.init(),e.setLickManager(s);let c=t.lickEventHandler??PG,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function RG(e){let t=e.getScoops();St(t).length>0||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,parentJid:null,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:(/* @__PURE__ */ new Date()).toISOString()})}function zG(e){let{orchestrator:t,processManager:r,lickManager:i,sharedFs:a}=e;tG({sharedFs:a,getStartingRoot:e=>{let n=St(t.getScoops()),r=n.find(t=>t.jid===e);return r?{jid:r.jid,lickTarget:r.jid===n[0]?.jid?void 0:r.folder}:null},fireLick:e=>i.emitEvent(e),processManager:r,runRealm:(e,t,n)=>vr(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>c().slice(10,22),splitResult:(e,t)=>n(e,t)})}async function BG(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-C1F4CP6u.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-wLGrnjph.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
|
|
1279
|
-
`,r=``;try{let t=await i.readFile(e);r=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await i.writeFile(e,r+n)},log:e=>{a.info?.(`browser.websocket frame`,{payload:e})}}})}}async function VG(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-B-61k0Zh.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-DQHez2UB.js`);return i(e,{locationHref:self.location.href,lickWsUrl:n??null,onHostfsInvalidate:e=>{if(!r)return;let n=r.getMountBackend(e.mount);if(!(n instanceof a)){t.debug?.(`hostfs_invalidate for unknown/non-hostfs mount`,{mount:e.mount});return}n.applyHostInvalidation(e.paths).catch(n=>{t.warn(`hostfs_invalidate apply failed`,{mount:e.mount,error:n instanceof Error?n.message:String(n)})})}}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function HG(e,t,n,r){let i=e.getTransport();if(i.isExtensionBridge)return n.debug?.(`Skipping NavigationWatcher: extension-bridge transport rejects sessionless Target.* discovery; the service worker observes handoffs via chrome.webRequest`),null;try{let e=new QP(i,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:n})},{...UG(t),isOwnTab:XP(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function UG(e){let t=ye();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(/* @__PURE__ */ Error(`aborted`));return}i.addEventListener(`abort`,()=>t(/* @__PURE__ */ Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>$P()}}async function WG(e,t,n){try{let r=await e.recoverInterruptedWork(e=>t.emitEvent(e));r.length>0&&n.info(`Recovered work interrupted by a reload`,{outcomes:r})}catch(e){n.warn(`Reload recovery failed`,e)}}async function GG(e,t,n,r,i,a){e&&(await YG(e,n,r),i(`mounts-restored`),await KG(e,t,n,r,a),i(`jshd-restored`),await qG(e,r))}async function KG(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-BUvJhiTF.js`),a=i.getSudoManager();await r({fs:e,processManager:t,lickManager:n,...a?{sudo:{broker:a.getBroker(),getPolicy:()=>a.getPolicy()}}:{}})}catch(e){r.warn(`jshd restore failed`,e)}}async function qG(e,t){try{let{restoreMcpServe:t}=await import(`./serve-runtime-CqUYUISo.js`),{executeJshFile:n}=await import(`./jsh-executor-DGOAl5iJ.js`).then(e=>e.r),{textAsStdin:r}=await import(`./just-bash-compat-DWUHpp9U.js`).then(e=>e.r),{createCommandContext:i}=await import(`./browser-4sjVvKih.js`).then(e=>e.n),{DEFAULT_HOME_DIR:a}=await import(`./home-dir-DAXEFyny.js`).then(e=>e.n),{DEFAULT_SHELL_PATH:o}=await import(`./jsh-discovery-D7D5iKYT.js`).then(e=>e.o),s=/* @__PURE__ */ new Map([[`HOME`,a],[`PATH`,o],[`PWD`,`/workspace`]]);await t(JG(e),async(t,a,o)=>{let c=i({fs:e,cwd:`/workspace`,env:s,stdin:r(o??``)}),l=await n(t,a,c);return{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode}})}catch(e){t.warn(`mcp serve restore failed`,e)}}function JG(e){return{readFile:async t=>{let n=await e.readFile(t);return typeof n==`string`?n:new TextDecoder().decode(n)},writeFile:async(t,n)=>{await e.writeFile(t,n)},exists:t=>e.exists(t),mkdir:async t=>{await e.exists(t)||await e.mkdir(t,{recursive:!0})}}}async function YG(e,t,n){try{let{getAllMountEntries:r}=await import(`./mount-table-store-xM3U8UHg.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>YM),{applyConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-B2A2zm7m.js`),s=await a(e,n),c=o(await r(),s);if(c.length===0)return;let{needsRecovery:l}=await i(c,e,n);if(l.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{reason:`mount-recovery`,mounts:l}})}catch(e){n.warn(`mount recovery failed`,e)}}function XG(){En(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-B_0cdTwX.js`);return e()})}function ZG(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-B_0cdTwX.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function QG(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DOwTR0vR.js`),{ScriptCatalog:r}=await import(`./script-catalog-DDeMaTU_.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function $G(e){return e===`node-rest`}function eK(e,t,n,r){import(`./gelatiere-unit-BIIKTgS2.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!Ae(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-GVNdni5w.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function tK(e,t){if(!e)return()=>{};import(`./memory-curation-seam-DitfDTyZ.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return Ae(`memory-v2`)&&import(`./memory-health-CCaMzT62.js`).then(i=>{n||(r=i.scheduleMemoryHealthChecks(e,{log:t}))}).catch(e=>t.warn(`memory health check failed to schedule`,e)),()=>{n=!0,r?.()}}function nK(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}jM(e,t,e.getSessionStore())}async function rK(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);XG();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await IG(t,n,r,i,e);if(s(`orchestrator-ready`),nK(l,f,o),f)try{await f.mountInternal(`/proc`,new _G(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await LG(l,e,o);s(`lick-manager-ready`),f&&zG({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),jG().__slicc_lickManager=m,eK(l,m,f,o);let ee=tK(f,o),{wsBridge:te,wsRegistry:ne}=await BG({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});jG().__slicc_wsSubscribers=ne;let h=$G(p.adapter)?await VG(m,o,e.localLickWsUrl??null,f):null,re=HG(n,m,o,e.appPageUrl);await GG(f,c,m,o,s,l),a||await RG(l),s(`cone-bootstrapped`),WG(l,m,o),f&&ZG(m,o);let ie=null,ae=null;f&&({bshWatchdogStop:ie,scriptCatalogDispose:ae}=await QG(f,n,o));let oe=null;f&&e.syncFsChannelNonce&&(oe=AG({nonce:e.syncFsChannelNonce}).dispose);let se=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){se||(se=!0,await iK({unsubLeader:u,unsubFollower:d,bshWatchdogStop:ie,memoryHealthStop:ee,scriptCatalogDispose:ae,lickWsBridgeStop:h,navigationWatcherStop:re,syncFsResponderDispose:oe,sharedFs:f,wsRegistry:ne,wsBridge:te,processManager:c,lickManager:m,browser:n,log:o}))}}}async function iK(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.memoryHealthStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}aK({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function aK(e){let t=jG();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,hr(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[d]}const oK=`x-bypass-llm-proxy`;function sK(e,t,n){return t?(r,i)=>{if(!cK(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(oK)||a.set(oK,`1`),e(r,{...i,headers:a})}:e}function cK(e,t,n){if(uK(e,t))return!0;let r=n?.()??null;return r?lK(e,r,t):!1}function lK(e,t,n){let r=dK(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function uK(e,t){let n=dK(e);try{return new URL(n,t).origin===t}catch{return!0}}function dK(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function fK(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}const pK=new TextEncoder;var mK=class{screen;cols=80;rows=24;held=null;constructor(e){this.screen=e}lease(){if(this.held)return null;let e={input:[],resize:[]};this.held=e,this.screen.mode(`pty`);let t=new TextDecoder,n=this,r=!1;return{get cols(){return n.cols},get rows(){return n.rows},write:e=>{r||this.screen.output(t.decode(e,{stream:!0}))},onInput:t=>void e.input.push(t),onResize:t=>void e.resize.push(t),release:()=>{if(r)return;r=!0;let n=t.decode();n&&this.screen.output(n),this.held===e&&(this.held=null),this.screen.mode(`line`)}}}input(e){let t=pK.encode(e);for(let e of this.held?.input??[])e(t)}resize(e,t){if(!(e<=0||t<=0)){this.cols=e,this.rows=t;for(let n of this.held?.resize??[])n(e,t)}}},hK=class{transport;createShell;log;pm;defaultOwner;sessions=/* @__PURE__ */ new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!gK(e)||e.source!==`panel`)return;let t=e.payload;vK(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:this.sessions.get(e.sid)?.terminal.input(e.data);return;case`terminal-resize`:this.sessions.get(e.sid)?.terminal.resize(e.cols,e.rows);return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t={currentExec:null,currentProcess:null};t.currentExecMsg=null;let n=new mK({output:e=>{let n=t.currentExecMsg;n&&this.emitStream(n,`stdout`,e)},mode:t=>this.emit({type:`terminal-mode`,sid:e.sid,mode:t})});e.cols&&e.rows&&n.resize(e.cols,e.rows),t.terminal=n,t.shell=this.createShell(e.sid,{cwd:e.cwd,env:e.env,terminal:n}),this.sessions.set(e.sid,t),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n,t.currentExecMsg=e,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=``;if(e.stdin)try{i=fr(ie(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null,t.currentExecMsg=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?_K(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,_K(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function gK(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function _K(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function vK(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var yK=class extends m{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};const bK={maxExecutionTimeMs:1/0,maxCommandCount:1/0,maxLoopIterations:1/0,maxParserTokens:1/0,maxParseIterations:1/0};function xK(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new hK({transport:t,processManager:i,createShell:(a,o)=>new yK(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Tn},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},terminal:o.terminal,sudo:s,executionLimits:bK}),logger:o});return{host:c,stop:c.start()}}function SK(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return TK(e);if(typeof e==`object`)return EK(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function CK(e){if(typeof e==`object`&&e&&!(e instanceof Error))return OK(e)??kK(e);let t=SK(e);if(t!==void 0)return wK(t)}function wK(e){let t=e.trim();if(!t)return e;let n=DK(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=DK(t.slice(r,i+1));if(e)return e}return e}function TK(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function EK(e){let t=OK(e),n=kK(e);return n&&t?`${n}: ${t}`:t??n}function DK(e){if(e.startsWith(`{`))try{return OK(JSON.parse(e))}catch{return}}function OK(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.message==`string`&&t.message.length>0)return t.message;if(typeof t.error==`string`&&t.error.length>0)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`&&e.message.length>0)return e.message}}function kK(e){if(!e||typeof e!=`object`)return;let t=e;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.type==`string`&&e.type.length>0)return e.type}if(typeof t.type==`string`&&t.type.length>0&&t.type!==`error`)return t.type}let AK=null,jK=!1;function MK(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function NK(e){return MK()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function PK(e={}){if(!jK&&(typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`telemetry-disabled`)!==`true`)){p(FK),lB(LK),RB(IK);try{let t=NK(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(AK=(await import(`./rum-worker-CwmNSpjO.js`)).default,BK(self)):t===`extension`?(ZK({filterViteNoise:!1}),AK=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&BK(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),ZK({filterViteNoise:!0}),HK(),AK=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),jK=!0,AK&&AK(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function FK(e){AK?.(`fill`,{source:e})}function IK(e,t){let n=zK(t);n!==null&&AK?.(`error`,{source:e,target:n})}function LK(e,t,n){if(e===`error`){let e=zK(n);if(e===null)return;AK?.(`error`,{source:`scoop:${t}`,target:e});return}AK?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function RK(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function zK(e){let t=SK(e);if(t===void 0)return e==null?void 0:null;if(KB(t))return null;let n=CK(e)??wK(t);return KB(n)?null:UK(n)}function BK(e){e.addEventListener(`error`,e=>{let t=e;IK(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{IK(`js`,e.reason)})}function VK(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function HK(){typeof window<`u`&&(window.addEventListener(`error`,e=>{let t=e.error;VK(t)&&(IK(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;VK(t)&&(IK(`js`,t),e.stopImmediatePropagation())},!0))}function UK(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
1279
|
+
`,r=``;try{let t=await i.readFile(e);r=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await i.writeFile(e,r+n)},log:e=>{a.info?.(`browser.websocket frame`,{payload:e})}}})}}async function VG(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-D4PsA45A.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-DQHez2UB.js`);return i(e,{locationHref:self.location.href,lickWsUrl:n??null,onHostfsInvalidate:e=>{if(!r)return;let n=r.getMountBackend(e.mount);if(!(n instanceof a)){t.debug?.(`hostfs_invalidate for unknown/non-hostfs mount`,{mount:e.mount});return}n.applyHostInvalidation(e.paths).catch(n=>{t.warn(`hostfs_invalidate apply failed`,{mount:e.mount,error:n instanceof Error?n.message:String(n)})})}}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function HG(e,t,n,r){let i=e.getTransport();if(i.isExtensionBridge)return n.debug?.(`Skipping NavigationWatcher: extension-bridge transport rejects sessionless Target.* discovery; the service worker observes handoffs via chrome.webRequest`),null;try{let e=new QP(i,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:n})},{...UG(t),isOwnTab:XP(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function UG(e){let t=ye();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(/* @__PURE__ */ Error(`aborted`));return}i.addEventListener(`abort`,()=>t(/* @__PURE__ */ Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>$P()}}async function WG(e,t,n){try{let r=await e.recoverInterruptedWork(e=>t.emitEvent(e));r.length>0&&n.info(`Recovered work interrupted by a reload`,{outcomes:r})}catch(e){n.warn(`Reload recovery failed`,e)}}async function GG(e,t,n,r,i,a){e&&(await YG(e,n,r),i(`mounts-restored`),await KG(e,t,n,r,a),i(`jshd-restored`),await qG(e,r))}async function KG(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-Uo3FkyTn.js`),a=i.getSudoManager();await r({fs:e,processManager:t,lickManager:n,...a?{sudo:{broker:a.getBroker(),getPolicy:()=>a.getPolicy()}}:{}})}catch(e){r.warn(`jshd restore failed`,e)}}async function qG(e,t){try{let{restoreMcpServe:t}=await import(`./serve-runtime-BMkuNcbl.js`),{executeJshFile:n}=await import(`./jsh-executor-BVFFU-rP.js`).then(e=>e.r),{textAsStdin:r}=await import(`./just-bash-compat-DWUHpp9U.js`).then(e=>e.r),{createCommandContext:i}=await import(`./browser-4sjVvKih.js`).then(e=>e.n),{DEFAULT_HOME_DIR:a}=await import(`./home-dir-DAXEFyny.js`).then(e=>e.n),{DEFAULT_SHELL_PATH:o}=await import(`./jsh-discovery-D7D5iKYT.js`).then(e=>e.o),s=/* @__PURE__ */ new Map([[`HOME`,a],[`PATH`,o],[`PWD`,`/workspace`]]);await t(JG(e),async(t,a,o)=>{let c=i({fs:e,cwd:`/workspace`,env:s,stdin:r(o??``)}),l=await n(t,a,c);return{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode}})}catch(e){t.warn(`mcp serve restore failed`,e)}}function JG(e){return{readFile:async t=>{let n=await e.readFile(t);return typeof n==`string`?n:new TextDecoder().decode(n)},writeFile:async(t,n)=>{await e.writeFile(t,n)},exists:t=>e.exists(t),mkdir:async t=>{await e.exists(t)||await e.mkdir(t,{recursive:!0})}}}async function YG(e,t,n){try{let{getAllMountEntries:r}=await import(`./mount-table-store-xM3U8UHg.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>YM),{applyConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-B2A2zm7m.js`),s=await a(e,n),c=o(await r(),s);if(c.length===0)return;let{needsRecovery:l}=await i(c,e,n);if(l.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{reason:`mount-recovery`,mounts:l}})}catch(e){n.warn(`mount recovery failed`,e)}}function XG(){En(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-BZOEx1T3.js`);return e()})}function ZG(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-BZOEx1T3.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function QG(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DOwTR0vR.js`),{ScriptCatalog:r}=await import(`./script-catalog-DDeMaTU_.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function $G(e){return e===`node-rest`}function eK(e,t,n,r){import(`./gelatiere-unit-BqTcFkxk.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!Ae(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-GVNdni5w.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function tK(e,t){if(!e)return()=>{};import(`./memory-curation-seam-C4r6A-jq.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return Ae(`memory-v2`)&&import(`./memory-health-CCaMzT62.js`).then(i=>{n||(r=i.scheduleMemoryHealthChecks(e,{log:t}))}).catch(e=>t.warn(`memory health check failed to schedule`,e)),()=>{n=!0,r?.()}}function nK(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}jM(e,t,e.getSessionStore())}async function rK(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);XG();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await IG(t,n,r,i,e);if(s(`orchestrator-ready`),nK(l,f,o),f)try{await f.mountInternal(`/proc`,new _G(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await LG(l,e,o);s(`lick-manager-ready`),f&&zG({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),jG().__slicc_lickManager=m,eK(l,m,f,o);let ee=tK(f,o),{wsBridge:te,wsRegistry:ne}=await BG({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});jG().__slicc_wsSubscribers=ne;let h=$G(p.adapter)?await VG(m,o,e.localLickWsUrl??null,f):null,re=HG(n,m,o,e.appPageUrl);await GG(f,c,m,o,s,l),a||await RG(l),s(`cone-bootstrapped`),WG(l,m,o),f&&ZG(m,o);let ie=null,ae=null;f&&({bshWatchdogStop:ie,scriptCatalogDispose:ae}=await QG(f,n,o));let oe=null;f&&e.syncFsChannelNonce&&(oe=AG({nonce:e.syncFsChannelNonce}).dispose);let se=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){se||(se=!0,await iK({unsubLeader:u,unsubFollower:d,bshWatchdogStop:ie,memoryHealthStop:ee,scriptCatalogDispose:ae,lickWsBridgeStop:h,navigationWatcherStop:re,syncFsResponderDispose:oe,sharedFs:f,wsRegistry:ne,wsBridge:te,processManager:c,lickManager:m,browser:n,log:o}))}}}async function iK(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.memoryHealthStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}aK({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function aK(e){let t=jG();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,hr(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[d]}const oK=`x-bypass-llm-proxy`;function sK(e,t,n){return t?(r,i)=>{if(!cK(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(oK)||a.set(oK,`1`),e(r,{...i,headers:a})}:e}function cK(e,t,n){if(uK(e,t))return!0;let r=n?.()??null;return r?lK(e,r,t):!1}function lK(e,t,n){let r=dK(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function uK(e,t){let n=dK(e);try{return new URL(n,t).origin===t}catch{return!0}}function dK(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function fK(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}const pK=new TextEncoder;var mK=class{screen;cols=80;rows=24;held=null;constructor(e){this.screen=e}lease(){if(this.held)return null;let e={input:[],resize:[]};this.held=e,this.screen.mode(`pty`);let t=new TextDecoder,n=this,r=!1;return{get cols(){return n.cols},get rows(){return n.rows},write:e=>{r||this.screen.output(t.decode(e,{stream:!0}))},onInput:t=>void e.input.push(t),onResize:t=>void e.resize.push(t),release:()=>{if(r)return;r=!0;let n=t.decode();n&&this.screen.output(n),this.held===e&&(this.held=null),this.screen.mode(`line`)}}}input(e){let t=pK.encode(e);for(let e of this.held?.input??[])e(t)}resize(e,t){if(!(e<=0||t<=0)){this.cols=e,this.rows=t;for(let n of this.held?.resize??[])n(e,t)}}},hK=class{transport;createShell;log;pm;defaultOwner;sessions=/* @__PURE__ */ new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!gK(e)||e.source!==`panel`)return;let t=e.payload;vK(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:this.sessions.get(e.sid)?.terminal.input(e.data);return;case`terminal-resize`:this.sessions.get(e.sid)?.terminal.resize(e.cols,e.rows);return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t={currentExec:null,currentProcess:null};t.currentExecMsg=null;let n=new mK({output:e=>{let n=t.currentExecMsg;n&&this.emitStream(n,`stdout`,e)},mode:t=>this.emit({type:`terminal-mode`,sid:e.sid,mode:t})});e.cols&&e.rows&&n.resize(e.cols,e.rows),t.terminal=n,t.shell=this.createShell(e.sid,{cwd:e.cwd,env:e.env,terminal:n}),this.sessions.set(e.sid,t),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n,t.currentExecMsg=e,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=``;if(e.stdin)try{i=fr(ie(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null,t.currentExecMsg=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?_K(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,_K(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function gK(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function _K(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function vK(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var yK=class extends m{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};const bK={maxExecutionTimeMs:1/0,maxCommandCount:1/0,maxLoopIterations:1/0,maxParserTokens:1/0,maxParseIterations:1/0};function xK(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new hK({transport:t,processManager:i,createShell:(a,o)=>new yK(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Tn},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},terminal:o.terminal,sudo:s,executionLimits:bK}),logger:o});return{host:c,stop:c.start()}}function SK(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return TK(e);if(typeof e==`object`)return EK(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function CK(e){if(typeof e==`object`&&e&&!(e instanceof Error))return OK(e)??kK(e);let t=SK(e);if(t!==void 0)return wK(t)}function wK(e){let t=e.trim();if(!t)return e;let n=DK(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=DK(t.slice(r,i+1));if(e)return e}return e}function TK(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function EK(e){let t=OK(e),n=kK(e);return n&&t?`${n}: ${t}`:t??n}function DK(e){if(e.startsWith(`{`))try{return OK(JSON.parse(e))}catch{return}}function OK(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.message==`string`&&t.message.length>0)return t.message;if(typeof t.error==`string`&&t.error.length>0)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`&&e.message.length>0)return e.message}}function kK(e){if(!e||typeof e!=`object`)return;let t=e;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.type==`string`&&e.type.length>0)return e.type}if(typeof t.type==`string`&&t.type.length>0&&t.type!==`error`)return t.type}let AK=null,jK=!1;function MK(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function NK(e){return MK()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function PK(e={}){if(!jK&&(typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`telemetry-disabled`)!==`true`)){p(FK),lB(LK),RB(IK);try{let t=NK(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(AK=(await import(`./rum-worker-CwmNSpjO.js`)).default,BK(self)):t===`extension`?(ZK({filterViteNoise:!1}),AK=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&BK(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),ZK({filterViteNoise:!0}),HK(),AK=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),jK=!0,AK&&AK(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function FK(e){AK?.(`fill`,{source:e})}function IK(e,t){let n=zK(t);n!==null&&AK?.(`error`,{source:e,target:n})}function LK(e,t,n){if(e===`error`){let e=zK(n);if(e===null)return;AK?.(`error`,{source:`scoop:${t}`,target:e});return}AK?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function RK(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function zK(e){let t=SK(e);if(t===void 0)return e==null?void 0:null;if(KB(t))return null;let n=CK(e)??wK(t);return KB(n)?null:UK(n)}function BK(e){e.addEventListener(`error`,e=>{let t=e;IK(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{IK(`js`,e.reason)})}function VK(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function HK(){typeof window<`u`&&(window.addEventListener(`error`,e=>{let t=e.error;VK(t)&&(IK(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;VK(t)&&(IK(`js`,t),e.stopImmediatePropagation())},!0))}function UK(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
1280
1280
|
`).filter(e=>!RK(e)).join(`
|
|
1281
|
-
`).trim();return e?e.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`):null}return t.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`)}const WK=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`),GK=[[/(\/|%2F)(join|controller)(\/|%2F)[^/?#&"\s\\]+/gi,`$1$2$3redacted`],[/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[0-9a-f]{16,}/gi,`redacted`],[/\b[0-9a-f]{32}--[0-9a-f]{16,}\b/gi,`redacted`]];function KK(e){let t=e;for(let[e,n]of GK)t=t.replace(e,n);return t}function qK(e){let t=typeof e==`string`?e:CK(e)??SK(e);if(typeof t!=`string`)return{kind:`absent`};let n=wK(t);if(n===`[object Object]`)return{kind:`noise`};let r=UK(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function JK(e){let t=qK(e.source),n=qK(e.target),r=t.kind!==`kept`,i=n.kind!==`kept`;if((t.kind!==`absent`||n.kind!==`absent`)&&r&&i||n.kind===`noise`&&e.source===`undefined error`)return!0;let a=!1;return t.kind===`kept`?t.mutated&&(e.source=t.value,a=!0):t.kind===`noise`&&(e.source=``,a=!0),n.kind===`kept`?n.mutated&&(e.target=n.value,a=!0):n.kind===`noise`&&(e.target=``,a=!0),a?JSON.stringify(e):null}function YK(e){try{if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(e)}catch{}return null}function XK(e){if(e.charCodeAt(0)!==123)return null;try{let t=JSON.parse(e);return t?.checkpoint===`error`?JK(t):null}catch{return null}}function ZK(e){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let t=navigator.sendBeacon;if(t[WK])return;let n=t.bind(navigator),r=((t,r)=>{let i=YK(r);if(i===null)return n(t,r);let a=KK(i);if(e.filterViteNoise){let e=XK(a);if(e===!0)return!0;if(e!==null)return n(t,e)}return n(t,a===i?r:a)});r[WK]=!0,navigator.sendBeacon=r}function QK(e){let t=new $K(e);return t.start(),{stop:()=>t.dispose()}}var $K=class{transport;client;writableClient;getWatcher;log;unsubscribe=null;watches=/* @__PURE__ */ new Map;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.getWatcher=e.getWatcher??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!eq(e)||e.source!==`panel`)return;let t=e.payload;if(tq(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(nq(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(rq(t)){this.handleWatchControl(t);return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.watches)for(let t of e)t();this.watches.clear()}handleWatchControl(e){e.type===`vfs-watch`?this.handleWatch(e):this.handleUnwatch(e)}handleWatch(e){this.dropWatch(e.subscriptionId);let t=this.getWatcher?.()??null;if(!t){this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!1,error:{code:`ENOSYS`,message:`vfs-rpc-host has no watcher wired`}});return}let n=e.basePaths.map(n=>t.watch(n,()=>!0,t=>{if(!this.watches.has(e.subscriptionId))return;let n={type:`vfs-watch-event`,subscriptionId:e.subscriptionId,events:t.map(e=>({type:e.type,path:e.path,...e.entryType?{entryType:e.entryType}:{}}))};this.transport.send(n)}));this.watches.set(e.subscriptionId,n),this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!0})}handleUnwatch(e){this.dropWatch(e.subscriptionId)}dropWatch(e){let t=this.watches.get(e);if(t){this.watches.delete(e);for(let e of t)e()}}sendWatchAck(e){this.transport.send(e)}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=e.includeStats===!0?await this.client.readDir(e.path,{includeStats:!0}):await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{if(t===`binary`&&Number.isInteger(e.start)){let t=await this.readFileWindow(e.path,e.start,e.end);this.sendBinaryReadResult(e.requestId,e.path,t);return}let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`)this.sendBinaryReadResult(e.requestId,e.path,n);else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new g(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async readFileWindow(e,t,n){let r=n??(await this.client.stat(e)).size;if(this.client.readFileRange)return this.client.readFileRange(e,t,r);let i=await this.client.readFile(e,{encoding:`binary`});if(!(i instanceof Uint8Array))throw new g(`EIO`,`readFile(binary) did not return Uint8Array`,e);return new Uint8Array(i.subarray(t,Math.min(r,i.byteLength)))}sendBinaryReadResult(e,t,n){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e,new g(`EIO`,`readFile(binary) did not return Uint8Array`),t);return}let r={type:`vfs-read-file-result`,requestId:e,ok:!0,encoding:`binary`,data:n},i=n.buffer,a=typeof ArrayBuffer<`u`&&i instanceof ArrayBuffer?[i]:void 0;this.transport.send(r,a)}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(iq(e.type),e.requestId,new g(`EACCES`,`vfs-rpc-host has no writable backend wired`),aq(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new g(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new g(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new g(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=oq(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=oq(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function eq(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function tq(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function nq(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function rq(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function iq(e){switch(e){case`vfs-write-file`:return`vfs-write-file-result`;case`vfs-mkdir`:return`vfs-mkdir-result`;case`vfs-rm`:return`vfs-rm-result`;case`vfs-flush`:return`vfs-flush-result`;case`vfs-list-mount-points`:return`vfs-list-mount-points-result`}}function aq(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function oq(e,t){return e instanceof g?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function sq(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=sK(e.bind(globalThis),t,cq)}function cq(){let e=Re();if(!e)return null;try{return new URL(e).origin}catch{return null}}function lq(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let uq=null,dq=null,fq=null,pq=null,mq=null,hq=null;const gq=fK(e=>yq(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&gq.handle(e.data)});function _q(e){let t=na(e.pageBuildId,`6.256.20-mvu1ba38`);return()=>{t&&IK(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.256.20-mvu1ba38`)}}function vq(e){sq(),Le(e.localApiBaseUrl??null),Ie(e.bridgeToken??null),_r(e.syncFsBridgeEnabled??!1),ne(e.pageLoadedAt??null),Ve(e.extensionDelegateId??null),lq(e.localStorageSeed??{}),e.flagFloat&&Ui(e.flagFloat)}async function yq(e){$i(e.instanceId),ia(e.instanceId);let t=_q(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{vq(e),PK().then(t).catch(()=>{}),await Pe(),n(`providers-registered`);let r=ca(e.kernelPort),i=new RP(r),a=RP.createCallbacks(i),o=new la(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new ji(o);uq=await rK({container:{},browser:s,bridge:i,callbacks:a,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,appPageUrl:e.appPageUrl??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-DfDodb7e.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=uq.sharedFs?.getWatcher();if(u){let e=null,t=/* @__PURE__ */ new Set;for(let n of kr)u.watch(n,e=>e.endsWith(`.shtml`),n=>{for(let e of n){let n=e.path.split(`/`).pop()?.replace(/\.shtml$/,``);n&&t.add(n)}e||=setTimeout(()=>{e=null;for(let e of t)l.reload(e).catch(()=>{});t.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-BJU93e51.js`).then(e=>e.r);hq=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=hq,s.setTrayTargetProvider(Bi(Oe));let f=await xq({host:uq,transport:r,browser:s,instanceId:e.instanceId});f&&(dq=f.stopTerminalHost,fq=f.stopVfsRpcHost,pq=f.stopSpeechAssetsResponder,mq=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){bq(e.kernelPort,t)}}function bq(e,t){ta(t);try{let n=t instanceof Error?t.message:String(t),r=t?.code;e.postMessage({type:`kernel-worker-boot-error`,message:n,...typeof r==`string`?{code:r}:{},...t instanceof Error&&t.stack?{stack:t.stack}:{}})}catch{}throw t}async function xq(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=()=>e.host.capabilityBroker.adapter===`node-rest`,r=xK({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),webhook:{hasLocalNodeServer:n},crontask:{hasLocalNodeServer:n},logger:console}),i=QK({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await Sq(t,e.instanceId),{startComputersHost:o}=await import(`./host-CJm3lA1s.js`),s=o({transport:e.transport,processManager:e.host.processManager});return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a,stopComputersHost:s.stop}}async function Sq(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DiGbVO32.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-D8hUeIiK.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-1DfC_94U.js`).then(e=>e.o),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{if(e.data?.type!==`kernel-worker-drain`)return;let t=e.ports[0];(uq?uq.orchestrator.flushConversations():Promise.resolve(!1)).catch(()=>!1).then(e=>t?.postMessage({type:`kernel-worker-drained`,ok:e}))}),self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(dq?.(),dq=null,fq?.(),fq=null,pq?.(),pq=null,mq?.(),mq=null,hq?.dispose(),hq=null,uq?.dispose())});export{mP as a,oM as c,RA as d,aa as f,Fr as h,pP as i,wj as l,ri as m,VV as n,SN as o,ni as p,YR as r,Hj as s,JH as t,QA as u};
|
|
1281
|
+
`).trim();return e?e.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`):null}return t.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`)}const WK=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`),GK=[[/(\/|%2F)(join|controller)(\/|%2F)[^/?#&"\s\\]+/gi,`$1$2$3redacted`],[/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[0-9a-f]{16,}/gi,`redacted`],[/\b[0-9a-f]{32}--[0-9a-f]{16,}\b/gi,`redacted`]];function KK(e){let t=e;for(let[e,n]of GK)t=t.replace(e,n);return t}function qK(e){let t=typeof e==`string`?e:CK(e)??SK(e);if(typeof t!=`string`)return{kind:`absent`};let n=wK(t);if(n===`[object Object]`)return{kind:`noise`};let r=UK(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function JK(e){let t=qK(e.source),n=qK(e.target),r=t.kind!==`kept`,i=n.kind!==`kept`;if((t.kind!==`absent`||n.kind!==`absent`)&&r&&i||n.kind===`noise`&&e.source===`undefined error`)return!0;let a=!1;return t.kind===`kept`?t.mutated&&(e.source=t.value,a=!0):t.kind===`noise`&&(e.source=``,a=!0),n.kind===`kept`?n.mutated&&(e.target=n.value,a=!0):n.kind===`noise`&&(e.target=``,a=!0),a?JSON.stringify(e):null}function YK(e){try{if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(e)}catch{}return null}function XK(e){if(e.charCodeAt(0)!==123)return null;try{let t=JSON.parse(e);return t?.checkpoint===`error`?JK(t):null}catch{return null}}function ZK(e){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let t=navigator.sendBeacon;if(t[WK])return;let n=t.bind(navigator),r=((t,r)=>{let i=YK(r);if(i===null)return n(t,r);let a=KK(i);if(e.filterViteNoise){let e=XK(a);if(e===!0)return!0;if(e!==null)return n(t,e)}return n(t,a===i?r:a)});r[WK]=!0,navigator.sendBeacon=r}function QK(e){let t=new $K(e);return t.start(),{stop:()=>t.dispose()}}var $K=class{transport;client;writableClient;getWatcher;log;unsubscribe=null;watches=/* @__PURE__ */ new Map;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.getWatcher=e.getWatcher??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!eq(e)||e.source!==`panel`)return;let t=e.payload;if(tq(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(nq(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(rq(t)){this.handleWatchControl(t);return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.watches)for(let t of e)t();this.watches.clear()}handleWatchControl(e){e.type===`vfs-watch`?this.handleWatch(e):this.handleUnwatch(e)}handleWatch(e){this.dropWatch(e.subscriptionId);let t=this.getWatcher?.()??null;if(!t){this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!1,error:{code:`ENOSYS`,message:`vfs-rpc-host has no watcher wired`}});return}let n=e.basePaths.map(n=>t.watch(n,()=>!0,t=>{if(!this.watches.has(e.subscriptionId))return;let n={type:`vfs-watch-event`,subscriptionId:e.subscriptionId,events:t.map(e=>({type:e.type,path:e.path,...e.entryType?{entryType:e.entryType}:{}}))};this.transport.send(n)}));this.watches.set(e.subscriptionId,n),this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!0})}handleUnwatch(e){this.dropWatch(e.subscriptionId)}dropWatch(e){let t=this.watches.get(e);if(t){this.watches.delete(e);for(let e of t)e()}}sendWatchAck(e){this.transport.send(e)}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=e.includeStats===!0?await this.client.readDir(e.path,{includeStats:!0}):await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{if(t===`binary`&&Number.isInteger(e.start)){let t=await this.readFileWindow(e.path,e.start,e.end);this.sendBinaryReadResult(e.requestId,e.path,t);return}let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`)this.sendBinaryReadResult(e.requestId,e.path,n);else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new g(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async readFileWindow(e,t,n){let r=n??(await this.client.stat(e)).size;if(this.client.readFileRange)return this.client.readFileRange(e,t,r);let i=await this.client.readFile(e,{encoding:`binary`});if(!(i instanceof Uint8Array))throw new g(`EIO`,`readFile(binary) did not return Uint8Array`,e);return new Uint8Array(i.subarray(t,Math.min(r,i.byteLength)))}sendBinaryReadResult(e,t,n){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e,new g(`EIO`,`readFile(binary) did not return Uint8Array`),t);return}let r={type:`vfs-read-file-result`,requestId:e,ok:!0,encoding:`binary`,data:n},i=n.buffer,a=typeof ArrayBuffer<`u`&&i instanceof ArrayBuffer?[i]:void 0;this.transport.send(r,a)}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(iq(e.type),e.requestId,new g(`EACCES`,`vfs-rpc-host has no writable backend wired`),aq(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new g(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new g(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new g(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=oq(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=oq(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function eq(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function tq(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function nq(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function rq(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function iq(e){switch(e){case`vfs-write-file`:return`vfs-write-file-result`;case`vfs-mkdir`:return`vfs-mkdir-result`;case`vfs-rm`:return`vfs-rm-result`;case`vfs-flush`:return`vfs-flush-result`;case`vfs-list-mount-points`:return`vfs-list-mount-points-result`}}function aq(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function oq(e,t){return e instanceof g?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function sq(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=sK(e.bind(globalThis),t,cq)}function cq(){let e=Re();if(!e)return null;try{return new URL(e).origin}catch{return null}}function lq(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let uq=null,dq=null,fq=null,pq=null,mq=null,hq=null;const gq=fK(e=>yq(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&gq.handle(e.data)});function _q(e){let t=na(e.pageBuildId,`6.256.21-mvu6vi8j`);return()=>{t&&IK(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.256.21-mvu6vi8j`)}}function vq(e){sq(),Le(e.localApiBaseUrl??null),Ie(e.bridgeToken??null),_r(e.syncFsBridgeEnabled??!1),ne(e.pageLoadedAt??null),Ve(e.extensionDelegateId??null),lq(e.localStorageSeed??{}),e.flagFloat&&Ui(e.flagFloat)}async function yq(e){$i(e.instanceId),ia(e.instanceId);let t=_q(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{vq(e),PK().then(t).catch(()=>{}),await Pe(),n(`providers-registered`);let r=ca(e.kernelPort),i=new RP(r),a=RP.createCallbacks(i),o=new la(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new ji(o);uq=await rK({container:{},browser:s,bridge:i,callbacks:a,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,appPageUrl:e.appPageUrl??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-DfDodb7e.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=uq.sharedFs?.getWatcher();if(u){let e=null,t=/* @__PURE__ */ new Set;for(let n of kr)u.watch(n,e=>e.endsWith(`.shtml`),n=>{for(let e of n){let n=e.path.split(`/`).pop()?.replace(/\.shtml$/,``);n&&t.add(n)}e||=setTimeout(()=>{e=null;for(let e of t)l.reload(e).catch(()=>{});t.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-BJU93e51.js`).then(e=>e.r);hq=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=hq,s.setTrayTargetProvider(Bi(Oe));let f=await xq({host:uq,transport:r,browser:s,instanceId:e.instanceId});f&&(dq=f.stopTerminalHost,fq=f.stopVfsRpcHost,pq=f.stopSpeechAssetsResponder,mq=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){bq(e.kernelPort,t)}}function bq(e,t){ta(t);try{let n=t instanceof Error?t.message:String(t),r=t?.code;e.postMessage({type:`kernel-worker-boot-error`,message:n,...typeof r==`string`?{code:r}:{},...t instanceof Error&&t.stack?{stack:t.stack}:{}})}catch{}throw t}async function xq(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=()=>e.host.capabilityBroker.adapter===`node-rest`,r=xK({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),webhook:{hasLocalNodeServer:n},crontask:{hasLocalNodeServer:n},logger:console}),i=QK({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await Sq(t,e.instanceId),{startComputersHost:o}=await import(`./host-CJm3lA1s.js`),s=o({transport:e.transport,processManager:e.host.processManager});return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a,stopComputersHost:s.stop}}async function Sq(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DiGbVO32.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-D8hUeIiK.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-1DfC_94U.js`).then(e=>e.o),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{if(e.data?.type!==`kernel-worker-drain`)return;let t=e.ports[0];(uq?uq.orchestrator.flushConversations():Promise.resolve(!1)).catch(()=>!1).then(e=>t?.postMessage({type:`kernel-worker-drained`,ok:e}))}),self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(dq?.(),dq=null,fq?.(),fq=null,pq?.(),pq=null,mq?.(),mq=null,hq?.dispose(),hq=null,uq?.dispose())});export{mP as a,oM as c,RA as d,aa as f,Fr as h,pP as i,wj as l,ri as m,VV as n,SN as o,ni as p,YR as r,Hj as s,JH as t,QA as u};
|