sliccy 6.165.0 → 6.166.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node-server/_shared/computer-protocol.d.ts +108 -0
- package/dist/node-server/_shared/computer-protocol.d.ts.map +1 -0
- package/dist/node-server/_shared/computer-protocol.js +10 -0
- package/dist/node-server/_shared/computer-protocol.js.map +1 -0
- package/dist/node-server/_shared/index.d.ts +1 -0
- package/dist/node-server/_shared/index.d.ts.map +1 -1
- package/dist/node-server/_shared/index.js +1 -0
- package/dist/node-server/_shared/index.js.map +1 -1
- package/dist/ui/.vite/manifest.json +184 -174
- package/dist/ui/assets/{SKILL-C8DJkgFD.js → SKILL-BGEZa-y0.js} +1 -1
- package/dist/ui/assets/SKILL-DB5CVwyu.js +1 -0
- package/dist/ui/assets/SKILL-DEFDsScb.js +1 -0
- package/dist/ui/assets/{SKILL-0AeLgxT3.js → SKILL-DZoCcID_.js} +1 -1
- package/dist/ui/assets/{account-store-lzZlhljv.js → account-store-BEqmysw9.js} +1 -1
- package/dist/ui/assets/{account-store-CJHBoL7P.js → account-store-C35GYvum.js} +1 -1
- package/dist/ui/assets/{adobe-DbBJWbF9.js → adobe-BDH5oLAN.js} +1 -1
- package/dist/ui/assets/{adobe-DUaaJHme.js → adobe-BcTGFCnQ.js} +1 -1
- package/dist/ui/assets/{agent-panels-DQh4wRpa.js → agent-panels-DvqNnkLk.js} +1 -1
- package/dist/ui/assets/{almost-bash-shell-headless-DdfO5taA.js → almost-bash-shell-headless-DqTtE9CM.js} +506 -508
- package/dist/ui/assets/{apply-layout-DeIHdw5o.js → apply-layout-CjYRGs37.js} +1 -1
- package/dist/ui/assets/{apps-X6cH7Ngi.js → apps-dzoLZ_5W.js} +1 -1
- package/dist/ui/assets/{azure-openai-DS5DA5ql.js → azure-openai-BffwoCtp.js} +1 -1
- package/dist/ui/assets/{azure-openai-DoDPxnFq.js → azure-openai-DKGdcr4S.js} +1 -1
- package/dist/ui/assets/{backend-hostfs-9Xwjq8kU.js → backend-hostfs-CWIlIhve.js} +1 -1
- package/dist/ui/assets/bridge-protocol-31SWTdS5.js +1 -0
- package/dist/ui/assets/{cdp-Bi4OGeyp.js → cdp-DXT6yEL1.js} +1 -1
- package/dist/ui/assets/{cerebras-D9Xp_f8D.js → cerebras-BF5efkRL.js} +1 -1
- package/dist/ui/assets/{cerebras-BzQeaK2Z.js → cerebras-By0l7t0i.js} +1 -1
- package/dist/ui/assets/{composer-speech-BVpldTNH.js → composer-speech-DIEePbQC.js} +1 -1
- package/dist/ui/assets/{connect-surface-CyUMMhhU.js → connect-surface-DBqs7oHf.js} +1 -1
- package/dist/ui/assets/{directed-approval-CaEocD9T.js → directed-approval-D1lGElvD.js} +1 -1
- package/dist/ui/assets/{ensure-speech-assets-B9REkBI_.js → ensure-speech-assets-BJXemBO4.js} +1 -1
- package/dist/ui/assets/fake-computer-1f2_4vxY.js +65 -0
- package/dist/ui/assets/{frozen-archive-writer-BWuT2QtJ.js → frozen-archive-writer-DYPhPMg7.js} +1 -1
- package/dist/ui/assets/{fs-C3QG5M_q.js → fs-BapOupIM.js} +2 -2
- package/dist/ui/assets/{fs-CmCsE1zE.js → fs-CBH-hQcI.js} +1 -1
- package/dist/ui/assets/{gelatiere-store-ijXRupBc.js → gelatiere-store-C2u47uk0.js} +1 -1
- package/dist/ui/assets/{gelatiere-unit-BlRXo_Ch.js → gelatiere-unit-wvDEO7gH.js} +1 -1
- package/dist/ui/assets/{github-2vLuAY6J.js → github-Bx7_6LBm.js} +2 -2
- package/dist/ui/assets/{github-Zcx-gHTn.js → github-Db015Tee.js} +1 -1
- package/dist/ui/assets/{github-auth-87ZWWpe-.js → github-auth-DtKS6UIX.js} +1 -1
- package/dist/ui/assets/{github-copilot-DaHQ2cTA.js → github-copilot-CtOjxhqK.js} +1 -1
- package/dist/ui/assets/{github-copilot-CdwPARvl.js → github-copilot-eCfmryv6.js} +1 -1
- package/dist/ui/assets/{github-install-CCQJ7A9f.js → github-install-B6W4-xcc.js} +1 -1
- package/dist/ui/assets/{github-zip-D4jSHksq.js → github-zip-Bv1smNmy.js} +1 -1
- package/dist/ui/assets/{handoff-link-NCw3cxSG.js → handoff-link-B3It6xQY.js} +1 -1
- package/dist/ui/assets/{hear-CovWNOND.js → hear-BZHckZJM.js} +1 -1
- package/dist/ui/assets/{help-BmMJZSmm.js → help-BU2Hjl0P.js} +1 -1
- package/dist/ui/assets/host-BQ2qKD-D.js +1 -0
- package/dist/ui/assets/{installer-BOAaojqu.js → installer-BbtH3u7z.js} +1 -1
- package/dist/ui/assets/js-realm-worker-BT3mfq3w.js +50 -0
- package/dist/ui/assets/jsh-CrSWPG4t.js +1 -0
- package/dist/ui/assets/jsh-executor-BWlgcE2N.js +18 -0
- package/dist/ui/assets/jsh-runtime-extensions-BnLXkzqP.js +1 -0
- package/dist/ui/assets/{kernel-worker-CrTnmx6N.js → kernel-worker-Dseu067f.js} +38 -38
- package/dist/ui/assets/keys-n5_C9sHW.js +1 -0
- package/dist/ui/assets/{lick-ws-bridge-56mwSRdV.js → lick-ws-bridge-Cc9sToY7.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-D4FyZHWP.js → lick-ws-bridge-ChigxI36.js} +1 -1
- package/dist/ui/assets/{live-session-snapshot-ZXxxxzvO.js → live-session-snapshot-B70raB09.js} +1 -1
- package/dist/ui/assets/{local-llm-B6tgSQ84.js → local-llm-Dcp5IIP-.js} +1 -1
- package/dist/ui/assets/{local-llm-BDbJaGUp.js → local-llm-DpSg-Oe3.js} +1 -1
- package/dist/ui/assets/{main-Dxem3Ydy.js → main-CfF8CFBr.js} +3 -3
- package/dist/ui/assets/{main-cherry-D1lfDTVL.js → main-cherry-VckJPHm5.js} +1 -1
- package/dist/ui/assets/{memory-curation-seam-ZGh8tSbe.js → memory-curation-seam-DUaZFZG9.js} +1 -1
- package/dist/ui/assets/{memory-health-CZHaK5wO.js → memory-health-D7uEvfAx.js} +1 -1
- package/dist/ui/assets/memory-v2-flag-BHVbti6Z.js +1 -0
- package/dist/ui/assets/{memory-write-execute-Csx1-nfE.js → memory-write-execute-rXtR1z76.js} +1 -1
- package/dist/ui/assets/{mount-DCCYSZwW.js → mount-8lU2iH4k.js} +3 -3
- package/dist/ui/assets/{mount-ByktCqqU.js → mount-DoM0CLGG.js} +1 -1
- package/dist/ui/assets/{new-session-CG_ht0Kw.js → new-session-DEhAjxP1.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-CQmrSZN1.js → oauth-bootstrap-DNTgbEZF.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-DZFSsW4q.js → onboarding-orchestrator-DzPQ0pVG.js} +1 -1
- package/dist/ui/assets/{openai-codex-dKSgjDc_.js → openai-codex-CsAhfz0D.js} +1 -1
- package/dist/ui/assets/{openai-codex-ebHt4iSf.js → openai-codex-DYRKYWTe.js} +1 -1
- package/dist/ui/assets/{openrouter-CsPQehN8.js → openrouter-D9T6tXUF.js} +1 -1
- package/dist/ui/assets/{openrouter-BQhA4-TP.js → openrouter-IyZlRHg4.js} +1 -1
- package/dist/ui/assets/{openrouter-free-kxAwjRgT.js → openrouter-free-CPshAgQD.js} +1 -1
- package/dist/ui/assets/{openrouter-free-BppbTow1.js → openrouter-free-DfbYsnmf.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-D0vfD1T8.js → openrouter-oauth-hZg6oH0A.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-B3y32yAJ.js → openrouter-oauth-xKlWi_wI.js} +1 -1
- package/dist/ui/assets/{opfs-mount-ld8qlksz.js → opfs-mount-C9Iamj6N.js} +1 -1
- package/dist/ui/assets/panel-rpc-handlers-Nu-wOrG9.js +2 -0
- package/dist/ui/assets/{panelize-shell-BdV-wKTx.js → panelize-shell-tFElgHWF.js} +1 -1
- package/dist/ui/assets/{pi-edit-execution-CoRFZcs7.js → pi-edit-execution-D6vx5LyF.js} +1 -1
- package/dist/ui/assets/{provider-CNKZIWc1.js → provider-3--cEcAF.js} +1 -1
- package/dist/ui/assets/{provider-DE1pR-oR.js → provider-Z5aj7SzG.js} +2 -2
- package/dist/ui/assets/{provider-settings-D8qwiWrG.js → provider-settings-D9sjEfYE.js} +1 -1
- package/dist/ui/assets/provider-store-access-M0PvJ08M.js +1 -0
- package/dist/ui/assets/provider-store-access-RxIHhH6d.js +1 -0
- package/dist/ui/assets/{providers-InF4o-U9.js → providers-CnoKdyLc.js} +2 -2
- package/dist/ui/assets/{providers-CUF9nsUE.js → providers-DVvrXbtx.js} +1 -1
- package/dist/ui/assets/{quick-llm-CQWR6xvc.js → quick-llm-DjWE-wQw.js} +1 -1
- package/dist/ui/assets/realm-inprocess-D0iWBQzz.js +30 -0
- package/dist/ui/assets/{recovery-screen-DWMb8zIg.js → recovery-screen-Y1CSyfR-.js} +1 -1
- package/dist/ui/assets/registry-Bq_j-EXx.js +1 -0
- package/dist/ui/assets/{restore-PqiSHlx3.js → restore-DOkDX8BI.js} +1 -1
- package/dist/ui/assets/{run-F7Bv3Fcu.js → run-B-fA26ea.js} +1 -1
- package/dist/ui/assets/run-BEt0RS3J.js +52 -0
- package/dist/ui/assets/{run-DJQAmghw.js → run-BOc9XLhg.js} +1 -1
- package/dist/ui/assets/{run-Bqg_NW7f.js → run-BWJSDhS7.js} +2 -2
- package/dist/ui/assets/{run-Do5pAlQf.js → run-DgNh1E56.js} +2 -2
- package/dist/ui/assets/{run-DoD-L3x8.js → run-a67LpkRp.js} +2 -2
- package/dist/ui/assets/{run-w1tdYqAg.js → run-vEDh-Me-.js} +2 -2
- package/dist/ui/assets/{session-command-memory-BKzFoCAZ.js → session-command-memory-DB2GmPSU.js} +2 -2
- package/dist/ui/assets/{session-jsonl-DjDV9zx6.js → session-jsonl-DFC-2T76.js} +1 -1
- package/dist/ui/assets/{session-jsonl-C7a0swa5.js → session-jsonl-D_pTYppB.js} +1 -1
- package/dist/ui/assets/{session-search-index-CMRSS2CP.js → session-search-index-CN1zDLlx.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-BmKhybEI.js → setup-feature-flags-remote-BVd31Z12.js} +1 -1
- package/dist/ui/assets/{signed-fetch-DDtJ0TE5.js → signed-fetch-BY2Mdjqe.js} +1 -1
- package/dist/ui/assets/{silent-renew-backoff-CBUhiIba.js → silent-renew-backoff-CKAAh6GN.js} +1 -1
- package/dist/ui/assets/{silent-renew-backoff-DIMz5UqB.js → silent-renew-backoff-Dmz3DJHb.js} +1 -1
- package/dist/ui/assets/slicc-version-BZyTvfoc.js +1 -0
- package/dist/ui/assets/{snapshot-features-BIG7eB0k.js → snapshot-features-DjMJkCGq.js} +1 -1
- package/dist/ui/assets/{snapshot-DyCo7e-C.js → snapshot-gi8tDzvN.js} +1 -1
- package/dist/ui/assets/{soundscape-bHynTI4A.js → soundscape-Bl3LhUk9.js} +1 -1
- package/dist/ui/assets/{speak-DbL0fEQT.js → speak-BY_fDou2.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-Bhwou11b.js → sprinkle-manager-C-NUJqPy.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-CEIEQSMS.js → sprinkle-renderer-CcA6ie5u.js} +1 -1
- package/dist/ui/assets/{state-BdNtTsoR.js → state-z3wOHLww.js} +1 -1
- package/dist/ui/assets/{store-CJD-1zaX.js → store-ByUcAFUa.js} +1 -1
- package/dist/ui/assets/{store-BRXCCWDC.js → store-ChWzn_H8.js} +1 -1
- package/dist/ui/assets/{sudo-QHJEgCZR.js → sudo-DNZFIZ-H.js} +1 -1
- package/dist/ui/assets/{supervisor-DILjXQCB.js → supervisor-BtH2-9sE.js} +1 -1
- package/dist/ui/assets/{sync-dialog-8D9LiBVV.js → sync-dialog-Jqz74VkZ.js} +1 -1
- package/dist/ui/assets/tab-ToMhjbM4.js +1 -0
- package/dist/ui/assets/{transformers-env-jBVeNAIF.js → transformers-env-pq1E2H6B.js} +1 -1
- package/dist/ui/assets/{tray-leader-BxfP0EC1.js → tray-leader-Bas0lH9O.js} +1 -1
- package/dist/ui/assets/{tray-leave-runtime-1j0s9Yqq.js → tray-leave-runtime-B9aV_guA.js} +1 -1
- package/dist/ui/assets/tray-runtime-config-BZoJXfW0.js +1 -0
- package/dist/ui/assets/{tray-sidecar-BUsex5hw.js → tray-sidecar-DA8NfCV6.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-DCwNWWGX.js → upgrade-detection-B5ym__Gu.js} +1 -1
- package/dist/ui/assets/{upskill-lick-skip-C9u8AmfA.js → upskill-lick-skip-CZGM2OFA.js} +1 -1
- package/dist/ui/assets/v86-DseFx8Yp.js +1 -0
- package/dist/ui/assets/v86-vm-DCm7zA2r.js +2 -0
- package/dist/ui/assets/{voice-reply-CgvrHu7l.js → voice-reply-CL5tDo0l.js} +1 -1
- package/dist/ui/assets/{wc-attach-CJV3boxa.js → wc-attach-C5yXIQNU.js} +2 -2
- package/dist/ui/assets/{wc-detached-BZT3Rtc5.js → wc-detached-f_qit-5b.js} +1 -1
- package/dist/ui/assets/{wc-extension-CZ1sQn79.js → wc-extension-DRx21-cq.js} +2 -2
- package/dist/ui/assets/{wc-follower-DO4HcEvu.js → wc-follower-DcKt92kM.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-CEpYsbPr.js → wc-follower-oauth-BF3qXDTt.js} +1 -1
- package/dist/ui/assets/{wc-gelatiere-C4XI_usG.js → wc-gelatiere-qAW7lWGW.js} +1 -1
- package/dist/ui/assets/{wc-live-Dz2OSXcJ.js → wc-live-DOMCfDT6.js} +6 -6
- package/dist/ui/assets/{wc-nav-ClJyDfXq.js → wc-nav-DzPuXq_n.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-BUUyiqjJ.js → wc-onboarding-CXM-z-7_.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-Sji0t7ST.js → wc-placeholder-BBqbsuml.js} +3 -3
- package/dist/ui/assets/{wc-secret-request-IsuAxr4v.js → wc-secret-request-BSUlxVVi.js} +1 -1
- package/dist/ui/assets/{wc-settings-lgNdcEqb.js → wc-settings-55mC-jVS.js} +3 -3
- package/dist/ui/assets/{wc-shell-Cj705NBI.js → wc-shell-C71iKreG.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-ByZ7W9gP.js → wc-shortcut-config-Crjq_rF1.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-D7Cv7m3r.js → wc-sprinkles-Caji5y7n.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-IV61nDvZ.js → wc-transcript-export-Dqe3SH1t.js} +2 -2
- package/dist/ui/assets/{wc-tray-XTl0wqt5.js → wc-tray-B7ayzT1W.js} +4 -4
- package/dist/ui/assets/welcome-detection-CEARSpAq.js +1 -0
- package/dist/ui/assets/{whisper-session-FGrrhHcr.js → whisper-session-DfILe4Yb.js} +2 -2
- package/dist/ui/assets/{xai-grok-BdK9whs2.js → xai-grok-CVLBrxdD.js} +1 -1
- package/dist/ui/assets/{xai-grok-Z7FTSyzw.js → xai-grok-Dp8n52fO.js} +1 -1
- package/dist/ui/index.html +3 -3
- package/dist/ui/packages/webapp/index.html +3 -3
- package/package.json +1 -1
- package/dist/ui/assets/SKILL-CtxHowg1.js +0 -96
- package/dist/ui/assets/bridge-protocol-DdqxTTSu.js +0 -1
- package/dist/ui/assets/js-realm-worker-Dfep1BlZ.js +0 -50
- package/dist/ui/assets/jsh-executor-D4Y05hfn.js +0 -18
- package/dist/ui/assets/jsh-runtime-extensions-Bcb8_nba.js +0 -1
- package/dist/ui/assets/memory-v2-flag-BkWGkfSv.js +0 -1
- package/dist/ui/assets/panel-rpc-handlers-DpxMB-do.js +0 -2
- package/dist/ui/assets/provider-store-access-BCysAaQ-.js +0 -1
- package/dist/ui/assets/provider-store-access-D-QWySrs.js +0 -1
- package/dist/ui/assets/realm-inprocess-BdTkrnDI.js +0 -30
- package/dist/ui/assets/slicc-version-Cu6HjDRg.js +0 -1
- package/dist/ui/assets/tray-runtime-config-CRZxBChd.js +0 -1
- package/dist/ui/assets/welcome-detection-B6Zr7LKu.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{C as t,S as n,_ as r,a as i,b as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,o as p,p as m,r as h,s as g,t as _,v as ee,w as te,x as v,y as ne}from"./almost-bash-shell-headless-DdfO5taA.js";import{t as y}from"./logger-LESFN7Hj.js";import{o as re}from"./snapshot-DyCo7e-C.js";import{n as ie,t as ae}from"./panel-rpc-BPwAqRch.js";import{a as oe,t as se}from"./providers-CUF9nsUE.js";import{r as ce,t as le}from"./base64-DzRgusa4.js";import{i as ue,r as de}from"./handoff-link-NCw3cxSG.js";import{a as fe,b as pe,f as me,g as he,h as ge,i as _e,m as ve,p as ye,v as be,x as xe,y as Se}from"./account-store-lzZlhljv.js";import{n as Ce}from"./proxied-fetch-DEK8DT-z.js";import{t as we}from"./slugify-BYJ6QVAt.js";import{i as Te,n as Ee,t as De}from"./archive-redaction-ByV7X5fs.js";import{a as Oe,l as ke,o as Ae,s as je,t as Me,u as Ne}from"./api-endpoint-3qEcn7BY.js";import{$ as Pe,A as Fe,At as Ie,B as Le,C as Re,Ct as ze,D as Be,Dt as b,E as Ve,Et as He,F as Ue,H as We,I as Ge,J as Ke,K as qe,L as Je,M as Ye,Mt as x,N as Xe,Nt as Ze,O as Qe,Ot as $e,P as et,Q as tt,R as nt,St as rt,T as it,Tt as S,U as at,V as ot,W as st,X as ct,Y as lt,Z as ut,_ as dt,_t as ft,a as pt,at as C,b as mt,bt as ht,c as gt,ct as w,d as _t,dt as vt,et as yt,f as bt,ft as xt,g as St,gt as Ct,h as wt,ht as Tt,i as Et,it as Dt,j as Ot,jt as kt,k as At,kt as T,l as jt,lt as Mt,m as Nt,mt as Pt,n as Ft,nt as It,o as Lt,ot as Rt,p as zt,pt as E,q as Bt,r as Vt,rt as D,s as Ht,st as O,t as Ut,tt as Wt,u as Gt,ut as Kt,v as qt,vt as Jt,w as Yt,wt as k,x as Xt,xt as Zt,y as Qt,yt as $t,z as en}from"./build-BRNa03GH.js";import{a as tn}from"./models-4WTk3EBD.js";import{o as nn,t as rn}from"./compat-uEPf6-XW.js";import{c as an,o as on,t as sn,u as cn}from"./core-DP-MJcag.js";import{i as ln,n as un,r as dn,t as fn}from"./context-compaction-DRymamfD.js";import{t as pn}from"./secrets-bridge-client-ZpBL1Zhl.js";import{n as mn,t as hn}from"./image-markers-DuyWsic3.js";import{a as gn,n as _n,t as vn}from"./path-utils-DNJG-zQf.js";import{t as yn}from"./merge-file-core-VJlzucJY.js";import{i as bn,n as xn,r as Sn,t as Cn}from"./workspace-mode-D0kUKBVS.js";import{C as wn,D as Tn,E as A,S as En,T as Dn,_ as On,a as kn,c as An,d as jn,f as Mn,g as Nn,h as Pn,l as Fn,m as In,n as Ln,o as Rn,p as zn,r as Bn,s as Vn,t as Hn,u as Un,v as Wn,w as Gn,y as Kn}from"./record-ChU1ND2B.js";import{a as qn,c as Jn,d as Yn,i as Xn,l as Zn,n as Qn,o as $n,r as er,s as tr,u as nr}from"./descriptor-S4Jug1iP.js";import{n as rr,t as ir}from"./thinking-level-5x0UAu9N.js";import{t as j}from"./types-D8gIX-W-.js";import{i as ar,n as or}from"./mount-index-CQfmUPuZ.js";import{a as sr,i as cr,n as lr,r as ur,s as dr,t as fr}from"./signed-fetch-DDtJ0TE5.js";import{n as pr}from"./mount-table-store-DrF_Ifaz.js";import{t as mr}from"./remote-cache-BE5T1-53.js";import"./mount-ByktCqqU.js";import{i as hr,n as gr,r as _r}from"./fs-CmCsE1zE.js";import{i as vr,n as yr,t as br}from"./key-6HWbWSGF.js";import{a as xr,i as Sr,o as Cr}from"./lick-urls-DdKPDlgq.js";import"./tray-runtime-config-CRZxBChd.js";import{r as wr}from"./slicc-version-Cu6HjDRg.js";import{r as Tr}from"./virtual-device-paths-CS5o4QVz.js";import{a as Er,i as Dr,r as Or}from"./cost-command-BULzLcvz.js";import{_ as kr,a as Ar,c as jr,d as Mr,f as Nr,g as Pr,h as Fr,l as Ir,m as Lr,n as Rr,p as zr,r as Br,s as Vr,t as Hr,u as Ur,v as Wr}from"./sudoers-BdBYQPUn.js";import{n as Gr,r as Kr,t as qr}from"./sudo-fs-D620mZry.js";import{t as Jr}from"./llm-session-id-BZyXP_j2.js";import{t as Yr}from"./buffer-polyfill-BccMjOKj.js";import{a as Xr,i as Zr,n as Qr,o as $r}from"./memory-budget-Bcf7Eolo.js";import{r as ei}from"./browser-2rCVqcqy.js";import{a as ti,i as ni,r as ri,t as ii}from"./jsh-executor-D4Y05hfn.js";import{t as ai}from"./jsh-discovery-D3Gk1cKA.js";import{t as oi}from"./process-manager-BkhAohXT.js";import{C as si,D as ci,E as li,d as ui,h as di,k as fi,u as pi,v as mi,x as hi}from"./sync-sab-wire-CC30v4TL.js";import{n as gi}from"./just-bash-compat-B-SPHuh_.js";import{t as _i}from"./lick-target-env-8JxfVcIV.js";const vi=[`/workspace`,`/shared`,`/scoops`,`/home`];var yi=class{pending=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 bi(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 xi=y(`cdp`);function Si(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 Ci=class{ws=null;nextId=1;_superseded=!1;pending=new yi;listeners=new Map;_state=`disconnected`;stateListeners=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(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,xi.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(xi.error(`Connection failed`,{url:t}),this.cleanup(),i(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(),xi.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),xi.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=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 bi(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;xi.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(xi.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;xi.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,xi.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?xi.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):xi.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Si(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{}}}},wi=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 Ti(e,t){if(e?.aborted)throw new wi(t)}function Ei(e,t){return e?{signal:e,error:()=>new wi(t)}:void 0}function Di(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new wi(n));return}let a=()=>{clearTimeout(o),i(new wi(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Oi(e,t,n){return t?t.aborted?Promise.reject(new wi(n)):new Promise((r,i)=>{let a=()=>i(new wi(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}const ki=y(`har-recorder`);var Ai=class{recordings=new Map;client;fs;eventCleanup=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)}`;Ti(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Ti(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Ti(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:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),ki.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=>{ki.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=>{ki.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 ji(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return ki.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 ki.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=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)),ki.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 ki.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 ji(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){ki.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return ki.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Mi=`(function() {
|
|
1
|
+
import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{C as t,S as n,_ as r,a as i,b as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,o as p,p as m,r as h,s as g,t as _,v as ee,w as te,x as v,y as ne}from"./almost-bash-shell-headless-DqTtE9CM.js";import{t as y}from"./logger-LESFN7Hj.js";import{o as re}from"./snapshot-gi8tDzvN.js";import{n as ie,t as ae}from"./panel-rpc-BPwAqRch.js";import{a as oe,t as se}from"./providers-DVvrXbtx.js";import{r as ce,t as le}from"./base64-DzRgusa4.js";import{i as ue,r as de}from"./handoff-link-B3It6xQY.js";import{a as fe,b as pe,f as me,g as he,h as ge,i as _e,m as ve,p as ye,v as be,x as xe,y as Se}from"./account-store-BEqmysw9.js";import{n as Ce}from"./proxied-fetch-DEK8DT-z.js";import{t as we}from"./slugify-BYJ6QVAt.js";import{i as Te,n as Ee,t as De}from"./archive-redaction-ByV7X5fs.js";import{a as Oe,l as ke,o as Ae,s as je,t as Me,u as Ne}from"./api-endpoint-3qEcn7BY.js";import{$ as Pe,A as Fe,At as Ie,B as Le,C as Re,Ct as ze,D as Be,Dt as b,E as Ve,Et as He,F as Ue,H as We,I as Ge,J as Ke,K as qe,L as Je,M as Ye,Mt as x,N as Xe,Nt as Ze,O as Qe,Ot as $e,P as et,Q as tt,R as nt,St as rt,T as it,Tt as S,U as at,V as ot,W as st,X as ct,Y as lt,Z as ut,_ as dt,_t as ft,a as pt,at as C,b as mt,bt as ht,c as gt,ct as w,d as _t,dt as vt,et as yt,f as bt,ft as xt,g as St,gt as Ct,h as wt,ht as Tt,i as Et,it as Dt,j as Ot,jt as kt,k as At,kt as T,l as jt,lt as Mt,m as Nt,mt as Pt,n as Ft,nt as It,o as Lt,ot as Rt,p as zt,pt as E,q as Bt,r as Vt,rt as D,s as Ht,st as O,t as Ut,tt as Wt,u as Gt,ut as Kt,v as qt,vt as Jt,w as Yt,wt as k,x as Xt,xt as Zt,y as Qt,yt as $t,z as en}from"./build-BRNa03GH.js";import{a as tn}from"./models-4WTk3EBD.js";import{o as nn,t as rn}from"./compat-uEPf6-XW.js";import{c as an,o as on,t as sn,u as cn}from"./core-DP-MJcag.js";import{i as ln,n as un,r as dn,t as fn}from"./context-compaction-DRymamfD.js";import{t as pn}from"./secrets-bridge-client-ZpBL1Zhl.js";import{n as mn,t as hn}from"./image-markers-DuyWsic3.js";import{a as gn,n as _n,t as vn}from"./path-utils-DNJG-zQf.js";import{t as yn}from"./merge-file-core-VJlzucJY.js";import{i as bn,n as xn,r as Sn,t as Cn}from"./workspace-mode-D0kUKBVS.js";import{C as wn,D as Tn,E as A,S as En,T as Dn,_ as On,a as kn,c as An,d as jn,f as Mn,g as Nn,h as Pn,l as Fn,m as In,n as Ln,o as Rn,p as zn,r as Bn,s as Vn,t as Hn,u as Un,v as Wn,w as Gn,y as Kn}from"./record-ChU1ND2B.js";import{a as qn,c as Jn,d as Yn,i as Xn,l as Zn,n as Qn,o as $n,r as er,s as tr,u as nr}from"./descriptor-S4Jug1iP.js";import{n as rr,t as ir}from"./thinking-level-5x0UAu9N.js";import{t as j}from"./types-D8gIX-W-.js";import{i as ar,n as or}from"./mount-index-CQfmUPuZ.js";import{a as sr,i as cr,n as lr,r as ur,s as dr,t as fr}from"./signed-fetch-BY2Mdjqe.js";import{n as pr}from"./mount-table-store-DrF_Ifaz.js";import{t as mr}from"./remote-cache-BE5T1-53.js";import"./mount-DoM0CLGG.js";import{i as hr,n as gr,r as _r}from"./fs-CBH-hQcI.js";import{i as vr,n as yr,t as br}from"./key-6HWbWSGF.js";import{a as xr,i as Sr,o as Cr}from"./lick-urls-DdKPDlgq.js";import"./tray-runtime-config-BZoJXfW0.js";import{r as wr}from"./slicc-version-BZyTvfoc.js";import{r as Tr}from"./virtual-device-paths-CS5o4QVz.js";import{a as Er,i as Dr,r as Or}from"./cost-command-BULzLcvz.js";import{_ as kr,a as Ar,c as jr,d as Mr,f as Nr,g as Pr,h as Fr,l as Ir,m as Lr,n as Rr,p as zr,r as Br,s as Vr,t as Hr,u as Ur,v as Wr}from"./sudoers-BdBYQPUn.js";import{n as Gr,r as Kr,t as qr}from"./sudo-fs-D620mZry.js";import{t as Jr}from"./llm-session-id-BZyXP_j2.js";import{t as Yr}from"./buffer-polyfill-BccMjOKj.js";import{a as Xr,i as Zr,n as Qr,o as $r}from"./memory-budget-Bcf7Eolo.js";import{r as ei}from"./browser-2rCVqcqy.js";import{a as ti,i as ni,r as ri,t as ii}from"./jsh-executor-BWlgcE2N.js";import{t as ai}from"./jsh-discovery-D3Gk1cKA.js";import{t as oi}from"./process-manager-BkhAohXT.js";import{C as si,D as ci,E as li,d as ui,h as di,k as fi,u as pi,v as mi,x as hi}from"./sync-sab-wire-CC30v4TL.js";import{n as gi}from"./just-bash-compat-B-SPHuh_.js";import{t as _i}from"./lick-target-env-8JxfVcIV.js";const vi=[`/workspace`,`/shared`,`/scoops`,`/home`];var yi=class{pending=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 bi(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 xi=y(`cdp`);function Si(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 Ci=class{ws=null;nextId=1;_superseded=!1;pending=new yi;listeners=new Map;_state=`disconnected`;stateListeners=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(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,xi.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(xi.error(`Connection failed`,{url:t}),this.cleanup(),i(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(),xi.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),xi.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=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 bi(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;xi.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(xi.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;xi.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,xi.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?xi.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):xi.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Si(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{}}}},wi=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 Ti(e,t){if(e?.aborted)throw new wi(t)}function Ei(e,t){return e?{signal:e,error:()=>new wi(t)}:void 0}function Di(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new wi(n));return}let a=()=>{clearTimeout(o),i(new wi(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Oi(e,t,n){return t?t.aborted?Promise.reject(new wi(n)):new Promise((r,i)=>{let a=()=>i(new wi(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}const ki=y(`har-recorder`);var Ai=class{recordings=new Map;client;fs;eventCleanup=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)}`;Ti(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Ti(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Ti(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:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),ki.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=>{ki.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=>{ki.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 ji(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return ki.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 ki.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=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)),ki.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 ki.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 ji(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){ki.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return ki.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Mi=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -874,27 +874,27 @@ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{C as t,S as n,_ as r,a
|
|
|
874
874
|
this.scrollIntoView({ block: 'center', inline: 'center' });
|
|
875
875
|
const r = this.getBoundingClientRect();
|
|
876
876
|
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
877
|
-
}`,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 Li(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)Li(n,t)}function Ri(e){let t=e.exceptionDetails;return t?t.exception?.description??t.text:null}function zi(e,t){let n=Ri(e);if(n!==null)throw Error(`${t}: ${n}`);return e.result?.value}function Bi(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 Vi(e){let t=new Map;for(let n of e){let e=typeof n.backendDOMNodeId==`number`?n.backendDOMNodeId:null;if(e===null)continue;let r=n.role,i=n.name,a=typeof r?.value==`string`?r.value.toLowerCase():``,o=typeof i?.value==`string`?i.value:``;if(!a)continue;let s=`${a}|${o}`;t.has(s)||t.set(s,e)}return t}function Hi(e,t){let n=`${e.role.toLowerCase()}|${e.name}`,r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)Hi(n,t)}function Ui(e){let t={role:re(e.role,`unknown`),name:re(e.name)},n=re(e.value);n!==``&&(t.value=n);let r=re(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>Ui(e)).filter(e=>e.role!==`unknown`)),t}const Wi=y(`browser-api`),Gi=[`Session with given id not found`,`Target closed`,`No session with given id`,`No tab attached for sessionId`];var Ki=class extends Error{};function qi(e){let t=e instanceof Error?e.message:String(e);return Gi.some(e=>t.includes(e))}function Ji(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}}function Yi(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var Xi=class{inner;onApplied;onStateChange;constructor(e,t){this.inner=e,this.onApplied=t,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=r===void 0?await this.inner.send(e,t,n):await this.inner.send(e,t,n,r);return n&&this.onApplied(n),i}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)}},Zi=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContexts=new Map;_sessions=new Map;_listenedTransports=new Set;_sessionReplacedSubs=new Map;_appliedSends=new Map;_pinnedTargets=new Map;_tabLocks=new Map;_bridgeLock=Promise.resolve();_bridgeHold=null;_bridgeWaiters=0;_viewportOverrides=new Map;_tabLockStats=new Map;_onSessionChange;_lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;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),Wi.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){Wi.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.frameContexts(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._frameContexts.get(`main:${t}`);if(r)for(let[e,t]of r)t===n&&r.delete(e)};handleExecutionContextsCleared=e=>{let t=this.eventSessionId(e);t&&this._frameContexts.get(`main:${t}`)?.clear()};eventSessionId(e){let t=e.sessionId;return typeof t==`string`?t:this.sessionId}handleDetachedFromTarget=e=>{let t=e.sessionId;if(typeof t==`string`){for(let[e,n]of this._sessions)if(n.sessionId===t){this.forgetSession(e,n);return}}};handleTargetDestroyed=e=>{let t=e.targetId;if(typeof t==`string`){for(let[e,n]of this._sessions)if(e===t||n.remote?.localTargetId===t){this.forgetSession(e,n);return}}};constructor(e){this.client=e??new Ci,this.localClient=this.client,this.addTransportListeners(this.client)}getTransport(){return this.accountedTransportFor(this.client)}getUnderlyingTransport(){return this.client}_accountedTransports=new WeakMap;accountedTransportFor(e){if(e instanceof Xi)return e;let t=this._accountedTransports.get(e);return t||(t=new Xi(e,e=>this.noteApplied(e)),this._accountedTransports.set(e,t)),t}noteApplied(e){this._appliedSends.set(e,(this._appliedSends.get(e)??0)+1)}createHarRecorder(e,t){return new Ai(t,e)}setSessionChangeCallback(e){this._onSessionChange=e}onSessionReplaced(e,t){let n=this._sessionReplacedSubs.get(e);return n||(n=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;Ti(r,`starting a command on tab ${e}`);let i=this.tabCounters(e);i.queueDepth+=1;let a;try{a=await this.acquireTabLock(e,i,r)}catch(e){throw--i.queueDepth,e}let o=this.pinTarget(e);try{return i.acquisitions+=1,await this.runOnTab(e,t,r)}finally{o(),--i.queueDepth,a()}}async runOnTab(e,t,n){try{return await this.attemptOnTab(e,t,n)}catch(r){if(r instanceof Ki||!qi(r))throw r;return Wi.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.reentrantOwner(e),n);Ti(n,`about to run a command on tab ${e}`);let i=r.sessionId,a=this._appliedSends.get(i)??0;try{return await t(r)}catch(t){if(!qi(t))throw t;let n=(this._appliedSends.get(i)??0)-a;if(n===0)throw t;this.invalidateSession(e);let r=t instanceof Error?t.message:String(t);throw Wi.warn(`CDP session reset mid-command — not replaying`,{targetId:e,applied:n,reason:r}),new Ki(`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})`)}}async attachHandle(e,t,n){let r=await this.attachToPageOwned(e,t,n),i=this._sessions.get(e);return new Ii(this,e,r,this.accountedTransportFor(i?.transport??this.client),n)}handleFor(e,t){return new Ii(this,e,t.sessionId,this.accountedTransportFor(t.transport))}getTabLockStats(e){if(e!==void 0)return Ji(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 Ji(t)}tabCounters(e){let t=this._tabLockStats.get(e);return t||(t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0},this._tabLockStats.set(e,t)),t}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){let r=Date.now();try{await Oi(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())}}reentrantOwner(e){let t=this._bridgeHold;if(!(!t||e===null||t.targetId!==e))return t.owner}async runGlobal(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e),targetId:e});try{return await t()}finally{n()}}viewportOverride(e){return this._viewportOverrides.get(e)}recordViewportOverride(e,t){this._viewportOverrides.set(e,t)}frameContexts(e,t){let n=`${t}:${e}`,r=this._frameContexts.get(n);return r||(r=new Map,this._frameContexts.set(n,r)),r}dropFrameContexts(e){this._frameContexts.delete(`main:${e}`),this._frameContexts.delete(`isolated:${e}`)}async reapplyViewportOverride(e,t){let n=this._viewportOverrides.get(e);if(n)try{await this.handleFor(e,t).applyViewportOverride(n)}catch(t){Wi.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){this._lastConnectOptions=e?{...e}:{},await this.client.connect({url:e?.url??Yi(),timeout:e?.timeout,...e?.protocols===void 0?{}:{protocols:e.protocols}}),this.supersededNotified=!1}async reconnectIfNeeded(){await this.ensureConnected(),this.client!==this.localClient&&await this.ensureLocalConnected()}primeConnectOptions(e){this._lastConnectOptions=e?{...e}:{}}setCdpSupersededHandler(e){this.supersededHandler=e}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}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._viewportOverrides.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.reentrantOwner(e))}async attachToPageOwned(e,t,n){let r=await this.acquireBridgeLock({owner:t,targetId:e,counters:this.tabCounters(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}`);Ti(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),Ti(t,`about to enable Page on tray tab ${e}`),await a.send(`Page.enable`,{},o.sessionId),Ti(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(),Ti(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),Ti(t,`about to enable Page on tab ${e}`),await this.localClient.send(`Page.enable`,{},n.sessionId),Ti(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.acquireBridgeLock({owner:this.reentrantOwner(e.targetId),targetId:e.targetId});try{return await this.wakeCaptureLocked(e,t,this._bridgeHold?.owner)}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(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){let e=this._lastConnectOptions;await this.localClient.connect({url:e?.url??Yi(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}if(this.client.state===`disconnected`){let e=this.client;this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.clearSessionsForTransport(e),this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0)}}transportForSession(e){for(let t of this._sessions.values())if(t.sessionId===e)return t.transport;return 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){if(e!==this.localClient&&this._listenedTransports.has(e)){for(let t of this._sessions.values())if(t.transport===e)return;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.values()].some(t=>t.remote?.runtimeId===e.runtimeId&&t.remote.localTargetId===e.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.runtimeId,e.localTargetId))}pruneAppliedSends(){if(this._appliedSends.size<=128)return;let e=new Set([...this._sessions.values()].map(e=>e.sessionId));for(let t of[...this._appliedSends.keys()])e.has(t)||this._appliedSends.delete(t)}rememberSession(e,t){this.addTransportListeners(t.transport),this.pruneAppliedSends(),this._sessions.set(e,t),this.enforceSessionCap(e)}enforceSessionCap(e){for(;this._sessions.size>32;){let t;for(let n of this._sessions.keys())if(!(n===e||this._pinnedTargets.has(n))){t=n;break}if(t===void 0)return;let n=this._sessions.get(t);this._sessions.delete(t),n&&(Wi.debug(`Evicting least-recently-used CDP session`,{targetId:t}),this.detachSession(t,n))}}pinTarget(e){this._pinnedTargets.set(e,(this._pinnedTargets.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(this._pinnedTargets.get(e)??1)-1;n>0?this._pinnedTargets.set(e,n):this._pinnedTargets.delete(e),this.enforceSessionCap()}}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.delete(e),this._sessions.set(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){Wi.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.values()].some(t=>t.remote?.runtimeId===e.remote?.runtimeId&&t.remote?.localTargetId===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])n.transport===e&&this.forgetSession(t,n)}clearSessions(){for(let[e,t]of[...this._sessions])this.forgetSession(e,t);this._sessions.clear(),this.sessionId=null,this.attachedTargetId=null}};const Qi=y(`panel-rpc-cdp`);var $i=class{getPanelRpc;runtimeId;localTargetId;timeoutMs;eventListeners=new Map;pendingOnce=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(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=>{Qi.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,ae)+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=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(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){Qi.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=>{Qi.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=>{Qi.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function ea(e){let t=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 $i(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}}}const ta=Object.freeze([Object.freeze({id:`experimental-settings`,label:`Experimental settings`,description:`Show controls for experimental features.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1,since:`2026-07-31`}),Object.freeze({id:`panel-layouts`,label:`Panel layouts`,description:`Arrange the UI as movable, resizable panels instead of the fixed workbench.`,defaultValue:`off`,userToggleable:!0,since:`2026-08-03`}),Object.freeze({id:`agentic-memory`,label:`Agentic memory`,description:`Curate session memory with a background agent instead of a one-shot extraction call.`,defaultValue:`off`,userToggleable:!0,since:`2026-08-05`}),Object.freeze({id:`multiple-cones`,label:`Multiple cones`,description:`Add, switch between and remove cones from the freezer rail. Extra cones share the workspace.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1,since:`2026-08-21`}),Object.freeze({id:`compact-on-idle`,label:`Compact on idle`,description:`When a cone has been idle for a while with a large context, summarize its history in the background. The full transcript is kept in /sessions.`,defaultValue:`on`,userToggleable:!1,since:`2026-09-02`}),Object.freeze({id:`memory-v2`,label:`Memory v2`,description:`Searchable session history, scoop pre-compaction snapshots, and the gelatiere — a resident advisor that reviews your sessions and suggests skills and use cases.`,defaultValue:`off`,userToggleable:!0,since:`2026-09-10`})]);new Map(ta.map(e=>[e.id,e]));const na=new Set([`1`,`on`,`true`]);let ra=`standalone`,ia={},aa={};function oa(e,t={},n=sa()){let r={};for(let i of ta){let a=n[i.id];if(typeof a==`string`&&ma(i,e)){r[i.id]=a;continue}let o=aa[i.id];if(typeof o==`string`&&ma(i,e)){r[i.id]=o;continue}let s=t[i.id];r[i.id]=typeof s==`string`?s:pa(i,e)}return r}function sa(){try{let e=ga()?.getItem(`slicc_feature_flags`);return e?ha(JSON.parse(e)):{}}catch{return{}}}function ca(e,t={}){ra=e,ia=ha(t),aa={}}function la(e,t){ra=e,ia=ha(t)}function ua(e){return oa(ra,ia)[e]}function da(e){return typeof e==`string`&&na.has(e.trim().toLowerCase())}function fa(e){return da(ua(e))}function pa(e,t){return e.floatDefaults?.[t]??e.defaultValue}function ma(e,t){return e.userToggleable&&(e.overridableFloats===void 0||e.overridableFloats.includes(t))}function ha(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t=e,n={};for(let e of ta){let r=t[e.id];typeof r==`string`&&(n[e.id]=r)}return n}function ga(){try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function _a(e){return`slicc_feature_flags_remote:${e}`}let va=null;function ya(e,t){let n=xa(t);va=e,ca(e,Sa(n,e)??{})}function ba(e,t){if(!va||e!==void 0&&e!==_a(va))return!1;let n=xa(t);return la(va,Sa(n,va)??{}),!0}function xa(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 Sa(e,t){try{let n=e?.getItem(_a(t));return n?Ca(JSON.parse(n)):null}catch{return null}}function Ca(e){return!wa(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function wa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ta=y(`stale-asset`),Ea=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Da(e){return Ea.test(e)}let Oa=null;function ka(e){if(!e){Oa=null;return}Oa=e}function Aa(e=!1){if(!Oa||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Oa,replayTurn:e})}finally{t.close()}}function ja(e){Da(e instanceof Error?e.message:String(e))&&Aa()}function Ma(e,t){return!e||e===t?!1:(Ta.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),Aa(),!0)}function Na(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Pa(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Fa=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Ia(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Fa.map(e=>La(i,e,t,r)))).filter(e=>e!==null)}async function La(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal,redirect:`manual`,credentials:`omit`});return e.status!==200||!Ra(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Ra(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 za=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new yi;unsubscribe=null;stateListeners=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,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=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 bi(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 Ba(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 Va(e){let t=Ba(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var Ha=class extends za{constructor(e){let t=Ba(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 Wa=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function Ga(e){return Wa.test(e)}function Ka(e,t){return`(${e} && ${t})`}function M(e,t){return`(${e} || ${t})`}function qa(e){return`!(${e})`}function Ja(e){return`Array.isArray(${e})`}function Ya(e){return`typeof ${e} === "bigint"`}function Xa(e){return`typeof ${e} === "boolean"`}function Za(e){return`Number.isInteger(${e})`}function Qa(e){return`${e} === null`}function $a(e){return`Number.isFinite(${e})`}function eo(e){return Ka(to(e),qa(Ja(e)))}function to(e){return`typeof ${e} === "object" && ${e} !== null`}function no(e){return`typeof ${e} === "string"`}function ro(e){return`typeof ${e} === "symbol"`}function io(e){return`${e} === undefined`}function ao(e){return`typeof ${e} === "function"`}function oo(e){return`Guard.IsConstructor(${e})`}function so(e,t){return`${e} === ${t}`}function co(e,t){return`${e} > ${t}`}function lo(e,t){return`${e} < ${t}`}function uo(e,t){return`${e} <= ${t}`}function fo(e,t){return`${e} >= ${t}`}function po(e,t){return`Guard.IsMinLength(${e}, ${t})`}function mo(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function ho(e,t,n,r){return E(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => ${r})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${n[0]}, ${n[1]}) => ${r})`}function go(e){return`Object.entries(${e})`}function _o(e){return`Object.getOwnPropertyNames(${e})`}function vo(e,t){return E(t,`"__proto__"`)||E(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function yo(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function bo(e){return`[${e.join(`, `)}]`}function xo(e,t){return`((${e.join(`, `)}) => ${t})`}function N(e,t){return`${e}(${t.join(`, `)})`}function So(e,t){return`new ${e}(${t.join(`, `)})`}function P(e,t){return`${e}${Ga(t)?`.${t}`:`[${F(t)}]`}`}function F(e){return b(e)?JSON.stringify(e):`${e}`}function Co(e,t,n){return`(${e} ? ${t} : ${n})`}function wo(e){return`{ ${e.join(`; `)}; }`}function To(e,t){return`const ${e} = ${t}`}function Eo(e,t){return`if(${e}) { ${t} }`}function Do(e){return`return ${e}`}function Oo(e){return E(e.length,0)?`true`:e.reduce((e,t)=>Ka(e,t))}function ko(e){return E(e.length,0)?`false`:e.reduce((e,t)=>M(e,t))}function Ao(e){return`++${e}`}function jo(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Mo=Ze;function No(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let Po;function Fo(){try{return Lo(`null`)(),!0}catch{return!1}}function Io(){return T(Po)&&(Po=Fo()),Po&&Wt().useAcceleration}function Lo(...e){return new globalThis.Function(...e)}function Ro(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 zo=Ro;function Bo(){return zo}const Vo=[/prompt is too long/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,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i],Ho=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Uo(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!Ho.some(t=>t.test(e.errorMessage))&&Vo.some(t=>t.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 Wo(e){return O(e,`~refine`)&&w(e[`~refine`])&&C(e[`~refine`],0,e=>S(e)&&O(e,`check`)&&O(e,`error`)&&Pt(e.check)&&Pt(e.error))}function Go(e){return S(e)&&!w(e)}function Ko(e){return Kt(e)}function I(e){return Go(e)||Ko(e)}function qo(e){return O(e,`additionalItems`)&&I(e.additionalItems)}function Jo(e){return O(e,`additionalProperties`)&&I(e.additionalProperties)}function Yo(e){return O(e,`allOf`)&&w(e.allOf)&&e.allOf.every(e=>I(e))}function Xo(e){return O(e,`$anchor`)&&b(e.$anchor)}function Zo(e){return O(e,`anyOf`)&&w(e.anyOf)&&e.anyOf.every(e=>I(e))}function Qo(e){return O(e,`const`)}function $o(e){return O(e,`contains`)&&I(e.contains)}function es(e){return O(e,`default`)}function ts(e){return O(e,`dependencies`)&&S(e.dependencies)&&Object.values(e.dependencies).every(e=>I(e)||w(e)&&e.every(e=>b(e)))}function ns(e){return O(e,`dependentRequired`)&&S(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>w(e)&&e.every(e=>b(e)))}function rs(e){return O(e,`dependentSchemas`)&&S(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>I(e))}function is(e){return O(e,`$dynamicAnchor`)&&b(e.$dynamicAnchor)}function as(e){return O(e,`$dynamicRef`)&&b(e.$dynamicRef)}function os(e){return O(e,`else`)&&I(e.else)}function ss(e){return O(e,`enum`)&&w(e.enum)}function cs(e){return O(e,`exclusiveMaximum`)&&(k(e.exclusiveMaximum)||Mt(e.exclusiveMaximum))}function ls(e){return O(e,`exclusiveMinimum`)&&(k(e.exclusiveMinimum)||Mt(e.exclusiveMinimum))}function us(e){return O(e,`format`)&&b(e.format)}function ds(e){return O(e,`$id`)&&b(e.$id)}function fs(e){return O(e,`if`)&&I(e.if)}function ps(e){return O(e,`items`)&&(I(e.items)||w(e.items)&&e.items.every(e=>I(e)))}function ms(e){return ps(e)&&w(e.items)}function hs(e){return O(e,`maximum`)&&(k(e.maximum)||Mt(e.maximum))}function gs(e){return O(e,`maxContains`)&&k(e.maxContains)}function _s(e){return O(e,`maxItems`)&&k(e.maxItems)}function vs(e){return O(e,`maxLength`)&&k(e.maxLength)}function ys(e){return O(e,`maxProperties`)&&k(e.maxProperties)}function bs(e){return O(e,`minimum`)&&(k(e.minimum)||Mt(e.minimum))}function xs(e){return O(e,`minContains`)&&k(e.minContains)}function Ss(e){return O(e,`minItems`)&&k(e.minItems)}function Cs(e){return O(e,`minLength`)&&k(e.minLength)}function ws(e){return O(e,`minProperties`)&&k(e.minProperties)}function Ts(e){return O(e,`multipleOf`)&&(k(e.multipleOf)||Mt(e.multipleOf))}function Es(e){return O(e,`not`)&&I(e.not)}function Ds(e){return O(e,`oneOf`)&&w(e.oneOf)&&e.oneOf.every(e=>I(e))}function Os(e){return O(e,`pattern`)&&(b(e.pattern)||e.pattern instanceof RegExp)}function ks(e){return O(e,`patternProperties`)&&S(e.patternProperties)&&Object.values(e.patternProperties).every(e=>I(e))}function As(e){return O(e,`prefixItems`)&&w(e.prefixItems)&&e.prefixItems.every(e=>I(e))}function js(e){return O(e,`properties`)&&S(e.properties)&&Object.values(e.properties).every(e=>I(e))}function Ms(e){return O(e,`propertyNames`)&&(S(e.propertyNames)||I(e.propertyNames))}function Ns(e){return O(e,`$recursiveAnchor`)&&Kt(e.$recursiveAnchor)}function Ps(e){return Ns(e)&&E(e.$recursiveAnchor,!0)}function Fs(e){return O(e,`$recursiveRef`)&&b(e.$recursiveRef)}function Is(e){return O(e,`$ref`)&&b(e.$ref)}function Ls(e){return O(e,`required`)&&w(e.required)&&e.required.every(e=>b(e))}function Rs(e){return O(e,`then`)&&I(e.then)}function zs(e){return O(e,`type`)&&(b(e.type)||w(e.type)&&e.type.every(e=>b(e)))}function Bs(e){return O(e,`uniqueItems`)&&Kt(e.uniqueItems)}function Vs(e){return O(e,`unevaluatedItems`)&&I(e.unevaluatedItems)}function Hs(e){return O(e,`unevaluatedProperties`)&&I(e.unevaluatedProperties)}function Us(e){return Vs(e)||Hs(e)||x(e).some(t=>Gs(e[t]))}function Ws(e){return e.some(e=>Gs(e))}function Gs(e){return w(e)?Ws(e):S(e)?Us(e):!1}function Ks(e,t){return Gs(t)||x(e).some(t=>Gs(e[t]))}var qs=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return N(P(`context`,`Push`),[])}Pop(){return N(P(`context`,`Pop`),[])}AddIndex(e){return N(P(`context`,`AddIndex`),[e])}AddKey(e){return N(P(`context`,`AddKey`),[e])}Merge(e){return N(P(`context`,`Merge`),[e])}},Js=class{constructor(){let e=new Set,t=new Set;this.stack=[{indices:e,keys:t}]}Push(){let e=new Set,t=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}},Ys=class extends Js{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Xs=class extends Ys{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const Zs={identifier:`External`,variables:[]};function Qs(e){let t=`External[${Zs.variables.length}]`;return Zs.variables.push(e),t}function $s(){Zs.variables=[]}function ec(){return{...Zs}}function tc(e,t,n,r){return ho(Qs(n[`~refine`].map(e=>e)),F(0),[`refinement`,`_`],N(P(`refinement`,`check`),[r]))}function nc(e,t,n,r){return C(n[`~refine`],0,(e,t)=>e.check(r))}function rc(e,t,n,r,i,a){return Rt(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let ic=0;function L(){return`var_${ic++}`}function ac(e){return ps(e)&&w(e.items)}function oc(e,t,n,r){if(!ac(n))return F(!0);let[i,a]=[L(),L()],o=Pf(e,t,n.additionalItems,i),s=lo(a,F(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?M(s,Ka(o,c)):M(s,o);return N(P(r,`every`),[xo([i,a],l)])}function sc(e,t,n,r){return!ac(n)||r.every((r,i)=>$t(i,n.items.length)||Ff(e,t,n.additionalItems,r)&&t.AddIndex(i))}function cc(e,t,n,r,i,a){return!ac(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return $t(o,i.items.length)||If(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function lc(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function uc(e){let t=[];return ks(e)&&t.push(...x(e.patternProperties)),js(e)&&t.push(...x(e.properties).map(lc)),E(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function dc(e,t,n){return Ls(t)&&js(t)&&!ks(t)&&E(t.additionalProperties,!1)&&E(x(t.properties).length,t.required.length)}function fc(e,t,n){return so(P(N(P(`Object`,`getOwnPropertyNames`),[n]),`length`),F(t.required.length))}function pc(e,t,n,r){let[i,a]=[L(),L()],o=Qs(new RegExp(uc(n))),s=Pf(e,t,n.additionalProperties,`${r}[${i}]`),c=N(P(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?M(c,Ka(s,l)):M(c,s);return ho(_o(r),F(0),[i,a],u)}function mc(e,t,n,r){return dc(t,n,r)?fc(t,n,r):pc(e,t,n,r)}function hc(e,t,n,r){let i=new RegExp(uc(n));return C(x(r),0,(a,o)=>i.test(a)||Ff(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function gc(e,t,n,r,i,a){let o=new RegExp(uc(i)),s=[];return Rt(x(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new Xs,p=o.test(c)||If(e,f,u,d,i.additionalProperties,a[c])&&t.AddKey(c);return p||s.push(c),p})||t.AddError({keyword:`additionalProperties`,schemaPath:n,instancePath:r,params:{additionalProperties:s}})}function _c(e,t,n,r,i){let a=To(`results`,`[]`),o=n.map((e,t)=>To(`context_${t}`,So(`CheckContext`,[]))),s=n.map((n,i)=>To(`condition_${i}`,N(xo([`context`],z(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>Eo(`condition_${t}`,N(P(`results`,`push`),[`context_${t}`]))),l=Do(Ka(i,t.Merge(`results`)));return N(xo([],wo([a,...o,...s,...c,l])),[])}function vc(e,t,n,r){return _c(e,t,n.allOf,r,so(P(`results`,`length`),F(n.allOf.length)))}function yc(e,t,n,r){return Oo(n.allOf.map(n=>z(e,t,n,r)))}function bc(e,t,n,r){return t.UseUnevaluated()?vc(e,t,n,r):yc(e,t,n,r)}function xc(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new Js;return B(e,i,n,r)?[...t,i]:t},[]);return E(i.length,n.allOf.length)&&t.Merge(i)}function Sc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new Xs,u=Lf(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=E(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function Cc(e,t,n,r){return _c(e,t,n.anyOf,r,co(P(`results`,`length`),F(0)))}function wc(e,t,n,r){return ko(n.anyOf.map(n=>z(e,t,n,r)))}function Tc(e,t,n,r){return t.UseUnevaluated()?Cc(e,t,n,r):wc(e,t,n,r)}function Ec(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new Js;return B(e,i,n,r)?[...t,i]:t},[]);return Ct(i.length,0)&&t.Merge(i)}function Dc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new Xs,l=Lf(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=Ct(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 Oc(e,t,n,r){return F(!!n)}function kc(e,t,n,r){return n}function Ac(e,t,n,r,i,a){return kc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function jc(e,t,n,r){return kt(n.const)?so(r,F(n.const)):yo(r,Qs(n.const))}function Mc(e,t,n,r){return kt(n.const)?E(r,n.const):xt(r,n.const)}function Nc(e,t,n,r,i,a){return Mc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Pc(e){return!(xs(e)&&E(e.minContains,0))}function Fc(e,t,n,r){if(!Pc(n))return F(!0);let i=L();return Ka(qa(so(P(r,`length`),F(0))),N(P(r,`some`),[xo([i],z(e,t,n.contains,i))]))}function Ic(e,t,n,r){return!Pc(n)||!E(r.length,0)&&r.some(r=>B(e,t,n.contains,r))}function Lc(e,t,n,r,i,a){return Ic(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Rc(e,t,n,r){return M(so(P(_o(r),`length`),F(0)),Oo(D(n.dependencies).map(([n,i])=>{let a=qa(vo(r,F(n))),o=z(e,t,i,r);return M(a,w(i)?(e=>Oo(e.map(e=>vo(r,F(e)))))(i):o)})))}function zc(e,t,n,r){let i=E(x(r).length,0),a=C(D(n.dependencies),0,([n,i])=>!O(r,n)||(w(i)?i.every(e=>O(r,e)):B(e,t,i,r)));return i||a}function Bc(e,t,n,r,i,a){let o=E(x(a).length,0),s=Rt(D(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!O(a,i)||(w(o)?o.every(e=>O(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):Lf(e,t,s,r,o,a))});return o||s}function Vc(e,t,n,r){return M(so(P(_o(r),`length`),F(0)),Oo(D(n.dependentRequired).map(([e,t])=>M(qa(vo(r,F(e))),Oo(t.map(e=>vo(r,F(e))))))))}function Hc(e,t,n,r){let i=E(x(r).length,0),a=C(D(n.dependentRequired),0,([e,t])=>!O(r,e)||t.every(e=>O(r,e)));return i||a}function Uc(e,t,n,r,i,a){let o=E(x(a).length,0),s=Rt(D(i.dependentRequired),0,([e,i])=>!O(a,e)||Rt(i,0,o=>O(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function Wc(e,t,n,r){return M(so(P(_o(r),`length`),F(0)),Oo(D(n.dependentSchemas).map(([n,i])=>M(qa(vo(r,F(n))),z(e,t,i,r)))))}function Gc(e,t,n,r){let i=E(x(r).length,0),a=C(D(n.dependentSchemas),0,([n,i])=>!O(r,n)||B(e,t,i,r));return i||a}function Kc(e,t,n,r,i,a){let o=E(x(a).length,0),s=Rt(D(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!O(a,i)||Lf(e,t,s,r,o,a)});return o||s}function qc(e,t,n,r){return qf(e,t,e.DynamicRef(n)??!1,r)}function Jc(e,t,n,r){let i=e.DynamicRef(n)??!1;return I(i)&&B(e,t,i,r)}function Yc(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return I(o)&&Lf(e,t,`#`,r,o,a)}function Xc(e,t,n,r){return ko(n.enum.map(e=>kt(e)?so(r,F(e)):yo(r,Qs(e))))}function Zc(e,t,n,r){return n.enum.some(e=>kt(e)?E(r,e):xt(r,e))}function Qc(e,t,n,r,i,a){return Zc(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function $c(e,t,n,r){return lo(r,F(n.exclusiveMaximum))}function el(e,t,n,r){return $t(r,n.exclusiveMaximum)}function tl(e,t,n,r,i,a){return el(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function nl(e,t,n,r){return co(r,F(n.exclusiveMinimum))}function rl(e,t,n,r){return Ct(r,n.exclusiveMinimum)}function il(e,t,n,r,i,a){return rl(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const al=[0,31,28,31,30,31,30,31,31,30,31,30,31],ol=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function sl(e){return e%4==0&&(e%100!=0||e%400==0)}function cl(e){let t=ol.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&&sl(n)?29:al[r])}const ll=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function ul(e,t=!0){let n=ll.exec(e);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4]===`-`?-1:1,s=+(n[5]||0),c=+(n[6]||0);if(s>23||c>59||t&&!n[4]&&e.toLowerCase().indexOf(`z`)===-1)return!1;if(r<=23&&i<=59&&a<60)return!0;let l=i-c*o,u=r-s*o-+(l<0);return(u===23||u===-1)&&(l===59||l===-1)&&a<61}function dl(e,t=!0){let n=e.split(/T/i);return n.length===2&&cl(n[0])&&ul(n[1],t)}const fl=/^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 pl(e){return fl.test(e)}const ml=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function hl(e){return ml.test(e)}function gl(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 _l(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);if(r>=128)throw Error(`Invalid punycode: non-basic before delimiter`);t.push(r)}let o=a<0?0:a+1;for(;o<e.length;){let a=r,s=1,c=36;for(;;){if(o>=e.length)throw Error(`Invalid punycode: unexpected end of input`);let t=e.charCodeAt(o++),n;if(t>=97&&t<=122)n=t-97;else if(t>=48&&t<=57)n=t-48+26;else if(t>=65&&t<=90)Ge();else throw Error(`Invalid punycode: bad digit character`);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=gl(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function vl(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function yl(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function bl(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function xl(e){return vl(e)||yl(e)||bl(e)}const Sl=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),Cl=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function wl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function Tl(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function El(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function Dl(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function Ol(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function kl(e){return e>=1632&&e<=1641}function Al(e){return e>=1776&&e<=1785}function jl(e){return Cl.has(e)}function Ml(e){if(e.length===0)return Ge();let t=[...e].map(e=>e.codePointAt(0)),n=t.length;if(t[0]===45||t[n-1]===45||n>=4&&t[2]===45&&t[3]===45||xl(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(Sl.has(n))return!1;(El(n)||Dl(n)||Ol(n))&&(r=!0),kl(n)&&(i=!0),Al(n)&&(a=!0);let o=t[e-1],s=t[e+1];switch(n){case 183:if(o!==108||s!==108)return!1;break;case 885:if(s===void 0||!wl(s))return!1;break;case 1523:case 1524:if(o===void 0||!Tl(o))return!1;break;case 8204:if(o===void 0||o<128&&!jl(o))return!1;break;case 8205:if(o===void 0||!jl(o))return!1}}return!(e.includes(`・`)&&!r||i&&a)}function Nl(e){if(e.charCodeAt(0)===45||e.charCodeAt(e.length-1)===45||e.length>=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!(n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45))return!1}return!0}function Pl(e){return e.toLowerCase().startsWith(`xn--`)}function Fl(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=_l(t);return n?Ml(n):!1}catch{return!1}}function Il(e){return e.length===0||e.length>63?!1:Pl(e)?Fl(e):Ml(e)}function Ll(e){return e.length===0||e.length>63?!1:Pl(e)?Fl(e):Nl(e)}function Rl(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!Ll(t))return!1;return!0}const zl=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function Bl(e){return zl.test(e)}function Vl(e){if(e.length===0||e.includes(` `))return!1;let t=e.normalize(`NFC`).replace(/[\u002E\u3002\uFF0E\uFF61]/g,`.`);if(t.length>253)return!1;for(let e of t.split(`.`))if(!Il(e))return!1;return!0}function Hl(e,t,n){let r=0,i=0,a=0,o=0;for(let s=t;s<n;s++){let t=e.charCodeAt(s);if(t===46){if(a===0||i>255||o===48&&a>1)return!1;r++,i=0,a=0,o=0}else if(t>=48&&t<=57)a===0&&(o=t),i=i*10+(t-48),a++;else return!1}return r===3&&a>0&&i<=255&&!(o===48&&a>1)}function Ul(e){return Hl(e,0,e.length)}function Wl(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Gl(e){let t=e.length;if(t===0)return!1;let n=0,r=!1,i=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;r=!0,i=2}for(;i<t;){let a=0,o=i;for(;i<t&&Wl(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!Hl(e,o,t))return!1;n+=2,i=t;break}if(a>4)return!1;if(n++,i===t)break;if(s!==58)return!1;if(i++,e.charCodeAt(i)===58){if(r||e.charCodeAt(i+1)===58)return!1;if(r=!0,i++,i===t)break}}return r?n<=7:n===8}function Kl(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function ql(e){if(e.includes(` `)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e===``)return!0;let t=e.indexOf(`:`);return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?Kl(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:Kl(e)}function Jl(e){try{return new URL(e),!0}catch{return!1}}const Yl=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Xl(e){return Yl.test(e)}const Zl=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Ql(e){return Zl.test(e)}function $l(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const eu=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function tu(e){return eu.test(e)}const nu=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function ru(e){return nu.test(e)}const iu=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function au(e){return iu.test(e)}function ou(e){return e>=97&&e<=122||e>=65&&e<=90}function su(e){return ou(e)||e>=48&&e<=57}function cu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function lu(e){return su(e)||e===43||e===45||e===46}function uu(e){return su(e)||e===45||e===46||e===95||e===126}function du(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function fu(e){return uu(e)||du(e)||e===58||e===64}function pu(e){let t=e.length;if(t===0||!ou(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!lu(t))return!1;n++}if(e.charCodeAt(n)!==58)return!1;if(n++,e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47){n+=2;let r=n,i=-1;for(let r=n;r<t;r++){let t=e.charCodeAt(r);if(t===64){i=r;break}if(t===47||t===63||t===35)break}if(i!==-1){for(let t=r;t<i;t++){let n=e.charCodeAt(t);if(n===91||n===93)return!1;if(n===37){if(t+2>=i||!cu(e.charCodeAt(t+1))||!cu(e.charCodeAt(t+2)))return!1;t+=2}else if(!uu(n)&&!du(n)&&n!==58)return!1}n=i+1}if(e.charCodeAt(n)===91){for(n++;n<t&&e.charCodeAt(n)!==93;)n++;if(e.charCodeAt(n)!==93)return!1;n++}else for(;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35||t===58)break;if(t<128&&!uu(t)&&!du(t))return!1;n++}if(e.charCodeAt(n)===58)for(n++;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35)break;if(t<48||t>57)return!1;n++}}for(;n<t;){let r=e.charCodeAt(n);if(r===37){if(n+2>=t||!cu(e.charCodeAt(n+1))||!cu(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(fu(r)||r===47||r===63||r===35))return!1;n++}return!0}const mu=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function hu(e){return mu.test(e)}const gu=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function _u(e){return gu.test(e)}const R=new Map;function vu(){R.clear()}function yu(){return[...R.entries()]}function bu(e,t){R.set(e,t)}function xu(e){return R.has(e)}function Su(e){return R.get(e)}function Cu(e,t){return R.get(e)?.(t)??!0}function wu(){vu(),R.set(`date-time`,dl),R.set(`date`,cl),R.set(`duration`,pl),R.set(`email`,hl),R.set(`hostname`,Rl),R.set(`idn-email`,Bl),R.set(`idn-hostname`,Vl),R.set(`ipv4`,Ul),R.set(`ipv6`,Gl),R.set(`iri-reference`,ql),R.set(`iri`,Jl),R.set(`json-pointer-uri-fragment`,Xl),R.set(`json-pointer`,Ql),R.set(`regex`,$l),R.set(`relative-json-pointer`,tu),R.set(`time`,ul),R.set(`uri-reference`,ru),R.set(`uri-template`,au),R.set(`uri`,pu),R.set(`url`,hu),R.set(`uuid`,_u)}wu();var Tu=e({Clear:()=>vu,Entries:()=>yu,Get:()=>Su,Has:()=>xu,IsDate:()=>cl,IsDateTime:()=>dl,IsDuration:()=>pl,IsEmail:()=>hl,IsHostname:()=>Rl,IsIPv4:()=>Ul,IsIPv6:()=>Gl,IsIdnEmail:()=>Bl,IsIdnHostname:()=>Vl,IsIri:()=>Jl,IsIriReference:()=>ql,IsJsonPointer:()=>Ql,IsJsonPointerUriFragment:()=>Xl,IsRegex:()=>$l,IsRelativeJsonPointer:()=>tu,IsTime:()=>ul,IsUri:()=>pu,IsUriReference:()=>ru,IsUriTemplate:()=>au,IsUrl:()=>hu,IsUuid:()=>_u,Reset:()=>wu,Set:()=>bu,Test:()=>Cu});function Eu(e,t,n,r){return N(P(`Format`,`Test`),[F(n.format),r])}function Du(e,t,n,r){return Cu(n.format,r)}function Ou(e,t,n,r,i,a){return Du(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function ku(e,t,n,r){let i=!Rs(n)||n.then,a=!os(n)||n.else;return Co(z(e,t,n.if,r),z(e,t,i,r),z(e,t,a,r))}function Au(e,t,n,r){let i=!Rs(n)||n.then,a=!os(n)||n.else;return B(e,t,n.if,r)?B(e,t,i,r):B(e,t,a,r)}function ju(e,t,n,r,i,a){let o=!Rs(i)||i.then,s=!os(i)||i.else,c=new Xs,l=Lf(e,c,`${n}/if`,r,i.if,a)?Lf(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):Lf(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 Mu(e,t,n,r){return Oo(n.items.map((n,i)=>{let a=uo(P(r,`length`),F(i)),o=Pf(e,t,n,`${r}[${i}]`),s=t.AddIndex(F(i));return M(a,t.UseUnevaluated()?Ka(o,s):o)}))}function Nu(e,t,n,r){return C(n.items,0,(n,i)=>Jt(r.length,i)||Ff(e,t,n,r[i])&&t.AddIndex(i))}function Pu(e,t,n,r,i,a){return Rt(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return Jt(a.length,o)||If(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Fu(e,t,n,r){let i=As(n)?n.prefixItems.length:0,a=Pf(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?Ka(a,o):a;return ho(r,F(i),[`element`,`index`],s)}function Iu(e,t,n,r){let i=As(n)?n.prefixItems.length:0;return C(r,i,(r,i)=>Ff(e,t,n.items,r)&&t.AddIndex(i))}function Lu(e,t,n,r,i,a){let o=As(i)?i.prefixItems.length:0;return Rt(a,o,(a,o)=>If(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function Ru(e,t,n,r){return ms(n)?Mu(e,t,n,r):Fu(e,t,n,r)}function zu(e,t,n,r){return ms(n)?Nu(e,t,n,r):Iu(e,t,n,r)}function Bu(e,t,n,r,i,a){return ms(i)?Pu(e,t,n,r,i,a):Lu(e,t,n,r,i,a)}function Vu(e){return $o(e)}function Hu(e,t,n,r){if(!Vu(n))return F(!0);let[i,a]=[L(),L()];return uo(N(P(r,`reduce`),[xo([i,a],Co(z(e,t,n.contains,a),Ao(i),i)),F(0)]),F(n.maxContains))}function Uu(e,t,n,r){if(!Vu(n))return!0;let i=r.reduce((r,i)=>B(e,t,n.contains,i)?++r:r,0);return Jt(i,n.maxContains)}function Wu(e,t,n,r,i,a){let o=xs(i)?i.minContains:1;return Uu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function Gu(e,t,n,r){return uo(r,F(n.maximum))}function Ku(e,t,n,r){return Jt(r,n.maximum)}function qu(e,t,n,r,i,a){return Ku(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function Ju(e,t,n,r){return uo(P(r,`length`),F(n.maxItems))}function Yu(e,t,n,r){return Jt(r.length,n.maxItems)}function Xu(e,t,n,r,i,a){return Yu(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function Zu(e,t,n,r){return mo(r,F(n.maxLength))}function Qu(e,t,n,r){return ht(r,n.maxLength)}function $u(e,t,n,r,i,a){return Qu(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function ed(e,t,n,r){return uo(P(_o(r),`length`),F(n.maxProperties))}function td(e,t,n,r){return Jt(x(r).length,n.maxProperties)}function nd(e,t,n,r,i,a){return td(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function rd(e){return $o(e)}function id(e,t,n,r){if(!rd(n))return F(!0);let[i,a]=[L(),L()];return fo(N(P(r,`reduce`),[xo([i,a],Co(z(e,t,n.contains,a),Ao(i),i)),F(0)]),F(n.minContains))}function ad(e,t,n,r){if(!rd(n))return!0;let i=r.reduce((r,i)=>B(e,t,n.contains,i)?++r:r,0);return Tt(i,n.minContains)}function od(e,t,n,r,i,a){return ad(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function sd(e,t,n,r){return fo(r,F(n.minimum))}function cd(e,t,n,r){return Tt(r,n.minimum)}function ld(e,t,n,r,i,a){return cd(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function ud(e,t,n,r){return fo(P(r,`length`),F(n.minItems))}function dd(e,t,n,r){return Tt(r.length,n.minItems)}function fd(e,t,n,r,i,a){return dd(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function pd(e,t,n,r){return po(r,F(n.minLength))}function md(e,t,n,r){return Zt(r,n.minLength)}function hd(e,t,n,r,i,a){return md(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function gd(e,t,n,r){return fo(P(_o(r),`length`),F(n.minProperties))}function _d(e,t,n,r){return Tt(x(r).length,n.minProperties)}function vd(e,t,n,r,i,a){return _d(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function yd(e,t,n,r){return jo(r,F(n.multipleOf))}function bd(e,t,n,r){return rt(r,n.multipleOf)}function xd(e,t,n,r,i,a){return bd(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function Sd(e,t,n,r){return _c(e,t,[n.not],r,qa(so(P(`results`,`length`),F(1))))}function Cd(e,t,n,r){return qa(z(e,t,n.not,r))}function wd(e,t,n,r){return t.UseUnevaluated()?Sd(e,t,n,r):Cd(e,t,n,r)}function Td(e,t,n,r){let i=new Js;return!B(e,i,n.not,r)&&t.Merge([i])}function Ed(e,t,n,r,i,a){return Td(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function Dd(e,t,n,r){return _c(e,t,n.oneOf,r,so(P(`results`,`length`),F(1)))}function Od(e,t,n,r){return so(N(P(bo(n.oneOf.map(n=>z(e,t,n,r))),`reduce`),[xo([`count`,`result`],Co(so(`result`,F(!0)),Ao(`count`),`count`)),F(0)]),F(1))}function kd(e,t,n,r){return t.UseUnevaluated()?Dd(e,t,n,r):Od(e,t,n,r)}function Ad(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new Js;return B(e,i,n,r)?[...t,i]:t},[]);return E(i.length,1)&&t.Merge(i)}function jd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new Xs,u=Lf(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=E(c.length,1)&&t.Merge(c);return!l&&E(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 Md(e,t,n,r){return N(P(Qs(b(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function Nd(e,t,n,r){return(b(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function Pd(e,t,n,r,i,a){return Nd(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function Fd(e,t,n,r){return Oo(D(n.patternProperties).map(([n,i])=>{let[a,o]=[L(),L()],s=qa(N(P(Qs(new RegExp(n,`u`)),`test`),[a])),c=Pf(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?M(s,Ka(c,l)):M(s,c);return ho(go(r),F(0),[`[${a}, ${o}]`,`_`],u)}))}function Id(e,t,n,r){return C(D(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return C(D(r),0,([n,r])=>!a.test(n)||Ff(e,t,i,r)&&t.AddKey(n))})}function Ld(e,t,n,r,i,a){return Rt(D(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return Rt(D(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||If(e,t,s,a,o,i)&&t.AddKey(n)})})}function Rd(e,t,n,r){return Oo(n.prefixItems.map((n,i)=>{let a=uo(P(r,`length`),F(i)),o=Pf(e,t,n,`${r}[${i}]`),s=t.AddIndex(F(i));return M(a,t.UseUnevaluated()?Ka(o,s):o)}))}function zd(e,t,n,r){return E(r.length,0)||C(n.prefixItems,0,(n,i)=>Jt(r.length,i)||Ff(e,t,n,r[i])&&t.AddIndex(i))}function Bd(e,t,n,r,i,a){return E(a.length,0)||Rt(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return Jt(a.length,o)||If(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Vd(e,t){return e.includes(t)||Wt().exactOptionalPropertyTypes}function Hd(e,t){return io(P(e,t))}function Ud(e,t){return T(e[t])}function Wd(e,t,n,r){let i=Ls(n)?n.required:[];return Oo(D(n.properties).map(([n,a])=>{let o=qa(vo(r,F(n))),s=Pf(e,t,a,P(r,n)),c=t.AddKey(F(n)),l=t.UseUnevaluated()?Ka(s,c):s,u=i.includes(n)?l:M(o,l);return Vd(i,n)?u:M(Hd(r,n),u)}))}function Gd(e,t,n,r){let i=Ls(n)?n.required:[];return C(D(n.properties),0,([n,a])=>{let o=!O(r,n)||Ff(e,t,a,r[n])&&t.AddKey(n);return Vd(i,n)?o:Ud(r,n)||o})}function Kd(e,t,n,r,i,a){let o=Ls(i)?i.required:[];return Rt(D(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!O(a,i)||If(e,t,c,l,s,a[i])&&t.AddKey(i);return Vd(o,i)?u():Ud(a,i)||u()})}function qd(e,t,n,r){let[i,a]=[L(),L()];return ho(_o(r),F(0),[i,a],z(e,t,n.propertyNames,i))}function Jd(e,t,n,r){return C(x(r),0,(r,i)=>B(e,t,n.propertyNames,r))}function Yd(e,t,n,r,i,a){let o=[];return Rt(x(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=Lf(e,new Xs,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Xd(e,t,n,r){return qf(e,t,e.RecursiveRef(n)??!1,r)}function Zd(e,t,n,r){let i=e.RecursiveRef(n)??!1;return I(i)&&B(e,t,i,r)}function Qd(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return I(o)&&Lf(e,t,`#`,r,o,a)}function $d(e,t,n,r){let i=xo([`context`,`value`],qf(e,t,n,`value`));return N(xo([`context`,`value`],wo([To(`nextContext`,So(`CheckContext`,[])),To(`result`,N(i,[`nextContext`,`value`])),Eo(`result`,t.Merge(`[nextContext]`)),Do(`result`)])),[`context`,r])}function ef(e,t,n,r){return qf(e,t,n,r)}function tf(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?$d(e,t,i,r):ef(e,t,i,r)}function nf(e,t,n,r){let i=e.Ref(n)??!1,a=new Js,o=I(i)&&B(e,a,i,r);return o&&t.Merge([a]),o}function rf(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new Xs,c=I(o)&&Lf(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function af(e,t,n,r){return Oo(n.required.map(e=>vo(r,F(e))))}function of(e,t,n,r){return C(n.required,0,e=>O(r,e))}function sf(e,t,n,r,i,a){let o=[];return Rt(i.required,0,e=>{let t=O(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function cf(e,t,n,r){return E(n,`object`)?eo(r):E(n,`array`)?Ja(r):E(n,`boolean`)?Xa(r):E(n,`integer`)?Za(r):E(n,`number`)?$a(r):E(n,`null`)?Qa(r):E(n,`string`)?no(r):E(n,`bigint`)?Ya(r):E(n,`constructor`)?oo(r):E(n,`function`)?ao(r):E(n,`symbol`)?ro(r):E(n,`undefined`)||E(n,`void`)?io(r):F(!0)}function lf(e,t,n,r,i){return E(n,`object`)?He(i):E(n,`array`)?w(i):E(n,`boolean`)?Kt(i):E(n,`integer`)?ft(i):E(n,`number`)?k(i):E(n,`null`)?ze(i):E(n,`string`)?b(i):E(n,`bigint`)?Mt(i):E(n,`constructor`)?vt(i):E(n,`function`)?Pt(i):E(n,`symbol`)?$e(i):E(n,`undefined`)?T(i):!E(n,`void`)||T(i)}function uf(e,t,n,r){return ko(n.map(n=>cf(e,t,n,r)))}function df(e,t,n,r,i){return n.some(n=>lf(e,t,n,r,i))}function ff(e,t,n,r){return w(n.type)?uf(e,t,n.type,r):cf(e,t,n.type,r)}function pf(e,t,n,r){return w(n.type)?df(e,t,n.type,n,r):lf(e,t,n.type,n,r)}function mf(e,t,n,r,i,a){return(w(i.type)?df(e,t,i.type,i,a):lf(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function hf(e,t,n,r){let[i,a]=[L(),L()],o=N(P(`context`,`GetIndices`),[]),s=N(P(`indices`,`has`),[i]),c=z(e,t,n.unevaluatedItems,a),l=N(P(`context`,`AddIndex`),[i]),u=ho(r,F(0),[a,i],Ka(M(s,c),l));return N(xo([`context`],wo([To(`indices`,o),Do(u)])),[`context`])}function gf(e,t,n,r){let i=t.GetIndices();return C(r,0,(r,a)=>(i.has(a)||B(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function _f(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return Rt(a,0,(a,c)=>{let l=new Xs,u=(o.has(c)||Lf(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 vf(e,t,n,r){let[i,a]=[L(),L()],o=N(P(`context`,`GetKeys`),[]),s=N(P(`keys`,`has`),[i]),c=N(P(`context`,`AddKey`),[i]),l=z(e,t,n.unevaluatedProperties,a),u=ho(go(r),F(0),[`[${i}, ${a}]`,`_`],M(s,Ka(l,c)));return N(xo([`context`],wo([To(`keys`,o),Do(u)])),[`context`])}function yf(e,t,n,r){let i=t.GetKeys();return C(D(r),0,([r,a])=>i.has(r)||B(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function bf(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return Rt(D(a),0,([a,c])=>{let l=new Xs,u=o.has(a)||Lf(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 xf(e){return!E(e.uniqueItems,!1)}function Sf(e,t,n,r){return xf(n)?so(P(So(`Set`,[N(P(r,`map`),[P(`Hashing`,`Hash`)])]),`size`),P(r,`length`)):F(!0)}function Cf(e,t,n,r){if(!xf(n))return!0;let i=new Set(r.map(et)).size,a=r.length;return E(i,a)}function wf(e,t,n,r,i,a){if(!xf(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=et(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return E(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function Tf(e,t){return zs(e)&&(w(e.type)&&Ct(e.type.length,0)&&C(e.type,0,e=>E(e,t))||E(e.type,t))}function Ef(e){return Tf(e,`object`)}function Df(e){return Go(e)&&(Jo(e)||ts(e)||ns(e)||rs(e)||js(e)||ks(e)||Ms(e)||ws(e)||ys(e)||Ls(e)||Hs(e))}function Of(e){return Tf(e,`array`)}function kf(e){return Go(e)&&(qo(e)||ps(e)||$o(e)||gs(e)||_s(e)||xs(e)||Ss(e)||As(e)||Vs(e)||Bs(e))}function Af(e){return Tf(e,`string`)}function jf(e){return Go(e)&&(Cs(e)||vs(e)||us(e)||Os(e))}function Mf(e){return Tf(e,`number`)||Tf(e,`bigint`)}function Nf(e){return Go(e)&&(bs(e)||hs(e)||cs(e)||ls(e)||Ts(e))}function Pf(e,t,n,r){return t.UseUnevaluated()?Ka(Ka(t.Push(),z(e,t,n,r)),t.Pop()):z(e,t,n,r)}function z(e,t,n,r){e.Push(n);let i=[];if(Ko(n))return Oc(e,t,n,r);if(zs(n)&&i.push(ff(e,t,n,r)),Df(n)){let a=[];Ls(n)&&a.push(af(e,t,n,r)),Jo(n)&&a.push(mc(e,t,n,r)),ts(n)&&a.push(Rc(e,t,n,r)),ns(n)&&a.push(Vc(e,t,n,r)),rs(n)&&a.push(Wc(e,t,n,r)),ks(n)&&a.push(Fd(e,t,n,r)),js(n)&&a.push(Wd(e,t,n,r)),Ms(n)&&a.push(qd(e,t,n,r)),ws(n)&&a.push(gd(e,t,n,r)),ys(n)&&a.push(ed(e,t,n,r));let o=Oo(a),s=M(qa(eo(r)),o);i.push(Ef(n)?o:s)}if(kf(n)){let a=[];qo(n)&&a.push(oc(e,t,n,r)),$o(n)&&a.push(Fc(e,t,n,r)),ps(n)&&a.push(Ru(e,t,n,r)),gs(n)&&a.push(Hu(e,t,n,r)),_s(n)&&a.push(Ju(e,t,n,r)),xs(n)&&a.push(id(e,t,n,r)),Ss(n)&&a.push(ud(e,t,n,r)),As(n)&&a.push(Rd(e,t,n,r)),Bs(n)&&a.push(Sf(e,t,n,r));let o=Oo(a),s=M(qa(Ja(r)),o);i.push(Of(n)?o:s)}if(jf(n)){let a=[];vs(n)&&a.push(Zu(e,t,n,r)),Cs(n)&&a.push(pd(e,t,n,r)),us(n)&&a.push(Eu(e,t,n,r)),Os(n)&&a.push(Md(e,t,n,r));let o=Oo(a),s=M(qa(no(r)),o);i.push(Af(n)?o:s)}if(Nf(n)){let a=[];cs(n)&&a.push($c(e,t,n,r)),ls(n)&&a.push(nl(e,t,n,r)),hs(n)&&a.push(Gu(e,t,n,r)),bs(n)&&a.push(sd(e,t,n,r)),Ts(n)&&a.push(yd(e,t,n,r));let o=Oo(a),s=M(qa(M($a(r),Ya(r))),o);i.push(Mf(n)?o:s)}Is(n)&&i.push(tf(e,t,n,r)),Fs(n)&&i.push(Xd(e,t,n,r)),as(n)&&i.push(qc(e,t,n,r)),Qo(n)&&i.push(jc(e,t,n,r)),ss(n)&&i.push(Xc(e,t,n,r)),fs(n)&&i.push(ku(e,t,n,r)),Es(n)&&i.push(wd(e,t,n,r)),Yo(n)&&i.push(bc(e,t,n,r)),Zo(n)&&i.push(Tc(e,t,n,r)),Ds(n)&&i.push(kd(e,t,n,r)),Vs(n)&&i.push(M(qa(Ja(r)),hf(e,t,n,r))),Hs(n)&&i.push(M(qa(to(r)),vf(e,t,n,r))),Wo(n)&&i.push(tc(e,t,n,r));let a=Oo(i);return e.Pop(n),a}function Ff(e,t,n,r){return t.Push()&&B(e,t,n,r)&&t.Pop()}function B(e,t,n,r){e.Push(n);let i=Ko(n)?kc(e,t,n,r):(!zs(n)||pf(e,t,n,r))&&(!(S(r)&&!w(r))||(!Ls(n)||of(e,t,n,r))&&(!Jo(n)||hc(e,t,n,r))&&(!ts(n)||zc(e,t,n,r))&&(!ns(n)||Hc(e,t,n,r))&&(!rs(n)||Gc(e,t,n,r))&&(!ks(n)||Id(e,t,n,r))&&(!js(n)||Gd(e,t,n,r))&&(!Ms(n)||Jd(e,t,n,r))&&(!ws(n)||_d(e,t,n,r))&&(!ys(n)||td(e,t,n,r)))&&(!w(r)||(!qo(n)||sc(e,t,n,r))&&(!$o(n)||Ic(e,t,n,r))&&(!ps(n)||zu(e,t,n,r))&&(!gs(n)||Uu(e,t,n,r))&&(!_s(n)||Yu(e,t,n,r))&&(!xs(n)||ad(e,t,n,r))&&(!Ss(n)||dd(e,t,n,r))&&(!As(n)||zd(e,t,n,r))&&(!Bs(n)||Cf(e,t,n,r)))&&(!b(r)||(!vs(n)||Qu(e,t,n,r))&&(!Cs(n)||md(e,t,n,r))&&(!us(n)||Du(e,t,n,r))&&(!Os(n)||Nd(e,t,n,r)))&&(!(k(r)||Mt(r))||(!cs(n)||el(e,t,n,r))&&(!ls(n)||rl(e,t,n,r))&&(!hs(n)||Ku(e,t,n,r))&&(!bs(n)||cd(e,t,n,r))&&(!Ts(n)||bd(e,t,n,r)))&&(!Is(n)||nf(e,t,n,r))&&(!Fs(n)||Zd(e,t,n,r))&&(!as(n)||Jc(e,t,n,r))&&(!Qo(n)||Mc(e,t,n,r))&&(!ss(n)||Zc(e,t,n,r))&&(!fs(n)||Au(e,t,n,r))&&(!Es(n)||Td(e,t,n,r))&&(!Yo(n)||xc(e,t,n,r))&&(!Zo(n)||Ec(e,t,n,r))&&(!Ds(n)||Ad(e,t,n,r))&&(!Vs(n)||!w(r)||gf(e,t,n,r))&&(!Hs(n)||!S(r)||yf(e,t,n,r))&&(!Wo(n)||nc(e,t,n,r));return e.Pop(n),i}function If(e,t,n,r,i,a){return t.Push()&&Lf(e,t,n,r,i,a)&&t.Pop()}function Lf(e,t,n,r,i,a){e.Push(i);let o=Ko(i)?Ac(e,t,n,r,i,a):!!((!zs(i)||mf(e,t,n,r,i,a))&+(!(S(a)&&!w(a))||!!((!Ls(i)||sf(e,t,n,r,i,a))&+(!Jo(i)||gc(e,t,n,r,i,a))&(!ts(i)||Bc(e,t,n,r,i,a))&(!ns(i)||Uc(e,t,n,r,i,a))&(!rs(i)||Kc(e,t,n,r,i,a))&(!ks(i)||Ld(e,t,n,r,i,a))&(!js(i)||Kd(e,t,n,r,i,a))&(!Ms(i)||Yd(e,t,n,r,i,a))&(!ws(i)||vd(e,t,n,r,i,a))&(!ys(i)||nd(e,t,n,r,i,a))))&(!w(a)||!!((!qo(i)||cc(e,t,n,r,i,a))&+(!$o(i)||Lc(e,t,n,r,i,a))&(!ps(i)||Bu(e,t,n,r,i,a))&(!gs(i)||Wu(e,t,n,r,i,a))&(!_s(i)||Xu(e,t,n,r,i,a))&(!xs(i)||od(e,t,n,r,i,a))&(!Ss(i)||fd(e,t,n,r,i,a))&(!As(i)||Bd(e,t,n,r,i,a))&(!Bs(i)||wf(e,t,n,r,i,a))))&(!b(a)||!!((!vs(i)||$u(e,t,n,r,i,a))&+(!Cs(i)||hd(e,t,n,r,i,a))&(!us(i)||Ou(e,t,n,r,i,a))&(!Os(i)||Pd(e,t,n,r,i,a))))&(!(k(a)||Mt(a))||!!((!cs(i)||tl(e,t,n,r,i,a))&+(!ls(i)||il(e,t,n,r,i,a))&(!hs(i)||qu(e,t,n,r,i,a))&(!bs(i)||ld(e,t,n,r,i,a))&(!Ts(i)||xd(e,t,n,r,i,a))))&(!Is(i)||rf(e,t,n,r,i,a))&(!Fs(i)||Qd(e,t,n,r,i,a))&(!as(i)||Yc(e,t,n,r,i,a))&(!Qo(i)||Nc(e,t,n,r,i,a))&(!ss(i)||Qc(e,t,n,r,i,a))&(!fs(i)||ju(e,t,n,r,i,a))&(!Es(i)||Ed(e,t,n,r,i,a))&(!Yo(i)||Sc(e,t,n,r,i,a))&(!Zo(i)||Dc(e,t,n,r,i,a))&(!Ds(i)||jd(e,t,n,r,i,a))&(!Vs(i)||!w(a)||_f(e,t,n,r,i,a))&(!Hs(i)||!S(a)||bf(e,t,n,r,i,a)))&&(!Wo(i)||rc(e,t,n,r,i,a));return e.Pop(i),o}const Rf=[0],zf=new Map,Bf=new Map;function Vf(){return et(Rf[0]++)}function Hf(e,t){zf.has(e)||zf.set(e,new Map);let n=zf.get(e);if(n.has(t))return n.get(t);let r=Vf();return n.set(t,r),r}function Uf(e,t,n,r){return e.UseUnevaluated()?N(`check_${n}`,[`context`,r]):N(`check_${n}`,[r])}function Wf(e,t,n,r){let i=z(e,t,n,`value`);return t.UseUnevaluated()?To(`check_${r}`,xo([`context`,`value`],i)):To(`check_${r}`,xo([`value`],i))}function Gf(){Rf[0]=0,zf.clear(),Bf.clear()}function Kf(){return[...Bf.values()]}function qf(e,t,n,r){let i=Hf(n,e.BaseURL().href),a=Uf(t,n,i,r);return Bf.has(i)?a:(Bf.set(i,``),Bf.set(i,Wf(e,t,n,i)),a)}function Jf(e,t){return S(t)&&!Ie(e)?t[e]:void 0}function Yf(e,t){return e.reduce((e,t)=>Jf(t,e),t)}function Xf(e){if(E(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 Zf(e,t){return Yf(Xf(t),e)}function Qf(e,t,n){if(e.$id===n.hash)return e;let r=new URL(e.$id,t.href),i=new URL(n.href,t.href);if(E(r.pathname,i.pathname))return n.hash.startsWith(`#`)?tp(e,t,n):e}function $f(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return E(r.href,i.href)?e:void 0}function ep(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return E(r.href,i.href)?e:void 0}function tp(e,t,n){if(n.href.endsWith(`#`))return e;if(!n.hash.startsWith(`#`))return;let r=decodeURIComponent(n.hash.slice(1));if(r.startsWith(`/`))return Zf(e,r)}function np(e,t,n){if(ds(e)){let r=Qf(e,t,n);if(!T(r))return r}if(Xo(e)){let r=$f(e,t,n);if(!T(r))return r}if(is(e)){let r=ep(e,t,n);if(!T(r))return r}return tp(e,t,n)}function rp(e,t,n){return e.reduce((e,r)=>{let i=ap(r,t,n);return T(i)?e:i},void 0)}function ip(e,t,n){return x(e).reduce((r,i)=>{let a=ap(e[i],t,n);return T(a)?r:a},void 0)}function ap(e,t,n){let r=Go(e)&&ds(e)?new URL(e.$id,t.href):t;if(Go(e)){let t=np(e,r,n);if(!T(t))return t}if(w(e))return rp(e,r,n);if(S(e))return ip(e,r,n)}function op(e,t){let n=new URL(`http://unknown/`),r=ds(e)?new URL(e.$id,n.href):n;return ap(e,r,new URL(t,r.href))}function sp(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?op(t,n.$dynamicRef):op(e,n.$dynamicRef);if(!T(i))return!Go(i)||!is(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var cp=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)},lp,up,dp,fp,pp,mp=class{constructor(e,t){lp.add(this),this.context=e,this.schema=t,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((e,t)=>new URL(t.$id,e),new URL(`http://unknown`))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(e){Go(e)&&(ds(e)&&(this.ids.push(e),cp(this,lp,`m`,up).call(this,e)),Xo(e)&&this.anchors.push(e),Ps(e)&&this.recursiveAnchors.push(e),is(e)&&this.dynamicAnchors.push(e))}Pop(e){Go(e)&&(ds(e)&&(this.ids.pop(),cp(this,lp,`m`,dp).call(this,e)),Xo(e)&&this.anchors.pop(),Ps(e)&&this.recursiveAnchors.pop(),is(e)&&this.dynamicAnchors.pop())}Ref(e){return cp(this,lp,`m`,fp).call(this,e)??cp(this,lp,`m`,pp).call(this,e)}RecursiveRef(e){return Ps(this.Base())?op(this.recursiveAnchors[0],e.$recursiveRef):op(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return sp(t,this.Base(),e,this.dynamicAnchors)}};lp=new WeakSet,up=function e(t,n=!0){if(!Go(t))return;let r=t;if(!(!n&&ds(r))){!n&&is(r)&&this.dynamicAnchors.push(r);for(let t of x(r))cp(this,lp,`m`,e).call(this,r[t],!1)}},dp=function e(t,n=!0){if(!Go(t))return;let r=t;if(!(!n&&ds(r))){!n&&is(r)&&this.dynamicAnchors.pop();for(let t of x(r))cp(this,lp,`m`,e).call(this,r[t],!1)}},fp=function(e){return O(this.context,e.$ref)?this.context[e.$ref]:void 0},pp=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?op(this.Base(),e.$ref):op(t,e.$ref)};function hp(e){return`${e.Functions().join(`;
|
|
878
|
-
`)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function gp(e,t){return Lo(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(Js,Ze,Tu,Ue,e.External().variables)}function _p(e){let t=new mp(e.Context(),e.Schema()),n=new Js;return r=>B(t,n,e.Schema(),r)}function vp(e,t){return Io()?gp(e,t):_p(e)}var yp=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)}},bp=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=hp(this),t=vp(this,e);return new yp(Io(),e,t)}};function xp(...e){let[t,n]=No(e,{2:(e,t)=>[e,t],1:e=>[{},e]});$s(),Gf();let r=new mp(t,n),i=new qs(Ks(t,n)),a=qf(r,i,n,`value`),o=Kf();return new bp(t,n,ec(),o,a,i.UseUnevaluated())}function Sp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=Wt(),a=Bo(),o=[];return[Lf(new mp(t,n),new Ys(e=>{if(!Tt(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function Cp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return B(new mp(t,n),new Js,n,r)}function wp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Cp(t,n,r)}function Tp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=Sp(t,n,r);return a}var Ep=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 Dp(e,t,n){return w(n)?n.map(n=>Rp(e,t.items,n)):n}function Op(e,t,n){return Rp({...e,...t.$defs},Ke(t.$ref),n)}function kp(e,t){let n=O(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=Vt(e,t),i=Ft(r);return We(i)?Et(i,n):i}function Ap(e,t,n){return Rp(e,kp(e,t),n)}function jp(e){return O(e,`additionalProperties`)?e.additionalProperties:void 0}function Mp(e,t,n){if(!S(n)||w(n))return n;let r=jp(t);for(let i of x(n)){if(O(t.properties,i)){n[i]=Rp(e,t.properties[i],n[i]);continue}if(Kt(r)&&E(r,!0)||yt(r)&&wp(e,r,n[i])){n[i]=Rp(e,r,n[i]);continue}delete n[i]}return n}function Np(e,t,n){if(!S(n))return n;let r=jp(t),[i,a]=[new RegExp(_t(t)),bt(t)];for(let t of x(n)){if(i.test(t)){n[t]=Rp(e,a,n[t]);continue}if(Kt(r)&&E(r,!0)||yt(r)&&wp(e,r,n[t])){n[t]=Rp(e,r,n[t]);continue}delete n[t]}return n}function Pp(e,t,n){return O(e,t.$ref)?Rp(e,e[t.$ref],n):n}function Fp(e,t,n){if(!w(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;i<r;i++)n[i]=Rp(e,t.items[i],n[i]);return Ct(n.length,r)?n.slice(0,r):n}function Ip(e){return It(e)}function Lp(e,t,n){for(let r of t.anyOf){let t=Rp(e,r,Ip(n));if(wp(e,r,t))return t}return n}function Rp(e,t,n){return tt(t)?Dp(e,t,n):Le(t)?Op(e,t,n):nt(t)?Ap(e,t,n):We(t)?Mp(e,t,n):gt(t)?Np(e,t,n):Bt(t)?Pp(e,t,n):zt(t)?Fp(e,t,n):St(t)?Lp(e,t,n):n}function zp(e,t){for(let n of Mo.Keys(e))Mo.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function Bp(e){let t={};for(let n of Mo.Keys(e))t[n]=Up(e[n]);return t}function Vp(e){return Hp(Ut(e))}function Hp(e){return e.map(e=>Up(e))}function Up(e){return zp(e,tt(e)?Pe(Up(e.items),ut(e)):nt(e)?Je(Hp(e.allOf)):St(e)?dt(Vp(e.anyOf)):We(e)?at(Bp(e.properties)):gt(e)?jt(Gt(e),Up(bt(e))):zt(e)?Nt(Hp(e.items)):e)}function Wp(e){return Up(e)}function Gp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Rp(t,Wt().unionPrioritySort?Wp(n):n,r)}function Kp(e){return S(e)&&O(e,`value`)}function V(e){return{value:e}}function qp(e){return w(e)?V(e):V([e])}function Jp(e){return E(e,!0)?V(BigInt(1)):V(BigInt(0))}const Yp=/^-?(0|[1-9]\d*)n$/,Xp=/^-?(0|[1-9]\d*)\.\d+$/,Zp=/^-?(0|[1-9]\d*)$/;function Qp(e){return Yp.test(e)}function $p(e){return Xp.test(e)}function em(e){return Zp.test(e)}function tm(e){let t=e.toLowerCase();return Qp(e)?V(BigInt(e.slice(0,e.length-1))):$p(e)?V(BigInt(e.split(`.`)[0])):em(e)?V(BigInt(e)):E(t,`false`)?V(BigInt(0)):E(t,`true`)?V(BigInt(1)):void 0}function nm(e){return Mt(e)?V(e):Kt(e)?Jp(e):k(e)?V(BigInt(Math.trunc(e))):ze(e)?V(BigInt(0)):b(e)?tm(e):T(e)?V(BigInt(0)):void 0}function rm(e){return E(e,BigInt(0))?V(!1):E(e,BigInt(1))?V(!0):void 0}function im(e){return E(e,0)?V(!1):E(e,1)?V(!0):void 0}function am(e){return E(e.toLowerCase(),`false`)?V(!1):E(e.toLowerCase(),`true`)?V(!0):E(e,`0`)?V(!1):E(e,`1`)?V(!0):void 0}function om(e){return Mt(e)?rm(e):Kt(e)?V(e):k(e)?im(e):ze(e)?V(!1):b(e)?am(e):T(e)?V(!1):void 0}function sm(e){return E(e,BigInt(0))?V(null):void 0}function cm(e){return E(e,!1)?V(null):void 0}function lm(e){return E(e,0)?V(null):void 0}function um(e){let t=e.toLowerCase();return E(t,`undefined`)||E(t,`null`)||E(e,``)||E(e,`0`)?V(null):void 0}function dm(e){return Mt(e)?sm(e):Kt(e)?cm(e):k(e)?lm(e):ze(e)?V(null):b(e)?um(e):T(e)?V(null):void 0}const fm=BigInt(2**53-1),pm=BigInt(-(2**53-1));function mm(e){return e<=fm&&e>=pm?V(Number(e)):void 0}function hm(e){return V(+!!e)}function gm(e){let t=+e;if(k(t))return V(t);let n=e.toLowerCase();if(E(n,`false`))return V(0);if(E(n,`true`))return V(1);let r=nm(e);if(Kp(r))return r.value<=fm&&r.value>=pm?V(Number(r.value)):void 0}function _m(e){return Mt(e)?mm(e):Kt(e)?hm(e):k(e)?V(e):ze(e)?V(0):b(e)?gm(e):T(e)?V(0):void 0}function vm(e){return Mt(e)||Kt(e)||k(e)?V(e.toString()):ze(e)?V(`null`):b(e)?V(e):T(e)?V(``):void 0}function ym(e){return E(e,BigInt(0))?V(void 0):void 0}function bm(e){return E(e,!1)?V(void 0):void 0}function xm(e){return E(e,0)?V(void 0):void 0}function Sm(e){let t=e.toLowerCase();return E(t,`undefined`)||E(t,`null`)||E(e,``)||E(e,`0`)?V(void 0):void 0}function Cm(e){return Mt(e)?ym(e):Kt(e)?bm(e):k(e)?xm(e):ze(e)?V(void 0):b(e)?Sm(e):T(e)?V(e):void 0}function wm(e,t,n){return qp(n).value.map(n=>Zm(e,t.items,n))}function Tm(e,t,n){let r=nm(n);return Kp(r)?r.value:n}function Em(e,t,n){let r=om(n);return Kp(r)?r.value:n}function Dm(e,t,n){return Zm({...e,...t.$defs},Ke(t.$ref),n)}function Om(e,t,n){return Zm(e,Ft(t),n)}function km(e,t,n){let r=_m(n);return Kp(r)?Math.trunc(r.value):n}function Am(e,t,n){let r=Vt(e,t);return Zm(e,Ft(r),n)}function jm(e,t,n){let r=nm(n);return Kp(r)&&E(t.const,r.value)?r.value:n}function Mm(e,t,n){let r=om(n);return Kp(r)&&E(t.const,r.value)?r.value:n}function Nm(e,t,n){let r=_m(n);return Kp(r)&&E(t.const,r.value)?r.value:n}function Pm(e,t,n){let r=vm(n);return Kp(r)&&E(t.const,r.value)?r.value:n}function Fm(e,t,n){return E(t.const,n)?n:it(t)?jm(e,t,n):Ve(t)?Mm(e,t,n):Be(t)?Nm(e,t,n):Qe(t)?Pm(e,t,n):Ge()}function Im(e,t,n){let r=dm(n);return Kp(r)?r.value:n}function Lm(e,t,n){let r=_m(n);return Kp(r)?r.value:n}function Rm(e,t,n,r){let i=x(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=Zm(e,n,r[t]));return r}function zm(e,t,n){return st(e)&&T(n[t])}function Bm(e,t,n){let r=Dt(t.properties),i=x(n);for(let[t,a]of r)for(let r of i)!t.test(r)||zm(a,r,n)||(n[r]=Zm(e,a,n[r]));return O(t,`additionalProperties`)&&S(t.additionalProperties)?Rm(e,r,t.additionalProperties,n):n}function Vm(e,t,n){return He(n)?Bm(e,t,n):n}function Hm(e,t,n){let r=Dt(t.patternProperties),i=x(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=Zm(e,a,n[r]));return O(t,`additionalProperties`)&&S(t.additionalProperties)?Rm(e,r,t.additionalProperties,n):n}function Um(e,t,n){return He(n)?Hm(e,t,n):n}function Wm(e,t,n){return O(e,t.$ref)?Zm(e,e[t.$ref],n):n}function Gm(e,t,n){let r=vm(n);return Kp(r)?r.value:n}function Km(e,t,n){return Zm(e,Ft(t),n)}function qm(e,t,n){if(!w(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=Zm(e,t.items[r],n[r]);return n}function Jm(e,t,n){let r=Cm(n);return Kp(r)?r.value:n}function Ym(e,t,n){if(t.anyOf.some(t=>wp(e,t,n)))return n;let r=t.anyOf.map(t=>Zm(e,t,Ip(n))).find(n=>wp(e,t,n));return T(r)?n:r}function Xm(e,t,n){return Kp(Cm(n))?void 0:n}function Zm(e,t,n){return tt(t)?wm(e,t,n):Ye(t)?Tm(e,t,n):Ot(t)?Em(e,t,n):Le(t)?Dm(e,t,n):en(t)?Om(e,t,n):Fe(t)?km(e,t,n):nt(t)?Am(e,t,n):Yt(t)?Fm(e,t,n):Re(t)?Im(e,t,n):Xt(t)?Lm(e,t,n):We(t)?Vm(e,t,n):gt(t)?Um(e,t,n):Bt(t)?Wm(e,t,n):qt(t)?Gm(e,t,n):pt(t)?Km(e,t,n):zt(t)?qm(e,t,n):Ht(t)?Jm(e,t,n):St(t)?Ym(e,t,n):Lt(t)?Xm(e,t,n):n}function Qm(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Zm(t,n,r)}function $m(e,t,n){if(!w(n))return n;for(let r=0;r<n.length;r++)n[r]=ch(e,t.items,n[r]);return n}function eh(e,t,n){return ch({...e,...t.$defs},Ke(t.$ref),n)}function th(e,t){return T(t)?Pt(e.default)?e.default():Ip(e.default):t}function nh(e,t,n){let r=Vt(e,t);return ch(e,Ft(r),n)}function rh(e,t,n){if(!S(n))return n;let r=x(t.properties);for(let i of r){let r=ch(e,t.properties[i],n[i]);T(r)&&(st(t.properties[i])||!O(t.properties[i],`default`))||(n[i]=r)}if(!Jo(t)||Kt(t.additionalProperties))return n;for(let i of x(n))r.includes(i)||(n[i]=ch(e,t.additionalProperties,n[i]));return n}function ih(e,t,n){if(!S(n))return n;let[r,i]=[new RegExp(_t(t)),bt(t)];for(let t of x(n))r.test(t)&&es(i)&&(n[t]=ch(e,i,n[t]));if(!Jo(t))return n;for(let i of x(n))r.test(i)||(n[i]=ch(e,t.additionalProperties,n[i]));return n}function ah(e,t,n){return O(e,t.$ref)?ch(e,e[t.$ref],n):n}function oh(e,t,n){if(!w(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]=ch(e,r[t],n[t]));return n}function sh(e,t,n){for(let r of t.anyOf){let t=ch(e,r,Ip(n));if(wp(e,r,t))return t}return n}function ch(e,t,n){let r=es(t)?th(t,n):n;return tt(t)?$m(e,t,r):Le(t)?eh(e,t,r):nt(t)?nh(e,t,r):We(t)?rh(e,t,r):gt(t)?ih(e,t,r):Bt(t)?ah(e,t,r):zt(t)?oh(e,t,r):St(t)?sh(e,t,r):r}function lh(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return ch(t,n,r)}function uh(e){return(...t)=>{let[n,r,i]=No(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function dh(e,t,n){return t[`~codec`].decode(n)}function fh(e,t,n){return t[`~codec`].encode(n)}function H(e,t,n,r){return Xe(n)?E(e,`Decode`)?dh(t,n,r):fh(t,n,r):r}function ph(e,t,n,r){if(!w(r))return r;for(let i=0;i<r.length;i++)r[i]=U(e,t,n.items,r[i]);return H(e,t,n,r)}function mh(e,t,n,r){let i=H(e,t,n,r);if(!w(i))return i;for(let r=0;r<i.length;r++)i[r]=U(e,t,n.items,i[r]);return i}function hh(e,t,n,r){return E(e,`Decode`)?ph(e,t,n,r):mh(e,t,n,r)}function gh(e,t,n,r){return r=U(e,{...t,...n.$defs},Ke(n.$ref),r),H(e,t,n,r)}function _h(e){return e.reduce((e,t)=>({...e,...t}),{})}function vh(e,t){for(let n of t)if(!xt(e,n))return n;return e}function yh(e,t,n,r){if(E(n.allOf.length,0))return H(e,t,n,r);let i=n.allOf.map(n=>U(e,t,n,Gp(n,Ip(r))));return H(e,t,n,i.every(e=>S(e))?_h(i):vh(r,i))}function bh(e,t,n,r){if(E(n.allOf.length,0))return H(e,t,n,r);let i=H(e,t,n,r),a=n.allOf.map(n=>U(e,t,n,Gp(n,Ip(i))));return a.every(e=>S(e))?_h(a):vh(i,a)}function xh(e,t,n,r){return E(e,`Decode`)?yh(e,t,n,r):bh(e,t,n,r)}function Sh(e,t,n,r){if(!He(r))return r;for(let i of x(n.properties))!O(r,i)||zm(n.properties[i],i,r)||(r[i]=U(e,t,n.properties[i],r[i]));return H(e,t,n,r)}function Ch(e,t,n,r){let i=H(e,t,n,r);if(!He(i))return i;for(let r of x(n.properties))!O(i,r)||zm(n.properties[r],r,i)||(i[r]=U(e,t,n.properties[r],i[r]));return i}function wh(e,t,n,r){return E(e,`Decode`)?Sh(e,t,n,r):Ch(e,t,n,r)}function Th(e,t,n,r){if(!He(r))return r;let i=new RegExp(_t(n));for(let a of x(r))i.test(a)&&(r[a]=U(e,t,bt(n),r[a]));return H(e,t,n,r)}function Eh(e,t,n,r){let i=H(e,t,n,r);if(!He(i))return i;let a=new RegExp(_t(n));for(let r of x(i))a.test(r)&&(i[r]=U(e,t,bt(n),i[r]));return i}function Dh(e,t,n,r){return E(e,`Decode`)?Th(e,t,n,r):Eh(e,t,n,r)}function Oh(e,t,n,r){return O(t,n.$ref)?U(e,t,t[n.$ref],r):r}function kh(e,t,n,r){return E(e,`Decode`)?H(e,t,n,Oh(e,t,n,r)):Oh(e,t,n,H(e,t,n,r))}function Ah(e,t,n,r){if(!w(r))return r;for(let i=0;i<Math.min(n.items.length,r.length);i++)r[i]=U(e,t,n.items[i],r[i]);return H(e,t,n,r)}function jh(e,t,n,r){let i=H(e,t,n,r);if(!w(i))return r;for(let r=0;r<Math.min(n.items.length,i.length);r++)i[r]=U(e,t,n.items[r],i[r]);return i}function Mh(e,t,n,r){return E(e,`Decode`)?Ah(e,t,n,r):jh(e,t,n,r)}function Nh(e,t,n,r){for(let i of n.anyOf)if(wp(t,i,r))return H(e,t,n,U(e,t,i,r));return r}function Ph(e,t,n,r){let i=H(e,t,n,r);for(let r of n.anyOf){let n=U(e,t,r,Ip(i));if(wp(t,r,n))return n}return i}function Fh(e,t,n,r){return E(e,`Decode`)?Nh(e,t,n,r):Ph(e,t,n,r)}function U(e,t,n,r){return tt(n)?hh(e,t,n,r):Le(n)?gh(e,t,n,r):nt(n)?xh(e,t,n,r):We(n)?wh(e,t,n,r):gt(n)?Dh(e,t,n,r):Bt(n)?kh(e,t,n,r):zt(n)?Mh(e,t,n,r):St(n)?Fh(e,t,n,r):H(e,t,n,r)}var Ih=class extends Ep{constructor(e,t){super(`Decode`,e,t)}};function Lh(e,t,n){if(!wp(e,t,n))throw new Ih(n,Tp(e,t,n));return n}function Rh(e,t,n){return U(`Decode`,e,Wt().unionPrioritySort?Wp(t):t,n)}const zh=uh([(e,t,n)=>Ip(n),(e,t,n)=>lh(e,t,n),(e,t,n)=>Qm(e,t,n),(e,t,n)=>Gp(e,t,n),(e,t,n)=>Lh(e,t,n),(e,t,n)=>Rh(e,t,n)]);function Bh(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return zh(t,n,r)}var Vh=class extends Ep{constructor(e,t){super(`Encode`,e,t)}};function Hh(e,t,n){if(!wp(e,t,n))throw new Vh(n,Tp(e,t,n));return n}function Uh(e,t,n){return U(`Encode`,e,Wt().unionPrioritySort?Wp(t):t,n)}const Wh=uh([(e,t,n)=>Ip(n),(e,t,n)=>Uh(e,t,n),(e,t,n)=>lh(e,t,n),(e,t,n)=>Qm(e,t,n),(e,t,n)=>Gp(e,t,n),(e,t,n)=>Hh(e,t,n)]);function Gh(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Wh(t,n,r)}function Kh(e,t){return Xe(t)||eg(e,t.items)}function qh(e,t){return Xe(t)||Zh({...e,...t.$defs},Ke(t.$ref))}function Jh(e,t){return Xe(t)||t.allOf.some(t=>eg(e,t))}function Yh(e,t){return Xe(t)||x(t.properties).some(n=>eg(e,t.properties[n]))}function Xh(e,t){return Xe(t)||eg(e,bt(t))}function Zh(e,t){return!tg.has(t.$ref)&&(tg.add(t.$ref),Xe(t)||O(e,t.$ref)&&eg(e,e[t.$ref]))}function Qh(e,t){return Xe(t)||t.items.some(t=>eg(e,t))}function $h(e,t){return Xe(t)||t.anyOf.some(t=>eg(e,t))}function eg(e,t){return tt(t)?Kh(e,t):Le(t)?qh(e,t):nt(t)?Jh(e,t):We(t)?Yh(e,t):gt(t)?Xh(e,t):Bt(t)?Zh(e,t):zt(t)?Qh(e,t):St(t)?$h(e,t):Xe(t)}const tg=new Set;function ng(...e){let[t,n]=No(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return tg.clear(),eg(t,n)}var rg=class extends Error{constructor(e,t){super(t),this.type=e}};function ig(e,t){return Pt(t.default)?t.default(t):S(t.default)?Ip(t.default):t.default}function ag(e,t){if(Bs(t)&&!es(t))throw new rg(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=Ss(t)?t.minItems:0;return Array.from({length:n},()=>Eg(e,t.items))}function og(e,t){return ls(t)?BigInt(t.exclusiveMinimum)+BigInt(1):bs(t)?BigInt(t.minimum):BigInt(0)}function sg(e,t){return!1}function cg(e,t){let n=Eg(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function lg(e,t){return Eg({...e,...t.$defs},Ke(t.$ref))}function ug(e,t){return Eg(e,Ft(t))}function dg(e,t){let n=Eg(e,t.returnType);return()=>n}function fg(e,t){return ls(t)&&k(t.exclusiveMinimum)?t.exclusiveMinimum+1:bs(t)?t.minimum:0}function pg(e,t){let n=Vt(e,t);return Eg(e,Ft(n))}function mg(e,t){return t.const}function hg(e,t){throw new rg(t,`Cannot create TNever types`)}function gg(e,t){return null}function _g(e,t){return ls(t)&&k(t.exclusiveMinimum)?t.exclusiveMinimum+1:bs(t)?t.minimum:0}function vg(e,t){return(T(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:Eg(e,t.properties[r])}),{})}function yg(e,t){if(ws(t)&&!es(t))throw new rg(t,`Record with the minProperties constraint must have a default annotation`);return{}}function bg(e,t){return O(e,t.$ref)?Eg(e,e[t.$ref]):(()=>{throw new rg(t,`Unable to deref Ref`)})()}function xg(e,t){if((Os(t)||us(t))&&!es(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=Cs(t)?t.minLength:0;return``.padEnd(n)}function Sg(e,t){return Symbol()}function Cg(e,t){let n=wt(t.pattern);if(qt(n))throw new rg(t,`Unable to create TemplateLiteral due to infinite type expansion`);return Eg(e,n)}function wg(e,t){return Array.from({length:t.minItems},(n,r)=>Eg(e,t.items[r]))}function Tg(e,t){if(E(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return Eg(e,t.anyOf[0])}function Eg(e,t){return es(t)?ig(e,t):tt(t)?ag(e,t):Ye(t)?og(e,t):Ot(t)?sg(e,t):ct(t)?cg(e,t):Le(t)?lg(e,t):en(t)?ug(e,t):lt(t)?dg(e,t):Fe(t)?fg(e,t):nt(t)?pg(e,t):Yt(t)?mg(e,t):qe(t)?hg(e,t):Re(t)?gg(e,t):Xt(t)?_g(e,t):We(t)?vg(e,t):gt(t)?yg(e,t):Bt(t)?bg(e,t):qt(t)?xg(e,t):mt(t)?Sg(e,t):pt(t)?Cg(e,t):zt(t)?wg(e,t):Ht(t)?void 0:St(t)?Tg(e,t):(Lt(t),void 0)}function Dg(...e){let[t,n]=No(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Eg(t,n)}var Og=class extends Ep{constructor(e,t){super(`Parse`,e,t)}};function kg(e,t,n){if(!wp(e,t,n))throw new Og(n,Tp(e,t,n));return n}const Ag=uh([(e,t,n)=>Ip(n),(e,t,n)=>lh(e,t,n),(e,t,n)=>Qm(e,t,n),(e,t,n)=>Gp(e,t,n),(e,t,n)=>kg(e,t,n)]),jg=at({type:At(`insert`),path:Qt(),value:ot()}),Mg=Object({type:At(`update`),path:Qt(),value:ot()}),Ng=at({type:At(`delete`),path:Qt()});dt([jg,Mg,Ng]);var Pg=class{constructor(e,t){this.hasCodec=ng(e,t),this.buildResult=xp(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(Wt().correctiveParse)return Ag(this.Context(),this.Type(),e);throw new Og(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:Tp(this.Context(),this.Type(),e)}Clean(e){return Gp(this.Context(),this.Type(),e)}Convert(e){return Qm(this.Context(),this.Type(),e)}Create(){return Dg(this.Context(),this.Type())}Default(e){return lh(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Bh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Gh(this.Context(),this.Type(),e):this.Parse(e)}};function Fg(...e){let[t,n]=No(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new Pg(t,n)}const Ig=new WeakMap,Lg=Symbol.for(`TypeBox.Kind`);function Rg(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function zg(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 Bg(e){try{return qg(e)}catch{return}}function Vg(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 Hg(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]=Gg(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=Gg(i,t.additionalProperties))}function Ug(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=Gg(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=Gg(e[n],t.items)}function Wg(e,t){for(let n of t)if(Bg(n)?.Check(e))return e;for(let n of t){let t=Gg(structuredClone(e),n);if(Bg(n)?.Check(t))return t}return e}function Gg(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=Gg(n,e);Array.isArray(t.anyOf)&&(n=Wg(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=Wg(n,t.oneOf));let r=Rg(t),i=r.length>1&&r.some(e=>zg(n,e));if(r.length>0&&!i)for(let e of r){let t=Vg(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&Hg(n,t),r.includes(`array`)&&Array.isArray(n)&&Ug(n,t),n}function Kg(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&&Kg(e[n],r)}else if(t.items)for(let n of e)Kg(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`&&Bg(i)?.Check(null)===!1?delete n[e]:Kg(n[e],i))}function qg(e){let t=e,n=Ig.get(t);if(n)return n;let r=Fg(e);return Ig.set(t,r),r}function Jg(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 Yg(e,t){let n=structuredClone(t.arguments);Kg(n,e.parameters),Qm(e.parameters,n);let r=qg(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Lg)){let t=Gg(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=>` - ${Jg(e)}: ${e.message}`).join(`
|
|
879
|
-
`)||`Unknown validation error`,a=`Validation failed for tool "${t.name}":\n${i}\n\nReceived arguments:\n${JSON.stringify(t.arguments,null,2)}`;throw Error(a)}function Xg(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function Zg(e,t,n,r,i,a){let o=[...e],s={...t,messages:[...t.messages,...e]};await r({type:`agent_start`}),await r({type:`turn_start`});for(let t of e)await r({type:`message_start`,message:t}),await r({type:`message_end`,message:t});return await $g(s,o,n,i,r,a??Xg()),o}async function Qg(e,t,n,r,i){if(e.messages.length===0)throw Error(`Cannot continue: no messages in context`);if(e.messages[e.messages.length-1].role===`assistant`)throw Error(`Cannot continue from message role: assistant`);let a=[],o={...e};return await n({type:`agent_start`}),await n({type:`turn_start`}),await $g(o,a,t,r,n,i??Xg()),a}async function $g(e,t,n,r,i,a){let o=e,s=n,c,l=await s.getSteeringMessages?.()||[];for(;;){let e=!0;for(;e||l.length>0;){if(c){let e=await s.prepareNextTurn?.(c);e&&(o=e.context??o,s={...s,model:e.model??s.model,reasoning:e.thinkingLevel===void 0?s.reasoning:e.thinkingLevel===`off`?void 0:e.thinkingLevel}),l.length===0&&(l=await s.getSteeringMessages?.()||[]),await i({type:`turn_start`})}if(l.length>0){for(let e of l)await i({type:`message_start`,message:e}),await i({type:`message_end`,message:e}),o.messages.push(e),t.push(e);l=[]}let n=await e_(o,s,r,i,a);if(t.push(n),n.stopReason===`error`||n.stopReason===`aborted`){await i({type:`turn_end`,message:n,toolResults:[]}),await i({type:`agent_end`,messages:t});return}let u=n.content.filter(e=>e.type===`toolCall`),d=[];if(e=!1,u.length>0){let a=n.stopReason===`length`?await t_(u,i):await n_(o,n,s,r,i);d.push(...a.messages),e=!a.terminate;for(let e of d)o.messages.push(e),t.push(e)}if(await i({type:`turn_end`,message:n,toolResults:d}),c={message:n,toolResults:d,context:o,newMessages:t},await s.shouldStopAfterTurn?.(c)){await i({type:`agent_end`,messages:t});return}l=await s.getSteeringMessages?.()||[]}let n=await s.getFollowUpMessages?.()||[];if(n.length>0){l=n;continue}break}await i({type:`agent_end`,messages:t})}async function e_(e,t,n,r,i){let a=e.messages;t.transformContext&&(a=await t.transformContext(a,n));let o=await t.convertToLlm(a),s={systemPrompt:e.systemPrompt,messages:o,tools:e.tools},c=(t.getApiKey?await t.getApiKey(t.model.provider):void 0)||t.apiKey,l=await i(t.model,s,{...t,apiKey:c,signal:n}),u=null,d=!1;for await(let t of l)switch(t.type){case`start`:u=t.partial,e.messages.push(u),d=!0,await r({type:`message_start`,message:{...u}});break;case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:u&&(u=t.partial,e.messages[e.messages.length-1]=u,await r({type:`message_update`,assistantMessageEvent:t,message:{...u}}));break;case`done`:case`error`:{let t=await l.result();return d?e.messages[e.messages.length-1]=t:e.messages.push(t),d||await r({type:`message_start`,message:{...t}}),await r({type:`message_end`,message:t}),t}}let f=await l.result();return d?e.messages[e.messages.length-1]=f:(e.messages.push(f),await r({type:`message_start`,message:{...f}})),await r({type:`message_end`,message:f}),f}async function t_(e,t){let n=[];for(let r of e){await t({type:`tool_execution_start`,toolCallId:r.id,toolName:r.name,args:r.arguments});let e={toolCall:r,result:u_(`Tool call "${r.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await d_(e,t);let i=f_(e);await p_(i,t),n.push(i)}return{messages:n,terminate:!1}}async function n_(e,t,n,r,i){let a=t.content.filter(e=>e.type===`toolCall`),o=a.some(t=>e.tools?.find(e=>e.name===t.name)?.executionMode===`sequential`);return n.toolExecution===`sequential`||o?r_(e,t,a,n,r,i):i_(e,t,a,n,r,i)}async function r_(e,t,n,r,i,a){let o=[],s=[];for(let c of n){await a({type:`tool_execution_start`,toolCallId:c.id,toolName:c.name,args:c.arguments});let n=await s_(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await l_(e,t,n,await c_(n,i,a),r,i),await d_(l,a);let u=f_(l);if(await p_(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:a_(o)}}async function i_(e,t,n,r,i,a){let o=[];for(let s of n){await a({type:`tool_execution_start`,toolCallId:s.id,toolName:s.name,args:s.arguments});let n=await s_(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await d_(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{let o=await c_(n,i,a),s=await l_(e,t,n,o,r,i);return await d_(s,a),s}),i?.aborted)break}let s=await Promise.all(o.map(e=>typeof e==`function`?e():Promise.resolve(e))),c=[];for(let e of s){let t=f_(e);await p_(t,a),c.push(t)}return{messages:c,terminate:a_(s)}}function a_(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function o_(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function s_(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:u_(`Tool ${n.name} not found`),isError:!0};try{let o=Yg(a,o_(a,n));if(r.beforeToolCall){let a=await r.beforeToolCall({assistantMessage:t,toolCall:n,args:o,context:e},i);if(i?.aborted)return{kind:`immediate`,result:u_(`Operation aborted`),isError:!0};if(a?.block){let e=u_(a.reason||`Tool execution was blocked`);return a.terminate===!0&&(e.terminate=!0),{kind:`immediate`,result:e,isError:!0}}}return i?.aborted?{kind:`immediate`,result:u_(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:u_(e instanceof Error?e.message:String(e)),isError:!0}}}async function c_(e,t,n){let r=[],i=!0;try{let a=await e.tool.execute(e.toolCall.id,e.args,t,t=>{i&&r.push(Promise.resolve(n({type:`tool_execution_update`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,args:e.toolCall.arguments,partialResult:t})))});return i=!1,await Promise.all(r),{result:a,isError:!1}}catch(e){return i=!1,await Promise.all(r),{result:u_(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function l_(e,t,n,r,i,a){let o=r.result,s=r.isError;if(i.afterToolCall)try{let r=await i.afterToolCall({assistantMessage:t,toolCall:n.toolCall,args:n.args,result:o,isError:s,context:e},a);r&&(o={...o,content:r.content??o.content,details:r.details??o.details,usage:r.usage??o.usage,terminate:r.terminate??o.terminate},s=r.isError??s)}catch(e){o=u_(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function u_(e){return{content:[{type:`text`,text:e}],details:{}}}async function d_(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function f_(e){return{role:`toolResult`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,...e.result.addedToolNames?.length?{addedToolNames:e.result.addedToolNames}:{},isError:e.isError,timestamp:Date.now()}}async function p_(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function m_(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const h_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},g_={id:`unknown`,name:`unknown`,api:`unknown`,provider:`unknown`,baseUrl:``,reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function __(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??g_,thinkingLevel:e?.thinkingLevel??`off`,get tools(){return t},set tools(e){t=e.slice()},get messages(){return n},set messages(e){n=e.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}var v_=class{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}drain(){if(this.mode===`all`){let e=this.messages.slice();return this.messages=[],e}let e=this.messages[0];return e?(this.messages=this.messages.slice(1),[e]):[]}clear(){this.messages=[]}},y_=class{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;beforeToolCall;afterToolCall;shouldStopAfterTurn;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let t=e??{};this._state=__(t.initialState),this.convertToLlm=t.convertToLlm??m_,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??Xg(),this.getApiKey=t.getApiKey,this.onPayload=t.onPayload,this.onResponse=t.onResponse,this.beforeToolCall=t.beforeToolCall,this.afterToolCall=t.afterToolCall,this.shouldStopAfterTurn=t.shouldStopAfterTurn,this.prepareNextTurn=t.prepareNextTurn,this.prepareNextTurnWithContext=t.prepareNextTurnWithContext,this.steeringQueue=new v_(t.steeringMode??`one-at-a-time`),this.followUpQueue=new v_(t.followUpMode??`one-at-a-time`),this.sessionId=t.sessionId,this.thinkingBudgets=t.thinkingBudgets,this.transport=t.transport??`auto`,this.maxRetryDelayMs=t.maxRetryDelayMs,this.toolExecution=t.toolExecution??`parallel`}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before resetting.`);this._state.messages=[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,t){if(this.activeRun)throw Error(`Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.`);let n=this.normalizePromptInput(e,t);await this.runPromptMessages(n)}async continue(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before continuing.`);let e=this._state.messages[this._state.messages.length-1];if(!e)throw Error(`No messages to continue from`);if(e.role===`assistant`){let e=this.steeringQueue.drain();if(e.length>0){await this.runPromptMessages(e,{skipInitialSteeringPoll:!0});return}let t=this.followUpQueue.drain();if(t.length>0){await this.runPromptMessages(t);return}throw Error(`Cannot continue from message role: assistant`)}await this.runContinuation()}normalizePromptInput(e,t){if(Array.isArray(e))return e;if(typeof e!=`string`)return[e];let n=[{type:`text`,text:e}];return t&&t.length>0&&n.push(...t),[{role:`user`,content:n,timestamp:Date.now()}]}async runPromptMessages(e,t={}){await this.runWithLifecycle(async n=>{await Zg(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await Qg(this.createContextSnapshot(),this.createLoopConfig(),e=>this.processEvents(e),e,this.streamFunction)})}createContextSnapshot(){return{systemPrompt:this._state.systemPrompt,messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let t=e.skipInitialSteeringPoll===!0,n=this.shouldStopAfterTurn;return{model:this._state.model,reasoning:this._state.thinkingLevel===`off`?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,shouldStopAfterTurn:n?async e=>await n(e,this.signal):void 0,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async e=>this.prepareNextTurnWithContext?await this.prepareNextTurnWithContext(e,this.signal):await this.prepareNextTurn?.(this.signal):void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>t?(t=!1,[]):this.steeringQueue.drain(),getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error(`Agent is already processing.`);let t=new AbortController,n=()=>{},r=new Promise(e=>{n=e});this.activeRun={promise:r,resolve:n,abortController:t},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(t.signal)}catch(e){await this.handleRunFailure(e,t.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,t){let n={role:`assistant`,content:[{type:`text`,text:``}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:h_,stopReason:t?`aborted`:`error`,errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:`message_start`,message:n}),await this.processEvents({type:`message_end`,message:n}),await this.processEvents({type:`turn_end`,message:n,toolResults:[]}),await this.processEvents({type:`agent_end`,messages:[n]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case`message_start`:this._state.streamingMessage=e.message;break;case`message_update`:this._state.streamingMessage=e.message;break;case`message_end`:this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case`tool_execution_start`:{let t=new Set(this._state.pendingToolCalls);t.add(e.toolCallId),this._state.pendingToolCalls=t;break}case`tool_execution_end`:{let t=new Set(this._state.pendingToolCalls);t.delete(e.toolCallId),this._state.pendingToolCalls=t;break}case`turn_end`:e.message.role===`assistant`&&e.message.errorMessage&&(this._state.errorMessage=e.message.errorMessage);break;case`agent_end`:this._state.streamingMessage=void 0}let t=this.activeRun?.abortController.signal;if(!t)throw Error(`Agent listener invoked outside active run`);for(let n of this.listeners)await n(e,t)}};function b_(e){if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=10||r===0?Math.round(n):Math.round(n*10)/10} ${t[r]}`}function x_(e){let t=e.mimeType||`application/octet-stream`;return`${e.name} (${t}, ${b_(e.size)})`}function S_(e){let t=x_(e);return e.kind===`image`&&e.data?e.path?`[Attached image: ${t} — full-resolution copy saved to ${e.path}]`:`[Attached image: ${t}]`:e.kind===`text`&&e.text!==void 0?[`----- BEGIN ATTACHMENT ${t} -----`,e.text,`----- END ATTACHMENT ${e.name} -----`].join(`
|
|
880
|
-
`):e.path?`[Attached ${e.kind===`image`?`image`:e.kind===`text`?`text file`:`file`} saved to ${e.path} — ${t}. Read it from the virtual filesystem when you need its contents.]`:e.error?`[Attachment not included: ${t}. ${e.error}]`:`[Attachment not included: ${t}. Unsupported binary attachment.]`}function
|
|
877
|
+
}`,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 Li(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)Li(n,t)}function Ri(e){let t=e.exceptionDetails;return t?t.exception?.description??t.text:null}function zi(e,t){let n=Ri(e);if(n!==null)throw Error(`${t}: ${n}`);return e.result?.value}function Bi(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 Vi(e){let t=new Map;for(let n of e){let e=typeof n.backendDOMNodeId==`number`?n.backendDOMNodeId:null;if(e===null)continue;let r=n.role,i=n.name,a=typeof r?.value==`string`?r.value.toLowerCase():``,o=typeof i?.value==`string`?i.value:``;if(!a)continue;let s=`${a}|${o}`;t.has(s)||t.set(s,e)}return t}function Hi(e,t){let n=`${e.role.toLowerCase()}|${e.name}`,r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)Hi(n,t)}function Ui(e){let t={role:re(e.role,`unknown`),name:re(e.name)},n=re(e.value);n!==``&&(t.value=n);let r=re(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>Ui(e)).filter(e=>e.role!==`unknown`)),t}const Wi=y(`browser-api`),Gi=[`Session with given id not found`,`Target closed`,`No session with given id`,`No tab attached for sessionId`];var Ki=class extends Error{};function qi(e){let t=e instanceof Error?e.message:String(e);return Gi.some(e=>t.includes(e))}function Ji(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}}function Yi(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var Xi=class{inner;onApplied;onStateChange;constructor(e,t){this.inner=e,this.onApplied=t,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=r===void 0?await this.inner.send(e,t,n):await this.inner.send(e,t,n,r);return n&&this.onApplied(n),i}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)}},Zi=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContexts=new Map;_sessions=new Map;_listenedTransports=new Set;_sessionReplacedSubs=new Map;_appliedSends=new Map;_pinnedTargets=new Map;_tabLocks=new Map;_bridgeLock=Promise.resolve();_bridgeHold=null;_bridgeWaiters=0;_viewportOverrides=new Map;_tabLockStats=new Map;_onSessionChange;_lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;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),Wi.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){Wi.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.frameContexts(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._frameContexts.get(`main:${t}`);if(r)for(let[e,t]of r)t===n&&r.delete(e)};handleExecutionContextsCleared=e=>{let t=this.eventSessionId(e);t&&this._frameContexts.get(`main:${t}`)?.clear()};eventSessionId(e){let t=e.sessionId;return typeof t==`string`?t:this.sessionId}handleDetachedFromTarget=e=>{let t=e.sessionId;if(typeof t==`string`){for(let[e,n]of this._sessions)if(n.sessionId===t){this.forgetSession(e,n);return}}};handleTargetDestroyed=e=>{let t=e.targetId;if(typeof t==`string`){for(let[e,n]of this._sessions)if(e===t||n.remote?.localTargetId===t){this.forgetSession(e,n);return}}};constructor(e){this.client=e??new Ci,this.localClient=this.client,this.addTransportListeners(this.client)}getTransport(){return this.accountedTransportFor(this.client)}getUnderlyingTransport(){return this.client}_accountedTransports=new WeakMap;accountedTransportFor(e){if(e instanceof Xi)return e;let t=this._accountedTransports.get(e);return t||(t=new Xi(e,e=>this.noteApplied(e)),this._accountedTransports.set(e,t)),t}noteApplied(e){this._appliedSends.set(e,(this._appliedSends.get(e)??0)+1)}createHarRecorder(e,t){return new Ai(t,e)}setSessionChangeCallback(e){this._onSessionChange=e}onSessionReplaced(e,t){let n=this._sessionReplacedSubs.get(e);return n||(n=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;Ti(r,`starting a command on tab ${e}`);let i=this.tabCounters(e);i.queueDepth+=1;let a;try{a=await this.acquireTabLock(e,i,r)}catch(e){throw--i.queueDepth,e}let o=this.pinTarget(e);try{return i.acquisitions+=1,await this.runOnTab(e,t,r)}finally{o(),--i.queueDepth,a()}}async runOnTab(e,t,n){try{return await this.attemptOnTab(e,t,n)}catch(r){if(r instanceof Ki||!qi(r))throw r;return Wi.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.reentrantOwner(e),n);Ti(n,`about to run a command on tab ${e}`);let i=r.sessionId,a=this._appliedSends.get(i)??0;try{return await t(r)}catch(t){if(!qi(t))throw t;let n=(this._appliedSends.get(i)??0)-a;if(n===0)throw t;this.invalidateSession(e);let r=t instanceof Error?t.message:String(t);throw Wi.warn(`CDP session reset mid-command — not replaying`,{targetId:e,applied:n,reason:r}),new Ki(`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})`)}}async attachHandle(e,t,n){let r=await this.attachToPageOwned(e,t,n),i=this._sessions.get(e);return new Ii(this,e,r,this.accountedTransportFor(i?.transport??this.client),n)}handleFor(e,t){return new Ii(this,e,t.sessionId,this.accountedTransportFor(t.transport))}getTabLockStats(e){if(e!==void 0)return Ji(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 Ji(t)}tabCounters(e){let t=this._tabLockStats.get(e);return t||(t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0},this._tabLockStats.set(e,t)),t}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){let r=Date.now();try{await Oi(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())}}reentrantOwner(e){let t=this._bridgeHold;if(!(!t||e===null||t.targetId!==e))return t.owner}async runGlobal(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e),targetId:e});try{return await t()}finally{n()}}viewportOverride(e){return this._viewportOverrides.get(e)}recordViewportOverride(e,t){this._viewportOverrides.set(e,t)}frameContexts(e,t){let n=`${t}:${e}`,r=this._frameContexts.get(n);return r||(r=new Map,this._frameContexts.set(n,r)),r}dropFrameContexts(e){this._frameContexts.delete(`main:${e}`),this._frameContexts.delete(`isolated:${e}`)}async reapplyViewportOverride(e,t){let n=this._viewportOverrides.get(e);if(n)try{await this.handleFor(e,t).applyViewportOverride(n)}catch(t){Wi.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){this._lastConnectOptions=e?{...e}:{},await this.client.connect({url:e?.url??Yi(),timeout:e?.timeout,...e?.protocols===void 0?{}:{protocols:e.protocols}}),this.supersededNotified=!1}async reconnectIfNeeded(){await this.ensureConnected(),this.client!==this.localClient&&await this.ensureLocalConnected()}primeConnectOptions(e){this._lastConnectOptions=e?{...e}:{}}setCdpSupersededHandler(e){this.supersededHandler=e}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}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._viewportOverrides.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.reentrantOwner(e))}async attachToPageOwned(e,t,n){let r=await this.acquireBridgeLock({owner:t,targetId:e,counters:this.tabCounters(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}`);Ti(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),Ti(t,`about to enable Page on tray tab ${e}`),await a.send(`Page.enable`,{},o.sessionId),Ti(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(),Ti(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),Ti(t,`about to enable Page on tab ${e}`),await this.localClient.send(`Page.enable`,{},n.sessionId),Ti(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.acquireBridgeLock({owner:this.reentrantOwner(e.targetId),targetId:e.targetId});try{return await this.wakeCaptureLocked(e,t,this._bridgeHold?.owner)}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(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){let e=this._lastConnectOptions;await this.localClient.connect({url:e?.url??Yi(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}if(this.client.state===`disconnected`){let e=this.client;this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.clearSessionsForTransport(e),this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0)}}transportForSession(e){for(let t of this._sessions.values())if(t.sessionId===e)return t.transport;return 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){if(e!==this.localClient&&this._listenedTransports.has(e)){for(let t of this._sessions.values())if(t.transport===e)return;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.values()].some(t=>t.remote?.runtimeId===e.runtimeId&&t.remote.localTargetId===e.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.runtimeId,e.localTargetId))}pruneAppliedSends(){if(this._appliedSends.size<=128)return;let e=new Set([...this._sessions.values()].map(e=>e.sessionId));for(let t of[...this._appliedSends.keys()])e.has(t)||this._appliedSends.delete(t)}rememberSession(e,t){this.addTransportListeners(t.transport),this.pruneAppliedSends(),this._sessions.set(e,t),this.enforceSessionCap(e)}enforceSessionCap(e){for(;this._sessions.size>32;){let t;for(let n of this._sessions.keys())if(!(n===e||this._pinnedTargets.has(n))){t=n;break}if(t===void 0)return;let n=this._sessions.get(t);this._sessions.delete(t),n&&(Wi.debug(`Evicting least-recently-used CDP session`,{targetId:t}),this.detachSession(t,n))}}pinTarget(e){this._pinnedTargets.set(e,(this._pinnedTargets.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(this._pinnedTargets.get(e)??1)-1;n>0?this._pinnedTargets.set(e,n):this._pinnedTargets.delete(e),this.enforceSessionCap()}}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.delete(e),this._sessions.set(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){Wi.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.values()].some(t=>t.remote?.runtimeId===e.remote?.runtimeId&&t.remote?.localTargetId===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])n.transport===e&&this.forgetSession(t,n)}clearSessions(){for(let[e,t]of[...this._sessions])this.forgetSession(e,t);this._sessions.clear(),this.sessionId=null,this.attachedTargetId=null}};const Qi=y(`panel-rpc-cdp`);var $i=class{getPanelRpc;runtimeId;localTargetId;timeoutMs;eventListeners=new Map;pendingOnce=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(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=>{Qi.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,ae)+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=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(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){Qi.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=>{Qi.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=>{Qi.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function ea(e){let t=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 $i(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}}}const ta=Object.freeze([Object.freeze({id:`experimental-settings`,label:`Experimental settings`,description:`Show controls for experimental features.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1,since:`2026-07-31`}),Object.freeze({id:`panel-layouts`,label:`Panel layouts`,description:`Arrange the UI as movable, resizable panels instead of the fixed workbench.`,defaultValue:`off`,userToggleable:!0,since:`2026-08-03`}),Object.freeze({id:`agentic-memory`,label:`Agentic memory`,description:`Curate session memory with a background agent instead of a one-shot extraction call.`,defaultValue:`off`,userToggleable:!0,since:`2026-08-05`}),Object.freeze({id:`multiple-cones`,label:`Multiple cones`,description:`Add, switch between and remove cones from the freezer rail. Extra cones share the workspace.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1,since:`2026-08-21`}),Object.freeze({id:`compact-on-idle`,label:`Compact on idle`,description:`When a cone has been idle for a while with a large context, summarize its history in the background. The full transcript is kept in /sessions.`,defaultValue:`on`,userToggleable:!1,since:`2026-09-02`}),Object.freeze({id:`memory-v2`,label:`Memory v2`,description:`Searchable session history, scoop pre-compaction snapshots, and the gelatiere — a resident advisor that reviews your sessions and suggests skills and use cases.`,defaultValue:`off`,userToggleable:!0,since:`2026-09-10`})]);new Map(ta.map(e=>[e.id,e]));const na=new Set([`1`,`on`,`true`]);let ra=`standalone`,ia={},aa={};function oa(e,t={},n=sa()){let r={};for(let i of ta){let a=n[i.id];if(typeof a==`string`&&ma(i,e)){r[i.id]=a;continue}let o=aa[i.id];if(typeof o==`string`&&ma(i,e)){r[i.id]=o;continue}let s=t[i.id];r[i.id]=typeof s==`string`?s:pa(i,e)}return r}function sa(){try{let e=ga()?.getItem(`slicc_feature_flags`);return e?ha(JSON.parse(e)):{}}catch{return{}}}function ca(e,t={}){ra=e,ia=ha(t),aa={}}function la(e,t){ra=e,ia=ha(t)}function ua(e){return oa(ra,ia)[e]}function da(e){return typeof e==`string`&&na.has(e.trim().toLowerCase())}function fa(e){return da(ua(e))}function pa(e,t){return e.floatDefaults?.[t]??e.defaultValue}function ma(e,t){return e.userToggleable&&(e.overridableFloats===void 0||e.overridableFloats.includes(t))}function ha(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t=e,n={};for(let e of ta){let r=t[e.id];typeof r==`string`&&(n[e.id]=r)}return n}function ga(){try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function _a(e){return`slicc_feature_flags_remote:${e}`}let va=null;function ya(e,t){let n=xa(t);va=e,ca(e,Sa(n,e)??{})}function ba(e,t){if(!va||e!==void 0&&e!==_a(va))return!1;let n=xa(t);return la(va,Sa(n,va)??{}),!0}function xa(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 Sa(e,t){try{let n=e?.getItem(_a(t));return n?Ca(JSON.parse(n)):null}catch{return null}}function Ca(e){return!wa(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function wa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ta=y(`stale-asset`),Ea=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Da(e){return Ea.test(e)}let Oa=null;function ka(e){if(!e){Oa=null;return}Oa=e}function Aa(e=!1){if(!Oa||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Oa,replayTurn:e})}finally{t.close()}}function ja(e){Da(e instanceof Error?e.message:String(e))&&Aa()}function Ma(e,t){return!e||e===t?!1:(Ta.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),Aa(),!0)}function Na(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Pa(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Fa=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Ia(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Fa.map(e=>La(i,e,t,r)))).filter(e=>e!==null)}async function La(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal,redirect:`manual`,credentials:`omit`});return e.status!==200||!Ra(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Ra(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 za=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new yi;unsubscribe=null;stateListeners=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,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=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 bi(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 Ba(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 Va(e){let t=Ba(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var Ha=class extends za{constructor(e){let t=Ba(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 Wa=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function Ga(e){return Wa.test(e)}function Ka(e,t){return`(${e} && ${t})`}function M(e,t){return`(${e} || ${t})`}function qa(e){return`!(${e})`}function Ja(e){return`Array.isArray(${e})`}function Ya(e){return`typeof ${e} === "bigint"`}function Xa(e){return`typeof ${e} === "boolean"`}function Za(e){return`Number.isInteger(${e})`}function Qa(e){return`${e} === null`}function $a(e){return`Number.isFinite(${e})`}function eo(e){return Ka(to(e),qa(Ja(e)))}function to(e){return`typeof ${e} === "object" && ${e} !== null`}function no(e){return`typeof ${e} === "string"`}function ro(e){return`typeof ${e} === "symbol"`}function io(e){return`${e} === undefined`}function ao(e){return`typeof ${e} === "function"`}function oo(e){return`Guard.IsConstructor(${e})`}function so(e,t){return`${e} === ${t}`}function co(e,t){return`${e} > ${t}`}function lo(e,t){return`${e} < ${t}`}function uo(e,t){return`${e} <= ${t}`}function fo(e,t){return`${e} >= ${t}`}function po(e,t){return`Guard.IsMinLength(${e}, ${t})`}function mo(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function ho(e,t,n,r){return E(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => ${r})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${n[0]}, ${n[1]}) => ${r})`}function go(e){return`Object.entries(${e})`}function _o(e){return`Object.getOwnPropertyNames(${e})`}function vo(e,t){return E(t,`"__proto__"`)||E(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function yo(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function bo(e){return`[${e.join(`, `)}]`}function xo(e,t){return`((${e.join(`, `)}) => ${t})`}function N(e,t){return`${e}(${t.join(`, `)})`}function So(e,t){return`new ${e}(${t.join(`, `)})`}function P(e,t){return`${e}${Ga(t)?`.${t}`:`[${F(t)}]`}`}function F(e){return b(e)?JSON.stringify(e):`${e}`}function Co(e,t,n){return`(${e} ? ${t} : ${n})`}function wo(e){return`{ ${e.join(`; `)}; }`}function To(e,t){return`const ${e} = ${t}`}function Eo(e,t){return`if(${e}) { ${t} }`}function Do(e){return`return ${e}`}function Oo(e){return E(e.length,0)?`true`:e.reduce((e,t)=>Ka(e,t))}function ko(e){return E(e.length,0)?`false`:e.reduce((e,t)=>M(e,t))}function Ao(e){return`++${e}`}function jo(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Mo=Ze;function No(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let Po;function Fo(){try{return Lo(`null`)(),!0}catch{return!1}}function Io(){return T(Po)&&(Po=Fo()),Po&&Wt().useAcceleration}function Lo(...e){return new globalThis.Function(...e)}function Ro(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 zo=Ro;function Bo(){return zo}const Vo=[/prompt is too long/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,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i],Ho=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Uo(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!Ho.some(t=>t.test(e.errorMessage))&&Vo.some(t=>t.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 Wo(e){return O(e,`~refine`)&&w(e[`~refine`])&&C(e[`~refine`],0,e=>S(e)&&O(e,`check`)&&O(e,`error`)&&Pt(e.check)&&Pt(e.error))}function Go(e){return S(e)&&!w(e)}function Ko(e){return Kt(e)}function I(e){return Go(e)||Ko(e)}function qo(e){return O(e,`additionalItems`)&&I(e.additionalItems)}function Jo(e){return O(e,`additionalProperties`)&&I(e.additionalProperties)}function Yo(e){return O(e,`allOf`)&&w(e.allOf)&&e.allOf.every(e=>I(e))}function Xo(e){return O(e,`$anchor`)&&b(e.$anchor)}function Zo(e){return O(e,`anyOf`)&&w(e.anyOf)&&e.anyOf.every(e=>I(e))}function Qo(e){return O(e,`const`)}function $o(e){return O(e,`contains`)&&I(e.contains)}function es(e){return O(e,`default`)}function ts(e){return O(e,`dependencies`)&&S(e.dependencies)&&Object.values(e.dependencies).every(e=>I(e)||w(e)&&e.every(e=>b(e)))}function ns(e){return O(e,`dependentRequired`)&&S(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>w(e)&&e.every(e=>b(e)))}function rs(e){return O(e,`dependentSchemas`)&&S(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>I(e))}function is(e){return O(e,`$dynamicAnchor`)&&b(e.$dynamicAnchor)}function as(e){return O(e,`$dynamicRef`)&&b(e.$dynamicRef)}function os(e){return O(e,`else`)&&I(e.else)}function ss(e){return O(e,`enum`)&&w(e.enum)}function cs(e){return O(e,`exclusiveMaximum`)&&(k(e.exclusiveMaximum)||Mt(e.exclusiveMaximum))}function ls(e){return O(e,`exclusiveMinimum`)&&(k(e.exclusiveMinimum)||Mt(e.exclusiveMinimum))}function us(e){return O(e,`format`)&&b(e.format)}function ds(e){return O(e,`$id`)&&b(e.$id)}function fs(e){return O(e,`if`)&&I(e.if)}function ps(e){return O(e,`items`)&&(I(e.items)||w(e.items)&&e.items.every(e=>I(e)))}function ms(e){return ps(e)&&w(e.items)}function hs(e){return O(e,`maximum`)&&(k(e.maximum)||Mt(e.maximum))}function gs(e){return O(e,`maxContains`)&&k(e.maxContains)}function _s(e){return O(e,`maxItems`)&&k(e.maxItems)}function vs(e){return O(e,`maxLength`)&&k(e.maxLength)}function ys(e){return O(e,`maxProperties`)&&k(e.maxProperties)}function bs(e){return O(e,`minimum`)&&(k(e.minimum)||Mt(e.minimum))}function xs(e){return O(e,`minContains`)&&k(e.minContains)}function Ss(e){return O(e,`minItems`)&&k(e.minItems)}function Cs(e){return O(e,`minLength`)&&k(e.minLength)}function ws(e){return O(e,`minProperties`)&&k(e.minProperties)}function Ts(e){return O(e,`multipleOf`)&&(k(e.multipleOf)||Mt(e.multipleOf))}function Es(e){return O(e,`not`)&&I(e.not)}function Ds(e){return O(e,`oneOf`)&&w(e.oneOf)&&e.oneOf.every(e=>I(e))}function Os(e){return O(e,`pattern`)&&(b(e.pattern)||e.pattern instanceof RegExp)}function ks(e){return O(e,`patternProperties`)&&S(e.patternProperties)&&Object.values(e.patternProperties).every(e=>I(e))}function As(e){return O(e,`prefixItems`)&&w(e.prefixItems)&&e.prefixItems.every(e=>I(e))}function js(e){return O(e,`properties`)&&S(e.properties)&&Object.values(e.properties).every(e=>I(e))}function Ms(e){return O(e,`propertyNames`)&&(S(e.propertyNames)||I(e.propertyNames))}function Ns(e){return O(e,`$recursiveAnchor`)&&Kt(e.$recursiveAnchor)}function Ps(e){return Ns(e)&&E(e.$recursiveAnchor,!0)}function Fs(e){return O(e,`$recursiveRef`)&&b(e.$recursiveRef)}function Is(e){return O(e,`$ref`)&&b(e.$ref)}function Ls(e){return O(e,`required`)&&w(e.required)&&e.required.every(e=>b(e))}function Rs(e){return O(e,`then`)&&I(e.then)}function zs(e){return O(e,`type`)&&(b(e.type)||w(e.type)&&e.type.every(e=>b(e)))}function Bs(e){return O(e,`uniqueItems`)&&Kt(e.uniqueItems)}function Vs(e){return O(e,`unevaluatedItems`)&&I(e.unevaluatedItems)}function Hs(e){return O(e,`unevaluatedProperties`)&&I(e.unevaluatedProperties)}function Us(e){return Vs(e)||Hs(e)||x(e).some(t=>Gs(e[t]))}function Ws(e){return e.some(e=>Gs(e))}function Gs(e){return w(e)?Ws(e):S(e)?Us(e):!1}function Ks(e,t){return Gs(t)||x(e).some(t=>Gs(e[t]))}var qs=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return N(P(`context`,`Push`),[])}Pop(){return N(P(`context`,`Pop`),[])}AddIndex(e){return N(P(`context`,`AddIndex`),[e])}AddKey(e){return N(P(`context`,`AddKey`),[e])}Merge(e){return N(P(`context`,`Merge`),[e])}},Js=class{constructor(){let e=new Set,t=new Set;this.stack=[{indices:e,keys:t}]}Push(){let e=new Set,t=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}},Ys=class extends Js{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Xs=class extends Ys{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const Zs={identifier:`External`,variables:[]};function Qs(e){let t=`External[${Zs.variables.length}]`;return Zs.variables.push(e),t}function $s(){Zs.variables=[]}function ec(){return{...Zs}}function tc(e,t,n,r){return ho(Qs(n[`~refine`].map(e=>e)),F(0),[`refinement`,`_`],N(P(`refinement`,`check`),[r]))}function nc(e,t,n,r){return C(n[`~refine`],0,(e,t)=>e.check(r))}function rc(e,t,n,r,i,a){return Rt(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let ic=0;function L(){return`var_${ic++}`}function ac(e){return ps(e)&&w(e.items)}function oc(e,t,n,r){if(!ac(n))return F(!0);let[i,a]=[L(),L()],o=Pf(e,t,n.additionalItems,i),s=lo(a,F(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?M(s,Ka(o,c)):M(s,o);return N(P(r,`every`),[xo([i,a],l)])}function sc(e,t,n,r){return!ac(n)||r.every((r,i)=>$t(i,n.items.length)||Ff(e,t,n.additionalItems,r)&&t.AddIndex(i))}function cc(e,t,n,r,i,a){return!ac(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return $t(o,i.items.length)||If(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function lc(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function uc(e){let t=[];return ks(e)&&t.push(...x(e.patternProperties)),js(e)&&t.push(...x(e.properties).map(lc)),E(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function dc(e,t,n){return Ls(t)&&js(t)&&!ks(t)&&E(t.additionalProperties,!1)&&E(x(t.properties).length,t.required.length)}function fc(e,t,n){return so(P(N(P(`Object`,`getOwnPropertyNames`),[n]),`length`),F(t.required.length))}function pc(e,t,n,r){let[i,a]=[L(),L()],o=Qs(new RegExp(uc(n))),s=Pf(e,t,n.additionalProperties,`${r}[${i}]`),c=N(P(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?M(c,Ka(s,l)):M(c,s);return ho(_o(r),F(0),[i,a],u)}function mc(e,t,n,r){return dc(t,n,r)?fc(t,n,r):pc(e,t,n,r)}function hc(e,t,n,r){let i=new RegExp(uc(n));return C(x(r),0,(a,o)=>i.test(a)||Ff(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function gc(e,t,n,r,i,a){let o=new RegExp(uc(i)),s=[];return Rt(x(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new Xs,p=o.test(c)||If(e,f,u,d,i.additionalProperties,a[c])&&t.AddKey(c);return p||s.push(c),p})||t.AddError({keyword:`additionalProperties`,schemaPath:n,instancePath:r,params:{additionalProperties:s}})}function _c(e,t,n,r,i){let a=To(`results`,`[]`),o=n.map((e,t)=>To(`context_${t}`,So(`CheckContext`,[]))),s=n.map((n,i)=>To(`condition_${i}`,N(xo([`context`],z(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>Eo(`condition_${t}`,N(P(`results`,`push`),[`context_${t}`]))),l=Do(Ka(i,t.Merge(`results`)));return N(xo([],wo([a,...o,...s,...c,l])),[])}function vc(e,t,n,r){return _c(e,t,n.allOf,r,so(P(`results`,`length`),F(n.allOf.length)))}function yc(e,t,n,r){return Oo(n.allOf.map(n=>z(e,t,n,r)))}function bc(e,t,n,r){return t.UseUnevaluated()?vc(e,t,n,r):yc(e,t,n,r)}function xc(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new Js;return B(e,i,n,r)?[...t,i]:t},[]);return E(i.length,n.allOf.length)&&t.Merge(i)}function Sc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new Xs,u=V(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=E(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function Cc(e,t,n,r){return _c(e,t,n.anyOf,r,co(P(`results`,`length`),F(0)))}function wc(e,t,n,r){return ko(n.anyOf.map(n=>z(e,t,n,r)))}function Tc(e,t,n,r){return t.UseUnevaluated()?Cc(e,t,n,r):wc(e,t,n,r)}function Ec(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new Js;return B(e,i,n,r)?[...t,i]:t},[]);return Ct(i.length,0)&&t.Merge(i)}function Dc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new Xs,l=V(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=Ct(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 Oc(e,t,n,r){return F(!!n)}function kc(e,t,n,r){return n}function Ac(e,t,n,r,i,a){return kc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function jc(e,t,n,r){return kt(n.const)?so(r,F(n.const)):yo(r,Qs(n.const))}function Mc(e,t,n,r){return kt(n.const)?E(r,n.const):xt(r,n.const)}function Nc(e,t,n,r,i,a){return Mc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Pc(e){return!(xs(e)&&E(e.minContains,0))}function Fc(e,t,n,r){if(!Pc(n))return F(!0);let i=L();return Ka(qa(so(P(r,`length`),F(0))),N(P(r,`some`),[xo([i],z(e,t,n.contains,i))]))}function Ic(e,t,n,r){return!Pc(n)||!E(r.length,0)&&r.some(r=>B(e,t,n.contains,r))}function Lc(e,t,n,r,i,a){return Ic(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Rc(e,t,n,r){return M(so(P(_o(r),`length`),F(0)),Oo(D(n.dependencies).map(([n,i])=>{let a=qa(vo(r,F(n))),o=z(e,t,i,r);return M(a,w(i)?(e=>Oo(e.map(e=>vo(r,F(e)))))(i):o)})))}function zc(e,t,n,r){let i=E(x(r).length,0),a=C(D(n.dependencies),0,([n,i])=>!O(r,n)||(w(i)?i.every(e=>O(r,e)):B(e,t,i,r)));return i||a}function Bc(e,t,n,r,i,a){let o=E(x(a).length,0),s=Rt(D(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!O(a,i)||(w(o)?o.every(e=>O(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):V(e,t,s,r,o,a))});return o||s}function Vc(e,t,n,r){return M(so(P(_o(r),`length`),F(0)),Oo(D(n.dependentRequired).map(([e,t])=>M(qa(vo(r,F(e))),Oo(t.map(e=>vo(r,F(e))))))))}function Hc(e,t,n,r){let i=E(x(r).length,0),a=C(D(n.dependentRequired),0,([e,t])=>!O(r,e)||t.every(e=>O(r,e)));return i||a}function Uc(e,t,n,r,i,a){let o=E(x(a).length,0),s=Rt(D(i.dependentRequired),0,([e,i])=>!O(a,e)||Rt(i,0,o=>O(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function Wc(e,t,n,r){return M(so(P(_o(r),`length`),F(0)),Oo(D(n.dependentSchemas).map(([n,i])=>M(qa(vo(r,F(n))),z(e,t,i,r)))))}function Gc(e,t,n,r){let i=E(x(r).length,0),a=C(D(n.dependentSchemas),0,([n,i])=>!O(r,n)||B(e,t,i,r));return i||a}function Kc(e,t,n,r,i,a){let o=E(x(a).length,0),s=Rt(D(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!O(a,i)||V(e,t,s,r,o,a)});return o||s}function qc(e,t,n,r){return Kf(e,t,e.DynamicRef(n)??!1,r)}function Jc(e,t,n,r){let i=e.DynamicRef(n)??!1;return I(i)&&B(e,t,i,r)}function Yc(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return I(o)&&V(e,t,`#`,r,o,a)}function Xc(e,t,n,r){return ko(n.enum.map(e=>kt(e)?so(r,F(e)):yo(r,Qs(e))))}function Zc(e,t,n,r){return n.enum.some(e=>kt(e)?E(r,e):xt(r,e))}function Qc(e,t,n,r,i,a){return Zc(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function $c(e,t,n,r){return lo(r,F(n.exclusiveMaximum))}function el(e,t,n,r){return $t(r,n.exclusiveMaximum)}function tl(e,t,n,r,i,a){return el(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function nl(e,t,n,r){return co(r,F(n.exclusiveMinimum))}function rl(e,t,n,r){return Ct(r,n.exclusiveMinimum)}function il(e,t,n,r,i,a){return rl(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const al=[0,31,28,31,30,31,30,31,31,30,31,30,31],ol=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function sl(e){return e%4==0&&(e%100!=0||e%400==0)}function cl(e){let t=ol.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&&sl(n)?29:al[r])}const ll=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function ul(e,t=!0){let n=ll.exec(e);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4]===`-`?-1:1,s=+(n[5]||0),c=+(n[6]||0);if(s>23||c>59||t&&!n[4]&&e.toLowerCase().indexOf(`z`)===-1)return!1;if(r<=23&&i<=59&&a<60)return!0;let l=i-c*o,u=r-s*o-+(l<0);return(u===23||u===-1)&&(l===59||l===-1)&&a<61}function dl(e,t=!0){let n=e.split(/T/i);return n.length===2&&cl(n[0])&&ul(n[1],t)}const fl=/^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 pl(e){return fl.test(e)}const ml=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function hl(e){return ml.test(e)}function gl(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 _l(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);if(r>=128)throw Error(`Invalid punycode: non-basic before delimiter`);t.push(r)}let o=a<0?0:a+1;for(;o<e.length;){let a=r,s=1,c=36;for(;;){if(o>=e.length)throw Error(`Invalid punycode: unexpected end of input`);let t=e.charCodeAt(o++),n;if(t>=97&&t<=122)n=t-97;else if(t>=48&&t<=57)n=t-48+26;else if(t>=65&&t<=90)Ge();else throw Error(`Invalid punycode: bad digit character`);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=gl(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function vl(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function yl(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function bl(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function xl(e){return vl(e)||yl(e)||bl(e)}const Sl=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),Cl=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function wl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function Tl(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function El(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function Dl(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function Ol(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function kl(e){return e>=1632&&e<=1641}function Al(e){return e>=1776&&e<=1785}function jl(e){return Cl.has(e)}function Ml(e){if(e.length===0)return Ge();let t=[...e].map(e=>e.codePointAt(0)),n=t.length;if(t[0]===45||t[n-1]===45||n>=4&&t[2]===45&&t[3]===45||xl(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(Sl.has(n))return!1;(El(n)||Dl(n)||Ol(n))&&(r=!0),kl(n)&&(i=!0),Al(n)&&(a=!0);let o=t[e-1],s=t[e+1];switch(n){case 183:if(o!==108||s!==108)return!1;break;case 885:if(s===void 0||!wl(s))return!1;break;case 1523:case 1524:if(o===void 0||!Tl(o))return!1;break;case 8204:if(o===void 0||o<128&&!jl(o))return!1;break;case 8205:if(o===void 0||!jl(o))return!1}}return!(e.includes(`・`)&&!r||i&&a)}function Nl(e){if(e.charCodeAt(0)===45||e.charCodeAt(e.length-1)===45||e.length>=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!(n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45))return!1}return!0}function Pl(e){return e.toLowerCase().startsWith(`xn--`)}function Fl(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=_l(t);return n?Ml(n):!1}catch{return!1}}function Il(e){return e.length===0||e.length>63?!1:Pl(e)?Fl(e):Ml(e)}function Ll(e){return e.length===0||e.length>63?!1:Pl(e)?Fl(e):Nl(e)}function Rl(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!Ll(t))return!1;return!0}const zl=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function Bl(e){return zl.test(e)}function Vl(e){if(e.length===0||e.includes(` `))return!1;let t=e.normalize(`NFC`).replace(/[\u002E\u3002\uFF0E\uFF61]/g,`.`);if(t.length>253)return!1;for(let e of t.split(`.`))if(!Il(e))return!1;return!0}function Hl(e,t,n){let r=0,i=0,a=0,o=0;for(let s=t;s<n;s++){let t=e.charCodeAt(s);if(t===46){if(a===0||i>255||o===48&&a>1)return!1;r++,i=0,a=0,o=0}else if(t>=48&&t<=57)a===0&&(o=t),i=i*10+(t-48),a++;else return!1}return r===3&&a>0&&i<=255&&!(o===48&&a>1)}function Ul(e){return Hl(e,0,e.length)}function Wl(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Gl(e){let t=e.length;if(t===0)return!1;let n=0,r=!1,i=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;r=!0,i=2}for(;i<t;){let a=0,o=i;for(;i<t&&Wl(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!Hl(e,o,t))return!1;n+=2,i=t;break}if(a>4)return!1;if(n++,i===t)break;if(s!==58)return!1;if(i++,e.charCodeAt(i)===58){if(r||e.charCodeAt(i+1)===58)return!1;if(r=!0,i++,i===t)break}}return r?n<=7:n===8}function Kl(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function ql(e){if(e.includes(` `)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e===``)return!0;let t=e.indexOf(`:`);return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?Kl(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:Kl(e)}function Jl(e){try{return new URL(e),!0}catch{return!1}}const Yl=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Xl(e){return Yl.test(e)}const Zl=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Ql(e){return Zl.test(e)}function $l(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const eu=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function tu(e){return eu.test(e)}const nu=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function ru(e){return nu.test(e)}const iu=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function au(e){return iu.test(e)}function ou(e){return e>=97&&e<=122||e>=65&&e<=90}function su(e){return ou(e)||e>=48&&e<=57}function cu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function lu(e){return su(e)||e===43||e===45||e===46}function uu(e){return su(e)||e===45||e===46||e===95||e===126}function du(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function fu(e){return uu(e)||du(e)||e===58||e===64}function pu(e){let t=e.length;if(t===0||!ou(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!lu(t))return!1;n++}if(e.charCodeAt(n)!==58)return!1;if(n++,e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47){n+=2;let r=n,i=-1;for(let r=n;r<t;r++){let t=e.charCodeAt(r);if(t===64){i=r;break}if(t===47||t===63||t===35)break}if(i!==-1){for(let t=r;t<i;t++){let n=e.charCodeAt(t);if(n===91||n===93)return!1;if(n===37){if(t+2>=i||!cu(e.charCodeAt(t+1))||!cu(e.charCodeAt(t+2)))return!1;t+=2}else if(!uu(n)&&!du(n)&&n!==58)return!1}n=i+1}if(e.charCodeAt(n)===91){for(n++;n<t&&e.charCodeAt(n)!==93;)n++;if(e.charCodeAt(n)!==93)return!1;n++}else for(;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35||t===58)break;if(t<128&&!uu(t)&&!du(t))return!1;n++}if(e.charCodeAt(n)===58)for(n++;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35)break;if(t<48||t>57)return!1;n++}}for(;n<t;){let r=e.charCodeAt(n);if(r===37){if(n+2>=t||!cu(e.charCodeAt(n+1))||!cu(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(fu(r)||r===47||r===63||r===35))return!1;n++}return!0}const mu=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function hu(e){return mu.test(e)}const gu=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function _u(e){return gu.test(e)}const R=new Map;function vu(){R.clear()}function yu(){return[...R.entries()]}function bu(e,t){R.set(e,t)}function xu(e){return R.has(e)}function Su(e){return R.get(e)}function Cu(e,t){return R.get(e)?.(t)??!0}function wu(){vu(),R.set(`date-time`,dl),R.set(`date`,cl),R.set(`duration`,pl),R.set(`email`,hl),R.set(`hostname`,Rl),R.set(`idn-email`,Bl),R.set(`idn-hostname`,Vl),R.set(`ipv4`,Ul),R.set(`ipv6`,Gl),R.set(`iri-reference`,ql),R.set(`iri`,Jl),R.set(`json-pointer-uri-fragment`,Xl),R.set(`json-pointer`,Ql),R.set(`regex`,$l),R.set(`relative-json-pointer`,tu),R.set(`time`,ul),R.set(`uri-reference`,ru),R.set(`uri-template`,au),R.set(`uri`,pu),R.set(`url`,hu),R.set(`uuid`,_u)}wu();var Tu=e({Clear:()=>vu,Entries:()=>yu,Get:()=>Su,Has:()=>xu,IsDate:()=>cl,IsDateTime:()=>dl,IsDuration:()=>pl,IsEmail:()=>hl,IsHostname:()=>Rl,IsIPv4:()=>Ul,IsIPv6:()=>Gl,IsIdnEmail:()=>Bl,IsIdnHostname:()=>Vl,IsIri:()=>Jl,IsIriReference:()=>ql,IsJsonPointer:()=>Ql,IsJsonPointerUriFragment:()=>Xl,IsRegex:()=>$l,IsRelativeJsonPointer:()=>tu,IsTime:()=>ul,IsUri:()=>pu,IsUriReference:()=>ru,IsUriTemplate:()=>au,IsUrl:()=>hu,IsUuid:()=>_u,Reset:()=>wu,Set:()=>bu,Test:()=>Cu});function Eu(e,t,n,r){return N(P(`Format`,`Test`),[F(n.format),r])}function Du(e,t,n,r){return Cu(n.format,r)}function Ou(e,t,n,r,i,a){return Du(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function ku(e,t,n,r){let i=!Rs(n)||n.then,a=!os(n)||n.else;return Co(z(e,t,n.if,r),z(e,t,i,r),z(e,t,a,r))}function Au(e,t,n,r){let i=!Rs(n)||n.then,a=!os(n)||n.else;return B(e,t,n.if,r)?B(e,t,i,r):B(e,t,a,r)}function ju(e,t,n,r,i,a){let o=!Rs(i)||i.then,s=!os(i)||i.else,c=new Xs,l=V(e,c,`${n}/if`,r,i.if,a)?V(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):V(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 Mu(e,t,n,r){return Oo(n.items.map((n,i)=>{let a=uo(P(r,`length`),F(i)),o=Pf(e,t,n,`${r}[${i}]`),s=t.AddIndex(F(i));return M(a,t.UseUnevaluated()?Ka(o,s):o)}))}function Nu(e,t,n,r){return C(n.items,0,(n,i)=>Jt(r.length,i)||Ff(e,t,n,r[i])&&t.AddIndex(i))}function Pu(e,t,n,r,i,a){return Rt(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return Jt(a.length,o)||If(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Fu(e,t,n,r){let i=As(n)?n.prefixItems.length:0,a=Pf(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?Ka(a,o):a;return ho(r,F(i),[`element`,`index`],s)}function Iu(e,t,n,r){let i=As(n)?n.prefixItems.length:0;return C(r,i,(r,i)=>Ff(e,t,n.items,r)&&t.AddIndex(i))}function Lu(e,t,n,r,i,a){let o=As(i)?i.prefixItems.length:0;return Rt(a,o,(a,o)=>If(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function Ru(e,t,n,r){return ms(n)?Mu(e,t,n,r):Fu(e,t,n,r)}function zu(e,t,n,r){return ms(n)?Nu(e,t,n,r):Iu(e,t,n,r)}function Bu(e,t,n,r,i,a){return ms(i)?Pu(e,t,n,r,i,a):Lu(e,t,n,r,i,a)}function Vu(e){return $o(e)}function Hu(e,t,n,r){if(!Vu(n))return F(!0);let[i,a]=[L(),L()];return uo(N(P(r,`reduce`),[xo([i,a],Co(z(e,t,n.contains,a),Ao(i),i)),F(0)]),F(n.maxContains))}function Uu(e,t,n,r){if(!Vu(n))return!0;let i=r.reduce((r,i)=>B(e,t,n.contains,i)?++r:r,0);return Jt(i,n.maxContains)}function Wu(e,t,n,r,i,a){let o=xs(i)?i.minContains:1;return Uu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function Gu(e,t,n,r){return uo(r,F(n.maximum))}function Ku(e,t,n,r){return Jt(r,n.maximum)}function qu(e,t,n,r,i,a){return Ku(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function Ju(e,t,n,r){return uo(P(r,`length`),F(n.maxItems))}function Yu(e,t,n,r){return Jt(r.length,n.maxItems)}function Xu(e,t,n,r,i,a){return Yu(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function Zu(e,t,n,r){return mo(r,F(n.maxLength))}function Qu(e,t,n,r){return ht(r,n.maxLength)}function $u(e,t,n,r,i,a){return Qu(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function ed(e,t,n,r){return uo(P(_o(r),`length`),F(n.maxProperties))}function td(e,t,n,r){return Jt(x(r).length,n.maxProperties)}function nd(e,t,n,r,i,a){return td(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function rd(e){return $o(e)}function id(e,t,n,r){if(!rd(n))return F(!0);let[i,a]=[L(),L()];return fo(N(P(r,`reduce`),[xo([i,a],Co(z(e,t,n.contains,a),Ao(i),i)),F(0)]),F(n.minContains))}function ad(e,t,n,r){if(!rd(n))return!0;let i=r.reduce((r,i)=>B(e,t,n.contains,i)?++r:r,0);return Tt(i,n.minContains)}function od(e,t,n,r,i,a){return ad(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function sd(e,t,n,r){return fo(r,F(n.minimum))}function cd(e,t,n,r){return Tt(r,n.minimum)}function ld(e,t,n,r,i,a){return cd(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function ud(e,t,n,r){return fo(P(r,`length`),F(n.minItems))}function dd(e,t,n,r){return Tt(r.length,n.minItems)}function fd(e,t,n,r,i,a){return dd(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function pd(e,t,n,r){return po(r,F(n.minLength))}function md(e,t,n,r){return Zt(r,n.minLength)}function hd(e,t,n,r,i,a){return md(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function gd(e,t,n,r){return fo(P(_o(r),`length`),F(n.minProperties))}function _d(e,t,n,r){return Tt(x(r).length,n.minProperties)}function vd(e,t,n,r,i,a){return _d(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function yd(e,t,n,r){return jo(r,F(n.multipleOf))}function bd(e,t,n,r){return rt(r,n.multipleOf)}function xd(e,t,n,r,i,a){return bd(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function Sd(e,t,n,r){return _c(e,t,[n.not],r,qa(so(P(`results`,`length`),F(1))))}function Cd(e,t,n,r){return qa(z(e,t,n.not,r))}function wd(e,t,n,r){return t.UseUnevaluated()?Sd(e,t,n,r):Cd(e,t,n,r)}function Td(e,t,n,r){let i=new Js;return!B(e,i,n.not,r)&&t.Merge([i])}function Ed(e,t,n,r,i,a){return Td(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function Dd(e,t,n,r){return _c(e,t,n.oneOf,r,so(P(`results`,`length`),F(1)))}function Od(e,t,n,r){return so(N(P(bo(n.oneOf.map(n=>z(e,t,n,r))),`reduce`),[xo([`count`,`result`],Co(so(`result`,F(!0)),Ao(`count`),`count`)),F(0)]),F(1))}function kd(e,t,n,r){return t.UseUnevaluated()?Dd(e,t,n,r):Od(e,t,n,r)}function Ad(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new Js;return B(e,i,n,r)?[...t,i]:t},[]);return E(i.length,1)&&t.Merge(i)}function jd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new Xs,u=V(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=E(c.length,1)&&t.Merge(c);return!l&&E(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 Md(e,t,n,r){return N(P(Qs(b(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function Nd(e,t,n,r){return(b(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function Pd(e,t,n,r,i,a){return Nd(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function Fd(e,t,n,r){return Oo(D(n.patternProperties).map(([n,i])=>{let[a,o]=[L(),L()],s=qa(N(P(Qs(new RegExp(n,`u`)),`test`),[a])),c=Pf(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?M(s,Ka(c,l)):M(s,c);return ho(go(r),F(0),[`[${a}, ${o}]`,`_`],u)}))}function Id(e,t,n,r){return C(D(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return C(D(r),0,([n,r])=>!a.test(n)||Ff(e,t,i,r)&&t.AddKey(n))})}function Ld(e,t,n,r,i,a){return Rt(D(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return Rt(D(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||If(e,t,s,a,o,i)&&t.AddKey(n)})})}function Rd(e,t,n,r){return Oo(n.prefixItems.map((n,i)=>{let a=uo(P(r,`length`),F(i)),o=Pf(e,t,n,`${r}[${i}]`),s=t.AddIndex(F(i));return M(a,t.UseUnevaluated()?Ka(o,s):o)}))}function zd(e,t,n,r){return E(r.length,0)||C(n.prefixItems,0,(n,i)=>Jt(r.length,i)||Ff(e,t,n,r[i])&&t.AddIndex(i))}function Bd(e,t,n,r,i,a){return E(a.length,0)||Rt(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return Jt(a.length,o)||If(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Vd(e,t){return e.includes(t)||Wt().exactOptionalPropertyTypes}function Hd(e,t){return io(P(e,t))}function Ud(e,t){return T(e[t])}function Wd(e,t,n,r){let i=Ls(n)?n.required:[];return Oo(D(n.properties).map(([n,a])=>{let o=qa(vo(r,F(n))),s=Pf(e,t,a,P(r,n)),c=t.AddKey(F(n)),l=t.UseUnevaluated()?Ka(s,c):s,u=i.includes(n)?l:M(o,l);return Vd(i,n)?u:M(Hd(r,n),u)}))}function Gd(e,t,n,r){let i=Ls(n)?n.required:[];return C(D(n.properties),0,([n,a])=>{let o=!O(r,n)||Ff(e,t,a,r[n])&&t.AddKey(n);return Vd(i,n)?o:Ud(r,n)||o})}function Kd(e,t,n,r,i,a){let o=Ls(i)?i.required:[];return Rt(D(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!O(a,i)||If(e,t,c,l,s,a[i])&&t.AddKey(i);return Vd(o,i)?u():Ud(a,i)||u()})}function qd(e,t,n,r){let[i,a]=[L(),L()];return ho(_o(r),F(0),[i,a],z(e,t,n.propertyNames,i))}function Jd(e,t,n,r){return C(x(r),0,(r,i)=>B(e,t,n.propertyNames,r))}function Yd(e,t,n,r,i,a){let o=[];return Rt(x(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=V(e,new Xs,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Xd(e,t,n,r){return Kf(e,t,e.RecursiveRef(n)??!1,r)}function Zd(e,t,n,r){let i=e.RecursiveRef(n)??!1;return I(i)&&B(e,t,i,r)}function Qd(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return I(o)&&V(e,t,`#`,r,o,a)}function $d(e,t,n,r){let i=xo([`context`,`value`],Kf(e,t,n,`value`));return N(xo([`context`,`value`],wo([To(`nextContext`,So(`CheckContext`,[])),To(`result`,N(i,[`nextContext`,`value`])),Eo(`result`,t.Merge(`[nextContext]`)),Do(`result`)])),[`context`,r])}function ef(e,t,n,r){return Kf(e,t,n,r)}function tf(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?$d(e,t,i,r):ef(e,t,i,r)}function nf(e,t,n,r){let i=e.Ref(n)??!1,a=new Js,o=I(i)&&B(e,a,i,r);return o&&t.Merge([a]),o}function rf(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new Xs,c=I(o)&&V(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function af(e,t,n,r){return Oo(n.required.map(e=>vo(r,F(e))))}function of(e,t,n,r){return C(n.required,0,e=>O(r,e))}function sf(e,t,n,r,i,a){let o=[];return Rt(i.required,0,e=>{let t=O(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function cf(e,t,n,r){return E(n,`object`)?eo(r):E(n,`array`)?Ja(r):E(n,`boolean`)?Xa(r):E(n,`integer`)?Za(r):E(n,`number`)?$a(r):E(n,`null`)?Qa(r):E(n,`string`)?no(r):E(n,`bigint`)?Ya(r):E(n,`constructor`)?oo(r):E(n,`function`)?ao(r):E(n,`symbol`)?ro(r):E(n,`undefined`)||E(n,`void`)?io(r):F(!0)}function lf(e,t,n,r,i){return E(n,`object`)?He(i):E(n,`array`)?w(i):E(n,`boolean`)?Kt(i):E(n,`integer`)?ft(i):E(n,`number`)?k(i):E(n,`null`)?ze(i):E(n,`string`)?b(i):E(n,`bigint`)?Mt(i):E(n,`constructor`)?vt(i):E(n,`function`)?Pt(i):E(n,`symbol`)?$e(i):E(n,`undefined`)?T(i):!E(n,`void`)||T(i)}function uf(e,t,n,r){return ko(n.map(n=>cf(e,t,n,r)))}function df(e,t,n,r,i){return n.some(n=>lf(e,t,n,r,i))}function ff(e,t,n,r){return w(n.type)?uf(e,t,n.type,r):cf(e,t,n.type,r)}function pf(e,t,n,r){return w(n.type)?df(e,t,n.type,n,r):lf(e,t,n.type,n,r)}function mf(e,t,n,r,i,a){return(w(i.type)?df(e,t,i.type,i,a):lf(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function hf(e,t,n,r){let[i,a]=[L(),L()],o=N(P(`context`,`GetIndices`),[]),s=N(P(`indices`,`has`),[i]),c=z(e,t,n.unevaluatedItems,a),l=N(P(`context`,`AddIndex`),[i]),u=ho(r,F(0),[a,i],Ka(M(s,c),l));return N(xo([`context`],wo([To(`indices`,o),Do(u)])),[`context`])}function gf(e,t,n,r){let i=t.GetIndices();return C(r,0,(r,a)=>(i.has(a)||B(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function _f(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return Rt(a,0,(a,c)=>{let l=new Xs,u=(o.has(c)||V(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 vf(e,t,n,r){let[i,a]=[L(),L()],o=N(P(`context`,`GetKeys`),[]),s=N(P(`keys`,`has`),[i]),c=N(P(`context`,`AddKey`),[i]),l=z(e,t,n.unevaluatedProperties,a),u=ho(go(r),F(0),[`[${i}, ${a}]`,`_`],M(s,Ka(l,c)));return N(xo([`context`],wo([To(`keys`,o),Do(u)])),[`context`])}function yf(e,t,n,r){let i=t.GetKeys();return C(D(r),0,([r,a])=>i.has(r)||B(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function bf(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return Rt(D(a),0,([a,c])=>{let l=new Xs,u=o.has(a)||V(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 xf(e){return!E(e.uniqueItems,!1)}function Sf(e,t,n,r){return xf(n)?so(P(So(`Set`,[N(P(r,`map`),[P(`Hashing`,`Hash`)])]),`size`),P(r,`length`)):F(!0)}function Cf(e,t,n,r){if(!xf(n))return!0;let i=new Set(r.map(et)).size,a=r.length;return E(i,a)}function wf(e,t,n,r,i,a){if(!xf(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=et(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return E(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function Tf(e,t){return zs(e)&&(w(e.type)&&Ct(e.type.length,0)&&C(e.type,0,e=>E(e,t))||E(e.type,t))}function Ef(e){return Tf(e,`object`)}function Df(e){return Go(e)&&(Jo(e)||ts(e)||ns(e)||rs(e)||js(e)||ks(e)||Ms(e)||ws(e)||ys(e)||Ls(e)||Hs(e))}function Of(e){return Tf(e,`array`)}function kf(e){return Go(e)&&(qo(e)||ps(e)||$o(e)||gs(e)||_s(e)||xs(e)||Ss(e)||As(e)||Vs(e)||Bs(e))}function Af(e){return Tf(e,`string`)}function jf(e){return Go(e)&&(Cs(e)||vs(e)||us(e)||Os(e))}function Mf(e){return Tf(e,`number`)||Tf(e,`bigint`)}function Nf(e){return Go(e)&&(bs(e)||hs(e)||cs(e)||ls(e)||Ts(e))}function Pf(e,t,n,r){return t.UseUnevaluated()?Ka(Ka(t.Push(),z(e,t,n,r)),t.Pop()):z(e,t,n,r)}function z(e,t,n,r){e.Push(n);let i=[];if(Ko(n))return Oc(e,t,n,r);if(zs(n)&&i.push(ff(e,t,n,r)),Df(n)){let a=[];Ls(n)&&a.push(af(e,t,n,r)),Jo(n)&&a.push(mc(e,t,n,r)),ts(n)&&a.push(Rc(e,t,n,r)),ns(n)&&a.push(Vc(e,t,n,r)),rs(n)&&a.push(Wc(e,t,n,r)),ks(n)&&a.push(Fd(e,t,n,r)),js(n)&&a.push(Wd(e,t,n,r)),Ms(n)&&a.push(qd(e,t,n,r)),ws(n)&&a.push(gd(e,t,n,r)),ys(n)&&a.push(ed(e,t,n,r));let o=Oo(a),s=M(qa(eo(r)),o);i.push(Ef(n)?o:s)}if(kf(n)){let a=[];qo(n)&&a.push(oc(e,t,n,r)),$o(n)&&a.push(Fc(e,t,n,r)),ps(n)&&a.push(Ru(e,t,n,r)),gs(n)&&a.push(Hu(e,t,n,r)),_s(n)&&a.push(Ju(e,t,n,r)),xs(n)&&a.push(id(e,t,n,r)),Ss(n)&&a.push(ud(e,t,n,r)),As(n)&&a.push(Rd(e,t,n,r)),Bs(n)&&a.push(Sf(e,t,n,r));let o=Oo(a),s=M(qa(Ja(r)),o);i.push(Of(n)?o:s)}if(jf(n)){let a=[];vs(n)&&a.push(Zu(e,t,n,r)),Cs(n)&&a.push(pd(e,t,n,r)),us(n)&&a.push(Eu(e,t,n,r)),Os(n)&&a.push(Md(e,t,n,r));let o=Oo(a),s=M(qa(no(r)),o);i.push(Af(n)?o:s)}if(Nf(n)){let a=[];cs(n)&&a.push($c(e,t,n,r)),ls(n)&&a.push(nl(e,t,n,r)),hs(n)&&a.push(Gu(e,t,n,r)),bs(n)&&a.push(sd(e,t,n,r)),Ts(n)&&a.push(yd(e,t,n,r));let o=Oo(a),s=M(qa(M($a(r),Ya(r))),o);i.push(Mf(n)?o:s)}Is(n)&&i.push(tf(e,t,n,r)),Fs(n)&&i.push(Xd(e,t,n,r)),as(n)&&i.push(qc(e,t,n,r)),Qo(n)&&i.push(jc(e,t,n,r)),ss(n)&&i.push(Xc(e,t,n,r)),fs(n)&&i.push(ku(e,t,n,r)),Es(n)&&i.push(wd(e,t,n,r)),Yo(n)&&i.push(bc(e,t,n,r)),Zo(n)&&i.push(Tc(e,t,n,r)),Ds(n)&&i.push(kd(e,t,n,r)),Vs(n)&&i.push(M(qa(Ja(r)),hf(e,t,n,r))),Hs(n)&&i.push(M(qa(to(r)),vf(e,t,n,r))),Wo(n)&&i.push(tc(e,t,n,r));let a=Oo(i);return e.Pop(n),a}function Ff(e,t,n,r){return t.Push()&&B(e,t,n,r)&&t.Pop()}function B(e,t,n,r){e.Push(n);let i=Ko(n)?kc(e,t,n,r):(!zs(n)||pf(e,t,n,r))&&(!(S(r)&&!w(r))||(!Ls(n)||of(e,t,n,r))&&(!Jo(n)||hc(e,t,n,r))&&(!ts(n)||zc(e,t,n,r))&&(!ns(n)||Hc(e,t,n,r))&&(!rs(n)||Gc(e,t,n,r))&&(!ks(n)||Id(e,t,n,r))&&(!js(n)||Gd(e,t,n,r))&&(!Ms(n)||Jd(e,t,n,r))&&(!ws(n)||_d(e,t,n,r))&&(!ys(n)||td(e,t,n,r)))&&(!w(r)||(!qo(n)||sc(e,t,n,r))&&(!$o(n)||Ic(e,t,n,r))&&(!ps(n)||zu(e,t,n,r))&&(!gs(n)||Uu(e,t,n,r))&&(!_s(n)||Yu(e,t,n,r))&&(!xs(n)||ad(e,t,n,r))&&(!Ss(n)||dd(e,t,n,r))&&(!As(n)||zd(e,t,n,r))&&(!Bs(n)||Cf(e,t,n,r)))&&(!b(r)||(!vs(n)||Qu(e,t,n,r))&&(!Cs(n)||md(e,t,n,r))&&(!us(n)||Du(e,t,n,r))&&(!Os(n)||Nd(e,t,n,r)))&&(!(k(r)||Mt(r))||(!cs(n)||el(e,t,n,r))&&(!ls(n)||rl(e,t,n,r))&&(!hs(n)||Ku(e,t,n,r))&&(!bs(n)||cd(e,t,n,r))&&(!Ts(n)||bd(e,t,n,r)))&&(!Is(n)||nf(e,t,n,r))&&(!Fs(n)||Zd(e,t,n,r))&&(!as(n)||Jc(e,t,n,r))&&(!Qo(n)||Mc(e,t,n,r))&&(!ss(n)||Zc(e,t,n,r))&&(!fs(n)||Au(e,t,n,r))&&(!Es(n)||Td(e,t,n,r))&&(!Yo(n)||xc(e,t,n,r))&&(!Zo(n)||Ec(e,t,n,r))&&(!Ds(n)||Ad(e,t,n,r))&&(!Vs(n)||!w(r)||gf(e,t,n,r))&&(!Hs(n)||!S(r)||yf(e,t,n,r))&&(!Wo(n)||nc(e,t,n,r));return e.Pop(n),i}function If(e,t,n,r,i,a){return t.Push()&&V(e,t,n,r,i,a)&&t.Pop()}function V(e,t,n,r,i,a){e.Push(i);let o=Ko(i)?Ac(e,t,n,r,i,a):!!((!zs(i)||mf(e,t,n,r,i,a))&+(!(S(a)&&!w(a))||!!((!Ls(i)||sf(e,t,n,r,i,a))&+(!Jo(i)||gc(e,t,n,r,i,a))&(!ts(i)||Bc(e,t,n,r,i,a))&(!ns(i)||Uc(e,t,n,r,i,a))&(!rs(i)||Kc(e,t,n,r,i,a))&(!ks(i)||Ld(e,t,n,r,i,a))&(!js(i)||Kd(e,t,n,r,i,a))&(!Ms(i)||Yd(e,t,n,r,i,a))&(!ws(i)||vd(e,t,n,r,i,a))&(!ys(i)||nd(e,t,n,r,i,a))))&(!w(a)||!!((!qo(i)||cc(e,t,n,r,i,a))&+(!$o(i)||Lc(e,t,n,r,i,a))&(!ps(i)||Bu(e,t,n,r,i,a))&(!gs(i)||Wu(e,t,n,r,i,a))&(!_s(i)||Xu(e,t,n,r,i,a))&(!xs(i)||od(e,t,n,r,i,a))&(!Ss(i)||fd(e,t,n,r,i,a))&(!As(i)||Bd(e,t,n,r,i,a))&(!Bs(i)||wf(e,t,n,r,i,a))))&(!b(a)||!!((!vs(i)||$u(e,t,n,r,i,a))&+(!Cs(i)||hd(e,t,n,r,i,a))&(!us(i)||Ou(e,t,n,r,i,a))&(!Os(i)||Pd(e,t,n,r,i,a))))&(!(k(a)||Mt(a))||!!((!cs(i)||tl(e,t,n,r,i,a))&+(!ls(i)||il(e,t,n,r,i,a))&(!hs(i)||qu(e,t,n,r,i,a))&(!bs(i)||ld(e,t,n,r,i,a))&(!Ts(i)||xd(e,t,n,r,i,a))))&(!Is(i)||rf(e,t,n,r,i,a))&(!Fs(i)||Qd(e,t,n,r,i,a))&(!as(i)||Yc(e,t,n,r,i,a))&(!Qo(i)||Nc(e,t,n,r,i,a))&(!ss(i)||Qc(e,t,n,r,i,a))&(!fs(i)||ju(e,t,n,r,i,a))&(!Es(i)||Ed(e,t,n,r,i,a))&(!Yo(i)||Sc(e,t,n,r,i,a))&(!Zo(i)||Dc(e,t,n,r,i,a))&(!Ds(i)||jd(e,t,n,r,i,a))&(!Vs(i)||!w(a)||_f(e,t,n,r,i,a))&(!Hs(i)||!S(a)||bf(e,t,n,r,i,a)))&&(!Wo(i)||rc(e,t,n,r,i,a));return e.Pop(i),o}const Lf=[0],Rf=new Map,zf=new Map;function Bf(){return et(Lf[0]++)}function Vf(e,t){Rf.has(e)||Rf.set(e,new Map);let n=Rf.get(e);if(n.has(t))return n.get(t);let r=Bf();return n.set(t,r),r}function Hf(e,t,n,r){return e.UseUnevaluated()?N(`check_${n}`,[`context`,r]):N(`check_${n}`,[r])}function Uf(e,t,n,r){let i=z(e,t,n,`value`);return t.UseUnevaluated()?To(`check_${r}`,xo([`context`,`value`],i)):To(`check_${r}`,xo([`value`],i))}function Wf(){Lf[0]=0,Rf.clear(),zf.clear()}function Gf(){return[...zf.values()]}function Kf(e,t,n,r){let i=Vf(n,e.BaseURL().href),a=Hf(t,n,i,r);return zf.has(i)?a:(zf.set(i,``),zf.set(i,Uf(e,t,n,i)),a)}function qf(e,t){return S(t)&&!Ie(e)?t[e]:void 0}function Jf(e,t){return e.reduce((e,t)=>qf(t,e),t)}function Yf(e){if(E(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 Xf(e,t){return Jf(Yf(t),e)}function Zf(e,t,n){if(e.$id===n.hash)return e;let r=new URL(e.$id,t.href),i=new URL(n.href,t.href);if(E(r.pathname,i.pathname))return n.hash.startsWith(`#`)?ep(e,t,n):e}function Qf(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return E(r.href,i.href)?e:void 0}function $f(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return E(r.href,i.href)?e:void 0}function ep(e,t,n){if(n.href.endsWith(`#`))return e;if(!n.hash.startsWith(`#`))return;let r=decodeURIComponent(n.hash.slice(1));if(r.startsWith(`/`))return Xf(e,r)}function tp(e,t,n){if(ds(e)){let r=Zf(e,t,n);if(!T(r))return r}if(Xo(e)){let r=Qf(e,t,n);if(!T(r))return r}if(is(e)){let r=$f(e,t,n);if(!T(r))return r}return ep(e,t,n)}function np(e,t,n){return e.reduce((e,r)=>{let i=ip(r,t,n);return T(i)?e:i},void 0)}function rp(e,t,n){return x(e).reduce((r,i)=>{let a=ip(e[i],t,n);return T(a)?r:a},void 0)}function ip(e,t,n){let r=Go(e)&&ds(e)?new URL(e.$id,t.href):t;if(Go(e)){let t=tp(e,r,n);if(!T(t))return t}if(w(e))return np(e,r,n);if(S(e))return rp(e,r,n)}function ap(e,t){let n=new URL(`http://unknown/`),r=ds(e)?new URL(e.$id,n.href):n;return ip(e,r,new URL(t,r.href))}function op(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?ap(t,n.$dynamicRef):ap(e,n.$dynamicRef);if(!T(i))return!Go(i)||!is(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var sp=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)},cp,lp,up,dp,fp,pp=class{constructor(e,t){cp.add(this),this.context=e,this.schema=t,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((e,t)=>new URL(t.$id,e),new URL(`http://unknown`))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(e){Go(e)&&(ds(e)&&(this.ids.push(e),sp(this,cp,`m`,lp).call(this,e)),Xo(e)&&this.anchors.push(e),Ps(e)&&this.recursiveAnchors.push(e),is(e)&&this.dynamicAnchors.push(e))}Pop(e){Go(e)&&(ds(e)&&(this.ids.pop(),sp(this,cp,`m`,up).call(this,e)),Xo(e)&&this.anchors.pop(),Ps(e)&&this.recursiveAnchors.pop(),is(e)&&this.dynamicAnchors.pop())}Ref(e){return sp(this,cp,`m`,dp).call(this,e)??sp(this,cp,`m`,fp).call(this,e)}RecursiveRef(e){return Ps(this.Base())?ap(this.recursiveAnchors[0],e.$recursiveRef):ap(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return op(t,this.Base(),e,this.dynamicAnchors)}};cp=new WeakSet,lp=function e(t,n=!0){if(!Go(t))return;let r=t;if(!(!n&&ds(r))){!n&&is(r)&&this.dynamicAnchors.push(r);for(let t of x(r))sp(this,cp,`m`,e).call(this,r[t],!1)}},up=function e(t,n=!0){if(!Go(t))return;let r=t;if(!(!n&&ds(r))){!n&&is(r)&&this.dynamicAnchors.pop();for(let t of x(r))sp(this,cp,`m`,e).call(this,r[t],!1)}},dp=function(e){return O(this.context,e.$ref)?this.context[e.$ref]:void 0},fp=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?ap(this.Base(),e.$ref):ap(t,e.$ref)};function mp(e){return`${e.Functions().join(`;
|
|
878
|
+
`)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function hp(e,t){return Lo(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(Js,Ze,Tu,Ue,e.External().variables)}function gp(e){let t=new pp(e.Context(),e.Schema()),n=new Js;return r=>B(t,n,e.Schema(),r)}function _p(e,t){return Io()?hp(e,t):gp(e)}var vp=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)}},yp=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=mp(this),t=_p(this,e);return new vp(Io(),e,t)}};function bp(...e){let[t,n]=No(e,{2:(e,t)=>[e,t],1:e=>[{},e]});$s(),Wf();let r=new pp(t,n),i=new qs(Ks(t,n)),a=Kf(r,i,n,`value`),o=Gf();return new yp(t,n,ec(),o,a,i.UseUnevaluated())}function xp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=Wt(),a=Bo(),o=[];return[V(new pp(t,n),new Ys(e=>{if(!Tt(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function Sp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return B(new pp(t,n),new Js,n,r)}function Cp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Sp(t,n,r)}function wp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=xp(t,n,r);return a}var Tp=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 Ep(e,t,n){return w(n)?n.map(n=>Lp(e,t.items,n)):n}function Dp(e,t,n){return Lp({...e,...t.$defs},Ke(t.$ref),n)}function Op(e,t){let n=O(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=Vt(e,t),i=Ft(r);return We(i)?Et(i,n):i}function kp(e,t,n){return Lp(e,Op(e,t),n)}function Ap(e){return O(e,`additionalProperties`)?e.additionalProperties:void 0}function jp(e,t,n){if(!S(n)||w(n))return n;let r=Ap(t);for(let i of x(n)){if(O(t.properties,i)){n[i]=Lp(e,t.properties[i],n[i]);continue}if(Kt(r)&&E(r,!0)||yt(r)&&Cp(e,r,n[i])){n[i]=Lp(e,r,n[i]);continue}delete n[i]}return n}function Mp(e,t,n){if(!S(n))return n;let r=Ap(t),[i,a]=[new RegExp(_t(t)),bt(t)];for(let t of x(n)){if(i.test(t)){n[t]=Lp(e,a,n[t]);continue}if(Kt(r)&&E(r,!0)||yt(r)&&Cp(e,r,n[t])){n[t]=Lp(e,r,n[t]);continue}delete n[t]}return n}function Np(e,t,n){return O(e,t.$ref)?Lp(e,e[t.$ref],n):n}function Pp(e,t,n){if(!w(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;i<r;i++)n[i]=Lp(e,t.items[i],n[i]);return Ct(n.length,r)?n.slice(0,r):n}function Fp(e){return It(e)}function Ip(e,t,n){for(let r of t.anyOf){let t=Lp(e,r,Fp(n));if(Cp(e,r,t))return t}return n}function Lp(e,t,n){return tt(t)?Ep(e,t,n):Le(t)?Dp(e,t,n):nt(t)?kp(e,t,n):We(t)?jp(e,t,n):gt(t)?Mp(e,t,n):Bt(t)?Np(e,t,n):zt(t)?Pp(e,t,n):St(t)?Ip(e,t,n):n}function Rp(e,t){for(let n of Mo.Keys(e))Mo.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function zp(e){let t={};for(let n of Mo.Keys(e))t[n]=Hp(e[n]);return t}function Bp(e){return Vp(Ut(e))}function Vp(e){return e.map(e=>Hp(e))}function Hp(e){return Rp(e,tt(e)?Pe(Hp(e.items),ut(e)):nt(e)?Je(Vp(e.allOf)):St(e)?dt(Bp(e.anyOf)):We(e)?at(zp(e.properties)):gt(e)?jt(Gt(e),Hp(bt(e))):zt(e)?Nt(Vp(e.items)):e)}function Up(e){return Hp(e)}function Wp(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Lp(t,Wt().unionPrioritySort?Up(n):n,r)}function Gp(e){return S(e)&&O(e,`value`)}function H(e){return{value:e}}function Kp(e){return w(e)?H(e):H([e])}function qp(e){return E(e,!0)?H(BigInt(1)):H(BigInt(0))}const Jp=/^-?(0|[1-9]\d*)n$/,Yp=/^-?(0|[1-9]\d*)\.\d+$/,Xp=/^-?(0|[1-9]\d*)$/;function Zp(e){return Jp.test(e)}function Qp(e){return Yp.test(e)}function $p(e){return Xp.test(e)}function em(e){let t=e.toLowerCase();return Zp(e)?H(BigInt(e.slice(0,e.length-1))):Qp(e)?H(BigInt(e.split(`.`)[0])):$p(e)?H(BigInt(e)):E(t,`false`)?H(BigInt(0)):E(t,`true`)?H(BigInt(1)):void 0}function tm(e){return Mt(e)?H(e):Kt(e)?qp(e):k(e)?H(BigInt(Math.trunc(e))):ze(e)?H(BigInt(0)):b(e)?em(e):T(e)?H(BigInt(0)):void 0}function nm(e){return E(e,BigInt(0))?H(!1):E(e,BigInt(1))?H(!0):void 0}function rm(e){return E(e,0)?H(!1):E(e,1)?H(!0):void 0}function im(e){return E(e.toLowerCase(),`false`)?H(!1):E(e.toLowerCase(),`true`)?H(!0):E(e,`0`)?H(!1):E(e,`1`)?H(!0):void 0}function am(e){return Mt(e)?nm(e):Kt(e)?H(e):k(e)?rm(e):ze(e)?H(!1):b(e)?im(e):T(e)?H(!1):void 0}function om(e){return E(e,BigInt(0))?H(null):void 0}function sm(e){return E(e,!1)?H(null):void 0}function cm(e){return E(e,0)?H(null):void 0}function lm(e){let t=e.toLowerCase();return E(t,`undefined`)||E(t,`null`)||E(e,``)||E(e,`0`)?H(null):void 0}function um(e){return Mt(e)?om(e):Kt(e)?sm(e):k(e)?cm(e):ze(e)?H(null):b(e)?lm(e):T(e)?H(null):void 0}const dm=BigInt(2**53-1),fm=BigInt(-(2**53-1));function pm(e){return e<=dm&&e>=fm?H(Number(e)):void 0}function mm(e){return H(+!!e)}function hm(e){let t=+e;if(k(t))return H(t);let n=e.toLowerCase();if(E(n,`false`))return H(0);if(E(n,`true`))return H(1);let r=tm(e);if(Gp(r))return r.value<=dm&&r.value>=fm?H(Number(r.value)):void 0}function gm(e){return Mt(e)?pm(e):Kt(e)?mm(e):k(e)?H(e):ze(e)?H(0):b(e)?hm(e):T(e)?H(0):void 0}function _m(e){return Mt(e)||Kt(e)||k(e)?H(e.toString()):ze(e)?H(`null`):b(e)?H(e):T(e)?H(``):void 0}function vm(e){return E(e,BigInt(0))?H(void 0):void 0}function ym(e){return E(e,!1)?H(void 0):void 0}function bm(e){return E(e,0)?H(void 0):void 0}function xm(e){let t=e.toLowerCase();return E(t,`undefined`)||E(t,`null`)||E(e,``)||E(e,`0`)?H(void 0):void 0}function Sm(e){return Mt(e)?vm(e):Kt(e)?ym(e):k(e)?bm(e):ze(e)?H(void 0):b(e)?xm(e):T(e)?H(e):void 0}function Cm(e,t,n){return Kp(n).value.map(n=>Xm(e,t.items,n))}function wm(e,t,n){let r=tm(n);return Gp(r)?r.value:n}function Tm(e,t,n){let r=am(n);return Gp(r)?r.value:n}function Em(e,t,n){return Xm({...e,...t.$defs},Ke(t.$ref),n)}function Dm(e,t,n){return Xm(e,Ft(t),n)}function Om(e,t,n){let r=gm(n);return Gp(r)?Math.trunc(r.value):n}function km(e,t,n){let r=Vt(e,t);return Xm(e,Ft(r),n)}function Am(e,t,n){let r=tm(n);return Gp(r)&&E(t.const,r.value)?r.value:n}function jm(e,t,n){let r=am(n);return Gp(r)&&E(t.const,r.value)?r.value:n}function Mm(e,t,n){let r=gm(n);return Gp(r)&&E(t.const,r.value)?r.value:n}function Nm(e,t,n){let r=_m(n);return Gp(r)&&E(t.const,r.value)?r.value:n}function Pm(e,t,n){return E(t.const,n)?n:it(t)?Am(e,t,n):Ve(t)?jm(e,t,n):Be(t)?Mm(e,t,n):Qe(t)?Nm(e,t,n):Ge()}function Fm(e,t,n){let r=um(n);return Gp(r)?r.value:n}function Im(e,t,n){let r=gm(n);return Gp(r)?r.value:n}function Lm(e,t,n,r){let i=x(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=Xm(e,n,r[t]));return r}function Rm(e,t,n){return st(e)&&T(n[t])}function zm(e,t,n){let r=Dt(t.properties),i=x(n);for(let[t,a]of r)for(let r of i)!t.test(r)||Rm(a,r,n)||(n[r]=Xm(e,a,n[r]));return O(t,`additionalProperties`)&&S(t.additionalProperties)?Lm(e,r,t.additionalProperties,n):n}function Bm(e,t,n){return He(n)?zm(e,t,n):n}function Vm(e,t,n){let r=Dt(t.patternProperties),i=x(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=Xm(e,a,n[r]));return O(t,`additionalProperties`)&&S(t.additionalProperties)?Lm(e,r,t.additionalProperties,n):n}function Hm(e,t,n){return He(n)?Vm(e,t,n):n}function Um(e,t,n){return O(e,t.$ref)?Xm(e,e[t.$ref],n):n}function Wm(e,t,n){let r=_m(n);return Gp(r)?r.value:n}function Gm(e,t,n){return Xm(e,Ft(t),n)}function Km(e,t,n){if(!w(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=Xm(e,t.items[r],n[r]);return n}function qm(e,t,n){let r=Sm(n);return Gp(r)?r.value:n}function Jm(e,t,n){if(t.anyOf.some(t=>Cp(e,t,n)))return n;let r=t.anyOf.map(t=>Xm(e,t,Fp(n))).find(n=>Cp(e,t,n));return T(r)?n:r}function Ym(e,t,n){return Gp(Sm(n))?void 0:n}function Xm(e,t,n){return tt(t)?Cm(e,t,n):Ye(t)?wm(e,t,n):Ot(t)?Tm(e,t,n):Le(t)?Em(e,t,n):en(t)?Dm(e,t,n):Fe(t)?Om(e,t,n):nt(t)?km(e,t,n):Yt(t)?Pm(e,t,n):Re(t)?Fm(e,t,n):Xt(t)?Im(e,t,n):We(t)?Bm(e,t,n):gt(t)?Hm(e,t,n):Bt(t)?Um(e,t,n):qt(t)?Wm(e,t,n):pt(t)?Gm(e,t,n):zt(t)?Km(e,t,n):Ht(t)?qm(e,t,n):St(t)?Jm(e,t,n):Lt(t)?Ym(e,t,n):n}function Zm(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Xm(t,n,r)}function Qm(e,t,n){if(!w(n))return n;for(let r=0;r<n.length;r++)n[r]=sh(e,t.items,n[r]);return n}function $m(e,t,n){return sh({...e,...t.$defs},Ke(t.$ref),n)}function eh(e,t){return T(t)?Pt(e.default)?e.default():Fp(e.default):t}function th(e,t,n){let r=Vt(e,t);return sh(e,Ft(r),n)}function nh(e,t,n){if(!S(n))return n;let r=x(t.properties);for(let i of r){let r=sh(e,t.properties[i],n[i]);T(r)&&(st(t.properties[i])||!O(t.properties[i],`default`))||(n[i]=r)}if(!Jo(t)||Kt(t.additionalProperties))return n;for(let i of x(n))r.includes(i)||(n[i]=sh(e,t.additionalProperties,n[i]));return n}function rh(e,t,n){if(!S(n))return n;let[r,i]=[new RegExp(_t(t)),bt(t)];for(let t of x(n))r.test(t)&&es(i)&&(n[t]=sh(e,i,n[t]));if(!Jo(t))return n;for(let i of x(n))r.test(i)||(n[i]=sh(e,t.additionalProperties,n[i]));return n}function ih(e,t,n){return O(e,t.$ref)?sh(e,e[t.$ref],n):n}function ah(e,t,n){if(!w(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]=sh(e,r[t],n[t]));return n}function oh(e,t,n){for(let r of t.anyOf){let t=sh(e,r,Fp(n));if(Cp(e,r,t))return t}return n}function sh(e,t,n){let r=es(t)?eh(t,n):n;return tt(t)?Qm(e,t,r):Le(t)?$m(e,t,r):nt(t)?th(e,t,r):We(t)?nh(e,t,r):gt(t)?rh(e,t,r):Bt(t)?ih(e,t,r):zt(t)?ah(e,t,r):St(t)?oh(e,t,r):r}function ch(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return sh(t,n,r)}function lh(e){return(...t)=>{let[n,r,i]=No(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function uh(e,t,n){return t[`~codec`].decode(n)}function dh(e,t,n){return t[`~codec`].encode(n)}function U(e,t,n,r){return Xe(n)?E(e,`Decode`)?uh(t,n,r):dh(t,n,r):r}function fh(e,t,n,r){if(!w(r))return r;for(let i=0;i<r.length;i++)r[i]=W(e,t,n.items,r[i]);return U(e,t,n,r)}function ph(e,t,n,r){let i=U(e,t,n,r);if(!w(i))return i;for(let r=0;r<i.length;r++)i[r]=W(e,t,n.items,i[r]);return i}function mh(e,t,n,r){return E(e,`Decode`)?fh(e,t,n,r):ph(e,t,n,r)}function hh(e,t,n,r){return r=W(e,{...t,...n.$defs},Ke(n.$ref),r),U(e,t,n,r)}function gh(e){return e.reduce((e,t)=>({...e,...t}),{})}function _h(e,t){for(let n of t)if(!xt(e,n))return n;return e}function vh(e,t,n,r){if(E(n.allOf.length,0))return U(e,t,n,r);let i=n.allOf.map(n=>W(e,t,n,Wp(n,Fp(r))));return U(e,t,n,i.every(e=>S(e))?gh(i):_h(r,i))}function yh(e,t,n,r){if(E(n.allOf.length,0))return U(e,t,n,r);let i=U(e,t,n,r),a=n.allOf.map(n=>W(e,t,n,Wp(n,Fp(i))));return a.every(e=>S(e))?gh(a):_h(i,a)}function bh(e,t,n,r){return E(e,`Decode`)?vh(e,t,n,r):yh(e,t,n,r)}function xh(e,t,n,r){if(!He(r))return r;for(let i of x(n.properties))!O(r,i)||Rm(n.properties[i],i,r)||(r[i]=W(e,t,n.properties[i],r[i]));return U(e,t,n,r)}function Sh(e,t,n,r){let i=U(e,t,n,r);if(!He(i))return i;for(let r of x(n.properties))!O(i,r)||Rm(n.properties[r],r,i)||(i[r]=W(e,t,n.properties[r],i[r]));return i}function Ch(e,t,n,r){return E(e,`Decode`)?xh(e,t,n,r):Sh(e,t,n,r)}function wh(e,t,n,r){if(!He(r))return r;let i=new RegExp(_t(n));for(let a of x(r))i.test(a)&&(r[a]=W(e,t,bt(n),r[a]));return U(e,t,n,r)}function Th(e,t,n,r){let i=U(e,t,n,r);if(!He(i))return i;let a=new RegExp(_t(n));for(let r of x(i))a.test(r)&&(i[r]=W(e,t,bt(n),i[r]));return i}function Eh(e,t,n,r){return E(e,`Decode`)?wh(e,t,n,r):Th(e,t,n,r)}function Dh(e,t,n,r){return O(t,n.$ref)?W(e,t,t[n.$ref],r):r}function Oh(e,t,n,r){return E(e,`Decode`)?U(e,t,n,Dh(e,t,n,r)):Dh(e,t,n,U(e,t,n,r))}function kh(e,t,n,r){if(!w(r))return r;for(let i=0;i<Math.min(n.items.length,r.length);i++)r[i]=W(e,t,n.items[i],r[i]);return U(e,t,n,r)}function Ah(e,t,n,r){let i=U(e,t,n,r);if(!w(i))return r;for(let r=0;r<Math.min(n.items.length,i.length);r++)i[r]=W(e,t,n.items[r],i[r]);return i}function jh(e,t,n,r){return E(e,`Decode`)?kh(e,t,n,r):Ah(e,t,n,r)}function Mh(e,t,n,r){for(let i of n.anyOf)if(Cp(t,i,r))return U(e,t,n,W(e,t,i,r));return r}function Nh(e,t,n,r){let i=U(e,t,n,r);for(let r of n.anyOf){let n=W(e,t,r,Fp(i));if(Cp(t,r,n))return n}return i}function Ph(e,t,n,r){return E(e,`Decode`)?Mh(e,t,n,r):Nh(e,t,n,r)}function W(e,t,n,r){return tt(n)?mh(e,t,n,r):Le(n)?hh(e,t,n,r):nt(n)?bh(e,t,n,r):We(n)?Ch(e,t,n,r):gt(n)?Eh(e,t,n,r):Bt(n)?Oh(e,t,n,r):zt(n)?jh(e,t,n,r):St(n)?Ph(e,t,n,r):U(e,t,n,r)}var Fh=class extends Tp{constructor(e,t){super(`Decode`,e,t)}};function Ih(e,t,n){if(!Cp(e,t,n))throw new Fh(n,wp(e,t,n));return n}function Lh(e,t,n){return W(`Decode`,e,Wt().unionPrioritySort?Up(t):t,n)}const Rh=lh([(e,t,n)=>Fp(n),(e,t,n)=>ch(e,t,n),(e,t,n)=>Zm(e,t,n),(e,t,n)=>Wp(e,t,n),(e,t,n)=>Ih(e,t,n),(e,t,n)=>Lh(e,t,n)]);function zh(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Rh(t,n,r)}var Bh=class extends Tp{constructor(e,t){super(`Encode`,e,t)}};function Vh(e,t,n){if(!Cp(e,t,n))throw new Bh(n,wp(e,t,n));return n}function Hh(e,t,n){return W(`Encode`,e,Wt().unionPrioritySort?Up(t):t,n)}const Uh=lh([(e,t,n)=>Fp(n),(e,t,n)=>Hh(e,t,n),(e,t,n)=>ch(e,t,n),(e,t,n)=>Zm(e,t,n),(e,t,n)=>Wp(e,t,n),(e,t,n)=>Vh(e,t,n)]);function Wh(...e){let[t,n,r]=No(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Uh(t,n,r)}function Gh(e,t){return Xe(t)||$h(e,t.items)}function Kh(e,t){return Xe(t)||Xh({...e,...t.$defs},Ke(t.$ref))}function qh(e,t){return Xe(t)||t.allOf.some(t=>$h(e,t))}function Jh(e,t){return Xe(t)||x(t.properties).some(n=>$h(e,t.properties[n]))}function Yh(e,t){return Xe(t)||$h(e,bt(t))}function Xh(e,t){return!eg.has(t.$ref)&&(eg.add(t.$ref),Xe(t)||O(e,t.$ref)&&$h(e,e[t.$ref]))}function Zh(e,t){return Xe(t)||t.items.some(t=>$h(e,t))}function Qh(e,t){return Xe(t)||t.anyOf.some(t=>$h(e,t))}function $h(e,t){return tt(t)?Gh(e,t):Le(t)?Kh(e,t):nt(t)?qh(e,t):We(t)?Jh(e,t):gt(t)?Yh(e,t):Bt(t)?Xh(e,t):zt(t)?Zh(e,t):St(t)?Qh(e,t):Xe(t)}const eg=new Set;function tg(...e){let[t,n]=No(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return eg.clear(),$h(t,n)}var ng=class extends Error{constructor(e,t){super(t),this.type=e}};function rg(e,t){return Pt(t.default)?t.default(t):S(t.default)?Fp(t.default):t.default}function ig(e,t){if(Bs(t)&&!es(t))throw new ng(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=Ss(t)?t.minItems:0;return Array.from({length:n},()=>Tg(e,t.items))}function ag(e,t){return ls(t)?BigInt(t.exclusiveMinimum)+BigInt(1):bs(t)?BigInt(t.minimum):BigInt(0)}function og(e,t){return!1}function sg(e,t){let n=Tg(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function cg(e,t){return Tg({...e,...t.$defs},Ke(t.$ref))}function lg(e,t){return Tg(e,Ft(t))}function ug(e,t){let n=Tg(e,t.returnType);return()=>n}function dg(e,t){return ls(t)&&k(t.exclusiveMinimum)?t.exclusiveMinimum+1:bs(t)?t.minimum:0}function fg(e,t){let n=Vt(e,t);return Tg(e,Ft(n))}function pg(e,t){return t.const}function mg(e,t){throw new ng(t,`Cannot create TNever types`)}function hg(e,t){return null}function gg(e,t){return ls(t)&&k(t.exclusiveMinimum)?t.exclusiveMinimum+1:bs(t)?t.minimum:0}function _g(e,t){return(T(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:Tg(e,t.properties[r])}),{})}function vg(e,t){if(ws(t)&&!es(t))throw new ng(t,`Record with the minProperties constraint must have a default annotation`);return{}}function yg(e,t){return O(e,t.$ref)?Tg(e,e[t.$ref]):(()=>{throw new ng(t,`Unable to deref Ref`)})()}function bg(e,t){if((Os(t)||us(t))&&!es(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=Cs(t)?t.minLength:0;return``.padEnd(n)}function xg(e,t){return Symbol()}function Sg(e,t){let n=wt(t.pattern);if(qt(n))throw new ng(t,`Unable to create TemplateLiteral due to infinite type expansion`);return Tg(e,n)}function Cg(e,t){return Array.from({length:t.minItems},(n,r)=>Tg(e,t.items[r]))}function wg(e,t){if(E(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return Tg(e,t.anyOf[0])}function Tg(e,t){return es(t)?rg(e,t):tt(t)?ig(e,t):Ye(t)?ag(e,t):Ot(t)?og(e,t):ct(t)?sg(e,t):Le(t)?cg(e,t):en(t)?lg(e,t):lt(t)?ug(e,t):Fe(t)?dg(e,t):nt(t)?fg(e,t):Yt(t)?pg(e,t):qe(t)?mg(e,t):Re(t)?hg(e,t):Xt(t)?gg(e,t):We(t)?_g(e,t):gt(t)?vg(e,t):Bt(t)?yg(e,t):qt(t)?bg(e,t):mt(t)?xg(e,t):pt(t)?Sg(e,t):zt(t)?Cg(e,t):Ht(t)?void 0:St(t)?wg(e,t):(Lt(t),void 0)}function Eg(...e){let[t,n]=No(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Tg(t,n)}var Dg=class extends Tp{constructor(e,t){super(`Parse`,e,t)}};function Og(e,t,n){if(!Cp(e,t,n))throw new Dg(n,wp(e,t,n));return n}const kg=lh([(e,t,n)=>Fp(n),(e,t,n)=>ch(e,t,n),(e,t,n)=>Zm(e,t,n),(e,t,n)=>Wp(e,t,n),(e,t,n)=>Og(e,t,n)]),Ag=at({type:At(`insert`),path:Qt(),value:ot()}),jg=Object({type:At(`update`),path:Qt(),value:ot()}),Mg=at({type:At(`delete`),path:Qt()});dt([Ag,jg,Mg]);var Ng=class{constructor(e,t){this.hasCodec=tg(e,t),this.buildResult=bp(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(Wt().correctiveParse)return kg(this.Context(),this.Type(),e);throw new Dg(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:wp(this.Context(),this.Type(),e)}Clean(e){return Wp(this.Context(),this.Type(),e)}Convert(e){return Zm(this.Context(),this.Type(),e)}Create(){return Eg(this.Context(),this.Type())}Default(e){return ch(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?zh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Wh(this.Context(),this.Type(),e):this.Parse(e)}};function Pg(...e){let[t,n]=No(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new Ng(t,n)}const Fg=new WeakMap,Ig=Symbol.for(`TypeBox.Kind`);function Lg(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function Rg(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 zg(e){try{return Kg(e)}catch{return}}function Bg(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 Vg(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]=Wg(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=Wg(i,t.additionalProperties))}function Hg(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=Wg(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=Wg(e[n],t.items)}function Ug(e,t){for(let n of t)if(zg(n)?.Check(e))return e;for(let n of t){let t=Wg(structuredClone(e),n);if(zg(n)?.Check(t))return t}return e}function Wg(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=Wg(n,e);Array.isArray(t.anyOf)&&(n=Ug(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=Ug(n,t.oneOf));let r=Lg(t),i=r.length>1&&r.some(e=>Rg(n,e));if(r.length>0&&!i)for(let e of r){let t=Bg(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&Vg(n,t),r.includes(`array`)&&Array.isArray(n)&&Hg(n,t),n}function Gg(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&&Gg(e[n],r)}else if(t.items)for(let n of e)Gg(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`&&zg(i)?.Check(null)===!1?delete n[e]:Gg(n[e],i))}function Kg(e){let t=e,n=Fg.get(t);if(n)return n;let r=Pg(e);return Fg.set(t,r),r}function qg(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 Jg(e,t){let n=structuredClone(t.arguments);Gg(n,e.parameters),Zm(e.parameters,n);let r=Kg(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Ig)){let t=Wg(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=>` - ${qg(e)}: ${e.message}`).join(`
|
|
879
|
+
`)||`Unknown validation error`,a=`Validation failed for tool "${t.name}":\n${i}\n\nReceived arguments:\n${JSON.stringify(t.arguments,null,2)}`;throw Error(a)}function Yg(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function Xg(e,t,n,r,i,a){let o=[...e],s={...t,messages:[...t.messages,...e]};await r({type:`agent_start`}),await r({type:`turn_start`});for(let t of e)await r({type:`message_start`,message:t}),await r({type:`message_end`,message:t});return await Qg(s,o,n,i,r,a??Yg()),o}async function Zg(e,t,n,r,i){if(e.messages.length===0)throw Error(`Cannot continue: no messages in context`);if(e.messages[e.messages.length-1].role===`assistant`)throw Error(`Cannot continue from message role: assistant`);let a=[],o={...e};return await n({type:`agent_start`}),await n({type:`turn_start`}),await Qg(o,a,t,r,n,i??Yg()),a}async function Qg(e,t,n,r,i,a){let o=e,s=n,c,l=await s.getSteeringMessages?.()||[];for(;;){let e=!0;for(;e||l.length>0;){if(c){let e=await s.prepareNextTurn?.(c);e&&(o=e.context??o,s={...s,model:e.model??s.model,reasoning:e.thinkingLevel===void 0?s.reasoning:e.thinkingLevel===`off`?void 0:e.thinkingLevel}),l.length===0&&(l=await s.getSteeringMessages?.()||[]),await i({type:`turn_start`})}if(l.length>0){for(let e of l)await i({type:`message_start`,message:e}),await i({type:`message_end`,message:e}),o.messages.push(e),t.push(e);l=[]}let n=await $g(o,s,r,i,a);if(t.push(n),n.stopReason===`error`||n.stopReason===`aborted`){await i({type:`turn_end`,message:n,toolResults:[]}),await i({type:`agent_end`,messages:t});return}let u=n.content.filter(e=>e.type===`toolCall`),d=[];if(e=!1,u.length>0){let a=n.stopReason===`length`?await e_(u,i):await t_(o,n,s,r,i);d.push(...a.messages),e=!a.terminate;for(let e of d)o.messages.push(e),t.push(e)}if(await i({type:`turn_end`,message:n,toolResults:d}),c={message:n,toolResults:d,context:o,newMessages:t},await s.shouldStopAfterTurn?.(c)){await i({type:`agent_end`,messages:t});return}l=await s.getSteeringMessages?.()||[]}let n=await s.getFollowUpMessages?.()||[];if(n.length>0){l=n;continue}break}await i({type:`agent_end`,messages:t})}async function $g(e,t,n,r,i){let a=e.messages;t.transformContext&&(a=await t.transformContext(a,n));let o=await t.convertToLlm(a),s={systemPrompt:e.systemPrompt,messages:o,tools:e.tools},c=(t.getApiKey?await t.getApiKey(t.model.provider):void 0)||t.apiKey,l=await i(t.model,s,{...t,apiKey:c,signal:n}),u=null,d=!1;for await(let t of l)switch(t.type){case`start`:u=t.partial,e.messages.push(u),d=!0,await r({type:`message_start`,message:{...u}});break;case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:u&&(u=t.partial,e.messages[e.messages.length-1]=u,await r({type:`message_update`,assistantMessageEvent:t,message:{...u}}));break;case`done`:case`error`:{let t=await l.result();return d?e.messages[e.messages.length-1]=t:e.messages.push(t),d||await r({type:`message_start`,message:{...t}}),await r({type:`message_end`,message:t}),t}}let f=await l.result();return d?e.messages[e.messages.length-1]=f:(e.messages.push(f),await r({type:`message_start`,message:{...f}})),await r({type:`message_end`,message:f}),f}async function e_(e,t){let n=[];for(let r of e){await t({type:`tool_execution_start`,toolCallId:r.id,toolName:r.name,args:r.arguments});let e={toolCall:r,result:l_(`Tool call "${r.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await u_(e,t);let i=d_(e);await f_(i,t),n.push(i)}return{messages:n,terminate:!1}}async function t_(e,t,n,r,i){let a=t.content.filter(e=>e.type===`toolCall`),o=a.some(t=>e.tools?.find(e=>e.name===t.name)?.executionMode===`sequential`);return n.toolExecution===`sequential`||o?n_(e,t,a,n,r,i):r_(e,t,a,n,r,i)}async function n_(e,t,n,r,i,a){let o=[],s=[];for(let c of n){await a({type:`tool_execution_start`,toolCallId:c.id,toolName:c.name,args:c.arguments});let n=await o_(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await c_(e,t,n,await s_(n,i,a),r,i),await u_(l,a);let u=d_(l);if(await f_(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:i_(o)}}async function r_(e,t,n,r,i,a){let o=[];for(let s of n){await a({type:`tool_execution_start`,toolCallId:s.id,toolName:s.name,args:s.arguments});let n=await o_(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await u_(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{let o=await s_(n,i,a),s=await c_(e,t,n,o,r,i);return await u_(s,a),s}),i?.aborted)break}let s=await Promise.all(o.map(e=>typeof e==`function`?e():Promise.resolve(e))),c=[];for(let e of s){let t=d_(e);await f_(t,a),c.push(t)}return{messages:c,terminate:i_(s)}}function i_(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function a_(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function o_(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:l_(`Tool ${n.name} not found`),isError:!0};try{let o=Jg(a,a_(a,n));if(r.beforeToolCall){let a=await r.beforeToolCall({assistantMessage:t,toolCall:n,args:o,context:e},i);if(i?.aborted)return{kind:`immediate`,result:l_(`Operation aborted`),isError:!0};if(a?.block){let e=l_(a.reason||`Tool execution was blocked`);return a.terminate===!0&&(e.terminate=!0),{kind:`immediate`,result:e,isError:!0}}}return i?.aborted?{kind:`immediate`,result:l_(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:l_(e instanceof Error?e.message:String(e)),isError:!0}}}async function s_(e,t,n){let r=[],i=!0;try{let a=await e.tool.execute(e.toolCall.id,e.args,t,t=>{i&&r.push(Promise.resolve(n({type:`tool_execution_update`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,args:e.toolCall.arguments,partialResult:t})))});return i=!1,await Promise.all(r),{result:a,isError:!1}}catch(e){return i=!1,await Promise.all(r),{result:l_(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function c_(e,t,n,r,i,a){let o=r.result,s=r.isError;if(i.afterToolCall)try{let r=await i.afterToolCall({assistantMessage:t,toolCall:n.toolCall,args:n.args,result:o,isError:s,context:e},a);r&&(o={...o,content:r.content??o.content,details:r.details??o.details,usage:r.usage??o.usage,terminate:r.terminate??o.terminate},s=r.isError??s)}catch(e){o=l_(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function l_(e){return{content:[{type:`text`,text:e}],details:{}}}async function u_(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function d_(e){return{role:`toolResult`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,...e.result.addedToolNames?.length?{addedToolNames:e.result.addedToolNames}:{},isError:e.isError,timestamp:Date.now()}}async function f_(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function p_(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const m_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},h_={id:`unknown`,name:`unknown`,api:`unknown`,provider:`unknown`,baseUrl:``,reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function g_(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??h_,thinkingLevel:e?.thinkingLevel??`off`,get tools(){return t},set tools(e){t=e.slice()},get messages(){return n},set messages(e){n=e.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}var __=class{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}drain(){if(this.mode===`all`){let e=this.messages.slice();return this.messages=[],e}let e=this.messages[0];return e?(this.messages=this.messages.slice(1),[e]):[]}clear(){this.messages=[]}},v_=class{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;beforeToolCall;afterToolCall;shouldStopAfterTurn;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let t=e??{};this._state=g_(t.initialState),this.convertToLlm=t.convertToLlm??p_,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??Yg(),this.getApiKey=t.getApiKey,this.onPayload=t.onPayload,this.onResponse=t.onResponse,this.beforeToolCall=t.beforeToolCall,this.afterToolCall=t.afterToolCall,this.shouldStopAfterTurn=t.shouldStopAfterTurn,this.prepareNextTurn=t.prepareNextTurn,this.prepareNextTurnWithContext=t.prepareNextTurnWithContext,this.steeringQueue=new __(t.steeringMode??`one-at-a-time`),this.followUpQueue=new __(t.followUpMode??`one-at-a-time`),this.sessionId=t.sessionId,this.thinkingBudgets=t.thinkingBudgets,this.transport=t.transport??`auto`,this.maxRetryDelayMs=t.maxRetryDelayMs,this.toolExecution=t.toolExecution??`parallel`}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before resetting.`);this._state.messages=[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,t){if(this.activeRun)throw Error(`Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.`);let n=this.normalizePromptInput(e,t);await this.runPromptMessages(n)}async continue(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before continuing.`);let e=this._state.messages[this._state.messages.length-1];if(!e)throw Error(`No messages to continue from`);if(e.role===`assistant`){let e=this.steeringQueue.drain();if(e.length>0){await this.runPromptMessages(e,{skipInitialSteeringPoll:!0});return}let t=this.followUpQueue.drain();if(t.length>0){await this.runPromptMessages(t);return}throw Error(`Cannot continue from message role: assistant`)}await this.runContinuation()}normalizePromptInput(e,t){if(Array.isArray(e))return e;if(typeof e!=`string`)return[e];let n=[{type:`text`,text:e}];return t&&t.length>0&&n.push(...t),[{role:`user`,content:n,timestamp:Date.now()}]}async runPromptMessages(e,t={}){await this.runWithLifecycle(async n=>{await Xg(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await Zg(this.createContextSnapshot(),this.createLoopConfig(),e=>this.processEvents(e),e,this.streamFunction)})}createContextSnapshot(){return{systemPrompt:this._state.systemPrompt,messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let t=e.skipInitialSteeringPoll===!0,n=this.shouldStopAfterTurn;return{model:this._state.model,reasoning:this._state.thinkingLevel===`off`?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,shouldStopAfterTurn:n?async e=>await n(e,this.signal):void 0,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async e=>this.prepareNextTurnWithContext?await this.prepareNextTurnWithContext(e,this.signal):await this.prepareNextTurn?.(this.signal):void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>t?(t=!1,[]):this.steeringQueue.drain(),getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error(`Agent is already processing.`);let t=new AbortController,n=()=>{},r=new Promise(e=>{n=e});this.activeRun={promise:r,resolve:n,abortController:t},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(t.signal)}catch(e){await this.handleRunFailure(e,t.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,t){let n={role:`assistant`,content:[{type:`text`,text:``}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:m_,stopReason:t?`aborted`:`error`,errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:`message_start`,message:n}),await this.processEvents({type:`message_end`,message:n}),await this.processEvents({type:`turn_end`,message:n,toolResults:[]}),await this.processEvents({type:`agent_end`,messages:[n]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case`message_start`:this._state.streamingMessage=e.message;break;case`message_update`:this._state.streamingMessage=e.message;break;case`message_end`:this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case`tool_execution_start`:{let t=new Set(this._state.pendingToolCalls);t.add(e.toolCallId),this._state.pendingToolCalls=t;break}case`tool_execution_end`:{let t=new Set(this._state.pendingToolCalls);t.delete(e.toolCallId),this._state.pendingToolCalls=t;break}case`turn_end`:e.message.role===`assistant`&&e.message.errorMessage&&(this._state.errorMessage=e.message.errorMessage);break;case`agent_end`:this._state.streamingMessage=void 0}let t=this.activeRun?.abortController.signal;if(!t)throw Error(`Agent listener invoked outside active run`);for(let n of this.listeners)await n(e,t)}};function y_(e){if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=10||r===0?Math.round(n):Math.round(n*10)/10} ${t[r]}`}function b_(e){let t=e.mimeType||`application/octet-stream`;return`${e.name} (${t}, ${y_(e.size)})`}function x_(e){let t=b_(e);return e.kind===`image`&&e.data?e.path?`[Attached image: ${t} — full-resolution copy saved to ${e.path}]`:`[Attached image: ${t}]`:e.kind===`text`&&e.text!==void 0?[`----- BEGIN ATTACHMENT ${t} -----`,e.text,`----- END ATTACHMENT ${e.name} -----`].join(`
|
|
880
|
+
`):e.path?`[Attached ${e.kind===`image`?`image`:e.kind===`text`?`text file`:`file`} saved to ${e.path} — ${t}. Read it from the virtual filesystem when you need its contents.]`:e.error?`[Attachment not included: ${t}. ${e.error}]`:`[Attachment not included: ${t}. Unsupported binary attachment.]`}function S_(e,t){if(!t?.length)return e;let n=t.map(x_),r=e.trim();return r?`${r}\n\n${n.join(`
|
|
881
881
|
|
|
882
882
|
`)}`:n.join(`
|
|
883
883
|
|
|
884
|
-
`)}function w_(e){return e?.length?e.filter(e=>e.kind===`image`&&e.data).map(e=>({type:`image`,data:e.data,mimeType:e.mimeType})):[]}const T_=`sessions`;function E_(){return new Promise((e,t)=>{let n=indexedDB.open(`agent-sessions`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(T_)||e.createObjectStore(T_,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var D_=class{dbPromise=null;getDB(){return this.dbPromise||=E_().then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise}async save(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(T_,`readwrite`).objectStore(T_).put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(T_,`readonly`).objectStore(T_).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async delete(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(T_,`readwrite`).objectStore(T_).delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async loadAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(T_,`readonly`).objectStore(T_).getAll();r.onsuccess=()=>t(r.result??[]),r.onerror=()=>n(r.error)})}async list(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(T_,`readonly`).objectStore(T_).getAll();r.onsuccess=()=>{t((r.result??[]).map(e=>({id:e.id,updatedAt:e.updatedAt})))},r.onerror=()=>n(r.error)})}async clearAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(T_,`readwrite`).objectStore(T_).clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}static newId(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}static createSession(e,t){let n=Date.now();return{id:e,messages:[],config:t,createdAt:n,updatedAt:n}}static updateMessages(e,t){return{...e,messages:t,updatedAt:Date.now()}}},O_=class{resolve;providerId;now;#e=null;#t=null;#n=null;#r=null;constructor(e,t,n=Date.now){this.resolve=e,this.providerId=t,this.now=n}#i(e){return e===`ok`?6e4:e===`unsupported`?18e5:3e5}isStale(){let e=this.#e;return!e||this.#t!==this.providerId()||this.now()-e.at>=this.#i(e.outcome)}snapshot(){return this.#t===this.providerId()?this.#e?.window??null:null}async refresh(e={}){if(!e.force&&!this.isStale())return this.snapshot();let t=this.providerId();return this.#n!==null&&this.#r===t?this.#n:(this.#n=this.resolve().then(e=>{let n=e?{...e,at:this.now()}:null;return this.#a(t,n?`ok`:`unsupported`,n),n}).catch(()=>{let e=this.snapshot();return this.#a(t,`failed`,e),e}).finally(()=>{this.#r===t&&(this.#n=null,this.#r=null)}),this.#r=t,this.#n)}#a(e,t,n){e===this.providerId()&&(this.#t=e,this.#e={outcome:t,window:n,at:this.now()})}clear(){this.#e=null,this.#t=null}},k_=e({clearBudgetWindowCache:()=>F_,getBudgetWindowSnapshot:()=>N_,refreshBudgetWindow:()=>P_});async function A_(){let e=me();if(!e)return null;let t=se(e);if(!t?.getBudgetUsage)return null;let n=await t.getBudgetUsage();return n?{...n,providerId:e}:null}function j_(){try{return me()}catch{return``}}const M_=new O_(A_,j_);function N_(){return M_.snapshot()}function P_(e){return M_.refresh(e)}function F_(){M_.clear()}const I_=`abject.abortive.abrasive.absolute.abstruse.abundant.abyssal.accessible.acerbic.acrid.adamant.adept.adlerian.adornian.adroit.adventurous.aeolian.aerated.aesthetic.affable.aged.ageless.agile.airborne.airlocked.airy.akkadian.alabaster.alacritous.alert.alien.alloyed.allusive.aloof.alpha.alpine.alternate.altruistic.amaranthine.amber.ambidextrous.ambivalent.ambrosial.amiable.amorphous.ample.analog.analytical.ancestral.ancient.angelic.animated.animist.anomalous.antediluvian.antic.antlered.apollinairian.apollonian.apt.aquatic.arbitrary.arcadian.arcane.archaic.archimedean.ardent.arduous.arendtian.argent.argentine.argive.aristotelian.armstrongian.aromatic.arresting.artful.arthurian.articulate.artificial.artisanal.artless.ascetic.ashen.ashy.asimovian.aspiring.assiduous.assyrian.asteroidal.astral.astute.asynchronous.athenian.atlantean.atomic.attentive.attic.audacious.audenesque.augmented.august.augustan.aureate.auric.auroral.austenian.austere.austral.authentic.autonomous.autumnal.avalonian.avid.avuncular.aztec.azure.babbagean.babylonian.bacchic.bachian.bactrian.ballardian.ballistic.balmy.banksian.barefoot.barreled.barthesian.bartokian.bashy.baudelairean.bayesian.beatific.beckettesque.beckettian.beethovenian.beguiling.bellicose.bemused.benevolent.benign.benjaminian.bergmanesque.beta.bewitched.binary.bionic.bismarckian.bitter.bitwise.blackened.blakean.blameless.bland.blazar.blazing.blended.blessed.blissful.blistered.blithe.blooming.blunt.blustery.boeotian.boggy.bohrian.boingy.boisterous.bold.bolted.bombastic.bonny.boolean.boreal.borgesian.borgian.bosky.botticellian.bottled.bouncy.boundless.bountiful.bourbon.bradburyan.brahmsian.braised.brambly.brash.brave.brazen.bready.breathless.brechtian.breezy.briared.briery.bright.brilliant.brined.briny.brisk.bristling.briton.brittenesque.broadband.brontean.bronzed.brooding.browned.browningesque.brucknerian.brumal.brusque.bubbling.bubbly.bucolic.budding.bunuelian.buoyant.burnished.burnt.buttered.buttery.bygone.byronic.bytewise.byzantine.cacophonous.caesarean.callow.calm.candescent.candid.candied.canny.cantorian.capable.capricious.caramelized.caravaggesque.carbon.carefree.carolingian.cartesian.carved.casked.cast.cavafian.cavalier.celebrated.celestial.celtic.ceramic.cerebral.ceremonious.cerulean.cervantine.cezannesque.chagallian.chalky.chaplinesque.charcoal.charismatic.charmed.charming.charred.chaucerian.cheeky.cheerful.chekhovian.cherished.cherubic.chewy.chilled.chilly.chimerical.chipper.chirpy.chivalrous.chopinesque.chromospheric.chronal.chthonic.chubby.chunky.churchillian.cimmerian.cindered.circumspect.circumstellar.citrusy.civil.clandestine.clangy.clarified.clarkean.classic.clement.clever.cloaked.clockwork.clompy.cloned.cloudlike.cloudy.clunky.clustered.coastal.cobalt.cognitive.coherent.coleridgean.colossal.coltranesque.comely.cometary.compiled.complacent.composite.concurrent.conradian.constablean.convivial.copernican.copious.coplandesque.cordial.corinthian.corked.cornelian.coronal.cortical.cosmic.coy.cozy.cracked.crackling.crafty.cranky.crashy.creamy.credible.crepuscular.cretan.crimson.crisp.crispy.crowned.crumbly.crunchy.crushed.cryo.cryofrozen.cryogenic.cryonic.cryptic.crystalline.cuddly.cumulative.cunning.cupric.cured.curious.cursed.cursory.cushy.cybernetic.cyberpunk.cynical.cyprian.daliesque.dancy.dandy.dantean.dantesque.dapper.dappled.daring.dark.darwinian.dashing.dashy.dauntless.davisian.dawning.dazzling.deathless.debonair.deboned.debussyan.decanted.decompiled.decorous.decrypted.deep.deferential.deft.degasian.delectable.deleuzian.delian.deliberate.delicate.delirious.delphic.delta.demure.depressurized.derridean.destined.devout.dewy.dexterous.diaphanous.diced.dickensian.dickian.dickinsonian.didactic.dieselpunk.diffident.digital.dignified.diligent.dimensional.dinky.dionysian.discerning.discreet.disheveled.disparate.distant.distinct.distributed.diurnal.divine.dizzy.docile.docked.dogged.doomed.dorian.dormant.dostoevskian.dotty.doughty.doughy.downy.dozy.draconic.dreamful.dreamy.drifting.dripping.drizzly.droll.drowsy.druidic.dulcet.dun.dunky.durkheimian.dusky.dwarven.dynamic.dystopian.eager.earnest.earthy.eastward.easygoing.ebony.ebullient.eclectic.eclipsed.ecstatic.edenic.edwardian.effervescent.effulgent.effusive.einsteinian.elamite.elastic.elated.eldritch.electric.electronic.elegant.elegiac.elgarian.eliotian.eliotic.elizabethan.ellingtonian.eloquent.elusive.elven.elvish.elysian.embered.emergent.eminent.emphatic.emulsified.enchanted.encoded.encrypted.endearing.endless.endogenous.energetic.enhanced.enigmatic.enthralling.ephemeral.epic.epicurean.equanimous.errant.erudite.escherian.esoteric.esteemed.eternal.ethereal.ethiopian.etruscan.euclidean.eulerian.euphonious.euphoric.evanescent.evening.eventide.everlasting.evocative.exacting.exalted.exemplary.exo.exogenous.expansive.expressive.exquisite.extraterrestrial.extruded.exuberant.fabled.fabulous.facetious.faithful.fallow.fanciful.fantastic.faradayic.faraway.farmhouse.fastidious.fated.fateful.fathomless.faulknerian.faunal.fearless.feathered.feathery.fecund.federated.feisty.felicitous.felliniesque.fenny.fermented.ferny.ferrous.fervent.fervid.festive.fetching.fey.fickle.fierce.fiery.filleted.filtered.fitzgeraldian.fizzy.flaky.flamboyant.flamed.flashy.flawless.fleecy.fleet.fleeting.flexible.flickering.flinty.floral.florid.flouncy.flourishing.flowering.fluent.fluffy.fluid.fluvial.foamy.folded.fond.foraged.forged.formidable.forthright.fortuitous.forward.foucauldian.fourier.fractal.fragrant.frank.frankish.freckled.free.fresh.freudian.friedmanite.frisky.frizzy.frolicsome.frosted.frosty.frothy.frozen.frugal.fruiting.fruity.funky.furred.furtive.futuristic.fuzzy.gaelic.galactic.galbraithian.galilean.gallant.gallic.galvanic.gamesome.gamma.gandhian.garlanded.garrulous.gauguinesque.gaussian.gauzy.generous.genetic.genial.genomic.genteel.gentle.geomagnetic.georgian.gershwinesque.ghostly.giant.gibsonian.giddy.gifted.giga.giggly.gilded.giottesque.glacial.glad.glazed.gleaming.gleeful.glimmering.glistening.glorious.glossy.glowing.gnomish.godardian.godelian.goethean.goethesque.gogolian.golden.gooey.goofy.gorgeous.gorsy.gossamer.gothic.gowned.goyaesque.graceful.gracious.grainy.grand.grassy.grated.gravitic.gregarious.grilled.groovy.ground.grounded.guileless.gushy.gusty.habermasian.habsburg.hadrianic.halcyon.hale.hallowed.haloed.halved.hamiltonian.han.handelian.handmade.handsome.hanoverian.hapless.happy.hardy.hardyesque.harmonious.hashed.haunted.haydnesque.hayekian.hazy.heady.heaneyesque.hearthside.hearty.heathen.heathered.heavenly.hegelian.heideggerian.heinesque.heinleinian.heirloom.heisenbergian.heliacal.hellenic.hellish.hemingwayesque.herbal.herbertian.herculean.hermetic.heroic.hexed.hibernal.hilbertian.histrionic.hitchcockian.hittite.hoar.hoary.hobbesian.hobbitish.hogarthian.holderlinian.holo.holographic.holy.homerian.homeric.homeward.honest.honeyed.honky.hooded.hooved.hopeful.hopkinsian.hopperesque.hoppy.horatian.horned.hospitable.hot.housemade.huggy.humble.humean.humming.humorous.hunky.hunnish.hurrian.hushed.hydraulic.hyper.hyperborean.hypersonic.hyperspatial.hypnotic.iberian.ibsenite.iced.icy.ideal.idyllic.igneous.illustrious.imaginative.immaculate.immense.immortal.impassioned.impeccable.impetuous.impish.impressive.incan.incandescent.incisive.incorrigible.indefatigable.indelible.indigo.indolent.indomitable.industrious.ineffable.inexorable.infernal.infinite.infra.infrared.infused.ingenious.ingenuous.inimitable.innocuous.inquisitive.insatiable.inspired.intense.intergalactic.interstellar.intragalactic.intrepid.intricate.intrinsic.intuitive.inventive.inveterate.invincible.inward.ionian.ionic.ionospheric.irenic.iridescent.irrepressible.ithacan.itinerant.ivory.jacobean.jammy.jangly.jaunty.jazzy.jeffersonian.jiggly.jingly.jocular.jocund.johnsonian.jolly.jouncy.jovial.jovian.joycean.joyful.joyous.jubilant.judicious.juiced.juicy.jumped.jumpy.jungian.junky.justinianic.jute.kafkaesque.kandinskian.kantian.keatonesque.keatsian.keen.keplerian.keynesian.kierkegaardian.kindly.kindred.kinetic.kiplingesque.klimtian.knowing.kooky.kubrickian.kurosawan.lacanian.laconic.lacquered.lacustrine.lacy.lamarckian.lambda.lambent.laminated.landed.languid.lanky.laplacian.larkinesque.laser.latent.lathed.latin.lattice.laudable.launched.laureled.lavish.layered.leaden.leafy.lean.learned.legendary.leguinian.leibnizian.lemian.lemurian.lenient.leonardesque.liberal.libyan.lidar.light.lighthearted.likable.lilac.lilting.liminal.limpid.lincolnesque.lingering.linnaean.lissome.lisztian.literate.lithe.littoral.lively.loamy.local.lockean.lofty.logical.loopy.loose.loquacious.lorcaesque.lorcan.lossless.lossy.lovecraftian.lovelacean.loyal.lucent.lucid.lucky.ludic.lukewarm.luminal.luminous.lunar.luscious.lush.lushy.lusitanian.lustrous.lydian.lynchian.lyotardian.lyric.lyrical.macerated.machiavellian.macro.magical.magnanimous.magnetar.magnetic.magnetospheric.magnificent.magrittean.mahlerian.majestic.mallarmean.malleable.malthusian.malty.mandelan.manetesque.manifold.marbled.marshy.martial.martian.marvelous.marxian.maser.masked.masterful.matchless.matin.matissean.mature.matutinal.mauve.maverick.mawkish.maxwellian.mayan.meandering.mechanical.median.medicean.mega.mellifluous.mellow.melodic.mendelian.merciful.mercurial.merovingian.merry.meshed.meta.metamorphic.meteoric.meticulous.metternichian.mettlesome.michelangelesque.micro.microwave.midnight.mighty.mild.milled.miltonian.miltonic.minced.mindful.mineral.ming.mingusian.minoan.minty.miraculous.mired.miroesque.mirthful.mischievous.misty.mobile.modest.modular.molecular.molieresque.momentous.mondrianesque.monetian.monkish.mono.montane.moonless.moonlit.mordant.morning.mossy.motley.mottled.mouthwatering.mozartian.mughal.multiversal.munificent.murmuring.mushy.musical.mutable.mutant.mycenaean.mysterious.mystical.mythic.nabokovian.nameless.nano.nanoscale.napoleonic.narrowband.nascent.natty.neat.nebular.nebulous.nefarious.neptunian.nerudian.networked.neural.neutron.neutronic.newtonian.nietzschean.nifty.nimble.noble.nocturnal.nonchalant.nonpareil.noontide.norse.northward.nostalgic.notable.novel.nozickian.nuanced.nubian.nuclear.numinous.nutty.oaky.obdurate.oblique.observant.obstinate.obtuse.oceanic.ochre.odyssean.olden.olympian.omega.omni.onward.opaline.opportune.optical.optimistic.opulent.oracular.orbital.orbiting.orderly.original.ornate.orphic.orwellian.osirian.ostentatious.otherworldly.otiose.ottoman.outgoing.outspoken.outward.overcast.overclocked.ovidian.pacific.pagan.painstaking.palatial.pale.pallid.palpable.paradisal.paradoxical.parallel.paramount.parkerish.parsonian.parthian.passionate.pastoral.patched.pathless.patient.pavlovian.peaceable.peaceful.peachy.pearly.peaty.pebbly.peeled.peered.peerless.pelagic.pellucid.penetrating.pensive.peppered.peppery.peppy.perceptive.perennial.perfect.perfumed.perky.persian.persistent.perspicacious.persuasive.pert.pervasive.pessoan.petaled.petrarchan.phantom.pharaonic.phased.philosophical.phlegmatic.phoenician.photonic.photospheric.phrygian.picassoesque.pickled.pictish.picturesque.pillowy.pindaric.pinteresque.piping.piquant.pirandellian.pithy.pivotal.pixelated.placid.planckian.planetary.planetoid.plangent.plasmic.plathian.platinum.platonic.playful.pleasant.plentiful.pliant.plinky.plonky.plucky.plumed.plummy.plush.plushy.plutonian.plutonic.pneumatic.poached.poesque.poetic.poignant.poised.polished.polite.pollockian.poly.polygonal.polymer.polynesian.popean.popped.popular.portly.posh.positronic.posthuman.potent.pouncy.powdery.powerful.pragmatic.prancy.precise.precocious.precognitive.preeminent.premier.prescient.pressed.pressurized.prestigious.pretty.primeval.primordial.princely.printed.pristine.private.prized.prodigious.profane.proficient.profound.profuse.prokofievian.prolific.promethean.prompt.proper.prophetic.prosaic.prosperous.protean.proto.protostellar.proud.proustian.providential.prudent.psionic.puccinian.puckish.pudgy.puffed.pulled.pulsar.punctilious.punctual.pungent.punic.pure.purposeful.pushkinian.pynchonesque.pythagorean.quaint.quantum.quartered.quasar.questing.quick.quiescent.quiet.quintessential.quirky.quixotic.rabelaisian.racinian.radar.radiant.radio.rainwashed.rainy.rakish.rambunctious.raphaelesque.rapid.rapturous.rare.rational.ravelian.rawlsian.raytraced.ready.reasonable.rebooted.receptive.recondite.recursive.redolent.reduced.reedy.refined.reflective.refulgent.regal.relativistic.relaxed.reliable.remarkable.rembrandtesque.remote.rendered.renoiresque.renowned.replete.replicated.resilient.resinous.resolute.resourceful.respectful.resplendent.responsive.restful.restive.restless.reticent.retro.reverent.rhapsodic.rhodian.rhythmic.ricardian.rich.richelieuvian.riemannian.rigorous.rilkean.rimbaudian.rimed.ringed.ripe.ripening.rippling.risible.riverine.riveted.roaming.roaring.roasted.robed.robotic.robust.rolled.roly.roman.romanov.romantic.rompy.rooseveltian.roseate.rosy.rothkoesque.rousing.rousseauian.rowdy.royal.rubenesque.ruddy.runic.rushy.russet.rustic.sabine.sable.sacred.sagacious.sage.saintly.salient.saline.salingeresque.salted.salty.salubrious.samian.sandaled.sandy.sanguine.sapid.sapient.sapphic.sardonic.sarmatian.sartrean.sassy.satiny.saturnian.saturnine.saucy.savory.savvy.saxon.scalding.scarlet.schielesque.schillerian.schoenbergian.scholarly.schubertian.schumannesque.schumpeterian.scintillating.scorched.scorsesean.scrappy.scruffy.scrupulous.scythian.seaborne.seamless.seared.seasonal.seaward.secure.sedate.sedgy.sedimentary.sedulous.seemly.seismic.selenic.selfless.sensible.sensitive.sentient.sentimental.seraphic.sere.serene.seuratian.shaded.shadowed.shadowy.shaggy.shaken.shakespearean.shamanic.shannonian.sharded.sharp.shaved.shavian.shelleyan.shielded.shimmering.shiny.shoreless.shostakovian.shrewd.shucked.sibelian.sibilant.sibylline.sicilian.sidereal.sienna.sifted.sigma.silicon.silken.silky.silly.silty.silver.silvered.simmering.simulated.sincere.singed.singing.singular.sinuous.sisyphean.sizzling.skeptical.skillful.skinnerian.skittish.skyward.sleek.sleepless.sleepy.slender.sliced.slick.slipstreamed.slow.sly.smart.smashy.smithian.smoked.smoky.smoldering.smooth.snappy.snazzy.snoozy.snowy.snug.snuggly.soaring.sociable.socratic.sodden.soft.sogdian.solar.solarpunk.solemn.solid.somnolent.sonar.song.sonic.sonorous.sooty.soporific.soulful.sound.soundless.sour.southward.sovereign.spaceborne.spacefaring.spacious.sparkling.sparkly.spartan.special.speckled.spectacular.spectral.speedy.spellbound.spiced.spicy.spielbergian.spiffy.spinozan.spirited.splashy.splendid.split.sploshy.spontaneous.spooky.sporty.spotless.spotted.sprightly.sproingy.spry.spun.spunky.squally.squashy.squelchy.squiggly.squishy.staid.stainless.stalwart.starborn.starfaring.starless.starlit.stasisbound.stately.steadfast.steady.steaming.steampunk.steely.steeped.steinbeckian.stellar.stellarborn.sticky.stirred.stirring.stoic.stoical.stolid.stompy.stoppardian.storied.stormy.stout.strained.stratospheric.straussian.stravinskian.streaky.stretched.striking.strindbergian.striped.strong.stuart.stubby.studious.stunning.sturdy.stygian.suave.subatomic.sublime.suborbital.subsonic.substantial.subtle.succinct.succulent.sudsy.sugared.sugary.sumerian.summery.sunless.sunlit.sunny.sunward.superb.supergalactic.superlative.superluminal.supersonic.supple.supreme.sure.surreptitious.svelte.swanky.sweeping.sweet.swift.swiftian.swirled.swooshy.sylvan.sympathetic.synaptic.synchronous.synthetic.syrupy.tableside.tachyonic.taciturn.talented.talleyrandian.tame.tang.tangy.tarantinoesque.tarkovskian.tart.tasteful.tattered.taut.tawny.tectonic.telekinetic.telepathic.temperate.tempered.temporal.tenacious.tender.tennysonian.tenuous.tepid.tera.terran.terrific.terse.textured.thackerayan.thankful.thawed.theban.thessalian.theta.thorny.thorough.thoughtful.thracian.threadbare.thriving.thundery.tidal.tidy.timeless.timely.timeworn.tinkly.tiny.tipsy.tireless.titanesque.titanian.titanic.titanium.titianesque.toasted.toasty.tocharian.tokenized.tolerant.tolkienesque.tolstoyan.tonic.tonky.toothsome.torched.totemic.tough.towering.trackless.tranquil.transcendent.transhuman.treacly.treasured.tremendous.tremulous.trenchant.tricky.trim.triumphant.trojan.trollopian.truculent.true.truffautian.truffled.trusty.truthful.tudor.turbo.turingian.turneresque.twangy.twilight.twilit.twinkling.twinkly.ubiquitous.ultra.ultrasonic.ultraviolet.umami.umber.unassuming.unbounded.uncanny.uncorked.unctuous.undaunted.underworldly.undocked.undying.unearthly.unerring.unflappable.unique.unknown.unruffled.upbeat.upgraded.upright.upstanding.upward.uranian.urbane.utopian.vacuous.valeryan.valiant.valorous.vandal.vangoghian.vast.veblenian.vectorized.vedic.vehement.veiled.velazquezian.velvet.velvety.venerable.venturous.venusian.veracious.verbose.verdant.verdian.verdurous.verlainian.vermeerian.vermilion.vernal.verneian.versatile.vesper.vespertine.vibrant.victorian.vigilant.vigorous.vintage.violet.virgilian.virtual.virtuous.visceral.vital.vivacious.vivid.vocal.voidborn.voidward.volcanic.voltairean.voluble.vonnegutian.voracious.voxel.vroomy.wacky.wagnerian.wakeful.waking.wan.wandering.warholian.warm.warped.wary.washingtonian.wayward.wealthy.weathered.weberian.welcome.welded.wellesian.wellsian.westward.whacky.whimsical.whimsy.whipped.whisked.whispering.whistlerian.whitmanesque.whole.wholesome.whooshy.wide.wiggly.wild.wildean.willowy.wilsonian.wily.windswept.windy.winged.winning.winsome.wintry.wired.wireframe.wireless.wise.wishful.wispy.wistful.wittgensteinian.witty.wobbly.wodehousian.wondrous.wonky.wooded.woody.woolly.woozy.wordless.wordsworthian.wormholed.worthy.wraithlike.wreathed.wriggly.wry.xenial.xeno.yanky.yearning.yeasty.yeatsian.young.youthful.yuletide.yummy.zany.zappy.zealous.zested.zestful.zesty.zeta.zingy.zippy.zodiacal.zonked.zonky.zoomy.zoroastrian`.split(`.`),L_=`abalone.absinthe.absyrtus.accelerator.achilles.acorn.acquerello.actuator.adobo.adonis.aeetes.aegis.aello.aeneas.aengus.aether.affogato.afterburner.agartha.agate.agni.agnolotti.aioli.airlock.ajax.aji.albatross.alder.ale.alecto.aleppo.alfheim.allegory.alliteration.almond.amaranth.amaretto.amaterasu.ambrosia.americano.amphiaraus.anago.anapest.ancho.anchovy.android.andromeda.anise.annal.annwn.ansible.antaeus.antenna.anthem.antigone.antimony.antistrophe.anubis.aoidos.aperol.aphelion.aphrodite.apogee.apollo.apple.apricot.aquamarine.aquavit.aqueduct.arabica.arachne.arawn.arbor.arborio.arc.arcadia.arch.archipelago.ares.argo.argon.argonaut.aria.ariadne.ark.arke.armagnac.array.arrow.artemis.arthur.artichoke.artifact.arugula.asgard.asgardia.ash.asparagus.aspen.assam.assonance.asteroid.astronaut.atalanta.athena.atlantis.atlas.atoll.atom.atropos.aubergine.augean.aura.aurora.avalon.avalonia.avocado.awning.axion.axle.azurite.bacchus.bagna.baharat.balder.ballad.balladeer.banana.banshee.baozi.bard.barge.barium.barley.barn.basalt.basil.basilisk.basmati.bastet.bastion.bay.bayleaf.beacon.beam.bean.bearing.beech.beetroot.behemoth.bellini.beowulf.bergamot.berth.beryl.beryllium.bifrost.biodome.birch.biscotti.bismuth.bisque.bit.bittern.blackberry.blast.blaster.blini.block.blodeuwedd.bloodstone.blossom.bluebell.blueberry.bolt.bomba.bonito.boom.borage.boson.botargo.bottarga.bouillon.boundary.bow.bower.bragi.bramble.bran.branch.brandy.branwen.breeze.brew.bridge.brigid.brioche.broccoli.brook.brulee.brunhild.brush.bucatini.buckler.buckwheat.buffer.bulkhead.bunting.burrata.burst.bus.busiris.butte.butter.buttercup.butterscotch.byte.cabbage.cabin.cacao.cachaca.cache.cacus.cadence.caesura.calamarata.calamari.calcite.caldera.calliope.calvados.calypso.cam.camellia.camelot.camembert.campari.canal.cannelloni.cannoli.canopy.cantaloupe.cantata.canticle.canvas.canyon.canzone.capacitor.capellini.caper.capon.cappelletti.cappuccino.capsule.caramel.cardamom.cardoon.carillon.carnaroli.carnation.carol.carrier.carrot.cascade.cashew.cassandra.cassis.castle.castor.cavatelli.caviar.cayenne.cedar.celaeno.celeriac.cell.centaur.cerberi.cerberus.cernunnos.ceryneian.cesium.ceto.ceylon.chaff.chaffinch.chai.chain.chalk.chamomile.champagne.chandra.channel.chanson.chanterelle.chard.charon.chartreuse.cheddar.cherry.chert.chervil.chestnut.chickweed.chicory.chili.chime.chimera.chimichurri.chimney.chip.chipotle.chirashi.chiron.chive.chocolate.chorale.chorizo.chorus.chronicle.chrysanthemum.chrysaor.chrysomallus.chutney.ciabatta.cibola.cider.cilantro.cinder.cinnamon.cipher.circe.circlet.circuit.cirque.cistern.citadel.citrine.citron.clementine.cliff.clio.clipper.cloak.clotho.cloud.clove.clover.cluster.coal.cobbler.cockaigne.cockpit.cocoa.coconut.codex.coffee.cog.cognac.coif.coil.col.colchis.collider.colony.combe.comet.compote.concerto.conchiglie.conduit.confit.console.consomme.consonance.continuum.contour.cookies.coordinate.core.coriander.cormorant.corona.coronet.cortado.corvette.cosmos.cottage.couplet.course.couscous.cove.cowl.cowslip.crab.craft.crag.cranberry.crane.crayon.cream.creme.crepe.cress.crocus.croissant.crosne.crown.cruiser.crumble.cryopod.cryosleep.crystal.cuchulainn.cuckoo.cucumber.cuirass.cumin.cupid.curlew.currant.current.curry.custard.cyborg.cycle.cyclops.cyclotron.cylinder.dactyl.daedalus.daemon.daffodil.dagda.dahlia.daiquiri.dais.daisy.dale.dam.dandelion.danu.daphne.darjeeling.dart.dashi.date.dawn.daydream.deck.deirdre.demeter.destroyer.dew.diadem.diary.dill.dimension.diode.diomedean.dionysus.ditalini.ditch.djinn.dock.doenjang.domain.donburi.donjon.door.doppio.dove.downlink.dreadnought.dream.drift.droid.dryad.dukkah.dulce.dumpling.dune.durga.dusk.dust.dyke.eagle.earlgrey.easel.echidna.echo.eclair.eclipse.ecliptic.edamame.eddy.edelweiss.edge.egret.einsteinium.elderflower.eldorado.electra.elegy.elm.elysium.ember.endive.enigma.enjambment.enkidu.envoi.eos.epigram.epistle.epode.erato.erinyes.eros.erymanthian.escargot.espresso.estuary.eumenides.euryale.eurybia.eurydice.eurytion.excalibur.exoplanet.fable.fafnir.falcon.fancy.farfalle.fate.feather.feldspar.fell.fence.fennel.fenrir.fenugreek.fermion.fern.fettuccine.fiddlehead.field.fig.finch.finn.fionn.firebird.firefly.fission.fizz.fjord.flake.flame.flare.flash.flicker.flint.flue.fluorite.flux.flywheel.focaccia.fog.folio.fondant.forge.fortress.foxglove.fragment.fraise.frame.frangipane.frappe.freesia.fregola.freighter.freya.frigate.frigg.frost.fudge.fugue.fumarole.furies.fusilli.fusion.gaia.galahad.galangal.galatea.galaxy.galette.galleon.gallium.ganache.ganesh.gannet.gantry.ganymede.garam.gardenia.garlic.garuda.gateway.gauntlet.gawain.gazebo.gear.gelato.gemelli.genmaicha.genoise.geranium.germ.germanium.geryon.geyser.ghazal.ghee.ghost.gilgamesh.ginger.gingko.ginnungagap.girder.glacier.glade.glaze.gleam.gleeman.glen.glimmer.glint.glitter.gloss.glow.gluon.gnocchi.gochujang.goldfinch.golem.goose.gooseberry.gorgon.gouda.governor.gradient.graeae.granary.granite.grapefruit.grappa.gratin.graviton.greave.grebe.gremolata.grenadine.grendel.grid.griffin.gruyere.guajillo.guava.gudrun.guinevere.gunkan.gwydion.gyoza.gyroscope.habanero.habitat.hades.hadron.haiku.hall.halloumi.halo.halva.hamachi.hangar.hanuman.harissa.harpies.harpy.harvest.hatch.hauberk.hawthorn.haze.hazel.hazelnut.heading.headland.heap.heart.hearth.heather.hecate.hedge.heimdall.hel.helheim.helios.helium.helix.helle.hellebore.helm.hemistich.hephaestus.hera.hermes.heron.hesperides.hestia.hibiscus.hippogriff.hirame.hive.hoisin.hojicha.hollandaise.hollow.holly.hologram.honey.honeycomb.honeysuckle.hood.hoopoe.horizon.horseradish.horus.hrothgar.hub.huckleberry.hue.huginn.hull.husk.hut.hyacinth.hydra.hydras.hylas.hymn.hyperborea.hypercube.hyperdrive.hyperion.hyperspace.hyssop.iamb.ibis.icarus.idas.idunn.idyll.igniter.igraine.ikura.indium.indra.inductor.infusion.injector.ink.inlet.inspiration.ion.iridium.iris.ishtar.isis.isolde.isotope.ivy.iwashi.izanagi.jackdaw.jackfruit.jalapeno.janus.jasmine.jason.jasper.javelin.jay.jet.jiaozi.jongleur.jonquil.jormungandr.jotunheim.journal.julep.jumpgate.juniper.juno.jupiter.kaffir.kale.kali.kampachi.karaage.karasumi.katsu.keel.keep.kefir.kelpie.kenning.kernel.kestrel.khinkali.kiln.kimchi.kingfisher.kinmedai.kirsch.kite.kitsune.kiwi.koan.kohlrabi.kombucha.koshihikari.kraken.krypton.kumquat.kvass.lachesis.lacquer.ladon.ladons.laertes.lager.lagoon.lake.lakshmi.lambic.lament.lance.lancelot.lander.lane.langoustine.lantern.lapis.lark.larkspur.lasagna.latte.laureate.laurel.lava.lavender.leaf.leda.leek.legend.lemon.lemonbalm.lemongrass.lemuria.lens.lentil.lepton.lernaean.lethe.letter.levee.lever.leviathan.lightyear.lily.lime.limerick.limoncello.linden.linguine.link.linnet.lir.lithium.lityerses.lobster.loch.lock.lodge.loki.loop.loquat.lotus.lovage.lugh.lullaby.lungo.luster.lychee.lynceus.lyonesse.lyricist.macadamia.macaron.macchiato.madai.madeleine.madrigal.magma.magnolia.magpie.mail.mainframe.maki.makrut.malachite.manannan.mango.manicotti.manor.manti.manticore.mantle.mantou.manuscript.maple.marble.marduk.margarita.marigold.marjoram.marquee.marrow.martini.marvel.marzipan.masago.masala.mascarpone.mast.matcha.matrix.mead.meadow.mech.medea.medusa.megaera.meleager.memoir.mentaiko.mercury.meringue.merlin.merlot.mesa.mesh.metaphor.meteor.meter.mezcal.mezzaluna.mica.midas.midgard.mill.mimir.mimosa.minerva.minotaur.minstrel.mint.minuet.miracle.mirin.mirror.miso.missive.mist.mjolnir.mocha.module.moira.mojito.molasses.mole.momo.monolith.moonbase.moonbeam.moonstone.moor.mopsus.mordred.morel.morgana.morpheus.morrigan.moss.mote.motet.mousse.mu.mulberry.muninn.muon.muse.muspelheim.mustard.myrtle.mystery.myth.nadir.naga.naiad.nanite.nanobot.narcissus.neapolitan.nebula.nectarine.needle.negroni.nemean.nemesis.neon.neptune.neptunium.nereid.nereus.nessus.nest.nestor.net.nettle.neutrino.nexus.niamh.nib.nibble.nibiru.niflheim.nightingale.nigiri.nike.niobe.njord.nocturne.node.nog.nori.norn.note.nougat.nova.nozzle.nuada.nutmeg.nyx.oak.oasis.oat.obelisk.oberon.obsidian.oceanid.oceanus.octave.octavo.ocypete.ode.odin.odysseus.oisin.okonomiyaki.olive.olympus.oni.onigiri.oolong.oracle.orange.orb.orbit.orbiter.orchard.orchid.oreads.orecchiette.oregano.orion.orpheus.orthros.orthrus.orzo.oscillator.osiris.osmium.osprey.ouroboros.outline.outpost.ouzo.oven.overture.owl.oyster.paccheri.packet.padron.page.palace.palette.palladium.palm.pan.pandan.pandora.panettone.pansotti.pansy.pantoum.papaya.pappardelle.paprika.papyrus.parable.paradox.parcae.parchment.parfait.parmesan.parsec.parsley.parsnip.particle.partridge.parvati.pasilla.passionfruit.pastel.pastis.patina.pavilion.pavlova.peach.peak.pear.pebble.pecan.pegasi.pegasus.pekoe.peleus.pelican.pelmeni.pen.pencil.penelope.penne.peony.pepper.peppermint.percival.peregrine.pergola.peridot.perigee.perihelion.perry.persephone.perseus.persillade.persimmon.pesto.petal.petrel.phase.pheasant.phoenix.pholus.phorcys.photon.phrixus.pickle.pierogi.pigment.pimento.pine.pineapple.ping.pinot.pipe.pipit.piquillo.pisco.pistachio.piston.pith.plane.plasma.plate.plover.plum.plume.pluto.plutonium.poblano.pod.podarge.poet.polenta.pollux.polyphemus.pomegranate.pomelo.pond.pontus.ponzu.pooka.pool.poplar.poppy.porcini.port.portal.porter.porthole.poseidon.positron.prairie.praline.prelude.primrose.prism.probe.profile.prometheus.prosciutto.prosecco.proteus.protocol.psalm.psyche.pudding.puffin.pulse.pumice.pumpkin.purslane.pwyll.pylon.pyrrhic.quadrant.quail.quark.quarto.quartz.quatrain.qubit.quetzalcoatl.queue.quill.quince.quinoa.quiver.radish.radium.radon.ragnarok.rain.rama.ramen.ramp.rampart.ramson.raspberry.ratatoskr.raven.ravioli.ray.reactor.realm.reaper.reed.reef.refrain.region.register.relay.relic.remnant.requiem.reservoir.residue.resistor.resonator.reverie.rhapsode.rhapsody.rhea.rhiannon.rhodium.rhododendron.rhubarb.rhyme.ricotta.riddle.ridge.riesling.rigatoni.rim.ring.risotto.ristretto.river.roast.robin.robusta.roc.rocket.rod.romesco.rondeau.rooibos.rook.root.rose.rosemary.rosewater.roundel.rover.rowan.rubidium.rum.rune.saba.saffron.saga.saison.sake.salmoriglio.salsa.salsify.sambal.sambuca.samphire.sancerre.sandpiper.sangria.sanma.sansho.saraswati.sashimi.sasquatch.satellite.satyr.sauternes.savanna.sawara.sazerac.scaffold.scalar.scallop.scansion.scepter.schnapps.schooner.scop.scorzonera.scotchbonnet.scroll.sector.seed.sekhmet.selene.selenite.selenium.selkie.sencha.sensor.sequoia.serenade.serrano.servo.sesame.sestina.sextet.shack.shade.shadow.shaft.shale.shallot.shambhala.shard.shed.sheen.sherbet.sherry.shield.shimmer.ship.shishito.shiso.shiva.shoyu.shrub.shumai.shuttle.sibyl.sif.signal.sigurd.silhouette.silo.simile.simurgh.singularity.siren.sita.skadi.skald.skiff.skuld.skylark.slant.slate.sleipnir.sling.slipstream.sliver.sloop.sluice.smithy.smoke.snowdrop.socket.sofrito.sonata.sonnet.soot.sorbet.sorrel.souffle.soul.soy.spaceport.spaghetti.spark.sparkle.sparrow.spear.speck.specter.speculoos.spelt.sphere.sphinx.sphinxes.spindle.spinel.spiral.spire.spirit.splinter.spoke.spondee.spore.spring.spritz.spruce.sriracha.ssamjang.stack.stanza.starbase.starlight.starling.starport.starship.stasis.station.steam.stellarator.steppe.stheno.stork.stracciatella.strawberry.stream.strontium.strophe.strozzapreti.strut.stylus.stymphalian.styx.subspace.sumac.summit.sunbeam.sunstone.supernova.surge.surya.susanoo.sushi.svartalfheim.swallow.swan.swarm.sycamore.syleus.synchrotron.tabard.tachyon.tagliatelle.tahini.takoyaki.taliesin.tamari.tamarind.tangerine.tanka.tanker.tapenade.tapioca.tarako.taranis.tare.tarn.tarragon.tartarus.telamon.telemetry.teleporter.tellurium.temaki.tempura.tengu.tensor.tent.tequila.tercet.teriyaki.terminal.tern.terraform.tesseract.tethys.thalassa.thalia.thallium.thaumas.themis.theseus.thistle.thor.thorium.thoth.threshold.throne.throttle.thrush.thruster.thule.thunderbird.thyme.tiamat.tiara.tide.tint.tintagel.tiphys.tiramisu.tirnanog.tisane.tisiphone.titan.tobiko.toccata.toddy.toffee.tofu.tokamak.tomatillo.tomato.tome.tone.tonka.tonkatsu.tor.tortellini.torus.tourmaline.tower.trace.track.transducer.transistor.treacle.trellis.triolet.tristan.triton.trochee.trofie.trope.troubadour.trouvere.truffle.trunk.truss.tug.tulip.tundra.tungsten.turbine.turmeric.turquoise.turret.twinkle.typhon.tyr.udon.ulysses.unagi.uni.unicorn.uplink.uramaki.urania.uranium.urd.urfa.uther.vale.valhalla.valkyrie.valve.vanadium.vanaheim.vanilla.vapor.vareniki.varnish.varuna.vector.veil.vellum.vent.venus.verbena.verdandi.verge.verjus.vermouth.verse.vessel.vesta.vestige.vialone.viewport.villanelle.vishnu.vodka.volcano.volta.volume.vortex.vulcan.wall.walnut.waltz.warbler.warpgate.wasabi.wash.watercress.watermelon.wave.waypoint.web.weir.well.wendigo.wheat.whisky.whisper.wiglaf.willow.wimple.window.wisteria.wonder.wonton.woodcock.woodpecker.word.wormhole.wraith.wren.wyrm.wyvern.xenon.yacht.yakitori.yama.yarrow.yeti.yew.yggdrasil.yokai.yuzu.zaatar.zabaglione.zenith.zephyr.zeus.zinnia.zircon.zirconium.ziti.zone.zucchini`.split(`.`);I_.length*L_.length;const R_=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`discovery`,`upgrade`,`workflow`,`bash`,`jshd`,`preview`,`scoop-notify`,`scoop-idle`,`scoop-wait`,`sudo-request`]);function z_(e){return e!=null&&R_.has(e)}const B_=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]),V_=65536;function H_(e,t=V_){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${K_(t)} of ${K_(e.length)} — the agent received the full output]`}function U_(e,t=V_,n=4){if(typeof e==`string`)return H_(e,t);if(typeof e!=`object`||!e||n<=0)return e;if(Array.isArray(e)){let r=null;for(let i=0;i<e.length;i++){let a=U_(e[i],t,n-1);a!==e[i]&&(r??=[...e],r[i]=a)}return r??e}let r=null;for(let[i,a]of Object.entries(e)){let o=U_(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}function W_(e,t=V_){if(!e)return e;if(!mn().test(e))return H_(e,t);let n=H_(e.replace(mn(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function G_(e,t=V_){if(e.length<=t)return e;if(!mn().test(e))return H_(e,t);let n=[],r=0;for(let i of e.matchAll(mn()))n.push(H_(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(H_(e.slice(r),t)),n.join(``)}function K_(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}var q_=e({agentMessagesToChatMessages:()=>J_,lickChannelFromBody:()=>lv,lickChannelFromSenderName:()=>cv,lickIdFromBody:()=>uv,splitEnvelopes:()=>sv,unwrapMessageEnvelope:()=>ov});function J_(e,t={}){let{source:n=`cone`,idSeed:r=av,hiddenToolNames:i=B_,uncapped:a=!1}=t,o=[],s=null,c=new Set;for(let t of e)Q_(t)?(o.push(...Y_(t,r)),s=null):$_(t)?(s=X_(t,n,r,i,c,a),o.push(s)):ev(t)&&Z_(t,s,c,a);return o}function Y_(e,t){let n=tv(e.content);if(n.length===0)return[];let r=[];for(let i of sv(n)){if(i.body.length===0&&i.sender==null)continue;let n=(i.sender?cv(i.sender):null)??lv(i.body),a=n?uv(i.body):void 0,o={id:n===`sudo-request`&&a?`sudo-request-${a}`:t(),role:`user`,content:i.body,timestamp:e.timestamp};n&&(o.source=`lick`,o.channel=n,a&&(o.lickId=a)),r.push(o)}return r}function X_(e,t,n,r,i,a=!1){let o=[];for(let t of iv(e,a))r.has(t.name)?i.add(t.id):o.push(t);let s={id:n(),role:`assistant`,content:tv(e.content),timestamp:e.timestamp,source:t,model:e.model},{usage:c}=e;return c&&(s.usage={input:c.input,output:c.output,cacheRead:c.cacheRead,cacheWrite:c.cacheWrite,cost:{input:c.cost.input,output:c.cost.output,cacheRead:c.cost.cacheRead,cacheWrite:c.cost.cacheWrite,total:c.cost.total}}),o.length>0&&(s.toolCalls=o),s}function Z_(e,t,n,r=!1){if(n.has(e.toolCallId))return;let i=t?.toolCalls?.find(t=>t.id===e.toolCallId);if(!i)return;let a=tv(e.content);i.result=r?a:H_(a),i.isError=e.isError}function Q_(e){return e.role===`user`}function $_(e){return e.role===`assistant`}function ev(e){return e.role===`toolResult`}function tv(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)nv(n)&&t.push(n.text);return t.join(``)}function nv(e){return e.type===`text`}function rv(e){return e.type===`toolCall`}function iv(e,t=!1){if(!Array.isArray(e.content))return[];let n=[];for(let r of e.content)rv(r)&&n.push({id:r.id,name:r.name,input:t?r.arguments:U_(r.arguments)});return n}function av(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function ov(e){if(!e.startsWith(`[`))return null;let t=e.indexOf(`] `);if(t<=0||e.lastIndexOf(`
|
|
885
|
-
`,t)!==-1)return null;let n=e.slice(t+2);if(n.startsWith(`User: `))return{sender:`User`,body:n.slice(6)};for(let e of
|
|
884
|
+
`)}function C_(e){return e?.length?e.filter(e=>e.kind===`image`&&e.data).map(e=>({type:`image`,data:e.data,mimeType:e.mimeType})):[]}const w_=`sessions`;function T_(){return new Promise((e,t)=>{let n=indexedDB.open(`agent-sessions`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(w_)||e.createObjectStore(w_,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var E_=class{dbPromise=null;getDB(){return this.dbPromise||=T_().then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise}async save(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(w_,`readwrite`).objectStore(w_).put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(w_,`readonly`).objectStore(w_).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async delete(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(w_,`readwrite`).objectStore(w_).delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async loadAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(w_,`readonly`).objectStore(w_).getAll();r.onsuccess=()=>t(r.result??[]),r.onerror=()=>n(r.error)})}async list(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(w_,`readonly`).objectStore(w_).getAll();r.onsuccess=()=>{t((r.result??[]).map(e=>({id:e.id,updatedAt:e.updatedAt})))},r.onerror=()=>n(r.error)})}async clearAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(w_,`readwrite`).objectStore(w_).clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}static newId(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}static createSession(e,t){let n=Date.now();return{id:e,messages:[],config:t,createdAt:n,updatedAt:n}}static updateMessages(e,t){return{...e,messages:t,updatedAt:Date.now()}}},D_=class{resolve;providerId;now;#e=null;#t=null;#n=null;#r=null;constructor(e,t,n=Date.now){this.resolve=e,this.providerId=t,this.now=n}#i(e){return e===`ok`?6e4:e===`unsupported`?18e5:3e5}isStale(){let e=this.#e;return!e||this.#t!==this.providerId()||this.now()-e.at>=this.#i(e.outcome)}snapshot(){return this.#t===this.providerId()?this.#e?.window??null:null}async refresh(e={}){if(!e.force&&!this.isStale())return this.snapshot();let t=this.providerId();return this.#n!==null&&this.#r===t?this.#n:(this.#n=this.resolve().then(e=>{let n=e?{...e,at:this.now()}:null;return this.#a(t,n?`ok`:`unsupported`,n),n}).catch(()=>{let e=this.snapshot();return this.#a(t,`failed`,e),e}).finally(()=>{this.#r===t&&(this.#n=null,this.#r=null)}),this.#r=t,this.#n)}#a(e,t,n){e===this.providerId()&&(this.#t=e,this.#e={outcome:t,window:n,at:this.now()})}clear(){this.#e=null,this.#t=null}},O_=e({clearBudgetWindowCache:()=>P_,getBudgetWindowSnapshot:()=>M_,refreshBudgetWindow:()=>N_});async function k_(){let e=me();if(!e)return null;let t=se(e);if(!t?.getBudgetUsage)return null;let n=await t.getBudgetUsage();return n?{...n,providerId:e}:null}function A_(){try{return me()}catch{return``}}const j_=new D_(k_,A_);function M_(){return j_.snapshot()}function N_(e){return j_.refresh(e)}function P_(){j_.clear()}const F_=`abject.abortive.abrasive.absolute.abstruse.abundant.abyssal.accessible.acerbic.acrid.adamant.adept.adlerian.adornian.adroit.adventurous.aeolian.aerated.aesthetic.affable.aged.ageless.agile.airborne.airlocked.airy.akkadian.alabaster.alacritous.alert.alien.alloyed.allusive.aloof.alpha.alpine.alternate.altruistic.amaranthine.amber.ambidextrous.ambivalent.ambrosial.amiable.amorphous.ample.analog.analytical.ancestral.ancient.angelic.animated.animist.anomalous.antediluvian.antic.antlered.apollinairian.apollonian.apt.aquatic.arbitrary.arcadian.arcane.archaic.archimedean.ardent.arduous.arendtian.argent.argentine.argive.aristotelian.armstrongian.aromatic.arresting.artful.arthurian.articulate.artificial.artisanal.artless.ascetic.ashen.ashy.asimovian.aspiring.assiduous.assyrian.asteroidal.astral.astute.asynchronous.athenian.atlantean.atomic.attentive.attic.audacious.audenesque.augmented.august.augustan.aureate.auric.auroral.austenian.austere.austral.authentic.autonomous.autumnal.avalonian.avid.avuncular.aztec.azure.babbagean.babylonian.bacchic.bachian.bactrian.ballardian.ballistic.balmy.banksian.barefoot.barreled.barthesian.bartokian.bashy.baudelairean.bayesian.beatific.beckettesque.beckettian.beethovenian.beguiling.bellicose.bemused.benevolent.benign.benjaminian.bergmanesque.beta.bewitched.binary.bionic.bismarckian.bitter.bitwise.blackened.blakean.blameless.bland.blazar.blazing.blended.blessed.blissful.blistered.blithe.blooming.blunt.blustery.boeotian.boggy.bohrian.boingy.boisterous.bold.bolted.bombastic.bonny.boolean.boreal.borgesian.borgian.bosky.botticellian.bottled.bouncy.boundless.bountiful.bourbon.bradburyan.brahmsian.braised.brambly.brash.brave.brazen.bready.breathless.brechtian.breezy.briared.briery.bright.brilliant.brined.briny.brisk.bristling.briton.brittenesque.broadband.brontean.bronzed.brooding.browned.browningesque.brucknerian.brumal.brusque.bubbling.bubbly.bucolic.budding.bunuelian.buoyant.burnished.burnt.buttered.buttery.bygone.byronic.bytewise.byzantine.cacophonous.caesarean.callow.calm.candescent.candid.candied.canny.cantorian.capable.capricious.caramelized.caravaggesque.carbon.carefree.carolingian.cartesian.carved.casked.cast.cavafian.cavalier.celebrated.celestial.celtic.ceramic.cerebral.ceremonious.cerulean.cervantine.cezannesque.chagallian.chalky.chaplinesque.charcoal.charismatic.charmed.charming.charred.chaucerian.cheeky.cheerful.chekhovian.cherished.cherubic.chewy.chilled.chilly.chimerical.chipper.chirpy.chivalrous.chopinesque.chromospheric.chronal.chthonic.chubby.chunky.churchillian.cimmerian.cindered.circumspect.circumstellar.citrusy.civil.clandestine.clangy.clarified.clarkean.classic.clement.clever.cloaked.clockwork.clompy.cloned.cloudlike.cloudy.clunky.clustered.coastal.cobalt.cognitive.coherent.coleridgean.colossal.coltranesque.comely.cometary.compiled.complacent.composite.concurrent.conradian.constablean.convivial.copernican.copious.coplandesque.cordial.corinthian.corked.cornelian.coronal.cortical.cosmic.coy.cozy.cracked.crackling.crafty.cranky.crashy.creamy.credible.crepuscular.cretan.crimson.crisp.crispy.crowned.crumbly.crunchy.crushed.cryo.cryofrozen.cryogenic.cryonic.cryptic.crystalline.cuddly.cumulative.cunning.cupric.cured.curious.cursed.cursory.cushy.cybernetic.cyberpunk.cynical.cyprian.daliesque.dancy.dandy.dantean.dantesque.dapper.dappled.daring.dark.darwinian.dashing.dashy.dauntless.davisian.dawning.dazzling.deathless.debonair.deboned.debussyan.decanted.decompiled.decorous.decrypted.deep.deferential.deft.degasian.delectable.deleuzian.delian.deliberate.delicate.delirious.delphic.delta.demure.depressurized.derridean.destined.devout.dewy.dexterous.diaphanous.diced.dickensian.dickian.dickinsonian.didactic.dieselpunk.diffident.digital.dignified.diligent.dimensional.dinky.dionysian.discerning.discreet.disheveled.disparate.distant.distinct.distributed.diurnal.divine.dizzy.docile.docked.dogged.doomed.dorian.dormant.dostoevskian.dotty.doughty.doughy.downy.dozy.draconic.dreamful.dreamy.drifting.dripping.drizzly.droll.drowsy.druidic.dulcet.dun.dunky.durkheimian.dusky.dwarven.dynamic.dystopian.eager.earnest.earthy.eastward.easygoing.ebony.ebullient.eclectic.eclipsed.ecstatic.edenic.edwardian.effervescent.effulgent.effusive.einsteinian.elamite.elastic.elated.eldritch.electric.electronic.elegant.elegiac.elgarian.eliotian.eliotic.elizabethan.ellingtonian.eloquent.elusive.elven.elvish.elysian.embered.emergent.eminent.emphatic.emulsified.enchanted.encoded.encrypted.endearing.endless.endogenous.energetic.enhanced.enigmatic.enthralling.ephemeral.epic.epicurean.equanimous.errant.erudite.escherian.esoteric.esteemed.eternal.ethereal.ethiopian.etruscan.euclidean.eulerian.euphonious.euphoric.evanescent.evening.eventide.everlasting.evocative.exacting.exalted.exemplary.exo.exogenous.expansive.expressive.exquisite.extraterrestrial.extruded.exuberant.fabled.fabulous.facetious.faithful.fallow.fanciful.fantastic.faradayic.faraway.farmhouse.fastidious.fated.fateful.fathomless.faulknerian.faunal.fearless.feathered.feathery.fecund.federated.feisty.felicitous.felliniesque.fenny.fermented.ferny.ferrous.fervent.fervid.festive.fetching.fey.fickle.fierce.fiery.filleted.filtered.fitzgeraldian.fizzy.flaky.flamboyant.flamed.flashy.flawless.fleecy.fleet.fleeting.flexible.flickering.flinty.floral.florid.flouncy.flourishing.flowering.fluent.fluffy.fluid.fluvial.foamy.folded.fond.foraged.forged.formidable.forthright.fortuitous.forward.foucauldian.fourier.fractal.fragrant.frank.frankish.freckled.free.fresh.freudian.friedmanite.frisky.frizzy.frolicsome.frosted.frosty.frothy.frozen.frugal.fruiting.fruity.funky.furred.furtive.futuristic.fuzzy.gaelic.galactic.galbraithian.galilean.gallant.gallic.galvanic.gamesome.gamma.gandhian.garlanded.garrulous.gauguinesque.gaussian.gauzy.generous.genetic.genial.genomic.genteel.gentle.geomagnetic.georgian.gershwinesque.ghostly.giant.gibsonian.giddy.gifted.giga.giggly.gilded.giottesque.glacial.glad.glazed.gleaming.gleeful.glimmering.glistening.glorious.glossy.glowing.gnomish.godardian.godelian.goethean.goethesque.gogolian.golden.gooey.goofy.gorgeous.gorsy.gossamer.gothic.gowned.goyaesque.graceful.gracious.grainy.grand.grassy.grated.gravitic.gregarious.grilled.groovy.ground.grounded.guileless.gushy.gusty.habermasian.habsburg.hadrianic.halcyon.hale.hallowed.haloed.halved.hamiltonian.han.handelian.handmade.handsome.hanoverian.hapless.happy.hardy.hardyesque.harmonious.hashed.haunted.haydnesque.hayekian.hazy.heady.heaneyesque.hearthside.hearty.heathen.heathered.heavenly.hegelian.heideggerian.heinesque.heinleinian.heirloom.heisenbergian.heliacal.hellenic.hellish.hemingwayesque.herbal.herbertian.herculean.hermetic.heroic.hexed.hibernal.hilbertian.histrionic.hitchcockian.hittite.hoar.hoary.hobbesian.hobbitish.hogarthian.holderlinian.holo.holographic.holy.homerian.homeric.homeward.honest.honeyed.honky.hooded.hooved.hopeful.hopkinsian.hopperesque.hoppy.horatian.horned.hospitable.hot.housemade.huggy.humble.humean.humming.humorous.hunky.hunnish.hurrian.hushed.hydraulic.hyper.hyperborean.hypersonic.hyperspatial.hypnotic.iberian.ibsenite.iced.icy.ideal.idyllic.igneous.illustrious.imaginative.immaculate.immense.immortal.impassioned.impeccable.impetuous.impish.impressive.incan.incandescent.incisive.incorrigible.indefatigable.indelible.indigo.indolent.indomitable.industrious.ineffable.inexorable.infernal.infinite.infra.infrared.infused.ingenious.ingenuous.inimitable.innocuous.inquisitive.insatiable.inspired.intense.intergalactic.interstellar.intragalactic.intrepid.intricate.intrinsic.intuitive.inventive.inveterate.invincible.inward.ionian.ionic.ionospheric.irenic.iridescent.irrepressible.ithacan.itinerant.ivory.jacobean.jammy.jangly.jaunty.jazzy.jeffersonian.jiggly.jingly.jocular.jocund.johnsonian.jolly.jouncy.jovial.jovian.joycean.joyful.joyous.jubilant.judicious.juiced.juicy.jumped.jumpy.jungian.junky.justinianic.jute.kafkaesque.kandinskian.kantian.keatonesque.keatsian.keen.keplerian.keynesian.kierkegaardian.kindly.kindred.kinetic.kiplingesque.klimtian.knowing.kooky.kubrickian.kurosawan.lacanian.laconic.lacquered.lacustrine.lacy.lamarckian.lambda.lambent.laminated.landed.languid.lanky.laplacian.larkinesque.laser.latent.lathed.latin.lattice.laudable.launched.laureled.lavish.layered.leaden.leafy.lean.learned.legendary.leguinian.leibnizian.lemian.lemurian.lenient.leonardesque.liberal.libyan.lidar.light.lighthearted.likable.lilac.lilting.liminal.limpid.lincolnesque.lingering.linnaean.lissome.lisztian.literate.lithe.littoral.lively.loamy.local.lockean.lofty.logical.loopy.loose.loquacious.lorcaesque.lorcan.lossless.lossy.lovecraftian.lovelacean.loyal.lucent.lucid.lucky.ludic.lukewarm.luminal.luminous.lunar.luscious.lush.lushy.lusitanian.lustrous.lydian.lynchian.lyotardian.lyric.lyrical.macerated.machiavellian.macro.magical.magnanimous.magnetar.magnetic.magnetospheric.magnificent.magrittean.mahlerian.majestic.mallarmean.malleable.malthusian.malty.mandelan.manetesque.manifold.marbled.marshy.martial.martian.marvelous.marxian.maser.masked.masterful.matchless.matin.matissean.mature.matutinal.mauve.maverick.mawkish.maxwellian.mayan.meandering.mechanical.median.medicean.mega.mellifluous.mellow.melodic.mendelian.merciful.mercurial.merovingian.merry.meshed.meta.metamorphic.meteoric.meticulous.metternichian.mettlesome.michelangelesque.micro.microwave.midnight.mighty.mild.milled.miltonian.miltonic.minced.mindful.mineral.ming.mingusian.minoan.minty.miraculous.mired.miroesque.mirthful.mischievous.misty.mobile.modest.modular.molecular.molieresque.momentous.mondrianesque.monetian.monkish.mono.montane.moonless.moonlit.mordant.morning.mossy.motley.mottled.mouthwatering.mozartian.mughal.multiversal.munificent.murmuring.mushy.musical.mutable.mutant.mycenaean.mysterious.mystical.mythic.nabokovian.nameless.nano.nanoscale.napoleonic.narrowband.nascent.natty.neat.nebular.nebulous.nefarious.neptunian.nerudian.networked.neural.neutron.neutronic.newtonian.nietzschean.nifty.nimble.noble.nocturnal.nonchalant.nonpareil.noontide.norse.northward.nostalgic.notable.novel.nozickian.nuanced.nubian.nuclear.numinous.nutty.oaky.obdurate.oblique.observant.obstinate.obtuse.oceanic.ochre.odyssean.olden.olympian.omega.omni.onward.opaline.opportune.optical.optimistic.opulent.oracular.orbital.orbiting.orderly.original.ornate.orphic.orwellian.osirian.ostentatious.otherworldly.otiose.ottoman.outgoing.outspoken.outward.overcast.overclocked.ovidian.pacific.pagan.painstaking.palatial.pale.pallid.palpable.paradisal.paradoxical.parallel.paramount.parkerish.parsonian.parthian.passionate.pastoral.patched.pathless.patient.pavlovian.peaceable.peaceful.peachy.pearly.peaty.pebbly.peeled.peered.peerless.pelagic.pellucid.penetrating.pensive.peppered.peppery.peppy.perceptive.perennial.perfect.perfumed.perky.persian.persistent.perspicacious.persuasive.pert.pervasive.pessoan.petaled.petrarchan.phantom.pharaonic.phased.philosophical.phlegmatic.phoenician.photonic.photospheric.phrygian.picassoesque.pickled.pictish.picturesque.pillowy.pindaric.pinteresque.piping.piquant.pirandellian.pithy.pivotal.pixelated.placid.planckian.planetary.planetoid.plangent.plasmic.plathian.platinum.platonic.playful.pleasant.plentiful.pliant.plinky.plonky.plucky.plumed.plummy.plush.plushy.plutonian.plutonic.pneumatic.poached.poesque.poetic.poignant.poised.polished.polite.pollockian.poly.polygonal.polymer.polynesian.popean.popped.popular.portly.posh.positronic.posthuman.potent.pouncy.powdery.powerful.pragmatic.prancy.precise.precocious.precognitive.preeminent.premier.prescient.pressed.pressurized.prestigious.pretty.primeval.primordial.princely.printed.pristine.private.prized.prodigious.profane.proficient.profound.profuse.prokofievian.prolific.promethean.prompt.proper.prophetic.prosaic.prosperous.protean.proto.protostellar.proud.proustian.providential.prudent.psionic.puccinian.puckish.pudgy.puffed.pulled.pulsar.punctilious.punctual.pungent.punic.pure.purposeful.pushkinian.pynchonesque.pythagorean.quaint.quantum.quartered.quasar.questing.quick.quiescent.quiet.quintessential.quirky.quixotic.rabelaisian.racinian.radar.radiant.radio.rainwashed.rainy.rakish.rambunctious.raphaelesque.rapid.rapturous.rare.rational.ravelian.rawlsian.raytraced.ready.reasonable.rebooted.receptive.recondite.recursive.redolent.reduced.reedy.refined.reflective.refulgent.regal.relativistic.relaxed.reliable.remarkable.rembrandtesque.remote.rendered.renoiresque.renowned.replete.replicated.resilient.resinous.resolute.resourceful.respectful.resplendent.responsive.restful.restive.restless.reticent.retro.reverent.rhapsodic.rhodian.rhythmic.ricardian.rich.richelieuvian.riemannian.rigorous.rilkean.rimbaudian.rimed.ringed.ripe.ripening.rippling.risible.riverine.riveted.roaming.roaring.roasted.robed.robotic.robust.rolled.roly.roman.romanov.romantic.rompy.rooseveltian.roseate.rosy.rothkoesque.rousing.rousseauian.rowdy.royal.rubenesque.ruddy.runic.rushy.russet.rustic.sabine.sable.sacred.sagacious.sage.saintly.salient.saline.salingeresque.salted.salty.salubrious.samian.sandaled.sandy.sanguine.sapid.sapient.sapphic.sardonic.sarmatian.sartrean.sassy.satiny.saturnian.saturnine.saucy.savory.savvy.saxon.scalding.scarlet.schielesque.schillerian.schoenbergian.scholarly.schubertian.schumannesque.schumpeterian.scintillating.scorched.scorsesean.scrappy.scruffy.scrupulous.scythian.seaborne.seamless.seared.seasonal.seaward.secure.sedate.sedgy.sedimentary.sedulous.seemly.seismic.selenic.selfless.sensible.sensitive.sentient.sentimental.seraphic.sere.serene.seuratian.shaded.shadowed.shadowy.shaggy.shaken.shakespearean.shamanic.shannonian.sharded.sharp.shaved.shavian.shelleyan.shielded.shimmering.shiny.shoreless.shostakovian.shrewd.shucked.sibelian.sibilant.sibylline.sicilian.sidereal.sienna.sifted.sigma.silicon.silken.silky.silly.silty.silver.silvered.simmering.simulated.sincere.singed.singing.singular.sinuous.sisyphean.sizzling.skeptical.skillful.skinnerian.skittish.skyward.sleek.sleepless.sleepy.slender.sliced.slick.slipstreamed.slow.sly.smart.smashy.smithian.smoked.smoky.smoldering.smooth.snappy.snazzy.snoozy.snowy.snug.snuggly.soaring.sociable.socratic.sodden.soft.sogdian.solar.solarpunk.solemn.solid.somnolent.sonar.song.sonic.sonorous.sooty.soporific.soulful.sound.soundless.sour.southward.sovereign.spaceborne.spacefaring.spacious.sparkling.sparkly.spartan.special.speckled.spectacular.spectral.speedy.spellbound.spiced.spicy.spielbergian.spiffy.spinozan.spirited.splashy.splendid.split.sploshy.spontaneous.spooky.sporty.spotless.spotted.sprightly.sproingy.spry.spun.spunky.squally.squashy.squelchy.squiggly.squishy.staid.stainless.stalwart.starborn.starfaring.starless.starlit.stasisbound.stately.steadfast.steady.steaming.steampunk.steely.steeped.steinbeckian.stellar.stellarborn.sticky.stirred.stirring.stoic.stoical.stolid.stompy.stoppardian.storied.stormy.stout.strained.stratospheric.straussian.stravinskian.streaky.stretched.striking.strindbergian.striped.strong.stuart.stubby.studious.stunning.sturdy.stygian.suave.subatomic.sublime.suborbital.subsonic.substantial.subtle.succinct.succulent.sudsy.sugared.sugary.sumerian.summery.sunless.sunlit.sunny.sunward.superb.supergalactic.superlative.superluminal.supersonic.supple.supreme.sure.surreptitious.svelte.swanky.sweeping.sweet.swift.swiftian.swirled.swooshy.sylvan.sympathetic.synaptic.synchronous.synthetic.syrupy.tableside.tachyonic.taciturn.talented.talleyrandian.tame.tang.tangy.tarantinoesque.tarkovskian.tart.tasteful.tattered.taut.tawny.tectonic.telekinetic.telepathic.temperate.tempered.temporal.tenacious.tender.tennysonian.tenuous.tepid.tera.terran.terrific.terse.textured.thackerayan.thankful.thawed.theban.thessalian.theta.thorny.thorough.thoughtful.thracian.threadbare.thriving.thundery.tidal.tidy.timeless.timely.timeworn.tinkly.tiny.tipsy.tireless.titanesque.titanian.titanic.titanium.titianesque.toasted.toasty.tocharian.tokenized.tolerant.tolkienesque.tolstoyan.tonic.tonky.toothsome.torched.totemic.tough.towering.trackless.tranquil.transcendent.transhuman.treacly.treasured.tremendous.tremulous.trenchant.tricky.trim.triumphant.trojan.trollopian.truculent.true.truffautian.truffled.trusty.truthful.tudor.turbo.turingian.turneresque.twangy.twilight.twilit.twinkling.twinkly.ubiquitous.ultra.ultrasonic.ultraviolet.umami.umber.unassuming.unbounded.uncanny.uncorked.unctuous.undaunted.underworldly.undocked.undying.unearthly.unerring.unflappable.unique.unknown.unruffled.upbeat.upgraded.upright.upstanding.upward.uranian.urbane.utopian.vacuous.valeryan.valiant.valorous.vandal.vangoghian.vast.veblenian.vectorized.vedic.vehement.veiled.velazquezian.velvet.velvety.venerable.venturous.venusian.veracious.verbose.verdant.verdian.verdurous.verlainian.vermeerian.vermilion.vernal.verneian.versatile.vesper.vespertine.vibrant.victorian.vigilant.vigorous.vintage.violet.virgilian.virtual.virtuous.visceral.vital.vivacious.vivid.vocal.voidborn.voidward.volcanic.voltairean.voluble.vonnegutian.voracious.voxel.vroomy.wacky.wagnerian.wakeful.waking.wan.wandering.warholian.warm.warped.wary.washingtonian.wayward.wealthy.weathered.weberian.welcome.welded.wellesian.wellsian.westward.whacky.whimsical.whimsy.whipped.whisked.whispering.whistlerian.whitmanesque.whole.wholesome.whooshy.wide.wiggly.wild.wildean.willowy.wilsonian.wily.windswept.windy.winged.winning.winsome.wintry.wired.wireframe.wireless.wise.wishful.wispy.wistful.wittgensteinian.witty.wobbly.wodehousian.wondrous.wonky.wooded.woody.woolly.woozy.wordless.wordsworthian.wormholed.worthy.wraithlike.wreathed.wriggly.wry.xenial.xeno.yanky.yearning.yeasty.yeatsian.young.youthful.yuletide.yummy.zany.zappy.zealous.zested.zestful.zesty.zeta.zingy.zippy.zodiacal.zonked.zonky.zoomy.zoroastrian`.split(`.`),I_=`abalone.absinthe.absyrtus.accelerator.achilles.acorn.acquerello.actuator.adobo.adonis.aeetes.aegis.aello.aeneas.aengus.aether.affogato.afterburner.agartha.agate.agni.agnolotti.aioli.airlock.ajax.aji.albatross.alder.ale.alecto.aleppo.alfheim.allegory.alliteration.almond.amaranth.amaretto.amaterasu.ambrosia.americano.amphiaraus.anago.anapest.ancho.anchovy.android.andromeda.anise.annal.annwn.ansible.antaeus.antenna.anthem.antigone.antimony.antistrophe.anubis.aoidos.aperol.aphelion.aphrodite.apogee.apollo.apple.apricot.aquamarine.aquavit.aqueduct.arabica.arachne.arawn.arbor.arborio.arc.arcadia.arch.archipelago.ares.argo.argon.argonaut.aria.ariadne.ark.arke.armagnac.array.arrow.artemis.arthur.artichoke.artifact.arugula.asgard.asgardia.ash.asparagus.aspen.assam.assonance.asteroid.astronaut.atalanta.athena.atlantis.atlas.atoll.atom.atropos.aubergine.augean.aura.aurora.avalon.avalonia.avocado.awning.axion.axle.azurite.bacchus.bagna.baharat.balder.ballad.balladeer.banana.banshee.baozi.bard.barge.barium.barley.barn.basalt.basil.basilisk.basmati.bastet.bastion.bay.bayleaf.beacon.beam.bean.bearing.beech.beetroot.behemoth.bellini.beowulf.bergamot.berth.beryl.beryllium.bifrost.biodome.birch.biscotti.bismuth.bisque.bit.bittern.blackberry.blast.blaster.blini.block.blodeuwedd.bloodstone.blossom.bluebell.blueberry.bolt.bomba.bonito.boom.borage.boson.botargo.bottarga.bouillon.boundary.bow.bower.bragi.bramble.bran.branch.brandy.branwen.breeze.brew.bridge.brigid.brioche.broccoli.brook.brulee.brunhild.brush.bucatini.buckler.buckwheat.buffer.bulkhead.bunting.burrata.burst.bus.busiris.butte.butter.buttercup.butterscotch.byte.cabbage.cabin.cacao.cachaca.cache.cacus.cadence.caesura.calamarata.calamari.calcite.caldera.calliope.calvados.calypso.cam.camellia.camelot.camembert.campari.canal.cannelloni.cannoli.canopy.cantaloupe.cantata.canticle.canvas.canyon.canzone.capacitor.capellini.caper.capon.cappelletti.cappuccino.capsule.caramel.cardamom.cardoon.carillon.carnaroli.carnation.carol.carrier.carrot.cascade.cashew.cassandra.cassis.castle.castor.cavatelli.caviar.cayenne.cedar.celaeno.celeriac.cell.centaur.cerberi.cerberus.cernunnos.ceryneian.cesium.ceto.ceylon.chaff.chaffinch.chai.chain.chalk.chamomile.champagne.chandra.channel.chanson.chanterelle.chard.charon.chartreuse.cheddar.cherry.chert.chervil.chestnut.chickweed.chicory.chili.chime.chimera.chimichurri.chimney.chip.chipotle.chirashi.chiron.chive.chocolate.chorale.chorizo.chorus.chronicle.chrysanthemum.chrysaor.chrysomallus.chutney.ciabatta.cibola.cider.cilantro.cinder.cinnamon.cipher.circe.circlet.circuit.cirque.cistern.citadel.citrine.citron.clementine.cliff.clio.clipper.cloak.clotho.cloud.clove.clover.cluster.coal.cobbler.cockaigne.cockpit.cocoa.coconut.codex.coffee.cog.cognac.coif.coil.col.colchis.collider.colony.combe.comet.compote.concerto.conchiglie.conduit.confit.console.consomme.consonance.continuum.contour.cookies.coordinate.core.coriander.cormorant.corona.coronet.cortado.corvette.cosmos.cottage.couplet.course.couscous.cove.cowl.cowslip.crab.craft.crag.cranberry.crane.crayon.cream.creme.crepe.cress.crocus.croissant.crosne.crown.cruiser.crumble.cryopod.cryosleep.crystal.cuchulainn.cuckoo.cucumber.cuirass.cumin.cupid.curlew.currant.current.curry.custard.cyborg.cycle.cyclops.cyclotron.cylinder.dactyl.daedalus.daemon.daffodil.dagda.dahlia.daiquiri.dais.daisy.dale.dam.dandelion.danu.daphne.darjeeling.dart.dashi.date.dawn.daydream.deck.deirdre.demeter.destroyer.dew.diadem.diary.dill.dimension.diode.diomedean.dionysus.ditalini.ditch.djinn.dock.doenjang.domain.donburi.donjon.door.doppio.dove.downlink.dreadnought.dream.drift.droid.dryad.dukkah.dulce.dumpling.dune.durga.dusk.dust.dyke.eagle.earlgrey.easel.echidna.echo.eclair.eclipse.ecliptic.edamame.eddy.edelweiss.edge.egret.einsteinium.elderflower.eldorado.electra.elegy.elm.elysium.ember.endive.enigma.enjambment.enkidu.envoi.eos.epigram.epistle.epode.erato.erinyes.eros.erymanthian.escargot.espresso.estuary.eumenides.euryale.eurybia.eurydice.eurytion.excalibur.exoplanet.fable.fafnir.falcon.fancy.farfalle.fate.feather.feldspar.fell.fence.fennel.fenrir.fenugreek.fermion.fern.fettuccine.fiddlehead.field.fig.finch.finn.fionn.firebird.firefly.fission.fizz.fjord.flake.flame.flare.flash.flicker.flint.flue.fluorite.flux.flywheel.focaccia.fog.folio.fondant.forge.fortress.foxglove.fragment.fraise.frame.frangipane.frappe.freesia.fregola.freighter.freya.frigate.frigg.frost.fudge.fugue.fumarole.furies.fusilli.fusion.gaia.galahad.galangal.galatea.galaxy.galette.galleon.gallium.ganache.ganesh.gannet.gantry.ganymede.garam.gardenia.garlic.garuda.gateway.gauntlet.gawain.gazebo.gear.gelato.gemelli.genmaicha.genoise.geranium.germ.germanium.geryon.geyser.ghazal.ghee.ghost.gilgamesh.ginger.gingko.ginnungagap.girder.glacier.glade.glaze.gleam.gleeman.glen.glimmer.glint.glitter.gloss.glow.gluon.gnocchi.gochujang.goldfinch.golem.goose.gooseberry.gorgon.gouda.governor.gradient.graeae.granary.granite.grapefruit.grappa.gratin.graviton.greave.grebe.gremolata.grenadine.grendel.grid.griffin.gruyere.guajillo.guava.gudrun.guinevere.gunkan.gwydion.gyoza.gyroscope.habanero.habitat.hades.hadron.haiku.hall.halloumi.halo.halva.hamachi.hangar.hanuman.harissa.harpies.harpy.harvest.hatch.hauberk.hawthorn.haze.hazel.hazelnut.heading.headland.heap.heart.hearth.heather.hecate.hedge.heimdall.hel.helheim.helios.helium.helix.helle.hellebore.helm.hemistich.hephaestus.hera.hermes.heron.hesperides.hestia.hibiscus.hippogriff.hirame.hive.hoisin.hojicha.hollandaise.hollow.holly.hologram.honey.honeycomb.honeysuckle.hood.hoopoe.horizon.horseradish.horus.hrothgar.hub.huckleberry.hue.huginn.hull.husk.hut.hyacinth.hydra.hydras.hylas.hymn.hyperborea.hypercube.hyperdrive.hyperion.hyperspace.hyssop.iamb.ibis.icarus.idas.idunn.idyll.igniter.igraine.ikura.indium.indra.inductor.infusion.injector.ink.inlet.inspiration.ion.iridium.iris.ishtar.isis.isolde.isotope.ivy.iwashi.izanagi.jackdaw.jackfruit.jalapeno.janus.jasmine.jason.jasper.javelin.jay.jet.jiaozi.jongleur.jonquil.jormungandr.jotunheim.journal.julep.jumpgate.juniper.juno.jupiter.kaffir.kale.kali.kampachi.karaage.karasumi.katsu.keel.keep.kefir.kelpie.kenning.kernel.kestrel.khinkali.kiln.kimchi.kingfisher.kinmedai.kirsch.kite.kitsune.kiwi.koan.kohlrabi.kombucha.koshihikari.kraken.krypton.kumquat.kvass.lachesis.lacquer.ladon.ladons.laertes.lager.lagoon.lake.lakshmi.lambic.lament.lance.lancelot.lander.lane.langoustine.lantern.lapis.lark.larkspur.lasagna.latte.laureate.laurel.lava.lavender.leaf.leda.leek.legend.lemon.lemonbalm.lemongrass.lemuria.lens.lentil.lepton.lernaean.lethe.letter.levee.lever.leviathan.lightyear.lily.lime.limerick.limoncello.linden.linguine.link.linnet.lir.lithium.lityerses.lobster.loch.lock.lodge.loki.loop.loquat.lotus.lovage.lugh.lullaby.lungo.luster.lychee.lynceus.lyonesse.lyricist.macadamia.macaron.macchiato.madai.madeleine.madrigal.magma.magnolia.magpie.mail.mainframe.maki.makrut.malachite.manannan.mango.manicotti.manor.manti.manticore.mantle.mantou.manuscript.maple.marble.marduk.margarita.marigold.marjoram.marquee.marrow.martini.marvel.marzipan.masago.masala.mascarpone.mast.matcha.matrix.mead.meadow.mech.medea.medusa.megaera.meleager.memoir.mentaiko.mercury.meringue.merlin.merlot.mesa.mesh.metaphor.meteor.meter.mezcal.mezzaluna.mica.midas.midgard.mill.mimir.mimosa.minerva.minotaur.minstrel.mint.minuet.miracle.mirin.mirror.miso.missive.mist.mjolnir.mocha.module.moira.mojito.molasses.mole.momo.monolith.moonbase.moonbeam.moonstone.moor.mopsus.mordred.morel.morgana.morpheus.morrigan.moss.mote.motet.mousse.mu.mulberry.muninn.muon.muse.muspelheim.mustard.myrtle.mystery.myth.nadir.naga.naiad.nanite.nanobot.narcissus.neapolitan.nebula.nectarine.needle.negroni.nemean.nemesis.neon.neptune.neptunium.nereid.nereus.nessus.nest.nestor.net.nettle.neutrino.nexus.niamh.nib.nibble.nibiru.niflheim.nightingale.nigiri.nike.niobe.njord.nocturne.node.nog.nori.norn.note.nougat.nova.nozzle.nuada.nutmeg.nyx.oak.oasis.oat.obelisk.oberon.obsidian.oceanid.oceanus.octave.octavo.ocypete.ode.odin.odysseus.oisin.okonomiyaki.olive.olympus.oni.onigiri.oolong.oracle.orange.orb.orbit.orbiter.orchard.orchid.oreads.orecchiette.oregano.orion.orpheus.orthros.orthrus.orzo.oscillator.osiris.osmium.osprey.ouroboros.outline.outpost.ouzo.oven.overture.owl.oyster.paccheri.packet.padron.page.palace.palette.palladium.palm.pan.pandan.pandora.panettone.pansotti.pansy.pantoum.papaya.pappardelle.paprika.papyrus.parable.paradox.parcae.parchment.parfait.parmesan.parsec.parsley.parsnip.particle.partridge.parvati.pasilla.passionfruit.pastel.pastis.patina.pavilion.pavlova.peach.peak.pear.pebble.pecan.pegasi.pegasus.pekoe.peleus.pelican.pelmeni.pen.pencil.penelope.penne.peony.pepper.peppermint.percival.peregrine.pergola.peridot.perigee.perihelion.perry.persephone.perseus.persillade.persimmon.pesto.petal.petrel.phase.pheasant.phoenix.pholus.phorcys.photon.phrixus.pickle.pierogi.pigment.pimento.pine.pineapple.ping.pinot.pipe.pipit.piquillo.pisco.pistachio.piston.pith.plane.plasma.plate.plover.plum.plume.pluto.plutonium.poblano.pod.podarge.poet.polenta.pollux.polyphemus.pomegranate.pomelo.pond.pontus.ponzu.pooka.pool.poplar.poppy.porcini.port.portal.porter.porthole.poseidon.positron.prairie.praline.prelude.primrose.prism.probe.profile.prometheus.prosciutto.prosecco.proteus.protocol.psalm.psyche.pudding.puffin.pulse.pumice.pumpkin.purslane.pwyll.pylon.pyrrhic.quadrant.quail.quark.quarto.quartz.quatrain.qubit.quetzalcoatl.queue.quill.quince.quinoa.quiver.radish.radium.radon.ragnarok.rain.rama.ramen.ramp.rampart.ramson.raspberry.ratatoskr.raven.ravioli.ray.reactor.realm.reaper.reed.reef.refrain.region.register.relay.relic.remnant.requiem.reservoir.residue.resistor.resonator.reverie.rhapsode.rhapsody.rhea.rhiannon.rhodium.rhododendron.rhubarb.rhyme.ricotta.riddle.ridge.riesling.rigatoni.rim.ring.risotto.ristretto.river.roast.robin.robusta.roc.rocket.rod.romesco.rondeau.rooibos.rook.root.rose.rosemary.rosewater.roundel.rover.rowan.rubidium.rum.rune.saba.saffron.saga.saison.sake.salmoriglio.salsa.salsify.sambal.sambuca.samphire.sancerre.sandpiper.sangria.sanma.sansho.saraswati.sashimi.sasquatch.satellite.satyr.sauternes.savanna.sawara.sazerac.scaffold.scalar.scallop.scansion.scepter.schnapps.schooner.scop.scorzonera.scotchbonnet.scroll.sector.seed.sekhmet.selene.selenite.selenium.selkie.sencha.sensor.sequoia.serenade.serrano.servo.sesame.sestina.sextet.shack.shade.shadow.shaft.shale.shallot.shambhala.shard.shed.sheen.sherbet.sherry.shield.shimmer.ship.shishito.shiso.shiva.shoyu.shrub.shumai.shuttle.sibyl.sif.signal.sigurd.silhouette.silo.simile.simurgh.singularity.siren.sita.skadi.skald.skiff.skuld.skylark.slant.slate.sleipnir.sling.slipstream.sliver.sloop.sluice.smithy.smoke.snowdrop.socket.sofrito.sonata.sonnet.soot.sorbet.sorrel.souffle.soul.soy.spaceport.spaghetti.spark.sparkle.sparrow.spear.speck.specter.speculoos.spelt.sphere.sphinx.sphinxes.spindle.spinel.spiral.spire.spirit.splinter.spoke.spondee.spore.spring.spritz.spruce.sriracha.ssamjang.stack.stanza.starbase.starlight.starling.starport.starship.stasis.station.steam.stellarator.steppe.stheno.stork.stracciatella.strawberry.stream.strontium.strophe.strozzapreti.strut.stylus.stymphalian.styx.subspace.sumac.summit.sunbeam.sunstone.supernova.surge.surya.susanoo.sushi.svartalfheim.swallow.swan.swarm.sycamore.syleus.synchrotron.tabard.tachyon.tagliatelle.tahini.takoyaki.taliesin.tamari.tamarind.tangerine.tanka.tanker.tapenade.tapioca.tarako.taranis.tare.tarn.tarragon.tartarus.telamon.telemetry.teleporter.tellurium.temaki.tempura.tengu.tensor.tent.tequila.tercet.teriyaki.terminal.tern.terraform.tesseract.tethys.thalassa.thalia.thallium.thaumas.themis.theseus.thistle.thor.thorium.thoth.threshold.throne.throttle.thrush.thruster.thule.thunderbird.thyme.tiamat.tiara.tide.tint.tintagel.tiphys.tiramisu.tirnanog.tisane.tisiphone.titan.tobiko.toccata.toddy.toffee.tofu.tokamak.tomatillo.tomato.tome.tone.tonka.tonkatsu.tor.tortellini.torus.tourmaline.tower.trace.track.transducer.transistor.treacle.trellis.triolet.tristan.triton.trochee.trofie.trope.troubadour.trouvere.truffle.trunk.truss.tug.tulip.tundra.tungsten.turbine.turmeric.turquoise.turret.twinkle.typhon.tyr.udon.ulysses.unagi.uni.unicorn.uplink.uramaki.urania.uranium.urd.urfa.uther.vale.valhalla.valkyrie.valve.vanadium.vanaheim.vanilla.vapor.vareniki.varnish.varuna.vector.veil.vellum.vent.venus.verbena.verdandi.verge.verjus.vermouth.verse.vessel.vesta.vestige.vialone.viewport.villanelle.vishnu.vodka.volcano.volta.volume.vortex.vulcan.wall.walnut.waltz.warbler.warpgate.wasabi.wash.watercress.watermelon.wave.waypoint.web.weir.well.wendigo.wheat.whisky.whisper.wiglaf.willow.wimple.window.wisteria.wonder.wonton.woodcock.woodpecker.word.wormhole.wraith.wren.wyrm.wyvern.xenon.yacht.yakitori.yama.yarrow.yeti.yew.yggdrasil.yokai.yuzu.zaatar.zabaglione.zenith.zephyr.zeus.zinnia.zircon.zirconium.ziti.zone.zucchini`.split(`.`);F_.length*I_.length;const L_=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`discovery`,`upgrade`,`workflow`,`bash`,`jshd`,`preview`,`scoop-notify`,`scoop-idle`,`scoop-wait`,`sudo-request`]);function R_(e){return e!=null&&L_.has(e)}const z_=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]),B_=65536;function V_(e,t=B_){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${G_(t)} of ${G_(e.length)} — the agent received the full output]`}function H_(e,t=B_,n=4){if(typeof e==`string`)return V_(e,t);if(typeof e!=`object`||!e||n<=0)return e;if(Array.isArray(e)){let r=null;for(let i=0;i<e.length;i++){let a=H_(e[i],t,n-1);a!==e[i]&&(r??=[...e],r[i]=a)}return r??e}let r=null;for(let[i,a]of Object.entries(e)){let o=H_(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}function U_(e,t=B_){if(!e)return e;if(!mn().test(e))return V_(e,t);let n=V_(e.replace(mn(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function W_(e,t=B_){if(e.length<=t)return e;if(!mn().test(e))return V_(e,t);let n=[],r=0;for(let i of e.matchAll(mn()))n.push(V_(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(V_(e.slice(r),t)),n.join(``)}function G_(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}var K_=e({agentMessagesToChatMessages:()=>q_,lickChannelFromBody:()=>cv,lickChannelFromSenderName:()=>sv,lickIdFromBody:()=>lv,splitEnvelopes:()=>ov,unwrapMessageEnvelope:()=>av});function q_(e,t={}){let{source:n=`cone`,idSeed:r=iv,hiddenToolNames:i=z_,uncapped:a=!1}=t,o=[],s=null,c=new Set;for(let t of e)Z_(t)?(o.push(...J_(t,r)),s=null):Q_(t)?(s=Y_(t,n,r,i,c,a),o.push(s)):$_(t)&&X_(t,s,c,a);return o}function J_(e,t){let n=ev(e.content);if(n.length===0)return[];let r=[];for(let i of ov(n)){if(i.body.length===0&&i.sender==null)continue;let n=(i.sender?sv(i.sender):null)??cv(i.body),a=n?lv(i.body):void 0,o={id:n===`sudo-request`&&a?`sudo-request-${a}`:t(),role:`user`,content:i.body,timestamp:e.timestamp};n&&(o.source=`lick`,o.channel=n,a&&(o.lickId=a)),r.push(o)}return r}function Y_(e,t,n,r,i,a=!1){let o=[];for(let t of rv(e,a))r.has(t.name)?i.add(t.id):o.push(t);let s={id:n(),role:`assistant`,content:ev(e.content),timestamp:e.timestamp,source:t,model:e.model},{usage:c}=e;return c&&(s.usage={input:c.input,output:c.output,cacheRead:c.cacheRead,cacheWrite:c.cacheWrite,cost:{input:c.cost.input,output:c.cost.output,cacheRead:c.cost.cacheRead,cacheWrite:c.cost.cacheWrite,total:c.cost.total}}),o.length>0&&(s.toolCalls=o),s}function X_(e,t,n,r=!1){if(n.has(e.toolCallId))return;let i=t?.toolCalls?.find(t=>t.id===e.toolCallId);if(!i)return;let a=ev(e.content);i.result=r?a:V_(a),i.isError=e.isError}function Z_(e){return e.role===`user`}function Q_(e){return e.role===`assistant`}function $_(e){return e.role===`toolResult`}function ev(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)tv(n)&&t.push(n.text);return t.join(``)}function tv(e){return e.type===`text`}function nv(e){return e.type===`toolCall`}function rv(e,t=!1){if(!Array.isArray(e.content))return[];let n=[];for(let r of e.content)nv(r)&&n.push({id:r.id,name:r.name,input:t?r.arguments:H_(r.arguments)});return n}function iv(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function av(e){if(!e.startsWith(`[`))return null;let t=e.indexOf(`] `);if(t<=0||e.lastIndexOf(`
|
|
885
|
+
`,t)!==-1)return null;let n=e.slice(t+2);if(n.startsWith(`User: `))return{sender:`User`,body:n.slice(6)};for(let e of L_){let t=`${e}:`;if(!n.startsWith(t))continue;let r=n.indexOf(`
|
|
886
886
|
`),i=r===-1?n.length:r,a=n.slice(0,i),o=-1,s=a.indexOf(`[`,t.length);if(s>t.length&&(o=a.lastIndexOf(`: `,s)),o<t.length&&(o=n.indexOf(`: `,t.length)),!(o<0||o>=i))return{sender:n.slice(0,o),body:n.slice(o+2)}}let r=n.indexOf(`
|
|
887
887
|
`),i=r===-1?n.length:r,a=n.indexOf(`: `);if(a<=0||a>=i)return null;let o=n.slice(0,a);return o.includes(`
|
|
888
|
-
`)?null:{sender:o,body:n.slice(a+2)}}function
|
|
888
|
+
`)?null:{sender:o,body:n.slice(a+2)}}function ov(e){if(e.length===0)return[];let t=e.split(`
|
|
889
889
|
`);if(!t[0].startsWith(`[`))return[{sender:null,body:e}];let n=[],r=null,i=()=>{if(!r)return;let e=r.rest.length>0?`${r.firstLine}\n${r.rest.join(`
|
|
890
|
-
`)}`:r.firstLine,t=
|
|
891
|
-
`),De())}function fv(e,t){e.push(`## ${t.role}`,``);let n=t.content.trim();n.length>0&&e.push(n,``);for(let n of t.toolCalls??[])pv(e,n)}function pv(e,t){e.push(`### tool: ${t.name}`,``,`Input:`,``,"```json",mv(t.input),"```",``),t.result!==void 0&&e.push(t.isError?`Result (error):`:`Result:`,``,"```",t.result,"```",``)}function mv(e){try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}const hv=y(`agent-bridge`),gv=`__slicc_agent`;function _v(e){for(let t=0;t<8;t++){let t=e.generateName(),n=`agent_${Vv(t)}`;if(!e.orchestrator.getScoops().some(e=>e.jid===n))return t}return e.generateUid()}function vv(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=An(n);if(!r||r.length===0)return null;let i=Fn(n);return i?{modelId:r,providerId:i}:{modelId:r}}function yv(e,t){let n=e.getWorkUnits(),r=(t===null?null:n.rootOf(t))??n.resolveDefaultRoot();return $n(r?.descriptor.workspace??Qn)}function bv(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=Pn(n).level;return r&&rr(r)?r:null}function xv(e,t){let n=e.modelId,r,i;if(n!==void 0){let a=e.modelProviderId!==void 0&&n!==``?`${e.modelProviderId}:${n}`:n,o=a===``?{ok:!1,error:`unknown model: ${n}`}:t(a);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};r=o.selection.modelId,i=o.selection.providerId}let a=e.thinkingLevel;if(a!==void 0&&!rr(a))return{error:{finalText:`agent: invalid thinking level: ${String(a)} (one of: ${ir.join(`, `)})`,exitCode:1}};let o=Sn(e.workspaceMode);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};let s=e.backgroundAfterSeconds;if(s!==void 0&&(typeof s!=`number`||!Number.isFinite(s)||s<0))return{error:{finalText:`agent: invalid backgroundAfterSeconds: ${String(s)} (seconds >= 0)`,exitCode:1}};let c=Sv(e);if(c)return c;let l=e.name;if(l!==void 0&&!Ov(l))return{error:{finalText:`agent: invalid name: ${l} (lowercase tokens joined by single dashes)`,exitCode:1}};for(let[t,n]of[[`maxTurns`,e.maxTurns],[`maxWallClockMs`,e.maxWallClockMs]])if(n!==void 0&&(!Number.isInteger(n)||n<=0))return{error:{finalText:`agent: ${t} must be a positive integer: ${String(n)}`,exitCode:1}};return{resolvedModelId:r,resolvedProviderId:i}}function Sv(e){let t=e.mergeOnSuccess,n=[[`successReceiptPath`,e.successReceiptPath],[`outcomeReceiptPath`,e.outcomeReceiptPath],[`mergeOnSuccess.targetPath`,t?.targetPath],[`mergeOnSuccess.basePath`,t?.basePath],[`mergeOnSuccess.draftPath`,t?.draftPath]],r=t===void 0?void 0:``;for(let[e,t]of n){let n=t??(e.startsWith(`mergeOnSuccess`)?r:void 0);if(n!==void 0&&!n.startsWith(`/`))return{error:{finalText:`agent: ${e} must be absolute: ${String(t)}`,exitCode:1}}}return null}function Cv(e){return/^agent run terminated: .*\bbound\b.*\bexceeded\b/.test(e)}async function wv(e,t){let n=async t=>{try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){if(Yv(e,`ENOENT`))return``;throw e}},r=async()=>{for(let n of[t.basePath,t.draftPath])try{await e.rm(n)}catch{}},i=async t=>{try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){if(Yv(e,`ENOENT`))return null;throw e}};try{let a=await i(t.draftPath);if(a===null)return await r(),{applied:!1,conflicts:0};let o=await n(t.targetPath);if(a===o)return await r(),{applied:!1,conflicts:0};let s=await i(t.basePath);if(s===null)return{applied:!1,conflicts:0,error:`base snapshot missing; target left as-is`};if(a===s)return await r(),{applied:!1,conflicts:0};if(o===s)return await e.writeFile(t.targetPath,a),await r(),{applied:!0,conflicts:0};let c=yn(o,s,a,{favor:`theirs`});return await e.writeFile(t.targetPath,c.content),await r(),{applied:!0,conflicts:c.conflicts}}catch(e){let n=Jv(e);return hv.warn(`mergeOnSuccess failed; target left as-is, staging kept`,{target:t.targetPath,error:n}),{applied:!1,conflicts:0,error:n}}}async function Tv(e,t,n,r){try{let i=t.slice(0,t.lastIndexOf(`/`));i&&await e.mkdir(i,{recursive:!0}),await e.writeFile(t,JSON.stringify({status:n.exitCode===0?`ok`:`failed`,exitCode:n.exitCode,finishedAt:new Date().toISOString(),...n.exitCode===0&&!r?.promotedOnTrip?{}:{reason:n.finalText.slice(0,500)},...r?{merge:r}:{}},null,2))}catch(e){hv.warn(`outcome receipt write failed`,{path:t,error:Jv(e)})}}async function Ev(e,t){try{let n=t.slice(0,t.lastIndexOf(`/`));n&&await e.mkdir(n,{recursive:!0}),await e.writeFile(t,new Date().toISOString())}catch(e){hv.warn(`success receipt write failed`,{path:t,error:Jv(e)})}}const Dv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function Ov(e){return Dv.test(e)}const kv=`agent: name already in use`;async function Av(e,t,n,r,i){if(t.persistSession===!1)return;let a=t.persistSession===!0?`/sessions`:`/tmp`,o=new Date().toISOString().replace(/[:.]/g,`-`),s=`${a}/agent-${r}-${o}.md`;try{let c=e.orchestrator.getScoopContext(n),l=typeof c?.getAgentMessages==`function`?c.getAgentMessages():[],u=dv({name:r,jid:n,prompt:t.prompt,exitCode:i.exitCode,messages:l,timestamp:o});await e.sharedFs.mkdir(a,{recursive:!0}),await e.sharedFs.writeFile(s,u)}catch(e){hv.warn(`agent session archive write failed`,{path:s,error:Jv(e)})}}function jv(e,t,n,r,i,a){let o=Uv(e.cwd),s=Wv(e.workspaceMode),c={visiblePaths:Kv(e,a,s),writablePaths:qv([...Gv(e.writablePaths,o,s),`${i}/`,`/tmp/`]),workspaceMode:s,allowedCommands:e.allowedCommands};return e.maxTurns!==void 0&&(c.maxTurns=e.maxTurns),e.maxWallClockMs!==void 0&&(c.maxWallClockMs=e.maxWallClockMs),e.backgroundAfterSeconds!==void 0&&(c.backgroundAfterSeconds=e.backgroundAfterSeconds),t&&(c.modelId=t,n!==void 0&&(c.modelProviderId=n)),r!==void 0&&(c.thinkingLevel=r),e.structuredOutputSchema!==void 0&&(c.structuredOutputSchema=e.structuredOutputSchema),c}function Mv(e,t){let n={sendMessages:[],responseBuffer:``,scoopError:null,unsubscribe:null};return n.unsubscribe=e.observeScoop(t,{onSendMessage:e=>{n.sendMessages.push(e)},onResponse:(e,t)=>{t?n.responseBuffer+=e:n.responseBuffer=e},onError:e=>{n.scoopError===null&&(n.scoopError=e)}}),n}async function Nv(e,t,n,r,i){if(await e.sendPrompt(t,n,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};if(r){let n=e.getScoopContext(t),r=n?.getStructuredOutput?.();for(let a=0;a<2&&!r?.captured;a++){if(await e.sendPrompt(t,`You did not call StructuredOutput. Call it now with your result, matching the schema.`,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};r=n?.getStructuredOutput?.()}return r?.captured?{finalText:JSON.stringify(r.value),exitCode:0}:{finalText:`agent: scoop did not produce StructuredOutput`,exitCode:1}}return{finalText:i.sendMessages.length>0?i.sendMessages[i.sendMessages.length-1]:i.responseBuffer,exitCode:0}}async function Pv(e,t,n,r){try{await e.orchestrator.unregisterScoop(t)}catch(e){hv.warn(`unregisterScoop failed`,{jid:t,error:Jv(e)})}try{await e.sharedFs.rm(r,{recursive:!0})}catch(e){Yv(e,`ENOENT`)||hv.warn(`scratch folder cleanup failed`,{folder:n,error:Jv(e)})}if(e.sessionStore)try{await e.sessionStore.delete(t)}catch(e){hv.warn(`sessionStore.delete failed`,{jid:t,error:Jv(e)})}}async function Fv(e,t,n,r,i){let a=await Iv(e,t,n,r,i),o;return a.exitCode===0&&t.mergeOnSuccess?(o=await wv(e.sharedFs,t.mergeOnSuccess),o.error!==void 0&&(a={finalText:`agent: mergeOnSuccess failed: ${o.error}`,exitCode:1})):t.mergeOnSuccess&&Cv(a.finalText)&&(o=await wv(e.sharedFs,t.mergeOnSuccess),o.applied?(o.promotedOnTrip=!0,hv.info(`run tripped its bound; staged rewrite promoted`,{target:t.mergeOnSuccess.targetPath,conflicts:o.conflicts}),a={finalText:`${a.finalText} — staged rewrite promoted`,exitCode:0}):o.error===void 0&&(o=void 0)),a.exitCode===0&&t.successReceiptPath&&await Ev(e.sharedFs,t.successReceiptPath),t.outcomeReceiptPath&&await Tv(e.sharedFs,t.outcomeReceiptPath,a,o),a}async function Iv(e,t,n,r,i){try{await e.orchestrator.registerScoop(n)}catch(e){return{finalText:i.scoopError??Jv(e),exitCode:1}}try{let n=await Nv(e.orchestrator,r,t.prompt,t.structuredOutputSchema,i);return t.signal?.aborted?{finalText:`agent: aborted`,exitCode:1}:n||{finalText:i.scoopError??``,exitCode:1}}catch(e){return{finalText:i.scoopError??Jv(e),exitCode:1}}}function Lv(e,t,n=null,r={}){let i={orchestrator:e,sharedFs:t,sessionStore:n,generateName:r.generateName??Bv,generateUid:r.generateUid??zv,resolveModel:r.resolveModel??Hv};async function a(e){let t=xv(e,i.resolveModel);if(`error`in t)return t.error;let n=vv(i.orchestrator,e.parentJid),r=t.resolvedModelId??n?.modelId??``,a=t.resolvedModelId===void 0?n?.providerId:t.resolvedProviderId,o=e.thinkingLevel??bv(i.orchestrator,e.parentJid)??void 0,s=e.name===void 0?_v(i):e.name,c=`agent-${s}`,l=`agent_${Vv(s)}`,u=new Set(i.orchestrator.getScoops().map(e=>e.jid));if(e.name!==void 0&&u.has(l))return{finalText:`${kv}: ${s}`,exitCode:1};let d=(e.exclusiveWith??[]).find(e=>u.has(`agent_${Vv(e)}`));if(d!==void 0)return{finalText:`${kv}: ${d}`,exitCode:1};let f=`/scoops/${c}`,p=e.parentJid??A(i.orchestrator.getScoops())[0]?.jid??null,m=jv(e,r,a,o,f,yv(i.orchestrator,p)),h={jid:l,name:c,folder:c,requiresTrigger:!1,assistantLabel:c,addedAt:new Date().toISOString(),config:m,configSchemaVersion:3,notifyOnComplete:e.notifyOnComplete===!0,parentJid:p},g=Mv(i.orchestrator,l),_=()=>{try{i.orchestrator.stopScoop(l)}catch(e){hv.warn(`stopScoop on abort failed`,{jid:l,error:Jv(e)})}};if(e.signal?.addEventListener(`abort`,_,{once:!0}),e.signal?.aborted)return e.signal.removeEventListener(`abort`,_),g.unsubscribe?.(),{finalText:`agent: aborted before start`,exitCode:1};let ee={finalText:``,exitCode:1};try{return ee=await Fv(i,e,h,l,g),ee}finally{e.signal?.removeEventListener(`abort`,_),g.unsubscribe?.(),await Av(i,e,l,s,ee),await Pv(i,l,c,f)}}return{spawn:a}}function Rv(e,t,n=null,r={}){let i=Lv(e,t,n,r);return globalThis[gv]=i,hv.info(`agent bridge published on globalThis.__slicc_agent`),i}function zv(){let e=globalThis;return typeof e.crypto?.randomUUID==`function`?e.crypto.randomUUID().replace(/-/g,``).slice(0,12):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function Bv(){return`${I_[Math.floor(Math.random()*I_.length)]}-${L_[Math.floor(Math.random()*L_.length)]}`}function Vv(e){return e.replace(/-/g,`_`)}function Hv(e){try{return he(e)}catch(t){return hv.warn(`defaultResolveModel: provider/account lookup threw; treating model as unknown`,{modelId:e,error:t instanceof Error?t.message:String(t)}),{ok:!1,error:`unknown model: ${e}`}}}function Uv(e){let t=_n(e);return t.endsWith(`/`)?t:`${t}/`}function Wv(e){let t=Sn(e);return t.ok?t.mode:Cn}function Gv(e,t,n=Cn){let r=n===`private`?[t]:[t,`/shared/`];return e===void 0||e.some(e=>typeof e!=`string`||!e.startsWith(`/`)||e.includes(`\0`))?r:e.map(Uv)}function Kv(e,t,n=Cn){if(e.visiblePaths!==void 0)return e.visiblePaths.map(Uv);if(n===`private`)return[];let r=[...t];return e.invokingCwd&&e.invokingCwd.length>0&&r.push(Uv(e.invokingCwd)),qv(r)}function qv(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function Jv(e){return e instanceof Error?e.message:String(e)}function Yv(e,t){if(typeof e!=`object`||!e)return!1;let n=e.code;return typeof n==`string`&&n===t}const Xv=`sessions`;function Zv(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Xv)||e.createObjectStore(Xv,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Qv=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Zv();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Xv,`readwrite`);i.objectStore(Xv).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Xv,`readonly`).objectStore(Xv).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(Xv,`readonly`).objectStore(Xv).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Xv,`readwrite`);i.objectStore(Xv).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};const $v={summarizing:`summarizing`,fallback:`fallback`,cancelled:`discarded`,idle:`summarized`};var ey=class{mintId;open=new Map;settled=new Map;constructor(e){this.mintId=e}apply(e,t,n,r){if(t===`extracting-memory`)return null;let i=this.open.get(e)??this.lateRetraction(e,t,n)??r;if(t!==`summarizing`&&!i)return null;t!==`summarizing`&&(this.open.delete(e),this.settled.delete(e));let a=i??this.mintId(e);if(t===`summarizing`&&this.open.set(e,a),(t===`idle`||t===`fallback`)&&n.roundId&&this.settled.set(e,{messageId:a,roundId:n.roundId}),t===`cancelled`)return{kind:`retract`,messageId:a};let o={trigger:n.trigger,state:$v[t],...n.transcriptPath?{transcriptPath:n.transcriptPath}:{}};return t===`summarizing`?{kind:`open`,messageId:a,marker:o}:{kind:`settle`,messageId:a,marker:o}}forget(e){this.open.delete(e),this.settled.delete(e)}lateRetraction(e,t,n){if(t!==`cancelled`||!n.roundId)return;let r=this.settled.get(e);return r?.roundId===n.roundId?r.messageId:void 0}},ty=e({formatMountRecoveryPrompt:()=>cy,mdInlineCode:()=>sy,recoverMounts:()=>ay,shellQuote:()=>oy});function ny(e){return e instanceof Error?e.message:String(e)}async function ry(e,t,n,r){let i=await pr(t.idbHandleKey),a=typeof i?.name==`string`?i.name:``,o={kind:`local`,path:e,dirName:a};if(!i||!(`queryPermission`in i))return{entry:o,ok:!1};let s;try{s=await i.queryPermission({mode:`readwrite`})}catch(t){return r?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:ny(t)}),{entry:o,ok:!1}}if(s!==`granted`)return{entry:o,ok:!1};try{let s=ar.fromHandle(i,{mountId:t.mountId});return await n.mount(e,s,{limits:or}),r?.info?.(`Restored mount from previous session`,{path:e,name:a}),{entry:o,ok:!0}}catch(t){return r?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:ny(t)}),{entry:o,ok:!1}}}async function iy(e,t,n,r){let{kind:i,source:a,profile:o,mountId:s}=t,c=i===`s3`?`S3`:i===`aem`?`AEM`:`DA`;try{let t={source:a,profile:o,cache:new mr({mountId:s,ttlMs:3e4}),mountId:s},l=i===`s3`?new cr({...t,signedFetch:lr(o)}):i===`aem`?new dr({...t,signedFetch:fr()}):new sr({...t,signedFetch:fr()});return await n.mount(e,l),r?.info?.(`Restored ${c} mount from previous session`,{path:e,source:a}),{entry:{kind:i,path:e,source:a,profile:o,reason:``},ok:!0}}catch(t){let n=ny(t);return r?.warn?.(`Failed to restore ${c} mount`,{path:e,error:n}),{entry:{kind:i,path:e,source:a,profile:o,reason:n},ok:!1}}}async function ay(e,t,n){let r=[],i=[];for(let{targetPath:a,descriptor:o}of e){if(o.kind===`hostfs`)continue;let e=o.kind===`local`?await ry(a,o,t,n):await iy(a,o,t,n);(e.ok?r:i).push(e.entry)}return{restored:r,needsRecovery:i}}function oy(e){return`'${e.replace(/'/g,`'\\''`)}'`}function sy(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function cy(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`||e.kind===`aem`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${sy(t)})`:``;return`- ${sy(e)}${n}`}),i=r.map(({path:e})=>` mount ${oy(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${oy(n)}`,a=`mount --source ${oy(t)}${i} ${oy(e)}`;return`- ${sy(e)} (${sy(t)}, profile ${sy(n)}) — ${r}\n Retry: ${sy(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
|
|
892
|
-
`)}const
|
|
893
|
-
|
|
894
|
-
Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function
|
|
895
|
-
`)}}function
|
|
896
|
-
This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function Sy(e,t){let n=fy(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Cy(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Sy(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function wy(e,t){let n=Sy(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill … --all\` with any branch/path scope from the body, so it installs EVERY skill under that scope — a broad path can be many); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Ty(e){let t=dy[e.type];return e.type===`session-reload`?py(e,t):e.type===`upgrade`?my(e,t):e.type===`cherry`?hy(e,t):e.type===`preview`?gy(e,t):e.type===`workflow`?_y(e,t):e.type===`bash`?yy(e,t):e.type===`jshd`?vy(e,t):e.type===`sudo-request`?by(e,t):e.type===`navigate`?wy(e,t):e.type===`webhook`?Cy(e,t):e.type===`discovery`?xy(e,t):Sy(e,t)}function Ey(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i=n?e.config:Dy(e,r),a={jid:e.id??(n?`cone_${t()}`:`scoop_${r}_${t()}`),name:e.name,folder:r,requiresTrigger:!n,assistantLabel:n?`sliccy`:r,addedAt:new Date(t()).toISOString(),parentJid:e.parentId,...i?{config:i,configSchemaVersion:3}:{},...e.notifyOnComplete===!1?{notifyOnComplete:!1}:{},...!n&&e.onParentClose===`detach`?{onParentClose:`detach`}:{}};return n||(a.trigger=`@${r}`),a}function Dy(e,t){let n=bn(e.workspace?.mode??e.config?.workspaceMode),r=e.workspace?.from??`/workspace`,i=qn(n,t,{root:r},e.workspace?.from),a=e.config;return{...a,workspaceMode:n,visiblePaths:a?.visiblePaths===void 0?i.visiblePaths:a.visiblePaths,writablePaths:a?.writablePaths===void 0?i.writablePaths:a.writablePaths}}function Oy(e,t){if(e.parentId===null||e.workspace?.from!==void 0)return e;let n=t.getScoop(e.parentId);return n?{...e,workspace:{mode:e.workspace?.mode??e.config?.workspaceMode??`shared-readonly`,from:nr(n).root}}:e}var ky=class{host;constructor(e){this.host=e}async create(e){e.parentId===null&&e.workspace?.mode!==void 0&&bn(e.workspace.mode);let t=Ey(Oy(e,this.host));if(Py(t.jid,e=>this.host.getScoop(e)),e.parentId!==null){let n=this.host.getScoop(e.parentId);if(!n)throw Error(`Parent work unit not found: ${e.parentId}`);On(t,n)}return await this.host.registerScoop(t),this.get(t.jid).descriptor}async createMany(e){if(e.length===0)return[];Fy(e,e=>this.host.getScoop(e),()=>this.host.getScoops());let t=Ny(e);for(let e of t)e.id&&Py(e.id,e=>this.host.getScoop(e));let n=Ly(t),r=[],i=new Map;try{for(let e of n){let t=await this.create(e);r.push(t.id),i.set(e,t)}}catch(e){for(let e=r.length-1;e>=0;e--)await this.close(r[e]).catch(()=>void 0);throw e}return t.map(e=>i.get(e))}async join(e,t){return(await this.host.waitForScoops(e,t?.timeoutMs)).map(e=>({id:e.jid,summary:e.summary,timedOut:e.timedOut}))}list(){return this.host.getScoops().map(e=>this.get(e.jid).descriptor)}get(e){return this.host.getScoop(e)?this.host.ensureLiveUnit(e):null}getParent(e){let t=this.host.getScoop(e)?.parentJid;return t?this.get(t):null}getChildren(e){return Kn(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return A(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=new Set,n=this.host.getScoop(e);for(;n&&n.parentJid!==null;){if(t.has(n.jid))return null;t.add(n.jid),n=this.host.getScoop(n.parentJid)}return n?this.get(n.jid):null}abort(e,t){let n=this.get(e);return n?n.abort(t):Promise.resolve()}async promote(e){let t=this.host.getScoop(e);if(!t)throw Error(`Work unit not found: ${e}`);if(t.parentJid===null)return this.get(e).descriptor;let n=yr(t),r=jy(t,t.parentJid);t.parentJid=null,Un(t);try{await this.host.persistScoop(t)}catch(e){throw My(t,r),e}return await this.host.rekeyConversation?.(n,{key:yr(t),workUnitId:t.jid,workspaceId:vr(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:Ln(t)}}),await this.host.reinitLiveUnit(e),this.get(e).descriptor}detach(e){return this.promote(e)}async close(e,t){let n=this.get(e);if(!n)return;let r=this.getChildren(e);for(let e of r)Ay(e,t)===`detach`?await this.promote(e.descriptor.id):await this.close(e.descriptor.id,t);await n.close()}};function Ay(e,t){return t?.descendants??e.descriptor.onParentClose}function jy(e,t){return{parentJid:t,trigger:e.trigger,requiresTrigger:e.requiresTrigger,approvesGuestRequests:e.approvesGuestRequests,onParentClose:e.onParentClose}}function My(e,t){e.parentJid=t.parentJid,e.trigger=t.trigger,e.requiresTrigger=t.requiresTrigger,e.approvesGuestRequests=t.approvesGuestRequests,e.onParentClose=t.onParentClose}function Ny(e){let t=Date.now();return e.map(e=>{if(e.id)return e;let n=e.folder??e.name,r=e.parentId===null?`cone_${t++}`:`scoop_${n}_${t++}`;return{...e,id:r}})}function Py(e,t){if(t(e))throw Error(`Work unit already exists: ${e}`)}function Fy(e,t,n){let r=new Set;for(let n of e)if(n.id){if(r.has(n.id))throw Error(`Duplicate work unit id in createMany: ${n.id}`);Py(n.id,t),r.add(n.id)}Iy(e,n);let i=[],a=new Set;for(let n of e)n.parentId!==null&&(t(n.parentId)||r.has(n.parentId)||a.has(n.parentId)||(a.add(n.parentId),i.push(n.parentId)));if(i.length>0)throw Error(`Parent work unit not found: ${i.join(`, `)}`)}function Iy(e,t){let n=new Set(t().map(e=>e.folder)),r=new Set;for(let t of e){let e=t.folder??t.name;if(r.has(e)||n.has(e))throw Error(`Duplicate work unit folder in createMany: ${e}`);r.add(e)}}function Ly(e){let t=e.length;if(t<=1)return e.slice();let n=new Map;for(let r=0;r<t;r++){let t=e[r].id;t&&n.set(t,r)}let r=Array(t).fill(0),i=Array.from({length:t},()=>[]);for(let a=0;a<t;a++){let t=e[a].parentId;if(t===null)continue;let o=n.get(t);o!==void 0&&(i[o].push(a),r[a]+=1)}let a=[];for(let e=0;e<t;e++)r[e]===0&&a.push(e);let o=[];for(let t=0;t<a.length;t++){let n=a[t];o.push(e[n]);for(let e of i[n])--r[e],r[e]===0&&a.push(e)}if(o.length!==t)throw Error(`createMany cycle: parentId edges in this batch form a cycle`);return o}const Ry=y(`kernel-agent-event-stream`);var zy=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){Ry.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${By()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=e.displayScoopJid?`tool-ui-${e.requestId??``}`:i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=e.displayScoopJid?`tool-ui-${e.requestId??``}`:this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function By(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Vy=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Hy(e);return{jid:e.jid,name:e.name,folder:e.folder,parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=A(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Hy(e){let t=An(e),n=Fn(e),{level:r,effortOverride:i}=Pn(e);if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{modelProviderId:n},...r===void 0?{}:{thinkingLevel:r},...i===void 0?{}:{effortOverride:i}}}const W={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Uy=null;function Wy(e){if(!e.objectStoreNames.contains(W.MESSAGES)){let t=e.createObjectStore(W.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(W.SESSIONS)||e.createObjectStore(W.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(W.TASKS)||e.createObjectStore(W.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(W.STATE)||e.createObjectStore(W.STATE,{keyPath:`key`})}function Gy(e,t){let n=e.isMain??!1;return{jid:e.jid,name:e.name,folder:e.folder,trigger:n?void 0:e.trigger||`@${e.folder}`,requiresTrigger:!n&&(e.requiresTrigger??!0),parentJid:n?null:t??null,assistantLabel:n?`sliccy`:e.config?.assistantName||e.folder,addedAt:e.addedAt,config:e.config?{systemPromptAppend:e.config.systemPromptAppend,timeout:e.config.timeout,assistantName:e.config.assistantName}:void 0}}function Ky(e,t){if(t.objectStoreNames.contains(`groups`)){let n=e.target.transaction.objectStore(`groups`).getAll();n.onsuccess=()=>{let e=n.result;t.deleteObjectStore(`groups`);let r=t.createObjectStore(W.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);let i=e.find(e=>e.isMain)?.jid;for(let t of e)r.put(Gy(t,i))};return}t.objectStoreNames.contains(W.SCOOPS)||t.createObjectStore(W.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function qy(e){e.objectStoreNames.contains(W.WEBHOOKS)||e.createObjectStore(W.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(W.CRONTASKS)||e.createObjectStore(W.CRONTASKS,{keyPath:`id`})}function Jy(e){let t=e.target.result,n=e.oldVersion;n<1&&Wy(t),n<2&&Ky(e,t),n<3&&qy(t)}function Yy(){if(!Uy)return null;let e=Object.values(W).every(e=>Uy.objectStoreNames.contains(e));return Uy.version===3&&e?Uy:(Uy.close(),Uy=null,null)}function Xy(e){e.onversionchange=()=>{e.close(),Uy===e&&(Uy=null)},e.onclose=()=>{Uy===e&&(Uy=null)}}async function Zy(){return Yy()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=Jy,n.onsuccess=()=>{let t=n.result;Xy(t),Uy=t,e(t)},n.onerror=()=>t(n.error)})}async function G(e,t=`readonly`){return(await Zy()).transaction(e,t).objectStore(e)}async function Qy(e){let t=await G(W.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function $y(){let e=await G(W.SCOOPS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>{let e={};for(let t of r.result)e[t.jid]=t;t(e)},r.onerror=()=>n(r.error)})}async function eb(e){let t=await G(W.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function tb(){let e=await G(W.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function nb(e){let t=(await G(W.MESSAGES,`readwrite`)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,``],!1,!1);return new Promise((e,r)=>{let i=t.openCursor(n);i.onsuccess=()=>{let t=i.result;if(!t){e();return}t.delete(),t.continue()},i.onerror=()=>r(i.error)})}async function rb(e){let t=await G(W.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ib(e){let t=await G(W.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ab(e){let t=(await G(W.MESSAGES)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,``],!1,!1);return new Promise((e,r)=>{let i=t.getAll(n);i.onsuccess=()=>e(i.result),i.onerror=()=>r(i.error)})}const ob=`wm1:`;function sb(e){if(!e)return{ts:``,ids:new Set};if(e.startsWith(ob))try{let t=JSON.parse(e.slice(4));return{ts:t.ts,ids:new Set(t.ids)}}catch{}return{ts:e,ids:null}}function cb(e){let t=e.ids?Array.from(e.ids):[];return`${ob}${JSON.stringify({ts:e.ts,ids:t})}`}function lb(e,t){return e.timestamp>t.ts?!0:e.timestamp<t.ts||t.ids===null?!1:!t.ids.has(e.id)}function ub(e,t){if(t.length===0)return e;let n=e.ts;for(let e of t)e.timestamp>n&&(n=e.timestamp);let r=new Set;if(e.ts===n&&e.ids)for(let t of e.ids)r.add(t);for(let e of t)e.timestamp===n&&r.add(e.id);return{ts:n,ids:r}}async function db(e,t,n){let r=(await G(W.MESSAGES)).index(`chatJid_timestamp`),i=sb(t),a=IDBKeyRange.bound([e,i.ts],[e,``],!1,!1);return new Promise((e,t)=>{let o=r.getAll(a);o.onsuccess=()=>{let t=o.result.filter(e=>lb(e,i));n&&(t=t.filter(e=>e.senderName!==n)),e(t)},o.onerror=()=>t(o.error)})}async function fb(e){let t=await G(W.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function pb(e){let t=await G(W.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function mb(){let e=await G(W.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function hb(e){let t=await G(W.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function gb(e){let t=await G(W.STATE);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result?.value??null),i.onerror=()=>r(i.error)})}async function _b(e,t){let n=await G(W.STATE,`readwrite`);return new Promise((r,i)=>{let a=n.put({key:e,value:t});a.onsuccess=()=>r(),a.onerror=()=>i(a.error)})}async function vb(){await Zy()}async function yb(e){let t=await G(W.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function bb(e){let t=await G(W.WEBHOOKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function xb(){try{let e=await G(W.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Sb(e){let t=await G(W.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Cb(e){let t=await G(W.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function wb(e){let t=await G(W.CRONTASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function Tb(){try{let e=await G(W.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Eb(e){let t=await G(W.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}y(`tray-leader`);function Db(){return Ob(xr(),r())}function Ob(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const kb=`__slicc_binary__`;function Ab(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[kb]===`b64`&&typeof t.data==`string`}function jb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function Mb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)&&!Ab(e)}function Nb(e){if(e instanceof Uint8Array)return{[kb]:`b64`,data:ce(e)};if(Array.isArray(e))return e.map(Nb);if(jb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Nb(r);return t}return e}function Pb(e){if(Ab(e))return le(e.data);if(Array.isArray(e))return e.map(Pb);if(Mb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Pb(r);return t}return e}const Fb=y(`panel-transport`);function Ib(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Lb(){return{onMessage:e=>{let t=(t,n,r)=>(Ib(t)&&e(Pb(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Nb(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||Fb.error(`Offscreen → panel transport send failed`,{error:t})})}}}const Rb=y(`kernel-bridge`);function zb(){return globalThis}function Bb(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var Vb=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;conesBeingCreated=new Map;currentMessageId=new Map;compactionRows=new ey(e=>`compaction-${e}-${Hb()}`);pendingMarkers=new Map;scoopPresentation=new Vy;agentEventStream=new zy;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=Lb(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Qv;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.flushPendingMarkers(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Hb()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&(e.currentMessageId.delete(t),e.flushPendingMarkers(t)),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n,r)=>{let i=e.compactionRows.apply(t,n,r);e.emit({type:`compaction-state`,scoopJid:t,state:n,trigger:r.trigger,...r.transcriptPath?{transcriptPath:r.transcriptPath}:{},...r.roundId?{roundId:r.roundId}:{},...i?{rowId:i.messageId}:{}}),e.recordCompactionRow(t,i)},onError:(t,n)=>{e.recordErrorCard(t,n),e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r,i)=>{B_.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{B_.has(n)||e.bufferToolEnd(t,n,r,i,a)},onToolUI:(t,n,r,i,a)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i,...a?{displayScoopJid:a}:{}})},onToolUIDone:(t,n,r)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n,...r?{displayScoopJid:r}:{}})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=U_(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??Hb(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=W_(n),e.isError=r)}}this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:G_(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(Ln(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],Db())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...Db()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Bb(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=ne(e),s=[];n&&s.push({source:`explicit target`,value:n}),o&&o!==n&&s.push({source:`configured route`,value:o});let c=[],l;for(let e of s){if(l=Ua(a,e.value),l)break;c.push(e)}if(l||=this.originRootOf(a,r?.unitJid)??A(a)[0],c.length>0&&Rb.warn(`Sprinkle lick target could not be resolved; using fallback`,{sprinkleName:e,unresolvedTargets:c,fallbackJid:l?.jid}),!l)return;let u=`sprinkle-${e}-${Date.now()}`,d=Ty({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r?.label})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,f=c.map(({source:e,value:t})=>`${e} ${JSON.stringify(t)}`).join(` and `),p=d+(f?`\n\n> Delivery note: ${f} could not be resolved; delivered to fallback ${JSON.stringify(l.folder)}.`:``),m={id:u,chatJid:l.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:p,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(l.jid).push({id:u,role:`user`,content:p,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),await this.orchestrator.handleMessage(m)}originRootOf(e,t){if(t)return Dn(e,e.find(e=>e.jid===t))}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=A(this.orchestrator.getScoops())[0];if(!t)return;let n=Wb(e).map((t,n)=>({...t,isStreaming:e[n]?.isStreaming}));this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?A(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromCanonicalRecord(e){let t=this.orchestrator?.getConversationStore?.();if(!t)return null;let{conversationKeyFor:n}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),r=await t.load(n(e));if(!r)return null;let{toChatMessages:i}=await Promise.resolve().then(()=>bC),a=await i(r,{source:In(e)});return a.length===0?null:this.overlayPersistedLickDecisionsOn(e,Wb(a))}async overlayPersistedLickDecisionsOn(e,t){if(!t.some(e=>e.channel===`sudo-request`||e.lickId||e.lickState))return t;let n=[];try{let t=await this.orchestrator?.getMessagesForScoop?.(e.jid);if(t)for(let e of t)n.push({id:e.id,content:e.content,channel:e.channel,lickId:e.lickId,lickState:e.lickState})}catch{}return Yb(t,n)}async hydrateBuffersFromRecords(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromCanonicalRecord(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid))}}queuedIdsFor(e){if(!(this.followerSync||!this.orchestrator))return this.orchestrator.getQueuedMessageIds(e)}async handleRequestScoopMessages(e){if(await this.conesBeingCreated.get(e),!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n,queuedIds:this.queuedIdsFor(e)});return}let r=await this.buildBufferFromCanonicalRecord(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r,queuedIds:this.queuedIdsFor(e)});return}this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:[],queuedIds:this.queuedIdsFor(e)})}async handleConeCreate(e,t,n,r){if(!this.orchestrator)return;let i=this.orchestrator.getScoops(),a=Bn(e,i),o=a===Hn,s=A(i)[0],c=r??(s?Vn(s):void 0),l=t?.trim(),u={...Ey({parentId:null,name:e,folder:a}),assistantLabel:o?`sliccy`:e,...l?{config:{systemPromptAppend:`This cone is for: ${l}`}}:{},...c?{model:c}:{}},d=()=>{};this.conesBeingCreated.set(u.jid,new Promise(e=>{d=e}));let f=()=>{this.conesBeingCreated.delete(u.jid),d()};try{await this.orchestrator.registerScoop(u),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(u)});let e=n?.trim();if(!e)return;let t=this.handleUserMessage({type:`user-message`,scoopJid:u.jid,text:e,messageId:`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});f(),await t}finally{f()}}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=t.approver;if(r&&r.kind!==`user`){let i=this.orchestrator;if(!i)console.warn(`[kernel-bridge] directed approval before orchestrator init — denying`);else try{n=await i.enqueueDirectedApproval(r,t)}catch(e){console.warn(`[kernel-bridge] directed approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n});return}let i=this.orchestrator?.getSudoManager()??null;if(!i)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await i.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}async handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}let o=await this.resolveBudgetWindow();this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a,...o?{budget:o}:{}})}budgetProbePending=!0;async resolveBudgetWindow(){return this.budgetProbePending?(this.budgetProbePending=!1,await Promise.race([P_().catch(()=>null),new Promise(e=>setTimeout(()=>e(null),2500))])??void 0):(P_().catch(()=>null),N_()??void 0)}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Ub(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await Promise.resolve().then(()=>q_),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:In(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Ub(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromCanonicalRecord(r);if(a){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}n()}async recordCompactionRow(e,t){if(!t||t.kind===`open`)return;let n=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n)return;let r=this.getBuffer(e);if(t.kind===`retract`){let e=r.findIndex(e=>e.id===t.messageId);e>=0&&r.splice(e,1)}else{let e=r.find(e=>e.id===t.messageId);e?e.compaction=t.marker:r.push({id:t.messageId,role:`assistant`,content:``,timestamp:Date.now(),compaction:t.marker})}let i=this.orchestrator?.getConversationStore?.();if(!i)return;let{conversationKeyFor:a}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),o=a(n);if(t.kind===`retract`){this.dropPendingMarker(e,t.messageId),await i.deleteMarker(o,t.messageId);return}let s={id:t.messageId,kind:`compaction`,timestamp:Date.now(),compaction:t.marker};await i.putMarker(o,s)||this.holdPendingMarker(e,s)}holdPendingMarker(e,t){let n=this.pendingMarkers.get(e)??[];this.pendingMarkers.set(e,[...n.filter(e=>e.id!==t.id),t].slice(-4))}dropPendingMarker(e,t){let n=this.pendingMarkers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,r)}async flushPendingMarkers(e){let t=this.pendingMarkers.get(e);if(!t||t.length===0)return;let n=this.orchestrator?.getConversationStore?.(),r=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n||!r)return;let{conversationKeyFor:i}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),a=i(r),o=[];for(let e of t)await n.putMarker(a,e)||o.push(e);o.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,o)}async recordErrorCard(e,t){let n=Hb(),r=Date.now();this.getBuffer(e).push({id:n,role:`assistant`,content:t,timestamp:r,error:!0});let i=this.orchestrator?.getConversationStore?.(),a=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!i||!a)return;let{conversationIdentityFor:o}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),s=o(a),c={id:n,kind:`error`,timestamp:r,text:t};await i.putMarker(s.key,c,{createWith:s})||this.holdPendingMarker(e,c)}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${Hb()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?In(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{e.source===`panel`&&this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name,e.description,e.prompt,e.model);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId,e.scoopJid,e.discardLiveSnapshot===!0);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`set-model`:case`refresh-model`:this.orchestrator.refreshModels();break;case`set-scoop-model`:await this.handleSetScoopModel(e);break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.handleWebhookEventMsg(e);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value)),ba(e.key);break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key)),ba(e.key);break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear()),ba()}}handleWebhookEventMsg(e){let t=this.orchestrator?.handleWebhookEvent(e.webhookId,e.headers,e.body);e.requestId&&this.emit({type:`lick-webhook-delivery`,requestId:e.requestId,disposition:t??`unknown-webhook`})}async handleAgentSpawn(e){let t=zb()[gv];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetScoopModel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopModel(e.scoopJid,e.model)}catch(e){console.error(`[kernel-bridge] set-scoop-model failed:`,e)}e.requestId&&this.emit({type:`set-scoop-model-ack`,requestId:e.requestId,scoopJid:e.scoopJid,model:e.model,applied:t})}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&this.messageBuffers.set(e,r)}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.guestGate?{guestGate:e.guestGate}:{},...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&wn(n)){if(A(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);let i=new Set(this.orchestrator.getScoops().map(e=>e.jid));for(let e of[...r,n])i.has(e.jid)||this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=Ln({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e,t,n=!1){let r=this.orchestrator?.getScoops()??[],i=(t?r.find(e=>e.jid===t):void 0)??A(r)[0],a=i?.jid;a&&(n?await this.orchestrator?.clearScoopMessages(a,{discardLiveSnapshot:!0}):await this.orchestrator?.clearScoopMessages(a)),this.sessionStore&&await this.sessionStore.delete(Ln({folder:i?.folder??`cone`})),a&&(this.messageBuffers.delete(a),this.currentMessageId.delete(a),this.agentEventStream.clear(a)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.origin)}handleSetFollowerForwarding(e){let t=zb().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=zb().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){on.markMounted(t);return}try{await on.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),on.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function Hb(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Ub(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
897
|
-
`)}function
|
|
890
|
+
`)}`:r.firstLine,t=av(e);t?n.push({sender:t.sender,body:t.body}):n.push({sender:null,body:e}),r=null};for(let e of t){if(e.startsWith(`[`)&&/^\[[^\]\n]+\] /.test(e)&&e.includes(`: `)&&av(e)){i(),r={firstLine:e,rest:[]};continue}r?r.rest.push(e):r={firstLine:e,rest:[]}}return i(),n.length===0?[{sender:null,body:e}]:n}function sv(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t);return R_(n)?n:null}function cv(e){let t=/^\[@[^\]\s]+ (completed|idle)\]/.exec(e);return t?t[1]===`idle`?`scoop-idle`:`scoop-notify`:/^\[@[^\]\s]+ sudo-request\]/.test(e)?`sudo-request`:/^\[scoop_wait [^\]]+\]/.test(e)?`scoop-wait`:e.startsWith(`[Session Reload]`)?`session-reload`:null}function lv(e){return/^(?:Lick ID|Request ID): (\S+)/m.exec(e)?.[1]}function uv(e){let t=q_(e.messages,{source:e.name}),n=t.filter(e=>e.role===`assistant`).length,r=[`# Agent session: ${e.name}`,``,`- jid: ${e.jid}`,`- exit code: ${e.exitCode}`,`- turns: ${n}`,`- messages: ${e.messages.length}`,`- timestamp: ${e.timestamp}`,``,`## Prompt`,``,e.prompt.length>0?e.prompt:`_(empty prompt)_`,``,`---`,``];if(t.length===0)r.push(`_(no messages captured)_`,``);else for(let e of t)dv(r,e);return Ee(r.join(`
|
|
891
|
+
`),De())}function dv(e,t){e.push(`## ${t.role}`,``);let n=t.content.trim();n.length>0&&e.push(n,``);for(let n of t.toolCalls??[])fv(e,n)}function fv(e,t){e.push(`### tool: ${t.name}`,``,`Input:`,``,"```json",pv(t.input),"```",``),t.result!==void 0&&e.push(t.isError?`Result (error):`:`Result:`,``,"```",t.result,"```",``)}function pv(e){try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}const mv=y(`agent-bridge`),hv=`__slicc_agent`;function gv(e){for(let t=0;t<8;t++){let t=e.generateName(),n=`agent_${Bv(t)}`;if(!e.orchestrator.getScoops().some(e=>e.jid===n))return t}return e.generateUid()}function _v(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=An(n);if(!r||r.length===0)return null;let i=Fn(n);return i?{modelId:r,providerId:i}:{modelId:r}}function vv(e,t){let n=e.getWorkUnits(),r=(t===null?null:n.rootOf(t))??n.resolveDefaultRoot();return $n(r?.descriptor.workspace??Qn)}function yv(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=Pn(n).level;return r&&rr(r)?r:null}function bv(e,t){let n=e.modelId,r,i;if(n!==void 0){let a=e.modelProviderId!==void 0&&n!==``?`${e.modelProviderId}:${n}`:n,o=a===``?{ok:!1,error:`unknown model: ${n}`}:t(a);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};r=o.selection.modelId,i=o.selection.providerId}let a=e.thinkingLevel;if(a!==void 0&&!rr(a))return{error:{finalText:`agent: invalid thinking level: ${String(a)} (one of: ${ir.join(`, `)})`,exitCode:1}};let o=Sn(e.workspaceMode);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};let s=e.backgroundAfterSeconds;if(s!==void 0&&(typeof s!=`number`||!Number.isFinite(s)||s<0))return{error:{finalText:`agent: invalid backgroundAfterSeconds: ${String(s)} (seconds >= 0)`,exitCode:1}};let c=xv(e);if(c)return c;let l=e.name;if(l!==void 0&&!Dv(l))return{error:{finalText:`agent: invalid name: ${l} (lowercase tokens joined by single dashes)`,exitCode:1}};for(let[t,n]of[[`maxTurns`,e.maxTurns],[`maxWallClockMs`,e.maxWallClockMs]])if(n!==void 0&&(!Number.isInteger(n)||n<=0))return{error:{finalText:`agent: ${t} must be a positive integer: ${String(n)}`,exitCode:1}};return{resolvedModelId:r,resolvedProviderId:i}}function xv(e){let t=e.mergeOnSuccess,n=[[`successReceiptPath`,e.successReceiptPath],[`outcomeReceiptPath`,e.outcomeReceiptPath],[`mergeOnSuccess.targetPath`,t?.targetPath],[`mergeOnSuccess.basePath`,t?.basePath],[`mergeOnSuccess.draftPath`,t?.draftPath]],r=t===void 0?void 0:``;for(let[e,t]of n){let n=t??(e.startsWith(`mergeOnSuccess`)?r:void 0);if(n!==void 0&&!n.startsWith(`/`))return{error:{finalText:`agent: ${e} must be absolute: ${String(t)}`,exitCode:1}}}return null}function Sv(e){return/^agent run terminated: .*\bbound\b.*\bexceeded\b/.test(e)}async function Cv(e,t){let n=async t=>{try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){if(Jv(e,`ENOENT`))return``;throw e}},r=async()=>{for(let n of[t.basePath,t.draftPath])try{await e.rm(n)}catch{}},i=async t=>{try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){if(Jv(e,`ENOENT`))return null;throw e}};try{let a=await i(t.draftPath);if(a===null)return await r(),{applied:!1,conflicts:0};let o=await n(t.targetPath);if(a===o)return await r(),{applied:!1,conflicts:0};let s=await i(t.basePath);if(s===null)return{applied:!1,conflicts:0,error:`base snapshot missing; target left as-is`};if(a===s)return await r(),{applied:!1,conflicts:0};if(o===s)return await e.writeFile(t.targetPath,a),await r(),{applied:!0,conflicts:0};let c=yn(o,s,a,{favor:`theirs`});return await e.writeFile(t.targetPath,c.content),await r(),{applied:!0,conflicts:c.conflicts}}catch(e){let n=qv(e);return mv.warn(`mergeOnSuccess failed; target left as-is, staging kept`,{target:t.targetPath,error:n}),{applied:!1,conflicts:0,error:n}}}async function wv(e,t,n,r){try{let i=t.slice(0,t.lastIndexOf(`/`));i&&await e.mkdir(i,{recursive:!0}),await e.writeFile(t,JSON.stringify({status:n.exitCode===0?`ok`:`failed`,exitCode:n.exitCode,finishedAt:new Date().toISOString(),...n.exitCode===0&&!r?.promotedOnTrip?{}:{reason:n.finalText.slice(0,500)},...r?{merge:r}:{}},null,2))}catch(e){mv.warn(`outcome receipt write failed`,{path:t,error:qv(e)})}}async function Tv(e,t){try{let n=t.slice(0,t.lastIndexOf(`/`));n&&await e.mkdir(n,{recursive:!0}),await e.writeFile(t,new Date().toISOString())}catch(e){mv.warn(`success receipt write failed`,{path:t,error:qv(e)})}}const Ev=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function Dv(e){return Ev.test(e)}const Ov=`agent: name already in use`;async function kv(e,t,n,r,i){if(t.persistSession===!1)return;let a=t.persistSession===!0?`/sessions`:`/tmp`,o=new Date().toISOString().replace(/[:.]/g,`-`),s=`${a}/agent-${r}-${o}.md`;try{let c=e.orchestrator.getScoopContext(n),l=typeof c?.getAgentMessages==`function`?c.getAgentMessages():[],u=uv({name:r,jid:n,prompt:t.prompt,exitCode:i.exitCode,messages:l,timestamp:o});await e.sharedFs.mkdir(a,{recursive:!0}),await e.sharedFs.writeFile(s,u)}catch(e){mv.warn(`agent session archive write failed`,{path:s,error:qv(e)})}}function Av(e,t,n,r,i,a){let o=Hv(e.cwd),s=Uv(e.workspaceMode),c={visiblePaths:Gv(e,a,s),writablePaths:Kv([...Wv(e.writablePaths,o,s),`${i}/`,`/tmp/`]),workspaceMode:s,allowedCommands:e.allowedCommands};return e.maxTurns!==void 0&&(c.maxTurns=e.maxTurns),e.maxWallClockMs!==void 0&&(c.maxWallClockMs=e.maxWallClockMs),e.backgroundAfterSeconds!==void 0&&(c.backgroundAfterSeconds=e.backgroundAfterSeconds),t&&(c.modelId=t,n!==void 0&&(c.modelProviderId=n)),r!==void 0&&(c.thinkingLevel=r),e.structuredOutputSchema!==void 0&&(c.structuredOutputSchema=e.structuredOutputSchema),c}function jv(e,t){let n={sendMessages:[],responseBuffer:``,scoopError:null,unsubscribe:null};return n.unsubscribe=e.observeScoop(t,{onSendMessage:e=>{n.sendMessages.push(e)},onResponse:(e,t)=>{t?n.responseBuffer+=e:n.responseBuffer=e},onError:e=>{n.scoopError===null&&(n.scoopError=e)}}),n}async function Mv(e,t,n,r,i){if(await e.sendPrompt(t,n,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};if(r){let n=e.getScoopContext(t),r=n?.getStructuredOutput?.();for(let a=0;a<2&&!r?.captured;a++){if(await e.sendPrompt(t,`You did not call StructuredOutput. Call it now with your result, matching the schema.`,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};r=n?.getStructuredOutput?.()}return r?.captured?{finalText:JSON.stringify(r.value),exitCode:0}:{finalText:`agent: scoop did not produce StructuredOutput`,exitCode:1}}return{finalText:i.sendMessages.length>0?i.sendMessages[i.sendMessages.length-1]:i.responseBuffer,exitCode:0}}async function Nv(e,t,n,r){try{await e.orchestrator.unregisterScoop(t)}catch(e){mv.warn(`unregisterScoop failed`,{jid:t,error:qv(e)})}try{await e.sharedFs.rm(r,{recursive:!0})}catch(e){Jv(e,`ENOENT`)||mv.warn(`scratch folder cleanup failed`,{folder:n,error:qv(e)})}if(e.sessionStore)try{await e.sessionStore.delete(t)}catch(e){mv.warn(`sessionStore.delete failed`,{jid:t,error:qv(e)})}}async function Pv(e,t,n,r,i){let a=await Fv(e,t,n,r,i),o;return a.exitCode===0&&t.mergeOnSuccess?(o=await Cv(e.sharedFs,t.mergeOnSuccess),o.error!==void 0&&(a={finalText:`agent: mergeOnSuccess failed: ${o.error}`,exitCode:1})):t.mergeOnSuccess&&Sv(a.finalText)&&(o=await Cv(e.sharedFs,t.mergeOnSuccess),o.applied?(o.promotedOnTrip=!0,mv.info(`run tripped its bound; staged rewrite promoted`,{target:t.mergeOnSuccess.targetPath,conflicts:o.conflicts}),a={finalText:`${a.finalText} — staged rewrite promoted`,exitCode:0}):o.error===void 0&&(o=void 0)),a.exitCode===0&&t.successReceiptPath&&await Tv(e.sharedFs,t.successReceiptPath),t.outcomeReceiptPath&&await wv(e.sharedFs,t.outcomeReceiptPath,a,o),a}async function Fv(e,t,n,r,i){try{await e.orchestrator.registerScoop(n)}catch(e){return{finalText:i.scoopError??qv(e),exitCode:1}}try{let n=await Mv(e.orchestrator,r,t.prompt,t.structuredOutputSchema,i);return t.signal?.aborted?{finalText:`agent: aborted`,exitCode:1}:n||{finalText:i.scoopError??``,exitCode:1}}catch(e){return{finalText:i.scoopError??qv(e),exitCode:1}}}function Iv(e,t,n=null,r={}){let i={orchestrator:e,sharedFs:t,sessionStore:n,generateName:r.generateName??zv,generateUid:r.generateUid??Rv,resolveModel:r.resolveModel??Vv};async function a(e){let t=bv(e,i.resolveModel);if(`error`in t)return t.error;let n=_v(i.orchestrator,e.parentJid),r=t.resolvedModelId??n?.modelId??``,a=t.resolvedModelId===void 0?n?.providerId:t.resolvedProviderId,o=e.thinkingLevel??yv(i.orchestrator,e.parentJid)??void 0,s=e.name===void 0?gv(i):e.name,c=`agent-${s}`,l=`agent_${Bv(s)}`,u=new Set(i.orchestrator.getScoops().map(e=>e.jid));if(e.name!==void 0&&u.has(l))return{finalText:`${Ov}: ${s}`,exitCode:1};let d=(e.exclusiveWith??[]).find(e=>u.has(`agent_${Bv(e)}`));if(d!==void 0)return{finalText:`${Ov}: ${d}`,exitCode:1};let f=`/scoops/${c}`,p=e.parentJid??A(i.orchestrator.getScoops())[0]?.jid??null,m=Av(e,r,a,o,f,vv(i.orchestrator,p)),h={jid:l,name:c,folder:c,requiresTrigger:!1,assistantLabel:c,addedAt:new Date().toISOString(),config:m,configSchemaVersion:3,notifyOnComplete:e.notifyOnComplete===!0,parentJid:p},g=jv(i.orchestrator,l),_=()=>{try{i.orchestrator.stopScoop(l)}catch(e){mv.warn(`stopScoop on abort failed`,{jid:l,error:qv(e)})}};if(e.signal?.addEventListener(`abort`,_,{once:!0}),e.signal?.aborted)return e.signal.removeEventListener(`abort`,_),g.unsubscribe?.(),{finalText:`agent: aborted before start`,exitCode:1};let ee={finalText:``,exitCode:1};try{return ee=await Pv(i,e,h,l,g),ee}finally{e.signal?.removeEventListener(`abort`,_),g.unsubscribe?.(),await kv(i,e,l,s,ee),await Nv(i,l,c,f)}}return{spawn:a}}function Lv(e,t,n=null,r={}){let i=Iv(e,t,n,r);return globalThis[hv]=i,mv.info(`agent bridge published on globalThis.__slicc_agent`),i}function Rv(){let e=globalThis;return typeof e.crypto?.randomUUID==`function`?e.crypto.randomUUID().replace(/-/g,``).slice(0,12):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function zv(){return`${F_[Math.floor(Math.random()*F_.length)]}-${I_[Math.floor(Math.random()*I_.length)]}`}function Bv(e){return e.replace(/-/g,`_`)}function Vv(e){try{return he(e)}catch(t){return mv.warn(`defaultResolveModel: provider/account lookup threw; treating model as unknown`,{modelId:e,error:t instanceof Error?t.message:String(t)}),{ok:!1,error:`unknown model: ${e}`}}}function Hv(e){let t=_n(e);return t.endsWith(`/`)?t:`${t}/`}function Uv(e){let t=Sn(e);return t.ok?t.mode:Cn}function Wv(e,t,n=Cn){let r=n===`private`?[t]:[t,`/shared/`];return e===void 0||e.some(e=>typeof e!=`string`||!e.startsWith(`/`)||e.includes(`\0`))?r:e.map(Hv)}function Gv(e,t,n=Cn){if(e.visiblePaths!==void 0)return e.visiblePaths.map(Hv);if(n===`private`)return[];let r=[...t];return e.invokingCwd&&e.invokingCwd.length>0&&r.push(Hv(e.invokingCwd)),Kv(r)}function Kv(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function qv(e){return e instanceof Error?e.message:String(e)}function Jv(e,t){if(typeof e!=`object`||!e)return!1;let n=e.code;return typeof n==`string`&&n===t}const Yv=`sessions`;function Xv(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Yv)||e.createObjectStore(Yv,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Zv=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Xv();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Yv,`readwrite`);i.objectStore(Yv).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Yv,`readonly`).objectStore(Yv).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(Yv,`readonly`).objectStore(Yv).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Yv,`readwrite`);i.objectStore(Yv).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};const Qv={summarizing:`summarizing`,fallback:`fallback`,cancelled:`discarded`,idle:`summarized`};var $v=class{mintId;open=new Map;settled=new Map;constructor(e){this.mintId=e}apply(e,t,n,r){if(t===`extracting-memory`)return null;let i=this.open.get(e)??this.lateRetraction(e,t,n)??r;if(t!==`summarizing`&&!i)return null;t!==`summarizing`&&(this.open.delete(e),this.settled.delete(e));let a=i??this.mintId(e);if(t===`summarizing`&&this.open.set(e,a),(t===`idle`||t===`fallback`)&&n.roundId&&this.settled.set(e,{messageId:a,roundId:n.roundId}),t===`cancelled`)return{kind:`retract`,messageId:a};let o={trigger:n.trigger,state:Qv[t],...n.transcriptPath?{transcriptPath:n.transcriptPath}:{}};return t===`summarizing`?{kind:`open`,messageId:a,marker:o}:{kind:`settle`,messageId:a,marker:o}}forget(e){this.open.delete(e),this.settled.delete(e)}lateRetraction(e,t,n){if(t!==`cancelled`||!n.roundId)return;let r=this.settled.get(e);return r?.roundId===n.roundId?r.messageId:void 0}},ey=e({formatMountRecoveryPrompt:()=>sy,mdInlineCode:()=>oy,recoverMounts:()=>iy,shellQuote:()=>ay});function ty(e){return e instanceof Error?e.message:String(e)}async function ny(e,t,n,r){let i=await pr(t.idbHandleKey),a=typeof i?.name==`string`?i.name:``,o={kind:`local`,path:e,dirName:a};if(!i||!(`queryPermission`in i))return{entry:o,ok:!1};let s;try{s=await i.queryPermission({mode:`readwrite`})}catch(t){return r?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:ty(t)}),{entry:o,ok:!1}}if(s!==`granted`)return{entry:o,ok:!1};try{let s=ar.fromHandle(i,{mountId:t.mountId});return await n.mount(e,s,{limits:or}),r?.info?.(`Restored mount from previous session`,{path:e,name:a}),{entry:o,ok:!0}}catch(t){return r?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:ty(t)}),{entry:o,ok:!1}}}async function ry(e,t,n,r){let{kind:i,source:a,profile:o,mountId:s}=t,c=i===`s3`?`S3`:i===`aem`?`AEM`:`DA`;try{let t={source:a,profile:o,cache:new mr({mountId:s,ttlMs:3e4}),mountId:s},l=i===`s3`?new cr({...t,signedFetch:lr(o)}):i===`aem`?new dr({...t,signedFetch:fr()}):new sr({...t,signedFetch:fr()});return await n.mount(e,l),r?.info?.(`Restored ${c} mount from previous session`,{path:e,source:a}),{entry:{kind:i,path:e,source:a,profile:o,reason:``},ok:!0}}catch(t){let n=ty(t);return r?.warn?.(`Failed to restore ${c} mount`,{path:e,error:n}),{entry:{kind:i,path:e,source:a,profile:o,reason:n},ok:!1}}}async function iy(e,t,n){let r=[],i=[];for(let{targetPath:a,descriptor:o}of e){if(o.kind===`hostfs`)continue;let e=o.kind===`local`?await ny(a,o,t,n):await ry(a,o,t,n);(e.ok?r:i).push(e.entry)}return{restored:r,needsRecovery:i}}function ay(e){return`'${e.replace(/'/g,`'\\''`)}'`}function oy(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function sy(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`||e.kind===`aem`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${oy(t)})`:``;return`- ${oy(e)}${n}`}),i=r.map(({path:e})=>` mount ${ay(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${ay(n)}`,a=`mount --source ${ay(t)}${i} ${ay(e)}`;return`- ${oy(e)} (${oy(t)}, profile ${oy(n)}) — ${r}\n Retry: ${oy(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
|
|
892
|
+
`)}const cy=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`bash`,`jshd`,`sudo-request`,`preview`,`discovery`]);function ly(e){return e!=null&&cy.has(e)}const uy={webhook:`Webhook Event`,sprinkle:`Sprinkle Event`,fswatch:`File Watch Event`,"session-reload":`Session Reload`,navigate:`Navigate Event`,upgrade:`Upgrade Event`,cherry:`Cherry Event`,workflow:`Workflow Event`,bash:`Background Command`,jshd:`jshd Unit`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`,preview:`Preview`,discovery:`Discovery Event`};function dy(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`session-reload`:return`mount-recovery`;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`cherry`:return e.cherryName;case`workflow`:return e.workflowName;case`bash`:return e.bashJobId;case`jshd`:return e.jshdName;case`sudo-request`:return e.sudoScoopName;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function fy(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=sy(n.mounts??[]);return e===null?null:{label:t,content:`${e}${r?`\n\nLick ID: ${r}\nThis card is actionable: call \`lick_confirm\` with this lick id to re-run the listed \`mount …\` command(s) so the user can re-authorize, or \`lick_dismiss\` to leave them unmounted. The card flips to ✓ on confirm / muted ✗ on dismiss.`:``}`}}let i=xy(e,t);if(!r)return i;let a=`\n\nLick ID: ${r}\nThis card is informational — there is NO confirm action. Call \`lick_dismiss\` with this lick id to acknowledge and clear it. The card flips to muted ✗ on dismiss.`;return{label:i.label,content:`${i.content}${a}`}}function py(e,t){let n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`,i=e.body?.releasedAt??null,a=i?`\nReleased: ${i}`:``,o=e.lickId;return{label:t,content:`[${t}: ${n}→${r}]\n\nSLICC was upgraded from \`${n}\` to \`${r}\`.${a}${o?`\n\nLick ID: ${o}\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`). The card is a binary action: call \`lick_confirm\` with this lick id to **Update workspace files** (it runs the three-way merge of bundled vfs-root content into the user's VFS), or \`lick_dismiss\` to clear it. The card flips to ✓ on confirm / muted ✗ on dismiss. Reviewing the changelog is a separate step you can run first — it is NOT a card action.`:`
|
|
893
|
+
|
|
894
|
+
Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function my(e,t){let n=e.cherryOrigin??`unknown origin`,r=e.cherryRuntimeId??`unknown`;return{label:t,content:`[${t}: ${e.cherryName??`unnamed`}] from ${n} (runtime ${r})\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function hy(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function gy(e,t){let n=e.workflowName??`workflow`,r=e.resultPath??`(no result file)`,i=e.preview??``;return{label:t,content:`[${t}: ${n}] ${e.body?.status??`complete`} — ${i}\nFull result: ${r} (read it only if you need the whole thing).`}}function _y(e,t){let n=e.jshdName??`unknown`,r=e.jshdRestarts??0,i=e.resultPath;return{label:t,content:`[${t}: ${n}] marked errored after ${r} restarts.\nThe restart policy stopped trying so the unit does not crash-loop.\n${i?`Logs: ${i} (page with \`jshd logs ${n}\`).`:`No log file was written.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nInspect with \`jshd status ${n}\`; start it again with \`jshd start -n ${n}\` after fixing the script.`}}function vy(e,t){let n=e.bashJobId??`unknown job`,r=e.bashJobPid===void 0?``:` (pid ${e.bashJobPid})`,i=e.bashCommand??`(unknown command)`,a=e.bashExitCode,o=a===0?`succeeded`:a===130||a===137||a===143?`was terminated (exit code ${a}) — killed by a signal, not by its own failure`:`failed (exit code ${a??`unknown`})`,s=e.resultPath;return{label:t,content:`[${t}: ${n}${r}] \`${i}\` ${o}.\n${s?`Full output: ${s} (page it with \`sed -n\`/\`tail\`/\`grep\` if the preview below is cut).`:`Its output could NOT be written to a file — the preview below is all that survived.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nThis is the delayed result of a command that was detached earlier in this session — do not re-run it. Act on it if it still matters, otherwise acknowledge and move on.`}}function yy(e,t){let n=e.sudoScoopName??`a scoop`,r=e.lickId??`(unknown)`,i=e.sudoKind??`unknown`,a=e.sudoDetail??``,o=[`[${t}: ${n}]`,`Lick ID: ${r}`,`Kind: ${i}`,`Detail: ${a}`];return e.sudoReason&&o.push(`Reason given: ${e.sudoReason}`),e.sudoSuggestedPattern&&o.push(`Suggested pattern: ${e.sudoSuggestedPattern}`),o.push(``,`Use the lick_confirm tool with lick_id="${r}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${r}" and a reason to deny.`),{label:t,content:o.join(`
|
|
895
|
+
`)}}function by(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.${e.discoveryKind===`llms-txt`&&e.lickId?`\n\nLick ID: ${e.lickId}\nThis card is dismiss-only: call \`lick_dismiss\` to add the advertising host to \`/etc/llmstxtignore\` and silence future discoveries without a prompt. There is NO confirm action.`:`
|
|
896
|
+
This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function xy(e,t){let n=dy(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Sy(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return xy(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Cy(e,t){let n=xy(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill … --all\` with any branch/path scope from the body, so it installs EVERY skill under that scope — a broad path can be many); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function wy(e){let t=uy[e.type];return e.type===`session-reload`?fy(e,t):e.type===`upgrade`?py(e,t):e.type===`cherry`?my(e,t):e.type===`preview`?hy(e,t):e.type===`workflow`?gy(e,t):e.type===`bash`?vy(e,t):e.type===`jshd`?_y(e,t):e.type===`sudo-request`?yy(e,t):e.type===`navigate`?Cy(e,t):e.type===`webhook`?Sy(e,t):e.type===`discovery`?by(e,t):xy(e,t)}function Ty(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i=n?e.config:Ey(e,r),a={jid:e.id??(n?`cone_${t()}`:`scoop_${r}_${t()}`),name:e.name,folder:r,requiresTrigger:!n,assistantLabel:n?`sliccy`:r,addedAt:new Date(t()).toISOString(),parentJid:e.parentId,...i?{config:i,configSchemaVersion:3}:{},...e.notifyOnComplete===!1?{notifyOnComplete:!1}:{},...!n&&e.onParentClose===`detach`?{onParentClose:`detach`}:{}};return n||(a.trigger=`@${r}`),a}function Ey(e,t){let n=bn(e.workspace?.mode??e.config?.workspaceMode),r=e.workspace?.from??`/workspace`,i=qn(n,t,{root:r},e.workspace?.from),a=e.config;return{...a,workspaceMode:n,visiblePaths:a?.visiblePaths===void 0?i.visiblePaths:a.visiblePaths,writablePaths:a?.writablePaths===void 0?i.writablePaths:a.writablePaths}}function Dy(e,t){if(e.parentId===null||e.workspace?.from!==void 0)return e;let n=t.getScoop(e.parentId);return n?{...e,workspace:{mode:e.workspace?.mode??e.config?.workspaceMode??`shared-readonly`,from:nr(n).root}}:e}var Oy=class{host;constructor(e){this.host=e}async create(e){e.parentId===null&&e.workspace?.mode!==void 0&&bn(e.workspace.mode);let t=Ty(Dy(e,this.host));if(Ny(t.jid,e=>this.host.getScoop(e)),e.parentId!==null){let n=this.host.getScoop(e.parentId);if(!n)throw Error(`Parent work unit not found: ${e.parentId}`);On(t,n)}return await this.host.registerScoop(t),this.get(t.jid).descriptor}async createMany(e){if(e.length===0)return[];Py(e,e=>this.host.getScoop(e),()=>this.host.getScoops());let t=My(e);for(let e of t)e.id&&Ny(e.id,e=>this.host.getScoop(e));let n=Iy(t),r=[],i=new Map;try{for(let e of n){let t=await this.create(e);r.push(t.id),i.set(e,t)}}catch(e){for(let e=r.length-1;e>=0;e--)await this.close(r[e]).catch(()=>void 0);throw e}return t.map(e=>i.get(e))}async join(e,t){return(await this.host.waitForScoops(e,t?.timeoutMs)).map(e=>({id:e.jid,summary:e.summary,timedOut:e.timedOut}))}list(){return this.host.getScoops().map(e=>this.get(e.jid).descriptor)}get(e){return this.host.getScoop(e)?this.host.ensureLiveUnit(e):null}getParent(e){let t=this.host.getScoop(e)?.parentJid;return t?this.get(t):null}getChildren(e){return Kn(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return A(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=new Set,n=this.host.getScoop(e);for(;n&&n.parentJid!==null;){if(t.has(n.jid))return null;t.add(n.jid),n=this.host.getScoop(n.parentJid)}return n?this.get(n.jid):null}abort(e,t){let n=this.get(e);return n?n.abort(t):Promise.resolve()}async promote(e){let t=this.host.getScoop(e);if(!t)throw Error(`Work unit not found: ${e}`);if(t.parentJid===null)return this.get(e).descriptor;let n=yr(t),r=Ay(t,t.parentJid);t.parentJid=null,Un(t);try{await this.host.persistScoop(t)}catch(e){throw jy(t,r),e}return await this.host.rekeyConversation?.(n,{key:yr(t),workUnitId:t.jid,workspaceId:vr(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:Ln(t)}}),await this.host.reinitLiveUnit(e),this.get(e).descriptor}detach(e){return this.promote(e)}async close(e,t){let n=this.get(e);if(!n)return;let r=this.getChildren(e);for(let e of r)ky(e,t)===`detach`?await this.promote(e.descriptor.id):await this.close(e.descriptor.id,t);await n.close()}};function ky(e,t){return t?.descendants??e.descriptor.onParentClose}function Ay(e,t){return{parentJid:t,trigger:e.trigger,requiresTrigger:e.requiresTrigger,approvesGuestRequests:e.approvesGuestRequests,onParentClose:e.onParentClose}}function jy(e,t){e.parentJid=t.parentJid,e.trigger=t.trigger,e.requiresTrigger=t.requiresTrigger,e.approvesGuestRequests=t.approvesGuestRequests,e.onParentClose=t.onParentClose}function My(e){let t=Date.now();return e.map(e=>{if(e.id)return e;let n=e.folder??e.name,r=e.parentId===null?`cone_${t++}`:`scoop_${n}_${t++}`;return{...e,id:r}})}function Ny(e,t){if(t(e))throw Error(`Work unit already exists: ${e}`)}function Py(e,t,n){let r=new Set;for(let n of e)if(n.id){if(r.has(n.id))throw Error(`Duplicate work unit id in createMany: ${n.id}`);Ny(n.id,t),r.add(n.id)}Fy(e,n);let i=[],a=new Set;for(let n of e)n.parentId!==null&&(t(n.parentId)||r.has(n.parentId)||a.has(n.parentId)||(a.add(n.parentId),i.push(n.parentId)));if(i.length>0)throw Error(`Parent work unit not found: ${i.join(`, `)}`)}function Fy(e,t){let n=new Set(t().map(e=>e.folder)),r=new Set;for(let t of e){let e=t.folder??t.name;if(r.has(e)||n.has(e))throw Error(`Duplicate work unit folder in createMany: ${e}`);r.add(e)}}function Iy(e){let t=e.length;if(t<=1)return e.slice();let n=new Map;for(let r=0;r<t;r++){let t=e[r].id;t&&n.set(t,r)}let r=Array(t).fill(0),i=Array.from({length:t},()=>[]);for(let a=0;a<t;a++){let t=e[a].parentId;if(t===null)continue;let o=n.get(t);o!==void 0&&(i[o].push(a),r[a]+=1)}let a=[];for(let e=0;e<t;e++)r[e]===0&&a.push(e);let o=[];for(let t=0;t<a.length;t++){let n=a[t];o.push(e[n]);for(let e of i[n])--r[e],r[e]===0&&a.push(e)}if(o.length!==t)throw Error(`createMany cycle: parentId edges in this batch form a cycle`);return o}const Ly=y(`kernel-agent-event-stream`);var Ry=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){Ly.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${zy()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=e.displayScoopJid?`tool-ui-${e.requestId??``}`:i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=e.displayScoopJid?`tool-ui-${e.requestId??``}`:this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function zy(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var By=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Vy(e);return{jid:e.jid,name:e.name,folder:e.folder,parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=A(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Vy(e){let t=An(e),n=Fn(e),{level:r,effortOverride:i}=Pn(e);if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{modelProviderId:n},...r===void 0?{}:{thinkingLevel:r},...i===void 0?{}:{effortOverride:i}}}const G={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Hy=null;function Uy(e){if(!e.objectStoreNames.contains(G.MESSAGES)){let t=e.createObjectStore(G.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(G.SESSIONS)||e.createObjectStore(G.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(G.TASKS)||e.createObjectStore(G.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(G.STATE)||e.createObjectStore(G.STATE,{keyPath:`key`})}function Wy(e,t){let n=e.isMain??!1;return{jid:e.jid,name:e.name,folder:e.folder,trigger:n?void 0:e.trigger||`@${e.folder}`,requiresTrigger:!n&&(e.requiresTrigger??!0),parentJid:n?null:t??null,assistantLabel:n?`sliccy`:e.config?.assistantName||e.folder,addedAt:e.addedAt,config:e.config?{systemPromptAppend:e.config.systemPromptAppend,timeout:e.config.timeout,assistantName:e.config.assistantName}:void 0}}function Gy(e,t){if(t.objectStoreNames.contains(`groups`)){let n=e.target.transaction.objectStore(`groups`).getAll();n.onsuccess=()=>{let e=n.result;t.deleteObjectStore(`groups`);let r=t.createObjectStore(G.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);let i=e.find(e=>e.isMain)?.jid;for(let t of e)r.put(Wy(t,i))};return}t.objectStoreNames.contains(G.SCOOPS)||t.createObjectStore(G.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function Ky(e){e.objectStoreNames.contains(G.WEBHOOKS)||e.createObjectStore(G.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(G.CRONTASKS)||e.createObjectStore(G.CRONTASKS,{keyPath:`id`})}function qy(e){let t=e.target.result,n=e.oldVersion;n<1&&Uy(t),n<2&&Gy(e,t),n<3&&Ky(t)}function Jy(){if(!Hy)return null;let e=Object.values(G).every(e=>Hy.objectStoreNames.contains(e));return Hy.version===3&&e?Hy:(Hy.close(),Hy=null,null)}function Yy(e){e.onversionchange=()=>{e.close(),Hy===e&&(Hy=null)},e.onclose=()=>{Hy===e&&(Hy=null)}}async function Xy(){return Jy()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=qy,n.onsuccess=()=>{let t=n.result;Yy(t),Hy=t,e(t)},n.onerror=()=>t(n.error)})}async function K(e,t=`readonly`){return(await Xy()).transaction(e,t).objectStore(e)}async function Zy(e){let t=await K(G.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Qy(){let e=await K(G.SCOOPS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>{let e={};for(let t of r.result)e[t.jid]=t;t(e)},r.onerror=()=>n(r.error)})}async function $y(e){let t=await K(G.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function eb(){let e=await K(G.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function tb(e){let t=(await K(G.MESSAGES,`readwrite`)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,``],!1,!1);return new Promise((e,r)=>{let i=t.openCursor(n);i.onsuccess=()=>{let t=i.result;if(!t){e();return}t.delete(),t.continue()},i.onerror=()=>r(i.error)})}async function nb(e){let t=await K(G.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function rb(e){let t=await K(G.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ib(e){let t=(await K(G.MESSAGES)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,``],!1,!1);return new Promise((e,r)=>{let i=t.getAll(n);i.onsuccess=()=>e(i.result),i.onerror=()=>r(i.error)})}const ab=`wm1:`;function ob(e){if(!e)return{ts:``,ids:new Set};if(e.startsWith(ab))try{let t=JSON.parse(e.slice(4));return{ts:t.ts,ids:new Set(t.ids)}}catch{}return{ts:e,ids:null}}function sb(e){let t=e.ids?Array.from(e.ids):[];return`${ab}${JSON.stringify({ts:e.ts,ids:t})}`}function cb(e,t){return e.timestamp>t.ts?!0:e.timestamp<t.ts||t.ids===null?!1:!t.ids.has(e.id)}function lb(e,t){if(t.length===0)return e;let n=e.ts;for(let e of t)e.timestamp>n&&(n=e.timestamp);let r=new Set;if(e.ts===n&&e.ids)for(let t of e.ids)r.add(t);for(let e of t)e.timestamp===n&&r.add(e.id);return{ts:n,ids:r}}async function ub(e,t,n){let r=(await K(G.MESSAGES)).index(`chatJid_timestamp`),i=ob(t),a=IDBKeyRange.bound([e,i.ts],[e,``],!1,!1);return new Promise((e,t)=>{let o=r.getAll(a);o.onsuccess=()=>{let t=o.result.filter(e=>cb(e,i));n&&(t=t.filter(e=>e.senderName!==n)),e(t)},o.onerror=()=>t(o.error)})}async function db(e){let t=await K(G.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function fb(e){let t=await K(G.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function pb(){let e=await K(G.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function mb(e){let t=await K(G.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function hb(e){let t=await K(G.STATE);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result?.value??null),i.onerror=()=>r(i.error)})}async function gb(e,t){let n=await K(G.STATE,`readwrite`);return new Promise((r,i)=>{let a=n.put({key:e,value:t});a.onsuccess=()=>r(),a.onerror=()=>i(a.error)})}async function _b(){await Xy()}async function vb(e){let t=await K(G.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function yb(e){let t=await K(G.WEBHOOKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function bb(){try{let e=await K(G.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function xb(e){let t=await K(G.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Sb(e){let t=await K(G.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Cb(e){let t=await K(G.CRONTASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function wb(){try{let e=await K(G.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Tb(e){let t=await K(G.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}y(`tray-leader`);function Eb(){return Db(xr(),r())}function Db(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const Ob=`__slicc_binary__`;function kb(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Ob]===`b64`&&typeof t.data==`string`}function Ab(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function jb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)&&!kb(e)}function Mb(e){if(e instanceof Uint8Array)return{[Ob]:`b64`,data:ce(e)};if(Array.isArray(e))return e.map(Mb);if(Ab(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Mb(r);return t}return e}function Nb(e){if(kb(e))return le(e.data);if(Array.isArray(e))return e.map(Nb);if(jb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Nb(r);return t}return e}const Pb=y(`panel-transport`);function Fb(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Ib(){return{onMessage:e=>{let t=(t,n,r)=>(Fb(t)&&e(Nb(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Mb(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||Pb.error(`Offscreen → panel transport send failed`,{error:t})})}}}const Lb=y(`kernel-bridge`);function Rb(){return globalThis}function zb(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var Bb=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;conesBeingCreated=new Map;currentMessageId=new Map;compactionRows=new $v(e=>`compaction-${e}-${Vb()}`);pendingMarkers=new Map;scoopPresentation=new By;agentEventStream=new Ry;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=Ib(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Zv;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.flushPendingMarkers(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Vb()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&(e.currentMessageId.delete(t),e.flushPendingMarkers(t)),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n,r)=>{let i=e.compactionRows.apply(t,n,r);e.emit({type:`compaction-state`,scoopJid:t,state:n,trigger:r.trigger,...r.transcriptPath?{transcriptPath:r.transcriptPath}:{},...r.roundId?{roundId:r.roundId}:{},...i?{rowId:i.messageId}:{}}),e.recordCompactionRow(t,i)},onError:(t,n)=>{e.recordErrorCard(t,n),e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r,i)=>{z_.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{z_.has(n)||e.bufferToolEnd(t,n,r,i,a)},onToolUI:(t,n,r,i,a)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i,...a?{displayScoopJid:a}:{}})},onToolUIDone:(t,n,r)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n,...r?{displayScoopJid:r}:{}})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=H_(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??Vb(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=U_(n),e.isError=r)}}this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:W_(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(Ln(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],Eb())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...Eb()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=zb(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=ne(e),s=[];n&&s.push({source:`explicit target`,value:n}),o&&o!==n&&s.push({source:`configured route`,value:o});let c=[],l;for(let e of s){if(l=Ua(a,e.value),l)break;c.push(e)}if(l||=this.originRootOf(a,r?.unitJid)??A(a)[0],c.length>0&&Lb.warn(`Sprinkle lick target could not be resolved; using fallback`,{sprinkleName:e,unresolvedTargets:c,fallbackJid:l?.jid}),!l)return;let u=`sprinkle-${e}-${Date.now()}`,d=wy({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r?.label})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,f=c.map(({source:e,value:t})=>`${e} ${JSON.stringify(t)}`).join(` and `),p=d+(f?`\n\n> Delivery note: ${f} could not be resolved; delivered to fallback ${JSON.stringify(l.folder)}.`:``),m={id:u,chatJid:l.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:p,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(l.jid).push({id:u,role:`user`,content:p,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),await this.orchestrator.handleMessage(m)}originRootOf(e,t){if(t)return Dn(e,e.find(e=>e.jid===t))}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=A(this.orchestrator.getScoops())[0];if(!t)return;let n=Ub(e).map((t,n)=>({...t,isStreaming:e[n]?.isStreaming}));this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?A(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromCanonicalRecord(e){let t=this.orchestrator?.getConversationStore?.();if(!t)return null;let{conversationKeyFor:n}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),r=await t.load(n(e));if(!r)return null;let{toChatMessages:i}=await Promise.resolve().then(()=>yC),a=await i(r,{source:In(e)});return a.length===0?null:this.overlayPersistedLickDecisionsOn(e,Ub(a))}async overlayPersistedLickDecisionsOn(e,t){if(!t.some(e=>e.channel===`sudo-request`||e.lickId||e.lickState))return t;let n=[];try{let t=await this.orchestrator?.getMessagesForScoop?.(e.jid);if(t)for(let e of t)n.push({id:e.id,content:e.content,channel:e.channel,lickId:e.lickId,lickState:e.lickState})}catch{}return Jb(t,n)}async hydrateBuffersFromRecords(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromCanonicalRecord(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid))}}queuedIdsFor(e){if(!(this.followerSync||!this.orchestrator))return this.orchestrator.getQueuedMessageIds(e)}async handleRequestScoopMessages(e){if(await this.conesBeingCreated.get(e),!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n,queuedIds:this.queuedIdsFor(e)});return}let r=await this.buildBufferFromCanonicalRecord(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r,queuedIds:this.queuedIdsFor(e)});return}this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:[],queuedIds:this.queuedIdsFor(e)})}async handleConeCreate(e,t,n,r){if(!this.orchestrator)return;let i=this.orchestrator.getScoops(),a=Bn(e,i),o=a===Hn,s=A(i)[0],c=r??(s?Vn(s):void 0),l=t?.trim(),u={...Ty({parentId:null,name:e,folder:a}),assistantLabel:o?`sliccy`:e,...l?{config:{systemPromptAppend:`This cone is for: ${l}`}}:{},...c?{model:c}:{}},d=()=>{};this.conesBeingCreated.set(u.jid,new Promise(e=>{d=e}));let f=()=>{this.conesBeingCreated.delete(u.jid),d()};try{await this.orchestrator.registerScoop(u),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(u)});let e=n?.trim();if(!e)return;let t=this.handleUserMessage({type:`user-message`,scoopJid:u.jid,text:e,messageId:`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});f(),await t}finally{f()}}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=t.approver;if(r&&r.kind!==`user`){let i=this.orchestrator;if(!i)console.warn(`[kernel-bridge] directed approval before orchestrator init — denying`);else try{n=await i.enqueueDirectedApproval(r,t)}catch(e){console.warn(`[kernel-bridge] directed approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n});return}let i=this.orchestrator?.getSudoManager()??null;if(!i)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await i.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}async handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}let o=await this.resolveBudgetWindow();this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a,...o?{budget:o}:{}})}budgetProbePending=!0;async resolveBudgetWindow(){return this.budgetProbePending?(this.budgetProbePending=!1,await Promise.race([N_().catch(()=>null),new Promise(e=>setTimeout(()=>e(null),2500))])??void 0):(N_().catch(()=>null),M_()??void 0)}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Hb(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await Promise.resolve().then(()=>K_),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:In(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Hb(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromCanonicalRecord(r);if(a){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}n()}async recordCompactionRow(e,t){if(!t||t.kind===`open`)return;let n=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n)return;let r=this.getBuffer(e);if(t.kind===`retract`){let e=r.findIndex(e=>e.id===t.messageId);e>=0&&r.splice(e,1)}else{let e=r.find(e=>e.id===t.messageId);e?e.compaction=t.marker:r.push({id:t.messageId,role:`assistant`,content:``,timestamp:Date.now(),compaction:t.marker})}let i=this.orchestrator?.getConversationStore?.();if(!i)return;let{conversationKeyFor:a}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),o=a(n);if(t.kind===`retract`){this.dropPendingMarker(e,t.messageId),await i.deleteMarker(o,t.messageId);return}let s={id:t.messageId,kind:`compaction`,timestamp:Date.now(),compaction:t.marker};await i.putMarker(o,s)||this.holdPendingMarker(e,s)}holdPendingMarker(e,t){let n=this.pendingMarkers.get(e)??[];this.pendingMarkers.set(e,[...n.filter(e=>e.id!==t.id),t].slice(-4))}dropPendingMarker(e,t){let n=this.pendingMarkers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,r)}async flushPendingMarkers(e){let t=this.pendingMarkers.get(e);if(!t||t.length===0)return;let n=this.orchestrator?.getConversationStore?.(),r=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n||!r)return;let{conversationKeyFor:i}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),a=i(r),o=[];for(let e of t)await n.putMarker(a,e)||o.push(e);o.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,o)}async recordErrorCard(e,t){let n=Vb(),r=Date.now();this.getBuffer(e).push({id:n,role:`assistant`,content:t,timestamp:r,error:!0});let i=this.orchestrator?.getConversationStore?.(),a=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!i||!a)return;let{conversationIdentityFor:o}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),s=o(a),c={id:n,kind:`error`,timestamp:r,text:t};await i.putMarker(s.key,c,{createWith:s})||this.holdPendingMarker(e,c)}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${Vb()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?In(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{e.source===`panel`&&this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name,e.description,e.prompt,e.model);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId,e.scoopJid,e.discardLiveSnapshot===!0);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`set-model`:case`refresh-model`:this.orchestrator.refreshModels();break;case`set-scoop-model`:await this.handleSetScoopModel(e);break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.handleWebhookEventMsg(e);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value)),ba(e.key);break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key)),ba(e.key);break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear()),ba()}}handleWebhookEventMsg(e){let t=this.orchestrator?.handleWebhookEvent(e.webhookId,e.headers,e.body);e.requestId&&this.emit({type:`lick-webhook-delivery`,requestId:e.requestId,disposition:t??`unknown-webhook`})}async handleAgentSpawn(e){let t=Rb()[hv];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetScoopModel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopModel(e.scoopJid,e.model)}catch(e){console.error(`[kernel-bridge] set-scoop-model failed:`,e)}e.requestId&&this.emit({type:`set-scoop-model-ack`,requestId:e.requestId,scoopJid:e.scoopJid,model:e.model,applied:t})}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&this.messageBuffers.set(e,r)}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.guestGate?{guestGate:e.guestGate}:{},...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&wn(n)){if(A(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);let i=new Set(this.orchestrator.getScoops().map(e=>e.jid));for(let e of[...r,n])i.has(e.jid)||this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=Ln({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e,t,n=!1){let r=this.orchestrator?.getScoops()??[],i=(t?r.find(e=>e.jid===t):void 0)??A(r)[0],a=i?.jid;a&&(n?await this.orchestrator?.clearScoopMessages(a,{discardLiveSnapshot:!0}):await this.orchestrator?.clearScoopMessages(a)),this.sessionStore&&await this.sessionStore.delete(Ln({folder:i?.folder??`cone`})),a&&(this.messageBuffers.delete(a),this.currentMessageId.delete(a),this.agentEventStream.clear(a)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.origin)}handleSetFollowerForwarding(e){let t=Rb().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=Rb().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){on.markMounted(t);return}try{await on.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),on.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function Vb(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Hb(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
897
|
+
`)}function Ub(e){return e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,lickId:e.lickId,lickState:e.lickState,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1,compaction:e.compaction,error:e.error}))}function Wb(e){return e===`confirmed`||e===`dismissed`}function Gb(e){return e.channel===`sudo-request`||!!e.lickId||!!e.lickState||e.id.startsWith(`sudo-request-`)}function Kb(e){return e.lickId?e.lickId:Gb(e)?/^(?:Lick ID|Request ID): (\S+)/m.exec(e.content)?.[1]||(e.id.startsWith(`sudo-request-`)?e.id.slice(13):void 0):void 0}function qb(e,t,n){let r=e.get(t);(!r||Wb(n.lickState)&&!Wb(r.lickState))&&e.set(t,n)}function Jb(e,t){if(!t||t.length===0)return e;let n=new Map,r=new Map,i=new Map;for(let e of t){if(!Gb(e))continue;let t=Kb(e);t&&qb(n,t,e),qb(r,e.id,e),qb(i,e.content,e)}return e.map(e=>{if(!Gb(e))return e;let t=Kb(e),a=(t?n.get(t):void 0)??r.get(e.id)??i.get(e.content);if(!a||!a.lickId&&!a.lickState)return e;let o=a.lickId??t??Kb(a),s=Wb(a.lickState)?a.lickState:e.lickState??a.lickState;return o===e.lickId&&s===e.lickState&&a.id===e.id?e:{...e,id:a.id,lickId:o,lickState:s}})}const Yb=y(`navigation-watcher`);function Xb(e){if(!e)return null;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:null}catch{return null}}function Zb(e){return e.replace(/\/+$/,``)||`/`}function Qb(e){return t=>{let n=Xb(e()??void 0);if(!n)return!1;let r=Xb(t.url);return r?n.origin===r.origin&&Zb(n.pathname)===Zb(r.pathname):!1}}function $b(e,t){return de(e,t)}var ex=class{transport;onEvent;sessions=new Map;started=!1;unsubscribeState=null;rearming=!1;rearmQueued=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;isOwnTab;probedOrigins=new Set;pendingAttachTargetIds=new Set;ownSessionIds=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);this.sessions.delete(t),this.ownSessionIds.delete(t),n&&this.pendingAttachTargetIds.delete(n.targetId)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId){for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url));this.reconcileTargetNetwork(t)}};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameRequestedNavigation=e=>{let t=e;this.maybeArmNetwork(t.sessionId,t.frameId,t.url)};onFrameStartedNavigating=e=>{let t=e;this.maybeArmNetwork(t.sessionId,t.frameId,t.url)};onFrameNavigated=e=>{let t=e,n=t.sessionId;if(!n)return;let r=this.sessions.get(n);if(!r)return;let i=t.frame;i?.id&&(i.parentId||(r.rootFrameId=i.id,typeof i.url==`string`&&(r.url=i.url)))};onResponseReceived=e=>{let t=e,n=t.sessionId;if(!n)return;let r=this.sessions.get(n);if(!r||t.type!==`Document`)return;let i=t.frameId;if(!i||i!==r.rootFrameId)return;let a=t.response;if(!a)return;let o=typeof a.url==`string`&&a.url.length>0?a.url:r.url;if(!o)return;let{match:s,links:c}=$b(a.headers,o);if(s){let e={url:o,verb:s.verb,target:s.target,links:c,targetId:r.targetId};s.instruction!=null&&(e.instruction=s.instruction),s.branch!=null&&(e.branch=s.branch),s.path!=null&&(e.path=s.path),r.title!=null&&(e.title=r.title),this.onEvent(e)}this.maybeRunDiscovery(o,c,r.targetId)};eventBindings=[[`Target.attachedToTarget`,this.onAttachedToTarget],[`Target.detachedFromTarget`,this.onDetachedFromTarget],[`Target.targetInfoChanged`,this.onTargetInfoChanged],[`Target.targetCreated`,this.onTargetCreated],[`Page.frameNavigated`,this.onFrameNavigated],[`Page.frameRequestedNavigation`,this.onFrameRequestedNavigation],[`Page.frameStartedNavigating`,this.onFrameStartedNavigating],[`Network.responseReceived`,this.onResponseReceived]];constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs,this.isOwnTab=n.isOwnTab??(()=>!1)}maybeRunDiscovery(e,t,n){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let r;try{r=new URL(e).origin}catch{return}let i=Na(t);i&&this.onDiscovery({origin:r,kind:i.kind,url:i.url,targetId:n}),this.probeFetch&&!this.probedOrigins.has(r)&&(this.probedOrigins.add(r),this.runWellKnownProbe(r,n))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await Ia(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){Yb.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){if(this.registerListeners(),!await this.enableDiscovery()){this.unregisterListeners();return}this.started=!0,this.subscribeTransportState(),await this.enumeratePreexistingTargets()}}registerListeners(){for(let[e,t]of this.eventBindings)this.transport.off(e,t),this.transport.on(e,t)}unregisterListeners(){for(let[e,t]of this.eventBindings)this.transport.off(e,t)}async enableDiscovery(){try{return await this.transport.send(`Target.setDiscoverTargets`,{discover:!0}),!0}catch(e){return Yb.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),!1}}async enumeratePreexistingTargets(){try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;e||typeof n!=`string`||await this.requestAttach(n,`Failed to attach to preexisting target`)}}catch(e){Yb.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}subscribeTransportState(){this.unsubscribeState||=this.transport.onStateChange?.(e=>{if(e===`disconnected`){this.clearConnectionScopedState();return}e===`connected`&&(this.rearming?this.rearmQueued=!0:this.rearmAfterReconnect())})??null}clearConnectionScopedState(){this.sessions.clear(),this.pendingAttachTargetIds.clear(),this.ownSessionIds.clear()}async rearmAfterReconnect(){if(!(!this.started||this.rearming)){this.rearming=!0;try{if(this.clearConnectionScopedState(),this.registerListeners(),!await this.enableDiscovery())return;await this.enumeratePreexistingTargets()}finally{this.rearming=!1,this.rearmQueued&&(this.rearmQueued=!1,this.rearmAfterReconnect())}}}async stop(){if(this.started){this.started=!1,this.unsubscribeState?.(),this.unsubscribeState=null,this.unregisterListeners(),this.clearConnectionScopedState();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){Yb.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;t?.type===`page`&&typeof t.targetId==`string`&&(t.attached||await this.requestAttach(t.targetId,`Failed to attach to discovered target`))}maybeArmNetwork(e,t,n){if(!e||!t)return;let r=this.sessions.get(e);!r||r.networkEnabled||!this.ownSessionIds.has(e)||r.rootFrameId===t&&(this.isOwnTabSafe({targetId:r.targetId,url:n})||this.setSessionNetwork(e,r,!0))}reconcileTargetNetwork(e){let t=this.isOwnTabSafe(e);for(let[n,r]of this.sessions)r.targetId===e.targetId&&this.ownSessionIds.has(n)&&r.networkEnabled!==!t&&this.setSessionNetwork(n,r,!t)}async setSessionNetwork(e,t,n){t.networkEnabled=n;try{await this.transport.send(n?`Network.enable`:`Network.disable`,{},e)}catch(r){t.networkEnabled=!n,Yb.debug(`Failed to ${n?`enable`:`disable`} Network on session`,{sessionId:e,targetId:t.targetId,error:r instanceof Error?r.message:String(r)})}}isOwnTabSafe(e){try{return this.isOwnTab(e)}catch(t){return Yb.debug(`isOwnTab predicate threw; treating target as foreign`,{targetId:e.targetId,error:t instanceof Error?t.message:String(t)}),!1}}async requestAttach(e,t){this.pendingAttachTargetIds.add(e);try{let t=(await this.transport.send(`Target.attachToTarget`,{targetId:e,flatten:!0}))?.sessionId;typeof t==`string`&&t.length>0&&(this.ownSessionIds.add(t),this.pendingAttachTargetIds.delete(e))}catch(n){this.pendingAttachTargetIds.delete(e),Yb.debug(t,{targetId:e,error:n instanceof Error?n.message:String(n)})}}claimOwnSession(e,t){return this.ownSessionIds.has(e)?!0:this.pendingAttachTargetIds.has(t)?(this.pendingAttachTargetIds.delete(t),this.ownSessionIds.add(e),!0):!1}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!t||!n||n.type!==`page`||typeof n.targetId!=`string`||(this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,networkEnabled:!1,title:n.title,url:n.url}),!this.claimOwnSession(t,n.targetId)))return;let r=this.isOwnTabSafe(n);r&&Yb.debug(`Attaching to the SLICC app tab with Network off`,{targetId:n.targetId,url:n.url});try{if(await this.transport.send(`Page.enable`,{},t),!r){let e=this.sessions.get(t);e&&await this.setSessionNetwork(t,e,!0)}let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){Yb.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}};function tx(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var nx=`# /etc/llmstxtignore — llms.txt discovery suppression
|
|
898
898
|
#
|
|
899
899
|
# One advertising hostname or glob per line. Matching is case-insensitive.
|
|
900
900
|
# \`#\` starts a comment; blank lines are ignored.
|
|
@@ -905,10 +905,10 @@ This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`c
|
|
|
905
905
|
|
|
906
906
|
github.com
|
|
907
907
|
app.slack.com
|
|
908
|
-
`;const
|
|
909
|
-
`)||n.includes(`\r`)||n.includes(`#`))throw Error(`Invalid llms.txt ignore hostname.`);let r=``;try{r=await e.readFile(
|
|
908
|
+
`;const rx=y(`llms-txt-ignore`),ix=`/etc/llmstxtignore`;function ax(e){return typeof e==`string`?e.split(/\r?\n/).map(e=>e.slice(0,e.indexOf(`#`)===-1?void 0:e.indexOf(`#`)).trim()).filter(Boolean).map(e=>e.toLowerCase()):[]}function ox(e){return`.+^$()[]|\\{}`.includes(e)?`\\${e}`:e}function sx(e){let t=``;for(let n of e)t+=n===`*`?`.*`:n===`?`?`.`:ox(n);return RegExp(`^${t}$`,`i`)}function cx(e,t){return t.some(t=>sx(t).test(e))}function lx(e){if(e.parentJid===null)return!0;let t=e.config?.allowedCommands;return t===void 0||t.includes(`*`)?!0:t.some(e=>[`curl`,`wget`,`discover`,`playwright-cli`,`playwright`,`puppeteer`].includes(e))}function ux(e,t){for(let n of[e,t])if(n)try{return new URL(n).hostname.toLowerCase()}catch{}return null}async function dx(e,t){let n=t.trim().toLowerCase();if(!n||n.includes(`
|
|
909
|
+
`)||n.includes(`\r`)||n.includes(`#`))throw Error(`Invalid llms.txt ignore hostname.`);let r=``;try{r=await e.readFile(ix,{encoding:`utf-8`})}catch(e){if(!(e instanceof j)||e.code!==`ENOENT`)throw e}if(cx(n,ax(r)))return!1;let i=r.length>0&&!r.endsWith(`
|
|
910
910
|
`)?`
|
|
911
|
-
`:``;return await e.writeFile(
|
|
911
|
+
`:``;return await e.writeFile(ix,`${r}${i}${n}\n`),!0}var fx=class{fs;watcher;entries=[];unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/llmstxtignore`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}ignores(e){if(e.type!==`discovery`||e.discoveryKind!==`llms-txt`)return!1;let t=ux(e.discoveryOrigin,e.discoveryUrl);return t!==null&&cx(t,this.entries)}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/llmstxtignore`)||await this.fs.writeFile(ix,nx)}catch(e){rx.warn(`Failed to seed default llms.txt ignore policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(ix,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);this.entries=ax(t)}catch(e){this.entries=[],rx.warn(`Failed to read llms.txt ignore policy`,{error:e instanceof Error?e.message:String(e)})}}},px=`# /etc/sudoers — SLICC agent approval policy
|
|
912
912
|
#
|
|
913
913
|
# This file controls which agent actions require a native human approval
|
|
914
914
|
# prompt (an OS dialog in CLI/Electron, a window.confirm/prompt in the Chrome
|
|
@@ -982,12 +982,12 @@ Write /etc/models
|
|
|
982
982
|
#
|
|
983
983
|
# Let connected followers export the live transcript without a prompt:
|
|
984
984
|
# NOPASSWD Export active
|
|
985
|
-
`;const
|
|
986
|
-
`);function
|
|
987
|
-
`)}\n`}var
|
|
988
|
-
`).some(e=>e.trim()===s))return
|
|
989
|
-
`)?o:`${o}\n`:
|
|
990
|
-
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(qr,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,gx,e=>{let t=new Set,n=!1,r=!1;for(let i of e){if(i.path===`/etc/sudoers.d`){r=!0;continue}let e=_x(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 Sx(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Cx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wx(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++)wx(e[r],`${t}/${r}`,n);return}if(Cx(e))for(let[r,i]of Object.entries(e))wx(i,`${t}/${Sx(r)}`,n)}function Tx(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=Tx(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(Cx(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=Tx(o,`${t}/${Sx(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function Ex(e,t,n){if(Cx(e))return Tx(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=Ex(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function Dx(e){let t=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 Ox(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new v(`redaction-unavailable`);let a=0,o=i;for(;o<e.length;){let t=e[o].length;if(o>i&&a+t>1048576)break;a+=t,o++}let s=e.slice(i,o),c;try{c=await t.redact(s,n)}catch{throw new v(`redaction-unavailable`)}if(c.length!==s.length)throw new v(`redaction-unavailable`);r.push(...c),i=o}return r}function kx(e,t,n,r){let i=[],a=Dx(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Dx(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}=Te(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 Ax(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 jx(e,t,r,i){if(i?.aborted)throw new v(`redaction-unavailable`);let{privacy:a,...o}=e,s=[];wx(o,``,s);let c=s.filter(e=>!n(e.pointer)),l=[...t.entries()],u=await Ox([...c.map(e=>e.value),...l.map(([,e])=>e)],r,i),d=[],f={},p=1,m=new Map,h=[];for(let e=0;e<c.length;e++){let t=c[e],n=kx(t.value,u[e],{kind:`json`,pointer:t.pointer},p);p=n.nextId,n.finalText!==t.value&&m.set(t.pointer,n.finalText),h.push(n)}Ax(h,d,f);let g=new Map,_=c.length,ee=[];for(let e=0;e<l.length;e++){let[t,n]=l[e],r=kx(n,u[_+e],{kind:`attachment`,attachmentId:t},p);p=r.nextId,g.set(t,r.finalText),ee.push(r)}Ax(ee,d,f);let te=Ex(e,``,m);return{document:{...te,privacy:{...te.privacy,redactionCounts:f,redactions:d}},textAttachments:g}}function Mx(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`}async function Nx(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const Px={"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 Fx(e,t){return Px[e]??(t===`text-redacted`?`.txt`:`.bin`)}function Ix(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${Fx(t,n)}`}function Lx(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 Rx(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 zx(e,t,n,r,i){let a=Mx(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(Lx(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=Lx(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 Bx(e,t,n,r){let i=[],a=new Set,o=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:Lx(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(zx(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function Vx(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 Hx(e,t,n,r,i,a,o){let s=Vx(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(zx(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function Ux(e,t,n,r,i){let a=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=Hx(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function Wx(e,t){let n=new Map,r=0,i=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,Ix(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 Gx(e,t,n,r,i){let{rawAttachments:a,textMap:o}=Wx(e,n),s,c;try{let e=await jx({...t,attachments:a},o,r,i);s=e.document,c=e.textAttachments}catch(e){throw e instanceof v?e:new v(`attachment-unreadable`)}let l=new Map;for(let t of e){if(l.has(t.attachmentId))throw new v(`schema-invalid`);l.set(t.attachmentId,t)}let u=new Map,d=await Promise.all(s.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=l.get(e.id);if(t===void 0)throw new v(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(c.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await Nx(n);return u.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...s,attachments:d},bundleFiles:u}}async function Kx(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??new Map,o=e.vfsReader,s=new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=Bx(Rx(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}=Ux(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],g=t;f.size>0&&(g={...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:_,bundleFiles:ee}=await Gx(h,g,s,r,i),te=[..._.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{..._,session:{..._.session,completeness:{status:te.length>0?`partial`:_.session.completeness.status,missing:te}}},bundleFiles:ee}}function qx(e){return Ln(e)}function Jx(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 Yx(e,t,n,r){let i=new Map;for(let e of t)i.set(e.id,e);let a=new Map;for(let e of n)a.set(e.id,e);let o=[],s=new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:wn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!wn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=qx(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function Xx(e,t,n={}){let r=e=>n.rootJid===void 0?e:Tn(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 v(`transfer-aborted`);let i=Jx(n,e),[a,o]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new v(`transfer-aborted`);let s=r(e.listScoops());if(i===Jx(s,e))return Yx(s,a,o,e)}}var Zx=e({SESSIONS_DIR:()=>Qx,SESSIONS_INDEX_PATH:()=>$x,parseFrozenArchive:()=>tS,readSessionsIndex:()=>eS});const Qx=`/sessions`,$x=`/sessions/index.json`;async function eS(e){try{let t=await e.readFile($x,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function tS(e){let t=e,n=`Untitled`,r={},i=t.match(/^---\n([\s\S]*?)\n---\n+/);if(i){t=t.slice(i[0].length),Object.assign(r,nS(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=rS(e[1]))}let a=t.match(/<!-- slicc:session-data\n([\s\S]*?)\n-->\n*/);if(a){try{let e=a[1].replace(/-- >/g,`-->`),t=JSON.parse(e);if(Array.isArray(t))return{title:n,messages:t,...r}}catch{}t=t.replace(/<!-- slicc:session-data\n[\s\S]*?\n-->\n*/,``)}return r.sidecar?{title:n,messages:[],...r}:(t=t.replace(/^#\s+[^\n]*\n+/,``),{title:n,messages:aS(t),...r})}function nS(e){let t={},n=iS(e,`cost`),r=iS(e,`models`);n&&(t.cost=n),r&&(t.models=r);let i=e.match(/^cone:\s*(.+?)\s*$/m)?.[1];i&&(t.cone=i);let a=e.match(/^coneLabel:\s*(.+?)\s*$/m)?.[1];a&&(t.coneLabel=rS(a)),/^memorySkipped:\s*true\s*$/m.test(e)&&(t.memorySkipped=!0),/^live:\s*true\s*$/m.test(e)&&(t.live=!0);let o=Number(e.match(/^liveThrough:\s*(\d+)\s*$/m)?.[1]);Number.isFinite(o)&&o>0&&(t.liveThrough=o);let s=Number(e.match(/^compactions:\s*(\d+)\s*$/m)?.[1]);Number.isFinite(s)&&s>0&&(t.compactions=s);let c=e.match(/^id:\s*(\S+)\s*$/m)?.[1];c&&(t.id=c);let l=e.match(/^sidecar:\s*(\S+)\s*$/m)?.[1];return l&&(t.sidecar=l),t}function rS(e){let t=e.trim();if(!t.startsWith(`"`))return t;try{let e=JSON.parse(t);if(typeof e==`string`)return e}catch{}return t.replace(/^"|"$/g,``)}function iS(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function aS(e){let t=[],n=/^## (User|Assistant)\s*\n/gm,r=[],i;for(;(i=n.exec(e))!==null;)r.push({role:i[1]===`User`?`user`:`assistant`,start:i.index,bodyStart:i.index+i[0].length});for(let n=0;n<r.length;n++){let i=n+1<r.length?r[n+1].start:e.length,a=e.slice(r[n].bodyStart,i).trim();t.push({id:`frozen-${n}`,role:r[n].role,content:a,timestamp:0})}return t}function oS(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function sS(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function cS(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(sS(t,r++));return n}function lS(e,t){let n=[],r=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=sS(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 uS(e,t){let n=[],r=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=sS(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 dS(e,t,n){let r=oS(t,n),i=cS(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:new Map}}function fS(e,t,n){let r=oS(t,n),{blocks:i,excluded:a,images:o}=lS(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 pS(e,t,n){let r=oS(t,n),{blocks:i,images:a}=uS(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 mS(e,t,n){return e.role===`user`?dS(e,t,n):e.role===`assistant`?fS(e,t,n):e.role===`toolResult`?pS(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function hS(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 gS(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=mS(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:hS(e),excludedReasoningBlocks:t,canonicalImages:n}}const _S=(()=>{let e=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 vS(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^_S[(t^e[n])&255];return~t>>>0}const yS=new TextEncoder;function K(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function bS(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 xS(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,K(r,4,20),K(r,6,2048),K(r,8,0),K(r,10,0),K(r,12,0),bS(r,14,n),bS(r,18,t),bS(r,22,t),K(r,26,e.length),K(r,28,0),r.set(e,30),r}function SS(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,K(i,4,20),K(i,6,20),K(i,8,2048),K(i,10,0),K(i,12,0),K(i,14,0),bS(i,16,n),bS(i,20,t),bS(i,24,t),K(i,28,e.length),K(i,30,0),K(i,32,0),K(i,34,0),K(i,36,0),bS(i,38,0),bS(i,42,r),i.set(e,46),i}function CS(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,K(r,4,0),K(r,6,0),K(r,8,e),K(r,10,e),bS(r,12,t),bS(r,16,n),K(r,20,0),r}function wS(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 TS(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${we(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*ES(e,t,n,r,i){if(n?.aborted)throw i(new v(`transfer-aborted`)),new v(`transfer-aborted`);let a=()=>i(new v(`transfer-aborted`));n?.addEventListener(`abort`,a,{once:!0});let o=Yr.create(),s=0,c=0,l=[],u=!1;function*d(e){o.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),a=yS.encode(`transcript.json`),f=vS(i),p=xS(a,i.length,f);if(l.push({nameBytes:a,size:i.length,crc:f,localOffset:c}),n?.aborted||(yield*d(p),n?.aborted))throw new v(`transfer-aborted`);yield*d(i);for(let[e,r]of t){if(n?.aborted)throw new v(`transfer-aborted`);let t=yS.encode(e),i=vS(r),a=xS(t,r.length,i);if(l.push({nameBytes:t,size:r.length,crc:i,localOffset:c}),yield*d(a),n?.aborted)throw new v(`transfer-aborted`);yield*d(r)}let m=c;for(let e of l){if(n?.aborted)throw new v(`transfer-aborted`);yield*d(SS(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new v(`transfer-aborted`);yield*d(CS(l.length,c-m,m)),u=!0,r({byteLength:s,sha256:o.hex()})}catch(e){throw u=!0,i(e),e}finally{n?.removeEventListener(`abort`,a),u||(u=!0,i(new v(`transfer-aborted`)))}}function DS(e,t,n){for(let e of t.keys())if(!wS(e))throw new v(`schema-invalid`);if(t.size+1>65535)throw new v(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new v(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return{filename:TS(e),chunks:ES(e,t,n,r,i),completion:a}}function OS(e,t,n,r,i,o={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:a},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...o},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function kS(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 AS(e){let n=t(e);if(!n.ok)throw new v(`schema-invalid`,n.error)}function jS(e,t,n){let r=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 MS(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);if(!n)return e;let r=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=await crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``);return{...e,byteLength:n.length,sha256:a}}))}function NS(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 PS=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),AS(i.document),r?.({phase:`packaging`}),DS(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await Xx(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=gS(n.sources),{document:i,bundleFiles:a}=await Kx({document:OS(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});AS(i),await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a})}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await Xx(this.deps.collection,e),r=gS(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=OS(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),Kx({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=await this.deps.snapshotStore.read(e);return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=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 jx(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new v(`redaction-unavailable`)}let a=jS(r.attachments,i,e.attachments),o=await MS(r.attachments,a);return{document:{...r,attachments:o},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await eS(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new v(`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 v(`session-not-found`)}let{loadFrozenArchive:o}=await import(`./session-jsonl-C7a0swa5.js`),{title:s,messages:c}=await o(this.deps.vfs,i,r.filename),l=`legacy-cone`,u=kS(c,l),d=NS(i),f={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:a},session:{id:e,title:s,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...d,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:l,kind:`cone`,name:s,messages:u}],delegations:[],attachments:[]},p=new Map([[l,c]]);return n?.({phase:`redacting`}),Kx({document:f,chatMessagesByConversation:p,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 v(`attachment-unreadable`);return t}};const FS=`/sessions/data`,IS=`document.json`;async function LS(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function RS(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new v(`session-not-found`)}function zS(e){return`${FS}/${e}`}function BS(e){return`${FS}/.tmp-${e}`}async function VS(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function HS(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 HS(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function US(e,t,n){await VS(e,n);let r=await e.readDir(t);for(let i of r){let r=`${t}/${i.name}`,a=`${n}/${i.name}`;if(i.type===`directory`)await US(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function WS(e,t,n){RS(t);let r=BS(t),i=zS(t),a=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!a.has(e))throw new v(`schema-invalid`);await HS(e,i),await VS(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await LS(r),i=a.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let o={...n.document,attachments:t},s=JSON.stringify(o,null,2);if(await e.writeFile(`${r}/${IS}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await VS(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await US(e,r,i),await e.flush()}catch(t){throw await HS(e,r),t}await HS(e,r)}async function GS(e,n){RS(n);let r=zS(n),i=`${r}/${IS}`,a;try{let t=await e.readFile(i,{encoding:`utf-8`});a=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new v(`session-not-found`)}let o;try{o=JSON.parse(a)}catch{throw new v(`schema-invalid`)}if(!t(o).ok)throw new v(`schema-invalid`);let s=new Map;for(let t of o.attachments){if(!t.present||!t.path)continue;let n=`${r}/${t.path}`,i;try{let t=await e.readFile(n,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new v(`transfer-corrupt`)}if(await LS(i)!==t.sha256)throw new v(`transfer-corrupt`);s.set(t.path,i)}return{document:o,attachments:s}}function KS(e){return`error`in e}function qS(){throw new v(`redaction-unavailable`)}function JS(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&qS(),e.texts}function YS(){return{async redact(e){let t;try{t=await fetch(Ae(`/api/secrets/redact-export`),{method:`POST`,headers:Me({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{qS()}t.ok||qS();let n;try{n=await t.json()}catch{qS()}return JS(n,e.length)}}}function XS(){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{qS()}return typeof t==`object`&&t&&KS(t)&&qS(),JS(t,e.length)}}}function ZS(){return{async redact(e){let t;try{t=await pn(`secrets.redact-export`,{texts:e})}catch{qS()}return t??qS(),typeof t==`object`&&t&&KS(t)&&qS(),JS(t,e.length)}}}function QS(){return{async redact(e){qS()}}}function $S(){let e=cn();return e===`connect`?QS():e===`extension-direct`?XS():e===`extension-delegate`?ZS():YS()}const eC=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function tC(e){return`e${e}`}function nC(e){let t=[];for(let n of e){let e=aC(n),r=sC(n);if(e===`assistant`){let e=t.length,i=tC(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:uC(n),message:n,model:lC(n)});for(let e of dC(n)){let n=t.length;t.push({id:tC(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:tC(i),seq:i,kind:`tool-result`,timestamp:r,text:uC(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=uC(n),a=e===`user`?iC(i):null,o=t.length,s=tC(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):eC.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 rC(e){let t=[];for(let n of e){let e=t.length,r=tC(e),i=cC(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:tC(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&z_(n.channel)?n.channel:iC(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):eC.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 iC(e){for(let t of sv(e)){let e=(t.sender?cv(t.sender):null)??lv(t.body);if(e)return e}return null}function aC(e){return e.role??``}function oC(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 sC(e){return oC(e.timestamp)}function cC(e){return oC(e.timestamp)}function lC(e){let t=e.model;return typeof t==`string`?t:void 0}function uC(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 dC(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 fC(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function pC(e){return e!==null&&e.version<=2}const mC=y(`work-unit-conversation`);var hC=class extends Error{};const gC=`conversations`;async function _C(e){let t=e.now??(()=>Date.now()),n=await yC(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=yr(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await vC(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}],mC.warn(`Skipping a unit whose conversation could not be migrated`,{key:c,folder:s.folder,error:o}),i instanceof hC){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),mC.info(`Canonical conversation migration complete`,{...r}),r}async function vC(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return mC.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw new hC(`canonical record unreadable: ${i.reason}`);let a=br(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:nC(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:rC(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function yC(e,t){let n=await e.getMigrationState(gC);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:gC,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var bC=e({applyAttachmentOverlays:()=>wC,interleaveMarkers:()=>TC,toAgentMessages:()=>SC,toChatMessages:()=>CC});const xC=new Set([`summarized`,`fallback`]);function SC(e){if(!pC(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 CC(e,t={}){if(!pC(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 TC(t,e.markers)}let n=e.projectionPrefix??[],r=SC(e);if(r.length===0)return TC([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>q_),a=wC(i(r,t),e.attachments);return TC([...n,...a],e.markers)}function wC(e,t){if(!t?.length)return e;let n=[...t].sort((e,t)=>e.timestamp-t.timestamp),r=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 TC(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||xC.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=EC(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(DC(r[a++]));i.push(t)}for(;a<r.length;)i.push(DC(r[a++]));return i}function EC(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 DC(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 OC(e){return{id:e.legacyKeys.chatSessionId,messages:await CC(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function kC(e){return{id:e.workUnitId,messages:SC(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var AC=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(kC)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(OC))}async latestPerUnit(){let e=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(nr({parentJid:null,folder:e}).root);return t?OC(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const jC=y(`work-unit-conversation`),q=`conversations`,MC=`migrations`;var NC=class{dbPromise=null;dbName;writeChains=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 BC((await this.getDb()).transaction(q,`readonly`).objectStore(q).get(e));return t?pC(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(jC.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(jC.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return jC.warn(`Conversation record read failed`,{key:e,error:HC(t)}),{status:`error`,reason:HC(t)}}}async save(e){let t=e.version>2?e.version:fC(e),n={...e,version:t},r=(await this.getDb()).transaction(q,`readwrite`);return r.objectStore(q).put(n),await VC(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(q,`readwrite`);t.objectStore(q).delete(e),await VC(t)}catch(t){jC.warn(`Conversation record delete failed`,{key:e,error:HC(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`){jC.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){jC.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:HC(n)})}}async loadAll(){try{return(await BC((await this.getDb()).transaction(q,`readonly`).objectStore(q).getAll())).filter(e=>pC(e)&&Array.isArray(e.entries))}catch(e){return jC.warn(`Conversation record listing failed`,{error:HC(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await BC((await this.getDb()).transaction(q,`readonly`).objectStore(q).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)!pC(e)||!Array.isArray(e.entries)||(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return jC.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:HC(t)}),null}}async listKeys(){try{return(await BC((await this.getDb()).transaction(q,`readonly`).objectStore(q).getAllKeys())).map(String)}catch(e){return jC.warn(`Conversation key listing failed`,{error:HC(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=nC(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=PC(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return jC.warn(`Conversation record write failed`,{key:e.key,error:HC(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?FC(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 jC.warn(`Conversation marker write failed`,{key:e,error:HC(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 BC((await this.getDb()).transaction(MC,`readonly`).objectStore(MC).get(e))??null}catch(t){return jC.warn(`Migration state read failed`,{id:e,error:HC(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(MC,`readwrite`);t.objectStore(MC).put(e),await VC(t)}catch(t){jC.warn(`Migration state write failed`,{id:e.id,error:HC(t)})}}async clearAll(){let e=(await this.getDb()).transaction([q,MC],`readwrite`);e.objectStore(q).clear(),e.objectStore(MC).clear(),await VC(e)}getDb(){return this.dbPromise||(this.dbPromise=zC(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 PC(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??[],...IC(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&LC(a,t))return null;let o=t.length>a.length&&LC(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 FC(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 IC(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function LC(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!RC(e[n],t[n]))return!1;return!0}function RC(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 zC(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(q)||e.createObjectStore(q,{keyPath:`key`}),e.objectStoreNames.contains(MC)||e.createObjectStore(MC,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function BC(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function VC(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function HC(e){return e instanceof Error?e.message:String(e)}var UC=e({CONE_MEMORY_PATH:()=>KC,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>GC,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>qC,applyConeMemoryBudget:()=>QC,readSessionCount:()=>XC,restructureConeMemory:()=>ZC,splitConeMemory:()=>YC});const WC=y(`cone-memory-budget`),GC=1.25,KC=Qn.memoryPath,qC=`/sessions/index.json`,JC=/^## Auto-extracted/m;function YC(e){let t=JC.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function XC(e){try{let t=await e.readFile(qC,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r.length:0}catch{return 0}}async function ZC(e){let{header:t,autoExtracted:n}=YC(e.currentContent);if(!n.trim())return e.currentContent;let r=`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.
|
|
985
|
+
`;const mx=y(`sudo:manager`);function hx(e){return e===`/etc/sudoers`||e===`/etc/sudoers.d`||e.startsWith(`/etc/sudoers.d/`)}function gx(e){if(!e.startsWith(`/etc/sudoers.d/`))return null;let t=e.slice(Rr.length+1);return t.includes(`/`)?null:kr(t)}function _x(e){return e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e}const vx=[`# Approved "Always" grants for one scoop. Loaded only for that scoop.`,`# Sandbox grants come from ScoopConfig, in memory — not here.`,`# Writes always require approval (self-protected).`,``].join(`
|
|
986
|
+
`);function yx(e){let t=[],n=e?.allowedCommands;if(n===void 0||n.includes(`*`))t.push(`NOPASSWD Cmnd *`);else for(let e of n){let n=Pr(e);n&&(t.push(`NOPASSWD Cmnd ${n}`),t.push(`NOPASSWD Cmnd ${n} *`))}for(let n of e?.writablePaths??[]){let e=Pr(n);e&&(t.push(`NOPASSWD Write ${_x(e)}`),t.push(`NOPASSWD Write ${_x(e)}/**`))}for(let n of e?.visiblePaths??[]){let e=Pr(n);e&&(t.push(`NOPASSWD Read ${_x(e)}`),t.push(`NOPASSWD Read ${_x(e)}/**`))}return`${t.join(`
|
|
987
|
+
`)}\n`}var bx=class{fs;watcher;broker;onPolicyReload;policy=jr();unwatch=null;reloadChain=Promise.resolve();scoopPolicies=new Map;scoopConfigPolicies=new Map;scoopReloadChains=new Map;constructor(e){this.fs=e.fs,this.watcher=e.watcher??null,this.broker=e.broker??s(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`&&Nr(this.policy,e.detail)===`nopasswd-allow`)return mx.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 mx.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(Vr(e.kind),n)}catch(n){return mx.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=[Ar(),this.policy];return n&&r.push(n),t&&r.push(t),Lr(...r)}registerScoopConfig(e,t){this.scoopConfigPolicies.set(e,Fr(yx(t??void 0))),this.onPolicyReload(e)}async initScoopPolicy(e,t){this.registerScoopConfig(e,t);let n=Ur(e);if(await this.fs.exists(n).catch(()=>!1)){let{migrateLegacyScoopSudoers:t}=await import(`./migrate-scoop-sudoers-PBnz9AA3.js`);await t(e,{fs:this.fs})}await this.reloadScoopPolicy(e)}async appendScoopRule(e,t,n){let r=Pr(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=Wr(e);if(!a)return mx.warn(`Unspellable scoop folder; not persisting`,{folder:e}),null;let o=await this.readTextOrEmpty(a),s=`NOPASSWD ${i} ${r}`;if(o.split(`
|
|
988
|
+
`).some(e=>e.trim()===s))return mx.info(`Per-scoop grant already present; skipping duplicate append`,{folder:e,kind:t,pattern:r}),r;try{await this.fs.mkdir(Rr,{recursive:!0})}catch{}let c=o?o.endsWith(`
|
|
989
|
+
`)?o:`${o}\n`:vx;return await this.fs.writeFile(a,`${c}${s}\n`),await this.reloadScoopPolicy(e),mx.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 j&&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=Wr(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(Br)];try{let t=(await this.fs.readDir(Rr)).filter(e=>e.type===`file`).filter(e=>kr(e.name)===null).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${Rr}/${n}`))}catch{}this.policy=Lr(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return jr();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return Fr(n)}catch(t){return mx.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),jr()}}async ensureDefaults(){try{await this.fs.mkdir(Rr,{recursive:!0})}catch{}await this.seedWhenAbsent(Br,()=>px),await this.seedWhenAbsent(Hr,async()=>(await import(`./approver-agent-CvnFt_s6.js`)).DEFAULT_APPROVALS_MD)}async seedWhenAbsent(e,t){try{if(await this.fs.exists(e))return;await this.fs.writeFile(e,await t()),mx.info(`Seeded bundled policy default`,{path:e})}catch(t){mx.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=Pr(t);if(!n)return;let r=``;try{if(await this.fs.exists(qr)){let e=await this.fs.readFile(qr,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof j&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(Rr,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
|
|
990
|
+
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(qr,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,hx,e=>{let t=new Set,n=!1,r=!1;for(let i of e){if(i.path===`/etc/sudoers.d`){r=!0;continue}let e=gx(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 xx(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Sx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cx(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++)Cx(e[r],`${t}/${r}`,n);return}if(Sx(e))for(let[r,i]of Object.entries(e))Cx(i,`${t}/${xx(r)}`,n)}function wx(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=wx(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(Sx(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=wx(o,`${t}/${xx(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function Tx(e,t,n){if(Sx(e))return wx(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=Tx(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function Ex(e){let t=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 Dx(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new v(`redaction-unavailable`);let a=0,o=i;for(;o<e.length;){let t=e[o].length;if(o>i&&a+t>1048576)break;a+=t,o++}let s=e.slice(i,o),c;try{c=await t.redact(s,n)}catch{throw new v(`redaction-unavailable`)}if(c.length!==s.length)throw new v(`redaction-unavailable`);r.push(...c),i=o}return r}function Ox(e,t,n,r){let i=[],a=Ex(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Ex(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}=Te(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 kx(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 Ax(e,t,r,i){if(i?.aborted)throw new v(`redaction-unavailable`);let{privacy:a,...o}=e,s=[];Cx(o,``,s);let c=s.filter(e=>!n(e.pointer)),l=[...t.entries()],u=await Dx([...c.map(e=>e.value),...l.map(([,e])=>e)],r,i),d=[],f={},p=1,m=new Map,h=[];for(let e=0;e<c.length;e++){let t=c[e],n=Ox(t.value,u[e],{kind:`json`,pointer:t.pointer},p);p=n.nextId,n.finalText!==t.value&&m.set(t.pointer,n.finalText),h.push(n)}kx(h,d,f);let g=new Map,_=c.length,ee=[];for(let e=0;e<l.length;e++){let[t,n]=l[e],r=Ox(n,u[_+e],{kind:`attachment`,attachmentId:t},p);p=r.nextId,g.set(t,r.finalText),ee.push(r)}kx(ee,d,f);let te=Tx(e,``,m);return{document:{...te,privacy:{...te.privacy,redactionCounts:f,redactions:d}},textAttachments:g}}function jx(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`}async function Mx(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const Nx={"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 Px(e,t){return Nx[e]??(t===`text-redacted`?`.txt`:`.bin`)}function Fx(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${Px(t,n)}`}function Ix(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 Lx(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 Rx(e,t,n,r,i){let a=jx(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(Ix(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=Ix(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 zx(e,t,n,r){let i=[],a=new Set,o=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:Ix(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(Rx(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function Bx(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 Vx(e,t,n,r,i,a,o){let s=Bx(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(Rx(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function Hx(e,t,n,r,i){let a=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=Vx(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function Ux(e,t){let n=new Map,r=0,i=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,Fx(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 Wx(e,t,n,r,i){let{rawAttachments:a,textMap:o}=Ux(e,n),s,c;try{let e=await Ax({...t,attachments:a},o,r,i);s=e.document,c=e.textAttachments}catch(e){throw e instanceof v?e:new v(`attachment-unreadable`)}let l=new Map;for(let t of e){if(l.has(t.attachmentId))throw new v(`schema-invalid`);l.set(t.attachmentId,t)}let u=new Map,d=await Promise.all(s.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=l.get(e.id);if(t===void 0)throw new v(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(c.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await Mx(n);return u.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...s,attachments:d},bundleFiles:u}}async function Gx(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??new Map,o=e.vfsReader,s=new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=zx(Lx(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}=Hx(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],g=t;f.size>0&&(g={...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:_,bundleFiles:ee}=await Wx(h,g,s,r,i),te=[..._.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{..._,session:{..._.session,completeness:{status:te.length>0?`partial`:_.session.completeness.status,missing:te}}},bundleFiles:ee}}function Kx(e){return Ln(e)}function qx(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 Jx(e,t,n,r){let i=new Map;for(let e of t)i.set(e.id,e);let a=new Map;for(let e of n)a.set(e.id,e);let o=[],s=new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:wn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!wn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=Kx(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function Yx(e,t,n={}){let r=e=>n.rootJid===void 0?e:Tn(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 v(`transfer-aborted`);let i=qx(n,e),[a,o]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new v(`transfer-aborted`);let s=r(e.listScoops());if(i===qx(s,e))return Jx(s,a,o,e)}}var Xx=e({SESSIONS_DIR:()=>Zx,SESSIONS_INDEX_PATH:()=>Qx,parseFrozenArchive:()=>eS,readSessionsIndex:()=>$x});const Zx=`/sessions`,Qx=`/sessions/index.json`;async function $x(e){try{let t=await e.readFile(Qx,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function eS(e){let t=e,n=`Untitled`,r={},i=t.match(/^---\n([\s\S]*?)\n---\n+/);if(i){t=t.slice(i[0].length),Object.assign(r,tS(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=nS(e[1]))}let a=t.match(/<!-- slicc:session-data\n([\s\S]*?)\n-->\n*/);if(a){try{let e=a[1].replace(/-- >/g,`-->`),t=JSON.parse(e);if(Array.isArray(t))return{title:n,messages:t,...r}}catch{}t=t.replace(/<!-- slicc:session-data\n[\s\S]*?\n-->\n*/,``)}return r.sidecar?{title:n,messages:[],...r}:(t=t.replace(/^#\s+[^\n]*\n+/,``),{title:n,messages:iS(t),...r})}function tS(e){let t={},n=rS(e,`cost`),r=rS(e,`models`);n&&(t.cost=n),r&&(t.models=r);let i=e.match(/^cone:\s*(.+?)\s*$/m)?.[1];i&&(t.cone=i);let a=e.match(/^coneLabel:\s*(.+?)\s*$/m)?.[1];a&&(t.coneLabel=nS(a)),/^memorySkipped:\s*true\s*$/m.test(e)&&(t.memorySkipped=!0),/^live:\s*true\s*$/m.test(e)&&(t.live=!0);let o=Number(e.match(/^liveThrough:\s*(\d+)\s*$/m)?.[1]);Number.isFinite(o)&&o>0&&(t.liveThrough=o);let s=Number(e.match(/^compactions:\s*(\d+)\s*$/m)?.[1]);Number.isFinite(s)&&s>0&&(t.compactions=s);let c=e.match(/^id:\s*(\S+)\s*$/m)?.[1];c&&(t.id=c);let l=e.match(/^sidecar:\s*(\S+)\s*$/m)?.[1];return l&&(t.sidecar=l),t}function nS(e){let t=e.trim();if(!t.startsWith(`"`))return t;try{let e=JSON.parse(t);if(typeof e==`string`)return e}catch{}return t.replace(/^"|"$/g,``)}function rS(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function iS(e){let t=[],n=/^## (User|Assistant)\s*\n/gm,r=[],i;for(;(i=n.exec(e))!==null;)r.push({role:i[1]===`User`?`user`:`assistant`,start:i.index,bodyStart:i.index+i[0].length});for(let n=0;n<r.length;n++){let i=n+1<r.length?r[n+1].start:e.length,a=e.slice(r[n].bodyStart,i).trim();t.push({id:`frozen-${n}`,role:r[n].role,content:a,timestamp:0})}return t}function aS(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function oS(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function sS(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(oS(t,r++));return n}function cS(e,t){let n=[],r=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=oS(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 lS(e,t){let n=[],r=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=oS(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 uS(e,t,n){let r=aS(t,n),i=sS(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:new Map}}function dS(e,t,n){let r=aS(t,n),{blocks:i,excluded:a,images:o}=cS(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 fS(e,t,n){let r=aS(t,n),{blocks:i,images:a}=lS(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 pS(e,t,n){return e.role===`user`?uS(e,t,n):e.role===`assistant`?dS(e,t,n):e.role===`toolResult`?fS(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function mS(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 hS(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=pS(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:mS(e),excludedReasoningBlocks:t,canonicalImages:n}}const gS=(()=>{let e=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 _S(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^gS[(t^e[n])&255];return~t>>>0}const vS=new TextEncoder;function q(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function yS(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 bS(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,q(r,4,20),q(r,6,2048),q(r,8,0),q(r,10,0),q(r,12,0),yS(r,14,n),yS(r,18,t),yS(r,22,t),q(r,26,e.length),q(r,28,0),r.set(e,30),r}function xS(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,q(i,4,20),q(i,6,20),q(i,8,2048),q(i,10,0),q(i,12,0),q(i,14,0),yS(i,16,n),yS(i,20,t),yS(i,24,t),q(i,28,e.length),q(i,30,0),q(i,32,0),q(i,34,0),q(i,36,0),yS(i,38,0),yS(i,42,r),i.set(e,46),i}function SS(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,q(r,4,0),q(r,6,0),q(r,8,e),q(r,10,e),yS(r,12,t),yS(r,16,n),q(r,20,0),r}function CS(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 wS(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${we(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*TS(e,t,n,r,i){if(n?.aborted)throw i(new v(`transfer-aborted`)),new v(`transfer-aborted`);let a=()=>i(new v(`transfer-aborted`));n?.addEventListener(`abort`,a,{once:!0});let o=Yr.create(),s=0,c=0,l=[],u=!1;function*d(e){o.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),a=vS.encode(`transcript.json`),f=_S(i),p=bS(a,i.length,f);if(l.push({nameBytes:a,size:i.length,crc:f,localOffset:c}),n?.aborted||(yield*d(p),n?.aborted))throw new v(`transfer-aborted`);yield*d(i);for(let[e,r]of t){if(n?.aborted)throw new v(`transfer-aborted`);let t=vS.encode(e),i=_S(r),a=bS(t,r.length,i);if(l.push({nameBytes:t,size:r.length,crc:i,localOffset:c}),yield*d(a),n?.aborted)throw new v(`transfer-aborted`);yield*d(r)}let m=c;for(let e of l){if(n?.aborted)throw new v(`transfer-aborted`);yield*d(xS(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new v(`transfer-aborted`);yield*d(SS(l.length,c-m,m)),u=!0,r({byteLength:s,sha256:o.hex()})}catch(e){throw u=!0,i(e),e}finally{n?.removeEventListener(`abort`,a),u||(u=!0,i(new v(`transfer-aborted`)))}}function ES(e,t,n){for(let e of t.keys())if(!CS(e))throw new v(`schema-invalid`);if(t.size+1>65535)throw new v(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new v(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return{filename:wS(e),chunks:TS(e,t,n,r,i),completion:a}}function DS(e,t,n,r,i,o={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:a},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...o},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function OS(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 kS(e){let n=t(e);if(!n.ok)throw new v(`schema-invalid`,n.error)}function AS(e,t,n){let r=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 jS(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);if(!n)return e;let r=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=await crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``);return{...e,byteLength:n.length,sha256:a}}))}function MS(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 NS=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),kS(i.document),r?.({phase:`packaging`}),ES(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await Yx(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=hS(n.sources),{document:i,bundleFiles:a}=await Gx({document:DS(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});kS(i),await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a})}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await Yx(this.deps.collection,e),r=hS(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=DS(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),Gx({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=await this.deps.snapshotStore.read(e);return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=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 Ax(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new v(`redaction-unavailable`)}let a=AS(r.attachments,i,e.attachments),o=await jS(r.attachments,a);return{document:{...r,attachments:o},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await $x(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new v(`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 v(`session-not-found`)}let{loadFrozenArchive:o}=await import(`./session-jsonl-D_pTYppB.js`),{title:s,messages:c}=await o(this.deps.vfs,i,r.filename),l=`legacy-cone`,u=OS(c,l),d=MS(i),f={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:a},session:{id:e,title:s,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...d,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:l,kind:`cone`,name:s,messages:u}],delegations:[],attachments:[]},p=new Map([[l,c]]);return n?.({phase:`redacting`}),Gx({document:f,chatMessagesByConversation:p,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 v(`attachment-unreadable`);return t}};const PS=`/sessions/data`,FS=`document.json`;async function IS(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function LS(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new v(`session-not-found`)}function RS(e){return`${PS}/${e}`}function zS(e){return`${PS}/.tmp-${e}`}async function BS(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function VS(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 VS(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function HS(e,t,n){await BS(e,n);let r=await e.readDir(t);for(let i of r){let r=`${t}/${i.name}`,a=`${n}/${i.name}`;if(i.type===`directory`)await HS(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function US(e,t,n){LS(t);let r=zS(t),i=RS(t),a=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!a.has(e))throw new v(`schema-invalid`);await VS(e,i),await BS(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await IS(r),i=a.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let o={...n.document,attachments:t},s=JSON.stringify(o,null,2);if(await e.writeFile(`${r}/${FS}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await BS(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await HS(e,r,i),await e.flush()}catch(t){throw await VS(e,r),t}await VS(e,r)}async function WS(e,n){LS(n);let r=RS(n),i=`${r}/${FS}`,a;try{let t=await e.readFile(i,{encoding:`utf-8`});a=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new v(`session-not-found`)}let o;try{o=JSON.parse(a)}catch{throw new v(`schema-invalid`)}if(!t(o).ok)throw new v(`schema-invalid`);let s=new Map;for(let t of o.attachments){if(!t.present||!t.path)continue;let n=`${r}/${t.path}`,i;try{let t=await e.readFile(n,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new v(`transfer-corrupt`)}if(await IS(i)!==t.sha256)throw new v(`transfer-corrupt`);s.set(t.path,i)}return{document:o,attachments:s}}function GS(e){return`error`in e}function KS(){throw new v(`redaction-unavailable`)}function qS(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&KS(),e.texts}function JS(){return{async redact(e){let t;try{t=await fetch(Ae(`/api/secrets/redact-export`),{method:`POST`,headers:Me({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{KS()}t.ok||KS();let n;try{n=await t.json()}catch{KS()}return qS(n,e.length)}}}function YS(){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{KS()}return typeof t==`object`&&t&&GS(t)&&KS(),qS(t,e.length)}}}function XS(){return{async redact(e){let t;try{t=await pn(`secrets.redact-export`,{texts:e})}catch{KS()}return t??KS(),typeof t==`object`&&t&&GS(t)&&KS(),qS(t,e.length)}}}function ZS(){return{async redact(e){KS()}}}function QS(){let e=cn();return e===`connect`?ZS():e===`extension-direct`?YS():e===`extension-delegate`?XS():JS()}const $S=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function eC(e){return`e${e}`}function tC(e){let t=[];for(let n of e){let e=iC(n),r=oC(n);if(e===`assistant`){let e=t.length,i=eC(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:lC(n),message:n,model:cC(n)});for(let e of uC(n)){let n=t.length;t.push({id:eC(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:eC(i),seq:i,kind:`tool-result`,timestamp:r,text:lC(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=lC(n),a=e===`user`?rC(i):null,o=t.length,s=eC(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):$S.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 nC(e){let t=[];for(let n of e){let e=t.length,r=eC(e),i=sC(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:eC(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&R_(n.channel)?n.channel:rC(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):$S.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 rC(e){for(let t of ov(e)){let e=(t.sender?sv(t.sender):null)??cv(t.body);if(e)return e}return null}function iC(e){return e.role??``}function aC(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 oC(e){return aC(e.timestamp)}function sC(e){return aC(e.timestamp)}function cC(e){let t=e.model;return typeof t==`string`?t:void 0}function lC(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 uC(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 dC(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function fC(e){return e!==null&&e.version<=2}const pC=y(`work-unit-conversation`);var mC=class extends Error{};const hC=`conversations`;async function gC(e){let t=e.now??(()=>Date.now()),n=await vC(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=yr(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await _C(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}],pC.warn(`Skipping a unit whose conversation could not be migrated`,{key:c,folder:s.folder,error:o}),i instanceof mC){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),pC.info(`Canonical conversation migration complete`,{...r}),r}async function _C(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return pC.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw new mC(`canonical record unreadable: ${i.reason}`);let a=br(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:tC(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:nC(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function vC(e,t){let n=await e.getMigrationState(hC);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:hC,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var yC=e({applyAttachmentOverlays:()=>CC,interleaveMarkers:()=>wC,toAgentMessages:()=>xC,toChatMessages:()=>SC});const bC=new Set([`summarized`,`fallback`]);function xC(e){if(!fC(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 SC(e,t={}){if(!fC(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 wC(t,e.markers)}let n=e.projectionPrefix??[],r=xC(e);if(r.length===0)return wC([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>K_),a=CC(i(r,t),e.attachments);return wC([...n,...a],e.markers)}function CC(e,t){if(!t?.length)return e;let n=[...t].sort((e,t)=>e.timestamp-t.timestamp),r=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 wC(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||bC.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=TC(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(EC(r[a++]));i.push(t)}for(;a<r.length;)i.push(EC(r[a++]));return i}function TC(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 EC(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 DC(e){return{id:e.legacyKeys.chatSessionId,messages:await SC(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function OC(e){return{id:e.workUnitId,messages:xC(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var kC=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(OC)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(DC))}async latestPerUnit(){let e=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(nr({parentJid:null,folder:e}).root);return t?DC(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const AC=y(`work-unit-conversation`),jC=`conversations`,MC=`migrations`;var NC=class{dbPromise=null;dbName;writeChains=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 BC((await this.getDb()).transaction(jC,`readonly`).objectStore(jC).get(e));return t?fC(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(AC.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(AC.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return AC.warn(`Conversation record read failed`,{key:e,error:HC(t)}),{status:`error`,reason:HC(t)}}}async save(e){let t=e.version>2?e.version:dC(e),n={...e,version:t},r=(await this.getDb()).transaction(jC,`readwrite`);return r.objectStore(jC).put(n),await VC(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(jC,`readwrite`);t.objectStore(jC).delete(e),await VC(t)}catch(t){AC.warn(`Conversation record delete failed`,{key:e,error:HC(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`){AC.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){AC.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:HC(n)})}}async loadAll(){try{return(await BC((await this.getDb()).transaction(jC,`readonly`).objectStore(jC).getAll())).filter(e=>fC(e)&&Array.isArray(e.entries))}catch(e){return AC.warn(`Conversation record listing failed`,{error:HC(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await BC((await this.getDb()).transaction(jC,`readonly`).objectStore(jC).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)!fC(e)||!Array.isArray(e.entries)||(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return AC.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:HC(t)}),null}}async listKeys(){try{return(await BC((await this.getDb()).transaction(jC,`readonly`).objectStore(jC).getAllKeys())).map(String)}catch(e){return AC.warn(`Conversation key listing failed`,{error:HC(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=tC(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=PC(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return AC.warn(`Conversation record write failed`,{key:e.key,error:HC(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?FC(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 AC.warn(`Conversation marker write failed`,{key:e,error:HC(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 BC((await this.getDb()).transaction(MC,`readonly`).objectStore(MC).get(e))??null}catch(t){return AC.warn(`Migration state read failed`,{id:e,error:HC(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(MC,`readwrite`);t.objectStore(MC).put(e),await VC(t)}catch(t){AC.warn(`Migration state write failed`,{id:e.id,error:HC(t)})}}async clearAll(){let e=(await this.getDb()).transaction([jC,MC],`readwrite`);e.objectStore(jC).clear(),e.objectStore(MC).clear(),await VC(e)}getDb(){return this.dbPromise||(this.dbPromise=zC(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 PC(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??[],...IC(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&LC(a,t))return null;let o=t.length>a.length&&LC(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 FC(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 IC(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function LC(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!RC(e[n],t[n]))return!1;return!0}function RC(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 zC(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(jC)||e.createObjectStore(jC,{keyPath:`key`}),e.objectStoreNames.contains(MC)||e.createObjectStore(MC,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function BC(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function VC(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function HC(e){return e instanceof Error?e.message:String(e)}var UC=e({CONE_MEMORY_PATH:()=>KC,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>GC,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>qC,applyConeMemoryBudget:()=>QC,readSessionCount:()=>XC,restructureConeMemory:()=>ZC,splitConeMemory:()=>YC});const WC=y(`cone-memory-budget`),GC=1.25,KC=Qn.memoryPath,qC=`/sessions/index.json`,JC=/^## Auto-extracted/m;function YC(e){let t=JC.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function XC(e){try{let t=await e.readFile(qC,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r.length:0}catch{return 0}}async function ZC(e){let{header:t,autoExtracted:n}=YC(e.currentContent);if(!n.trim())return e.currentContent;let r=`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.
|
|
991
991
|
|
|
992
992
|
<auto-extracted>
|
|
993
993
|
${n}
|
|
@@ -1003,7 +1003,7 @@ Rules:
|
|
|
1003
1003
|
`)?``:`
|
|
1004
1004
|
`}${o}\n`}async function QC(e){if(!e.model||!e.apiKey)return{restructured:!1,reason:`no-llm`};let t=e.memoryPath??KC,n=``;try{let r=await e.vfs.readFile(t,{encoding:`utf-8`});n=typeof r==`string`?r:new TextDecoder().decode(r)}catch{return{restructured:!1,reason:`missing-file`}}let r=await XC(e.vfs),i=Xr(r),a=i*GC;if(n.length<=a)return{restructured:!1,reason:`under-threshold`};WC.info(`Cone memory over threshold — restructuring`,{size:n.length,budget:i,threshold:a,sessionCount:r});try{let r=await ZC({currentContent:n,budget:i,model:e.model,apiKey:e.apiKey,headers:e.headers,signal:e.signal});return await e.vfs.writeFile(t,r),WC.info(`Cone memory restructured`,{before:n.length,after:r.length}),{restructured:!0}}catch(e){return WC.warn(`Cone memory restructure failed — leaving appended content in place`,{error:e instanceof Error?e.message:String(e)}),{restructured:!1,reason:`error`}}}const $C=`.skill`,ew=`/workspace/skills`,tw=`SKILL.md`,nw=y(`skills-discovery`),rw=[`native`,`agents`,`claude`,`marketplace`,`plugin`],iw=new Map([[`.agents`,`agents`],[`.claude`,`claude`]]),aw=new Set([`.git`,`.slicc`,`node_modules`]),ow=2e4,sw=[`mkdir`,`mount`,`rename`,`rm`,`unmount`,`writeFile`],cw=new WeakMap,lw=new WeakSet;async function uw(e,t=ew){let n=await hw(e,t),r=await fw(e),i=await dw(e);return[...rw.flatMap(e=>(e===`native`?n:e===`plugin`?i:r.filter(t=>t.source===e)).sort((e,t)=>e.path.localeCompare(t.path)))]}async function dw(e){let t;try{let n=await e.readTextFile(`/workspace/.plugins/plugins.json`),r=JSON.parse(n);if(!r||typeof r!=`object`||!r.plugins)return[];t=Object.values(r.plugins).map(e=>e?.root).filter(e=>typeof e==`string`)}catch{return[]}let n=[];for(let r of t){let t=`${r}/skills`,i=await Sw(e,t);for(let r of i){if(r.type!==`directory`)continue;let i=`${t}/${r.name}`,a=`${i}/${tw}`;await xw(e,a)&&n.push({source:`plugin`,sourceRoot:t,path:i,skillFilePath:a})}}return n}async function fw(e){if(pw(e))return(await yw(e)).map(e=>({...e}));bw(e);let t=e,n=cw.get(t);if(n)return n.map(e=>({...e}));let r=await yw(e);return cw.set(t,r),r.map(e=>({...e}))}function pw(e){try{return e[Gr]===!0}catch{return!1}}function mw(e,t){let n=new Map,r=new Map;for(let i of e){let e=t(i);if(!n.has(e)){n.set(e,i);continue}let a=r.get(e)??{name:e,winner:n.get(e),shadowed:[]};a.shadowed.push(i),r.set(e,a)}return{winners:Array.from(n.values()),collisions:Array.from(r.values())}}async function hw(e,t){let n=await Sw(e,t),r=[];for(let i of n){if(i.type!==`directory`)continue;let n=`${t}/${i.name}`,a=`${n}/${tw}`;await xw(e,a)&&r.push({source:`native`,sourceRoot:t,path:n,skillFilePath:a})}return r}async function gw(e,t){let n;try{n=await e.readTextFile(t)}catch{return[]}let r;try{r=JSON.parse(n)}catch{return[]}if(typeof r!=`object`||!r)return[];let i=r.plugins;if(!Array.isArray(i))return[];let a=t.replace(/\/[^/]+$/,``).replace(/\/.claude-plugin$/,``),o=[];for(let e of i){if(typeof e!=`object`||!e)continue;let t=e.source;if(typeof t!=`string`||t.startsWith(`/`)||t.split(`/`).includes(`..`))continue;let n=t.replace(/^\.\//,``).replace(/\/$/,``).replace(/^\.$/,``);o.push(n?`${a}/${n}`:a)}return o}async function _w(e,t,n){let r=await gw(e,`${t}/marketplace.json`),i=[];for(let t of r){let r=`${t}/skills`,a=await Sw(e,r);for(let t of a){if(t.type!==`directory`)continue;let a=`${r}/${t.name}`,o=`${a}/${tw}`;!await xw(e,o)||n.has(a)||(n.add(a),i.push({source:`marketplace`,sourceRoot:r,path:a,skillFilePath:o}))}}return i}async function vw(e,t,n,r){let i=`${t}/skills`,a=await Sw(e,i),o=[];for(let t of a){if(t.type!==`directory`)continue;let a=`${i}/${t.name}`,s=`${a}/${tw}`;!await xw(e,s)||r.has(a)||(r.add(a),o.push({source:n,sourceRoot:i,path:a,skillFilePath:s}))}return o}async function yw(e){let t=[],n=new Set,r=new Set([`/`]),i=[{path:`/`,depth:0}];for(let a=0;a<i.length;a+=1){if(a>=ow){nw.warn(`skills discovery: directory budget exhausted; walk truncated`,{budget:ow});break}let{path:o,depth:s}=i[a],c=await Sw(e,o);for(let a of c){if(a.type!==`directory`||a.name===`.`||a.name===`..`)continue;let c=o===`/`?`/${a.name}`:`${o}/${a.name}`,l=iw.get(a.name);if(l){let r=await vw(e,c,l,n);t.push(...r)}if(a.name===`.claude-plugin`){let r=await _w(e,c,n);t.push(...r);continue}!aw.has(a.name)&&s<24&&!r.has(c)&&(r.add(c),i.push({path:c,depth:s+1}))}}return t}function bw(e){if(pw(e))return;let t=e;if(lw.has(t))return;lw.add(t);let n=e;for(let r of sw){let i=n[r];if(typeof i==`function`)try{n[r]=async(...n)=>{let r=await i.apply(e,n);return cw.delete(t),r}}catch{}}}async function xw(e,t){try{return await e.stat(t),!0}catch{return!1}}async function Sw(e,t){try{return[...await e.readDir(t)].sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}async function Cw(e,t=`/workspace/skills`){let n=await uw(e,t),r=[];for(let t of n){let n=t.path.split(`/`).pop()??t.path,i=``;if(t.skillFilePath)try{i=Ew(await e.readTextFile(t.skillFilePath))??``}catch{}r.push({name:n,source:t.source,sourceRoot:t.sourceRoot,path:t.path,skillFilePath:t.skillFilePath,description:i})}let{winners:i,collisions:a}=mw(r,e=>e.name),o=new Map(a.map(e=>[e.winner.path,e.shadowed.map(e=>e.path)]));return i.map(e=>({...e,shadowedPaths:o.get(e.path)}))}async function ww(e,t,n=`/workspace/skills`){return(await Cw(e,n)).find(e=>e.name===t)||null}async function Tw(e,t,n=`/workspace/skills`){let r=await ww(e,t,n);if(!r?.skillFilePath)return null;try{return await e.readTextFile(r.skillFilePath)}catch{return null}}function Ew(e){let t=e.replace(/^\uFEFF/,``).replace(/\r\n?/g,`
|
|
1005
1005
|
`).trimStart().match(/^---\s*\n([\s\S]*?)\n---/);if(!t)return null;for(let e of t[1].split(`
|
|
1006
|
-
`)){let t=e.match(/^description:\s*(.*)$/);if(t)return t[1].trim()}return null}const Dw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Ow(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e;return!!(t===`.DS_Store`||t===`Thumbs.db`||t===`desktop.ini`||t.startsWith(`._`))}var kw=class extends Error{};function Aw(e){let t=e.replace(/\\/g,`/`);if(!t||t.endsWith(`/`))return null;if(t.startsWith(`/`)||/^[A-Za-z]:\//.test(t))throw Error(`Blocked suspicious path "${e}".`);let n=t.split(`/`);if(n.some(e=>e===``||e===`.`||e===`..`))throw Error(`Blocked suspicious path "${e}".`);return n.join(`/`)}function jw(e){if(!Dw.test(e))throw Error(`Invalid skill: skill name "${e}" must be a simple directory name.`)}function Mw(e){let t=[];for(let[n,r]of Object.entries(e)){let e=Aw(n);e&&(Ow(e)||t.push({originalPath:n,path:e,bytes:r}))}return t}function Nw(e){let t=e.filter(e=>e.path===`SKILL.md`||e.path.endsWith(`/SKILL.md`));if(t.length===0)throw Error(`Skill archive is missing ${tw}.`);if(t.length>1)throw Error(`Skill archive contains multiple ${tw} files.`);return t[0]}function Pw(e){let t=0,n=0;return ei(e,{filter(e){if(t++,t>1e3)throw new kw(`Skill archives may contain at most 1000 entries.`);if(n+=e.originalSize,n>52428800)throw new kw(`Skill archives must expand to 50 MB or smaller after extraction.`);return!0}})}function Fw(e){let t=`${Date.now()}-${Math.random().toString(16).slice(2,8)}`;return vn(ew,`.${e}.tmp-${t}`)}function Iw(e,t){return t===`SKILL.md`?e.replace(/\.skill$/i,``):t.slice(0,-9).split(`/`).pop()??``}function Lw(e){if(!e.name.toLowerCase().endsWith(`.skill`))throw Error(`Only ${$C} archives can be installed with drag and drop.`);if(e.size>52428800)throw Error(`Skill archives must be 50 MB or smaller.`)}async function Rw(e){try{return Pw(new Uint8Array(await e.arrayBuffer()))}catch(e){if(e instanceof kw)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Invalid .skill archive: ${t}`)}}function zw(e){return e.path===`SKILL.md`?``:e.path.slice(0,-9)}function Bw(e,t){return t&&(e===t||!e.startsWith(`${t}/`))?null:(t?e.slice(t.length+1):e)||null}async function Vw(e,t,n,r){let i=vn(t,n),{dir:a}=gn(i);a!==`/`&&await e.mkdir(a,{recursive:!0}),await e.writeFile(i,r)}async function Hw(e,t,n,r){let i=0;for(let a of t){let t=Bw(a.path,n);t&&(await Vw(e,r,t,a.bytes),i++)}return i}async function Uw(e,t){await e.exists(t)&&await e.rm(t,{recursive:!0})}async function Ww(e,t){let n=vn(ew,t);if(await e.exists(n))throw Error(`Skill "${t}" already exists at ${n}.`);return n}async function Gw(e,t){Lw(t);let n=Mw(await Rw(t)),r=Nw(n),i=Iw(t.name,r.path);jw(i);let a=await Ww(e,i),o=Fw(i),s=zw(r);await e.mkdir(o,{recursive:!0});try{let t=await Hw(e,n,s,o);return await e.rename(o,a),{skillName:i,destinationPath:a,fileCount:t}}catch(t){throw await Uw(e,o),t}}var Kw=e({MAX_SKILL_ARCHIVE_SIZE_BYTES:()=>52428800,SKILLS_DIR:()=>`skills`,SKILL_ARCHIVE_EXTENSION:()=>$C,SKILL_FILE:()=>tw,WORKSPACE_SKILLS_PATH:()=>ew,discoverSkillCandidates:()=>uw,discoverSkills:()=>Cw,getSkillInfo:()=>ww,installSkillFromDrop:()=>Gw,readSkillInstructions:()=>Tw,resolveSkillNameCollisions:()=>mw});const qw=y(`skills`),Jw=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-BMBoR1hd.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-BMBoR1hd.js`).then(e=>e.default),"/packages/vfs-root/etc/APPROVALS.md":()=>import(`./APPROVALS-CoZKeFYV.js`).then(e=>e.default),"/packages/vfs-root/etc/MEMORY.md":()=>import(`./MEMORY-Dl8Y_nOo.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/etc/slicc/keys.json":()=>import(`./keys-BMebW-sj.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-Bzu6oiWk.js`).then(e=>e.default),"/packages/vfs-root/shared/GELATIERE.md":()=>import(`./GELATIERE-CLK_MA5a.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/suggestions/suggestions.shtml":()=>import(`./suggestions-B34zKgsF.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-BzW33ZtP.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/WIKI.md":()=>import(`./WIKI-DoBxwf2u.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/index.md":()=>import(`./wiki-BXN4hgmw.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/log.md":()=>import(`./log-DEDI5t_h.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-cOU0zXaK.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BNnF2azP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-BTVvFyRd.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-rlhaTrPD.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-BmzmDv0e.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/patterns.md":()=>import(`./patterns-ChiGbijt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dns/SKILL.md":()=>import(`./SKILL-BKyxMoME.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ffmpeg/SKILL.md":()=>import(`./SKILL-C6co9TnL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/gelatiere/SKILL.md":()=>import(`./SKILL-DXpn0mQK.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-BGww2dFz.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/image-processing/SKILL.md":()=>import(`./SKILL-DpjPj8Lx.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/jshd/SKILL.md":()=>import(`./SKILL-
|
|
1006
|
+
`)){let t=e.match(/^description:\s*(.*)$/);if(t)return t[1].trim()}return null}const Dw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Ow(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e;return!!(t===`.DS_Store`||t===`Thumbs.db`||t===`desktop.ini`||t.startsWith(`._`))}var kw=class extends Error{};function Aw(e){let t=e.replace(/\\/g,`/`);if(!t||t.endsWith(`/`))return null;if(t.startsWith(`/`)||/^[A-Za-z]:\//.test(t))throw Error(`Blocked suspicious path "${e}".`);let n=t.split(`/`);if(n.some(e=>e===``||e===`.`||e===`..`))throw Error(`Blocked suspicious path "${e}".`);return n.join(`/`)}function jw(e){if(!Dw.test(e))throw Error(`Invalid skill: skill name "${e}" must be a simple directory name.`)}function Mw(e){let t=[];for(let[n,r]of Object.entries(e)){let e=Aw(n);e&&(Ow(e)||t.push({originalPath:n,path:e,bytes:r}))}return t}function Nw(e){let t=e.filter(e=>e.path===`SKILL.md`||e.path.endsWith(`/SKILL.md`));if(t.length===0)throw Error(`Skill archive is missing ${tw}.`);if(t.length>1)throw Error(`Skill archive contains multiple ${tw} files.`);return t[0]}function Pw(e){let t=0,n=0;return ei(e,{filter(e){if(t++,t>1e3)throw new kw(`Skill archives may contain at most 1000 entries.`);if(n+=e.originalSize,n>52428800)throw new kw(`Skill archives must expand to 50 MB or smaller after extraction.`);return!0}})}function Fw(e){let t=`${Date.now()}-${Math.random().toString(16).slice(2,8)}`;return vn(ew,`.${e}.tmp-${t}`)}function Iw(e,t){return t===`SKILL.md`?e.replace(/\.skill$/i,``):t.slice(0,-9).split(`/`).pop()??``}function Lw(e){if(!e.name.toLowerCase().endsWith(`.skill`))throw Error(`Only ${$C} archives can be installed with drag and drop.`);if(e.size>52428800)throw Error(`Skill archives must be 50 MB or smaller.`)}async function Rw(e){try{return Pw(new Uint8Array(await e.arrayBuffer()))}catch(e){if(e instanceof kw)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Invalid .skill archive: ${t}`)}}function zw(e){return e.path===`SKILL.md`?``:e.path.slice(0,-9)}function Bw(e,t){return t&&(e===t||!e.startsWith(`${t}/`))?null:(t?e.slice(t.length+1):e)||null}async function Vw(e,t,n,r){let i=vn(t,n),{dir:a}=gn(i);a!==`/`&&await e.mkdir(a,{recursive:!0}),await e.writeFile(i,r)}async function Hw(e,t,n,r){let i=0;for(let a of t){let t=Bw(a.path,n);t&&(await Vw(e,r,t,a.bytes),i++)}return i}async function Uw(e,t){await e.exists(t)&&await e.rm(t,{recursive:!0})}async function Ww(e,t){let n=vn(ew,t);if(await e.exists(n))throw Error(`Skill "${t}" already exists at ${n}.`);return n}async function Gw(e,t){Lw(t);let n=Mw(await Rw(t)),r=Nw(n),i=Iw(t.name,r.path);jw(i);let a=await Ww(e,i),o=Fw(i),s=zw(r);await e.mkdir(o,{recursive:!0});try{let t=await Hw(e,n,s,o);return await e.rename(o,a),{skillName:i,destinationPath:a,fileCount:t}}catch(t){throw await Uw(e,o),t}}var Kw=e({MAX_SKILL_ARCHIVE_SIZE_BYTES:()=>52428800,SKILLS_DIR:()=>`skills`,SKILL_ARCHIVE_EXTENSION:()=>$C,SKILL_FILE:()=>tw,WORKSPACE_SKILLS_PATH:()=>ew,discoverSkillCandidates:()=>uw,discoverSkills:()=>Cw,getSkillInfo:()=>ww,installSkillFromDrop:()=>Gw,readSkillInstructions:()=>Tw,resolveSkillNameCollisions:()=>mw});const qw=y(`skills`),Jw=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-BMBoR1hd.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-BMBoR1hd.js`).then(e=>e.default),"/packages/vfs-root/etc/APPROVALS.md":()=>import(`./APPROVALS-CoZKeFYV.js`).then(e=>e.default),"/packages/vfs-root/etc/MEMORY.md":()=>import(`./MEMORY-Dl8Y_nOo.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/etc/slicc/keys.json":()=>import(`./keys-BMebW-sj.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-Bzu6oiWk.js`).then(e=>e.default),"/packages/vfs-root/shared/GELATIERE.md":()=>import(`./GELATIERE-CLK_MA5a.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/suggestions/suggestions.shtml":()=>import(`./suggestions-B34zKgsF.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-BzW33ZtP.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/WIKI.md":()=>import(`./WIKI-DoBxwf2u.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/index.md":()=>import(`./wiki-BXN4hgmw.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/log.md":()=>import(`./log-DEDI5t_h.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-cOU0zXaK.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BNnF2azP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-BTVvFyRd.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/computer/SKILL.md":()=>import(`./SKILL-DB5CVwyu.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-rlhaTrPD.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-BmzmDv0e.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/patterns.md":()=>import(`./patterns-ChiGbijt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dns/SKILL.md":()=>import(`./SKILL-BKyxMoME.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ffmpeg/SKILL.md":()=>import(`./SKILL-C6co9TnL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/gelatiere/SKILL.md":()=>import(`./SKILL-DXpn0mQK.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-BGww2dFz.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/image-processing/SKILL.md":()=>import(`./SKILL-DpjPj8Lx.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/jshd/SKILL.md":()=>import(`./SKILL-DZoCcID_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/jshd/examples/fake-computer.jsh":()=>import(`./fake-computer-1f2_4vxY.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/meminfo/SKILL.md":()=>import(`./SKILL-DXIigmDy.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/memory/SKILL.md":()=>import(`./SKILL-DYIL6DC-.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-COPOzXIi.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-BS0BC3cr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-DGelbGt_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-BGEZa-y0.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-BnLXkzqP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/slicc/SKILL.md":()=>import(`./SKILL-CRLGKQWi.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":()=>import(`./SKILL-Bpepfqq0.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/icon-example.md":()=>import(`./icon-example-LUkiEXyS.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":()=>import(`./style-guide-BvFX24DM.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ssh/SKILL.md":()=>import(`./SKILL-BflWplWz.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/theme/SKILL.md":()=>import(`./SKILL-C9-SR5fY.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/transcript-export/SKILL.md":()=>import(`./SKILL-DJtLE66_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/upgrade/SKILL.md":()=>import(`./SKILL-3ejR48eL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/v86/SKILL.md":()=>import(`./SKILL-DEFDsScb.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/welcome/SKILL.md":()=>import(`./SKILL-C3909YTo.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/SKILL.md":()=>import(`./SKILL-UcxSfshP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/wiki.jsh":()=>import(`./wiki-DA0qKUVC.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/workflows/SKILL.md":()=>import(`./SKILL-Bt-RhG0L.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/SKILL.md":()=>import(`./SKILL-CED8RXQP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/x_search.jsh":()=>import(`./x_search-C-5p00-C.js`).then(e=>e.default)}),Yw=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function Xw(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}const Zw={};function Qw(){let e={};for(let[t,n]of Object.entries(Jw))e[t]=n;for(let[t,n]of Object.entries(Yw))e[t]=async()=>Xw(await n());for(let[t,n]of Object.entries(Zw)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function $w(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){qw.debug(`Skipped shadowed runtime skill`,{name:n.metadata.name,path:n.path,winnerPath:t.get(n.metadata.name)?.path});continue}t.set(n.metadata.name,n)}return Array.from(t.values())}function eT(e){let t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!t)return{metadata:{},body:e};let[,n,r]=t,i={};for(let e of n.split(`
|
|
1007
1007
|
`)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break;case`layout`:i.layout=a;break;case`theme`:i.theme=a}}return{metadata:i,body:r}}async function tT(e,t){let n=await nT(e,t),r=await rT(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=$w([...i,...r,...a]);return qw.info(`Skills loaded`,{count:o.length,dir:t}),o}async function nT(e,t){let n=await Cw(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=eT(await e.readTextFile(t.skillFilePath)),a=n.name||t.name;r.push({metadata:{name:a,description:n.description||t.description||``,allowedTools:n.allowedTools},content:i,path:t.skillFilePath,source:t.source}),qw.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{qw.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function rT(e,t){let n=[];try{let r=await e.readDir(t);for(let i of r)if(i.type===`file`&&i.name.endsWith(`.md`)){let r=`${t}/${i.name}`;try{let t=await e.readFile(r,{encoding:`utf-8`}),{metadata:a,body:o}=eT(typeof t==`string`?t:new TextDecoder().decode(t)),s=a.name||i.name.replace(`.md`,``);n.push({metadata:{name:s,description:a.description||``,allowedTools:a.allowedTools},content:o,path:r}),qw.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{qw.debug(`Standalone skills directory not found`,{dir:t})}return n}function iT(e){return e.length===0?``:`
|
|
1008
1008
|
---
|
|
1009
1009
|
AVAILABLE SKILLS
|
|
@@ -1025,9 +1025,9 @@ ${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowed
|
|
|
1025
1025
|
`)+`
|
|
1026
1026
|
`;await e.writeFile(`/workspace/CLAUDE.md`,l);let u=a.length;for(;u>0&&a[u-1]===``;)u--;let d=u===0?``:a.slice(0,u).join(`
|
|
1027
1027
|
`)+`
|
|
1028
|
-
`;await e.writeFile(`/shared/CLAUDE.md`,d),this.globalMemoryCache=d,await this.writeMigrationSentinel(t),cT.info(`Migrated legacy cone memory from /shared/CLAUDE.md to /workspace/CLAUDE.md`,{blockCount:i.length})}async writeMigrationSentinel(e){let t=this.deps.getSharedFs();if(t){try{await t.mkdir(`/workspace`,{recursive:!0})}catch{}await t.writeFile(e,`Migration completed at ${new Date().toISOString()}\n`)}}};function dT(e){return Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)}function fT(e,t){return e.y===t.y&&e.m===t.m&&e.d===t.d&&e.h===t.h&&e.i===t.i&&e.s===t.s}function pT(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`Invalid ISO8601 passed to timezone parser.`);let r=e.substring(9);return r.includes(`Z`)||r.includes(`+`)||r.includes(`-`)?_T(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):_T(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}function mT(e,t,n){return hT(pT(e,t),n)}function hT(e,t){let n=new Date(dT(e)),r=gT(n,e.tz),i=dT(e)-dT(r),a=new Date(n.getTime()+i),o=gT(a,e.tz);if(fT(o,e)){let t=new Date(a.getTime()-36e5);return fT(gT(t,e.tz),e)?t:a}let s=new Date(a.getTime()+dT(e)-dT(o));if(fT(gT(s,e.tz),e))return s;if(t)throw Error(`Invalid date passed to fromTZ()`);return a.getTime()>s.getTime()?a:s}function gT(e,t){let n,r;try{n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,hour12:!1}),r=n.formatToParts(e)}catch(e){let n=e instanceof Error?e.message:String(e);throw RangeError(`toTZ: Invalid timezone '${t}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${n}`)}let i={year:0,month:0,day:0,hour:0,minute:0,second:0};for(let e of r)(e.type===`year`||e.type===`month`||e.type===`day`||e.type===`hour`||e.type===`minute`||e.type===`second`)&&(i[e.type]=parseInt(e.value,10));if(isNaN(i.year)||isNaN(i.month)||isNaN(i.day)||isNaN(i.hour)||isNaN(i.minute)||isNaN(i.second))throw Error(`toTZ: Failed to parse all date components from timezone '${t}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(i)}`);return i.hour===24&&(i.hour=0),{y:i.year,m:i.month,d:i.day,h:i.hour,i:i.minute,s:i.second,tz:t}}function _T(e,t,n,r,i,a,o){return{y:e,m:t,d:n,h:r,i,s:a,tz:o}}var vT=[1,2,4,8,16],yT=class{pattern;timezone;mode;alternativeWeekdays;sloppyRanges;second;minute;hour;day;month;dayOfWeek;year;lastDayOfMonth;lastWeekday;nearestWeekdays;starDOM;starDOW;starYear;useAndLogic;constructor(e,t,n){this.pattern=e,this.timezone=t,this.mode=n?.mode??`auto`,this.alternativeWeekdays=n?.alternativeWeekdays??!1,this.sloppyRanges=n?.sloppyRanges??!1,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.year=Array(1e4).fill(0),this.lastDayOfMonth=!1,this.lastWeekday=!1,this.nearestWeekdays=Array(31).fill(0),this.starDOM=!1,this.starDOW=!1,this.starYear=!1,this.useAndLogic=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.match(/\S+/g)||[``],t=e.length;if(e.length<5||e.length>7)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five, six, or seven space separated parts are required.`);if(this.mode!==`auto`){let e;switch(this.mode){case`5-part`:e=5;break;case`6-part`:e=6;break;case`7-part`:e=7;break;case`5-or-6-parts`:e=[5,6];break;case`6-or-7-parts`:e=[6,7];break;default:e=0}if(!(Array.isArray(e)?e.includes(t):t===e)){let n=Array.isArray(e)?e.join(` or `):e.toString();throw TypeError(`CronPattern: mode '${this.mode}' requires exactly ${n} parts, but pattern '${this.pattern}' has ${t} parts.`)}}if(e.length===5&&e.unshift(`0`),e.length===6&&e.push(`*`),e[3].toUpperCase()===`LW`?(this.lastWeekday=!0,e[3]=``):e[3].toUpperCase().indexOf(`L`)>=0&&(e[3]=e[3].replace(/L/gi,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[6]==`*`&&(this.starYear=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.alternativeWeekdays?this.replaceAlphaDaysQuartz(e[5]):this.replaceAlphaDays(e[5])),e[5].startsWith(`+`)&&(this.useAndLogic=!0,e[5]=e[5].substring(1),e[5]===``))throw TypeError(`CronPattern: Day-of-week field cannot be empty after '+' modifier.`);switch(e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0&&(e[0]=e[0].replace(/\?/g,`*`),e[1]=e[1].replace(/\?/g,`*`),e[2]=e[2].replace(/\?/g,`*`),e[3]=e[3].replace(/\?/g,`*`),e[4]=e[4].replace(/\?/g,`*`),e[5]=e[5].replace(/\?/g,`*`),e[6]&&=e[6].replace(/\?/g,`*`)),this.mode){case`5-part`:e[0]=`0`,e[6]=`*`;break;case`6-part`:e[6]=`*`;break;case`5-or-6-parts`:e[6]=`*`}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1);let n=this.alternativeWeekdays?-1:0;this.partToArray(`dayOfWeek`,e[5],n,63),this.partToArray(`year`,e[6],0,1),!this.alternativeWeekdays&&this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth,o=e===`day`&&this.lastWeekday;if(t===``&&!a&&!o)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let s=t.split(`,`);if(s.length>1)for(let t=0;t<s.length;t++)this.partToArray(e,s[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===3?/[^/*0-9,\-WwLl]+/:t===5?/[^/*0-9,\-#Ll]+/:/[^/*0-9,\-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=e.toUpperCase().includes(`W`);if(t!==`day`&&a)throw TypeError(`CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.`);a&&(t=`nearestWeekdays`);let o=parseInt(i[0],10)+n;if(isNaN(o))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,o,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`||e===`nearestWeekdays`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`){if(t<0||t>=12)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`year`&&(t<1||t>=1e4))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t+` (supported range: 1-9999)`);this[e][t]=n}validateNotNaN(e,t){if(isNaN(e))throw TypeError(t)}validateRange(e,t,n,r,i){if(e>t)throw TypeError(`CronPattern: From value is larger than to value: '`+i+`'`);if(n!==void 0){if(n===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(n>this[r].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[r].length+`)`)}}handleRangeWithStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in ranges with stepping.`);let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);this.validateNotNaN(l,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(u,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateNotNaN(d,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(l,u,d,t,e);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}else if(n.toUpperCase().endsWith(`L`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)`);r=`L`,n=n.slice(0,-1)}return[n,r]}handleRange(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in a range.`);let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;this.validateNotNaN(o,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(s,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateRange(o,s,void 0,t,e);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in parts with stepping.`);let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);if(this.sloppyRanges)a[0]===``&&(a[0]=`*`);else{if(a[0]===``)throw TypeError(`CronPattern: Syntax error, stepping with missing prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`);if(a[0]!==`*`)throw TypeError(`CronPattern: Syntax error, stepping with numeric prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`)}let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);this.validateNotNaN(s,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(0,this[t].length-1,s,t,e);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaDaysQuartz(e){return e.replace(/sun/gi,`1`).replace(/mon/gi,`2`).replace(/tue/gi,`3`).replace(/wed/gi,`4`).replace(/thu/gi,`5`).replace(/fri/gi,`6`).replace(/sat/gi,`7`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();if(t===`@yearly`||t===`@annually`)return`0 0 1 1 *`;if(t===`@monthly`)return`0 0 1 * *`;if(t===`@weekly`)return`0 0 * * 0`;if(t===`@daily`||t===`@midnight`)return`0 0 * * *`;if(t===`@hourly`)return`0 * * * *`;if(t===`@reboot`)throw TypeError(`CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.`);return e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t.toUpperCase()===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|32;else if(t===63)this.dayOfWeek[e]=63;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|vT[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},bT=[31,28,31,30,31,30,31,31,30,31,30,31],J=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Y=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date){if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`)}else if(t==null)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}getLastDayOfMonth(e,t){return t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():bT[t]}getLastWeekday(e,t){let n=this.getLastDayOfMonth(e,t),r=new Date(Date.UTC(e,t,n)).getUTCDay();return r===0?n-2:r===6?n-1:n}getNearestWeekday(e,t,n){let r=this.getLastDayOfMonth(e,t);if(n>r)return-1;let i=new Date(Date.UTC(e,t,n)).getUTCDay();return i===0?n===r?n-2:n+1:i===6?n===1?n+2:n-1:n}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&63&&vT[a-1]&r)return!0;if(r&32){let r=this.getLastDayOfMonth(e,t);for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0){if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else try{let t=gT(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${t}`)}}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.month<0||this.day>bT[this.month]||this.day<1||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}return!1}fromString(e){if(typeof this.tz==`number`){let t=mT(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(mT(e,this.tz))}findNext(e,t,n,r){return this._findMatch(e,t,n,r,1)}_findMatch(e,t,n,r,i){let a=this[t],o;n.lastDayOfMonth&&(o=this.getLastDayOfMonth(this.year,this.month));let s=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0,c=this[t]+r,l=i===1?e=>e<n[t].length:e=>e>=0;for(let u=c;l(u);u+=i){let i=n[t][u];if(t===`day`&&!i){for(let e=0;e<n.nearestWeekdays.length;e++)if(n.nearestWeekdays[e]){let t=this.getNearestWeekday(this.year,this.month,e-r);if(t===-1)continue;if(t===u-r){i=1;break}}}if(t===`day`&&n.lastWeekday){let e=this.getLastWeekday(this.year,this.month);u-r===e&&(i=1)}if(t===`day`&&n.lastDayOfMonth&&u-r==o&&(i=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(s+(u-r-1))%7];if(t&&t&63)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,u-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);n.useAndLogic?i&&=t:!e.domAndDow&&!n.starDOM?i||=t:i&&=t}if(i)return this[t]=u-r,a===this[t]?1:2}return 3}recurse(e,t,n){if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year+1;n<e.year.length&&n<1e4;n++)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=0,this.day=1,this.hour=0,this.minute=0,this.second=0,this.ms=0}if(this.year>=1e4)return null}let r=this.findNext(t,J[n][0],e,J[n][2]);if(r>1){let i=n+1;for(;i<J.length;)this[J[i][0]]=-J[i][2],i++;if(r===3){if(this[J[n][1]]++,this[J[n][0]]=-J[n][2],this.apply(),n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0&&this.year<1e4;)this.year++;if(this.year>=1e4||this.year>=e.year.length)return null}return this.recurse(e,t,0)}if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=J.length?this:(e.starYear?this.year>=3e3:this.year>=1e4)?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}decrement(e,t){return this.second-=t.interval!==void 0&&t.interval>1?t.interval:1,this.ms=0,this.apply(),this.recurseBackward(e,t,0,0)}recurseBackward(e,t,n,r=0){if(r>1e4)return null;if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year-1;n>=0;n--)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=11,this.day=31,this.hour=23,this.minute=59,this.second=59,this.ms=0}if(this.year<0)return null}let i=this.findPrevious(t,J[n][0],e,J[n][2]);if(i>1){let a=n+1;for(;a<J.length;){let t=J[a][0],n=J[a][2],r=this.getMaxPatternValue(t,e,n);this[t]=r,a++}if(i===3){if(this[J[n][1]]--,n===0){let e=this.getLastDayOfMonth(this.year,this.month);this.day>e&&(this.day=e)}if(n===1){if(this.day<=0)this.day=1;else{let e=this.year,t=this.month;for(;t<0;)t+=12,e--;for(;t>11;)t-=12,e++;let n=t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():bT[t];this.day>n&&(this.day=n)}}this.apply();let i=J[n][0],a=J[n][2],o=this.getMaxPatternValue(i,e,a);if(i===`day`){let e=this.getLastDayOfMonth(this.year,this.month);this[i]=Math.min(o,e)}else this[i]=o;if(this.apply(),n===0){let t=J[1][2],n=this.getMaxPatternValue(`day`,e,t),r=this.getLastDayOfMonth(this.year,this.month),i=Math.min(n,r);i!==this.day&&(this.day=i,this.hour=this.getMaxPatternValue(`hour`,e,J[2][2]),this.minute=this.getMaxPatternValue(`minute`,e,J[3][2]),this.second=this.getMaxPatternValue(`second`,e,J[4][2]))}if(n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0;)this.year--;if(this.year<0)return null}return this.recurseBackward(e,t,0,r+1)}if(this.apply())return this.recurseBackward(e,t,n-1,r+1)}return n+=1,n>=J.length?this:this.year<0?null:this.recurseBackward(e,t,n,r+1)}getMaxPatternValue(e,t,n){if(e===`day`&&t.lastDayOfMonth||e===`day`&&!t.starDOW)return this.getLastDayOfMonth(this.year,this.month);for(let r=t[e].length-1;r>=0;r--)if(t[e][r])return r-n;return t[e].length-1-n}findPrevious(e,t,n,r){return this._findMatch(e,t,n,r,-1)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):hT(_T(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}match(e,t){if(!e.starYear&&(this.year<0||this.year>=e.year.length||e.year[this.year]===0))return!1;for(let n=0;n<J.length;n++){let r=J[n][0],i=J[n][2],a=this[r];if(a+i<0||a+i>=e[r].length)return!1;let o=e[r][a+i];if(r===`day`){if(!o){for(let t=0;t<e.nearestWeekdays.length;t++)if(e.nearestWeekdays[t]){let e=this.getNearestWeekday(this.year,this.month,t-i);if(e!==-1&&e===a){o=1;break}}}if(e.lastWeekday&&a===this.getLastWeekday(this.year,this.month)&&(o=1),e.lastDayOfMonth&&a===this.getLastDayOfMonth(this.year,this.month)&&(o=1),!e.starDOW){let n=new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay(),r=e.dayOfWeek[(n+(a-1))%7];r&&r&63&&(r=+!!this.isNthWeekdayOfMonth(this.year,this.month,a,r)),e.useAndLogic?o&&=r:!t.domAndDow&&!e.starDOM?o||=r:o&&=r}}if(!o)return!1}return!0}};function xT(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode!==void 0&&e.domAndDow===void 0?e.domAndDow=!e.legacyMode:e.domAndDow===void 0&&(e.domAndDow=!1),e.legacyMode=!e.domAndDow,e.paused=e.paused!==void 0&&e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch!==void 0&&e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.dayOffset=e.dayOffset===void 0?0:parseInt(e.dayOffset.toString(),10),e.unref=e.unref!==void 0&&e.unref,e.mode=e.mode===void 0?`auto`:e.mode,e.alternativeWeekdays=e.alternativeWeekdays!==void 0&&e.alternativeWeekdays,e.sloppyRanges=e.sloppyRanges!==void 0&&e.sloppyRanges,![`auto`,`5-part`,`6-part`,`7-part`,`5-or-6-parts`,`6-or-7-parts`].includes(e.mode))throw Error(`CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.`);if(e.startAt&&(e.startAt=new Y(e.startAt,e.timezone)),e.stopAt&&(e.stopAt=new Y(e.stopAt,e.timezone)),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);if(e.dayOffset!==void 0&&e.dayOffset!==0&&isNaN(e.dayOffset))throw Error(`CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.`);return e}function ST(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function CT(e){return ST(e)}function wT(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var TT=3e4,ET=[],DT=class{name;options;_states;fn;getTz(){return this.options.timezone||this.options.utcOffset}applyDayOffset(e){if(this.options.dayOffset!==void 0&&this.options.dayOffset!==0){let t=this.options.dayOffset*24*60*60*1e3;return new Date(e.getTime()+t)}return e}constructor(e,t,n){let r,i;if(ST(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(ST(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=xT(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new yT(`* * * * *`,void 0,{mode:`auto`})},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Y(e,this.getTz()):this._states.pattern=new yT(e,this.options.timezone,{mode:this.options.mode,alternativeWeekdays:this.options.alternativeWeekdays,sloppyRanges:this.options.sloppyRanges}),this.name){if(ET.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);ET.push(this)}return i!==void 0&&CT(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?this.applyDayOffset(t.getDate(!1)):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=t||this._states.currentRun||void 0;return this._enumerateRuns(e,n,`next`)}previousRuns(e,t){return this._enumerateRuns(e,t||void 0,`previous`)}_enumerateRuns(e,t,n){let r=[],i=t?new Y(t,this.getTz()):null,a=n===`next`?this._next:this._previous;for(;e--;){let e=a.call(this,i);if(!e)break;let t=e.getDate(!1);r.push(this.applyDayOffset(t)),i=e}return r}match(e){if(this._states.once){let t=new Y(e,this.getTz());t.ms=0;let n=new Y(this._states.once,this.getTz());return n.ms=0,t.getTime()===n.getTime()}let t=new Y(e,this.getTz());return t.ms=0,t.match(this._states.pattern,this.options)}getPattern(){if(!this._states.once)return this._states.pattern?this._states.pattern.pattern:void 0}getOnce(){return this._states.once?this._states.once.getDate():null}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Y||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Y(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=ET.indexOf(this);e>=0&&ET.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>TT&&(t=TT),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&wT(this._states.currentTimeout),this)}async _trigger(e){this._states.blocking=!0,this._states.currentRun=new Y(void 0,this.getTz());try{if(this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){if(ST(this.options.catch))try{this.options.catch(e,this)}catch{}}else this.fn!==void 0&&await this.fn(this,this.options.context)}finally{this._states.previousRun=new Y(e,this.getTz()),this._states.blocking=!1}}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&ST(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Y(e,this.getTz()),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Y(e,this.getTz());return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_previous(e){let t=new Y(e,this.getTz());this.options.stopAt&&t.getTime()>this.options.stopAt.getTime()&&(t=this.options.stopAt);let n=new Y(t,this.getTz());return this._states.once?this._states.once.getTime()<t.getTime()?this._states.once:null:(n=n.decrement(this._states.pattern,this.options),n===null||this.options.startAt&&n.getTime()<this.options.startAt.getTime()?null:n)}_calculatePreviousRun(e,t){let n=new Y(void 0,this.getTz()),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Y(r,this.getTz()).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function OT(e,t){try{return new DT(e.trim(),{domAndDow:!0}).nextRun(t)??null}catch{return null}}var kT=e({FORWARDABLE_TO_LEADER:()=>AT,LickManager:()=>NT,buildActiveLicksError:()=>IT,getLickManager:()=>RT,lickScoopMatches:()=>PT,lickTargetCandidates:()=>FT});const X=y(`lick-manager`),AT=new Set([`navigate`,`discovery`]);function jT(e){if(typeof e!=`object`||!e)return null;let t=e;return typeof t.verb!=`string`||typeof t.target!=`string`?null:ue({verb:t.verb,target:t.target,branch:typeof t.branch==`string`?t.branch:void 0,path:typeof t.path==`string`?t.path:void 0,instruction:typeof t.instruction==`string`?t.instruction:void 0})}function MT(e){return!e.discoveryKind&&!e.discoveryUrl&&!e.discoveryOrigin?null:Pa({origin:e.discoveryOrigin,kind:e.discoveryKind,url:e.discoveryUrl})}var NT=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;forwarder=null;seenNavigateFingerprints=new Set;seenDiscoveryFingerprints=new Set;unitRoster=null;discoveryIgnore=null;async init(){await vb();let e=await xb();for(let t of e)this.webhooks.set(t.id,t);X.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Tb();for(let e of t)this.crontasks.set(e.id,e);X.info(`Loaded crontasks`,{count:this.crontasks.size}),await this.reconcileOrphans(),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),X.info(`Cron scheduler started`)}setUnitRosterProvider(e){this.unitRoster=e}resolveLickTarget(e){let t=this.unitRoster?.();return t?t.some(t=>PT(e,t.name,t.folder))?{status:`resolved`}:{status:`unresolved`,candidates:FT(t)}:{status:`unverifiable`}}setDiscoveryIgnore(e){this.discoveryIgnore=e}isOrphanedLick(e){return e?this.resolveLickTarget(e).status===`unresolved`:!1}async reconcileOrphans(){if(this.unitRoster){for(let e of Array.from(this.webhooks.values()))if(this.isOrphanedLick(e.scoop)){X.warn(`Removing orphaned webhook at init; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.webhooks.delete(e.id);try{await Sb(e.id)}catch(t){X.warn(`Failed to delete orphaned webhook from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}for(let e of Array.from(this.crontasks.values()))if(this.isOrphanedLick(e.scoop)){X.warn(`Removing orphaned cron task at init; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.crontasks.delete(e.id);try{await Eb(e.id)}catch(t){X.warn(`Failed to delete orphaned cron task from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}}}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}setForwarder(e){this.forwarder=e}dispatch(e){if(!(e.type===`discovery`&&this.shouldSuppressDiscovery(e))){if(this.forwarder&&AT.has(e.type)){this.forwarder(e);return}this.eventHandler?.(e)}}handleForwardedEvent(e){e.type===`discovery`&&this.shouldSuppressDiscovery(e)||this.isDuplicateFingerprint(e)||this.eventHandler?.(e)}emitEvent(e){e.type===`discovery`&&this.shouldSuppressDiscovery(e)||this.isDuplicateFingerprint(e)||(X.info(`External lick event`,{type:e.type,target:e.targetScoop}),this.dispatch(e))}isDuplicateFingerprint(e){let t=null,n,r;if(e.type===`navigate`)t=jT(e.body),n=this.seenNavigateFingerprints,r=`navigate`;else if(e.type===`discovery`)t=MT(e),n=this.seenDiscoveryFingerprints,r=`discovery`;else return!1;return t===null?!1:n.has(t)?(X.debug(`Suppressing duplicate ${r} lick`,{fingerprint:t}),!0):(n.add(t),!1)}shouldSuppressDiscovery(e){return e.discoverySource===`live-navigation`?this.discoveryIgnore?.(e)?(X.debug(`Suppressing ignored llms.txt discovery`,{origin:e.discoveryOrigin}),!0):!1:(X.debug(`Suppressing discovery without live-navigation provenance`),!0)}async createWebhook(e,t,n){let r=this.generateId(),i={id:r,name:e,createdAt:new Date().toISOString(),filter:n,scoop:t};return n&&this.compileFilter(n,!0),this.webhooks.set(r,i),await yb(i),X.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await Sb(e),X.info(`Webhook deleted`,{id:e}),!0):await bb(e)!==null&&(await Sb(e),X.info(`Webhook deleted`,{id:e}),!0)}listWebhooks(){return Array.from(this.webhooks.values())}getWebhook(e){return this.webhooks.get(e)}handleWebhookEvent(e,t,n){let r=this.webhooks.get(e);if(!r)return X.warn(`Webhook not found`,{webhookId:e}),`unknown-webhook`;if(this.isOrphanedLick(r.scoop))return X.warn(`Webhook target scoop not found — dropping delivery`,{webhookId:e,name:r.name,scoop:r.scoop}),`unresolved-target`;let i={type:`webhook`,webhookId:e,webhookName:r.name,targetScoop:r.scoop,timestamp:new Date().toISOString(),headers:t,body:n};if(r.filter)try{let t=this.compileFilter(r.filter,!0)(i);if(t===!1)return X.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name}),`filtered`;typeof t==`object`&&t&&(i=t)}catch(t){X.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}return X.info(`Webhook event received`,{webhookId:e,name:r.name,targetScoop:r.scoop}),this.dispatch(i),`delivered`}async createCronTask(e,t,n,r){let i=OT(t,new Date);if(!i)throw Error(`Invalid cron expression`);r&&this.compileFilter(r,!1);let a=this.generateId(),o={id:a,name:e,cron:t,scoop:n,filter:r,nextRun:i.toISOString(),lastRun:null,status:`active`,createdAt:new Date().toISOString()};return this.crontasks.set(a,o),await Cb(o),X.info(`Cron task created`,{id:a,name:e,cron:t,scoop:n}),o}async deleteCronTask(e){return this.crontasks.has(e)?(this.crontasks.delete(e),await Eb(e),X.info(`Cron task deleted`,{id:e}),!0):await wb(e)!==null&&(await Eb(e),X.info(`Cron task deleted`,{id:e}),!0)}listCronTasks(){return Array.from(this.crontasks.values())}getCronTask(e){return this.crontasks.get(e)}getLicksForScoop(e,t){return{webhooks:Array.from(this.webhooks.values()).filter(n=>PT(n.scoop,e,t)),cronTasks:Array.from(this.crontasks.values()).filter(n=>PT(n.scoop,e,t))}}async getLicksForScoopFromDb(e,t){let[n,r]=await Promise.all([xb(),Tb()]);return{webhooks:n.filter(n=>PT(n.scoop,e,t)),cronTasks:r.filter(n=>PT(n.scoop,e,t))}}async deleteIfOrphanedCron(e){if(!this.isOrphanedLick(e.scoop))return!1;X.warn(`Deleting orphaned cron task; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.crontasks.delete(e.id);try{await Eb(e.id)}catch(t){X.warn(`Failed to delete orphaned cron task from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}return!0}async runCronScheduler(){let e=new Date;for(let t of this.crontasks.values())await this.deleteIfOrphanedCron(t)||t.status===`active`&&t.nextRun&&(new Date(t.nextRun)>e||await this.runDueCronTask(t,e))}async runDueCronTask(e,t){let n={time:t.toISOString()};if(e.filter)try{let r=this.compileFilter(e.filter,!1)(null);if(r===!1){X.debug(`Cron task skipped by filter`,{id:e.id,name:e.name}),e.nextRun=OT(e.cron,t)?.toISOString()??null,e.lastRun=t.toISOString(),await Cb(e);return}typeof r==`object`&&r&&(n=r)}catch(t){X.error(`Cron filter error`,{id:e.id,error:t instanceof Error?t.message:String(t)})}let r={type:`cron`,cronId:e.id,cronName:e.name,targetScoop:e.scoop,timestamp:t.toISOString(),body:n};X.info(`Cron task running`,{id:e.id,name:e.name}),this.dispatch(r),e.nextRun=OT(e.cron,t)?.toISOString()??null,e.lastRun=t.toISOString(),await Cb(e)}generateId(){let e=``;for(let t=0;t<12;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return e}compileFilter(e,t){try{return t?Function(`event`,`return (${e})(event);`):Function(`return (${e})();`)}catch(e){throw Error(`Invalid filter function: ${e instanceof Error?e.message:String(e)}`)}}};function PT(e,t,n){return e?e===t||e===n||`${e}-scoop`===n:!1}function FT(e){let t=new Set;for(let n of e)t.add(n.folder),n.name&&n.name!==n.folder&&t.add(n.name);return Array.from(t)}function IT(e,t,n){if(t.length===0&&n.length===0)return null;let r=[];t.length>0&&r.push(`${t.length} active webhook${t.length>1?`s`:``}`),n.length>0&&r.push(`${n.length} active cron task${n.length>1?`s`:``}`);let i=[...t.map(e=>` webhook delete ${e.id}`),...n.map(e=>` crontask delete ${e.id}`)].join(`
|
|
1029
|
-
`);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}let LT=null;function RT(){return LT||=new NT,LT}function zT(e){if(e.kind===`local`)return`mount ${
|
|
1030
|
-
`)}async resolveSessionReloadPlain(e,t){return t.decision===`deny`?(this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:!1,message:`Session-reload notice acknowledged.`}):{settled:!0,persisted:!1,message:`Nothing to confirm — the reload already completed. Use lick_dismiss to acknowledge and clear this notice.`}}async resolveUpgrade(e,t,n){this.entries.delete(e);let r;return r=n.decision===`deny`?`Upgrade dismissed — workspace files were left unchanged.`:await this.runUpgrade(t),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async resolveDiscovery(e,t,n){if(n.decision!==`deny`)return{settled:!0,persisted:!1,message:`Nothing to confirm — use lick_dismiss to ignore this llms.txt host.`};let r=this.deps.getConeFs();if(!r)throw Error(`llms.txt dismissal could not persist: cone filesystem unavailable.`);let i=await
|
|
1028
|
+
`;await e.writeFile(`/shared/CLAUDE.md`,d),this.globalMemoryCache=d,await this.writeMigrationSentinel(t),cT.info(`Migrated legacy cone memory from /shared/CLAUDE.md to /workspace/CLAUDE.md`,{blockCount:i.length})}async writeMigrationSentinel(e){let t=this.deps.getSharedFs();if(t){try{await t.mkdir(`/workspace`,{recursive:!0})}catch{}await t.writeFile(e,`Migration completed at ${new Date().toISOString()}\n`)}}};function dT(e){return Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)}function fT(e,t){return e.y===t.y&&e.m===t.m&&e.d===t.d&&e.h===t.h&&e.i===t.i&&e.s===t.s}function pT(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`Invalid ISO8601 passed to timezone parser.`);let r=e.substring(9);return r.includes(`Z`)||r.includes(`+`)||r.includes(`-`)?_T(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):_T(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}function mT(e,t,n){return hT(pT(e,t),n)}function hT(e,t){let n=new Date(dT(e)),r=gT(n,e.tz),i=dT(e)-dT(r),a=new Date(n.getTime()+i),o=gT(a,e.tz);if(fT(o,e)){let t=new Date(a.getTime()-36e5);return fT(gT(t,e.tz),e)?t:a}let s=new Date(a.getTime()+dT(e)-dT(o));if(fT(gT(s,e.tz),e))return s;if(t)throw Error(`Invalid date passed to fromTZ()`);return a.getTime()>s.getTime()?a:s}function gT(e,t){let n,r;try{n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,hour12:!1}),r=n.formatToParts(e)}catch(e){let n=e instanceof Error?e.message:String(e);throw RangeError(`toTZ: Invalid timezone '${t}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${n}`)}let i={year:0,month:0,day:0,hour:0,minute:0,second:0};for(let e of r)(e.type===`year`||e.type===`month`||e.type===`day`||e.type===`hour`||e.type===`minute`||e.type===`second`)&&(i[e.type]=parseInt(e.value,10));if(isNaN(i.year)||isNaN(i.month)||isNaN(i.day)||isNaN(i.hour)||isNaN(i.minute)||isNaN(i.second))throw Error(`toTZ: Failed to parse all date components from timezone '${t}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(i)}`);return i.hour===24&&(i.hour=0),{y:i.year,m:i.month,d:i.day,h:i.hour,i:i.minute,s:i.second,tz:t}}function _T(e,t,n,r,i,a,o){return{y:e,m:t,d:n,h:r,i,s:a,tz:o}}var vT=[1,2,4,8,16],yT=class{pattern;timezone;mode;alternativeWeekdays;sloppyRanges;second;minute;hour;day;month;dayOfWeek;year;lastDayOfMonth;lastWeekday;nearestWeekdays;starDOM;starDOW;starYear;useAndLogic;constructor(e,t,n){this.pattern=e,this.timezone=t,this.mode=n?.mode??`auto`,this.alternativeWeekdays=n?.alternativeWeekdays??!1,this.sloppyRanges=n?.sloppyRanges??!1,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.year=Array(1e4).fill(0),this.lastDayOfMonth=!1,this.lastWeekday=!1,this.nearestWeekdays=Array(31).fill(0),this.starDOM=!1,this.starDOW=!1,this.starYear=!1,this.useAndLogic=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.match(/\S+/g)||[``],t=e.length;if(e.length<5||e.length>7)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five, six, or seven space separated parts are required.`);if(this.mode!==`auto`){let e;switch(this.mode){case`5-part`:e=5;break;case`6-part`:e=6;break;case`7-part`:e=7;break;case`5-or-6-parts`:e=[5,6];break;case`6-or-7-parts`:e=[6,7];break;default:e=0}if(!(Array.isArray(e)?e.includes(t):t===e)){let n=Array.isArray(e)?e.join(` or `):e.toString();throw TypeError(`CronPattern: mode '${this.mode}' requires exactly ${n} parts, but pattern '${this.pattern}' has ${t} parts.`)}}if(e.length===5&&e.unshift(`0`),e.length===6&&e.push(`*`),e[3].toUpperCase()===`LW`?(this.lastWeekday=!0,e[3]=``):e[3].toUpperCase().indexOf(`L`)>=0&&(e[3]=e[3].replace(/L/gi,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[6]==`*`&&(this.starYear=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.alternativeWeekdays?this.replaceAlphaDaysQuartz(e[5]):this.replaceAlphaDays(e[5])),e[5].startsWith(`+`)&&(this.useAndLogic=!0,e[5]=e[5].substring(1),e[5]===``))throw TypeError(`CronPattern: Day-of-week field cannot be empty after '+' modifier.`);switch(e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0&&(e[0]=e[0].replace(/\?/g,`*`),e[1]=e[1].replace(/\?/g,`*`),e[2]=e[2].replace(/\?/g,`*`),e[3]=e[3].replace(/\?/g,`*`),e[4]=e[4].replace(/\?/g,`*`),e[5]=e[5].replace(/\?/g,`*`),e[6]&&=e[6].replace(/\?/g,`*`)),this.mode){case`5-part`:e[0]=`0`,e[6]=`*`;break;case`6-part`:e[6]=`*`;break;case`5-or-6-parts`:e[6]=`*`}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1);let n=this.alternativeWeekdays?-1:0;this.partToArray(`dayOfWeek`,e[5],n,63),this.partToArray(`year`,e[6],0,1),!this.alternativeWeekdays&&this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth,o=e===`day`&&this.lastWeekday;if(t===``&&!a&&!o)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let s=t.split(`,`);if(s.length>1)for(let t=0;t<s.length;t++)this.partToArray(e,s[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===3?/[^/*0-9,\-WwLl]+/:t===5?/[^/*0-9,\-#Ll]+/:/[^/*0-9,\-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=e.toUpperCase().includes(`W`);if(t!==`day`&&a)throw TypeError(`CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.`);a&&(t=`nearestWeekdays`);let o=parseInt(i[0],10)+n;if(isNaN(o))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,o,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`||e===`nearestWeekdays`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`){if(t<0||t>=12)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`year`&&(t<1||t>=1e4))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t+` (supported range: 1-9999)`);this[e][t]=n}validateNotNaN(e,t){if(isNaN(e))throw TypeError(t)}validateRange(e,t,n,r,i){if(e>t)throw TypeError(`CronPattern: From value is larger than to value: '`+i+`'`);if(n!==void 0){if(n===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(n>this[r].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[r].length+`)`)}}handleRangeWithStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in ranges with stepping.`);let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);this.validateNotNaN(l,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(u,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateNotNaN(d,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(l,u,d,t,e);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}else if(n.toUpperCase().endsWith(`L`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)`);r=`L`,n=n.slice(0,-1)}return[n,r]}handleRange(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in a range.`);let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;this.validateNotNaN(o,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(s,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateRange(o,s,void 0,t,e);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in parts with stepping.`);let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);if(this.sloppyRanges)a[0]===``&&(a[0]=`*`);else{if(a[0]===``)throw TypeError(`CronPattern: Syntax error, stepping with missing prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`);if(a[0]!==`*`)throw TypeError(`CronPattern: Syntax error, stepping with numeric prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`)}let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);this.validateNotNaN(s,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(0,this[t].length-1,s,t,e);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaDaysQuartz(e){return e.replace(/sun/gi,`1`).replace(/mon/gi,`2`).replace(/tue/gi,`3`).replace(/wed/gi,`4`).replace(/thu/gi,`5`).replace(/fri/gi,`6`).replace(/sat/gi,`7`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();if(t===`@yearly`||t===`@annually`)return`0 0 1 1 *`;if(t===`@monthly`)return`0 0 1 * *`;if(t===`@weekly`)return`0 0 * * 0`;if(t===`@daily`||t===`@midnight`)return`0 0 * * *`;if(t===`@hourly`)return`0 * * * *`;if(t===`@reboot`)throw TypeError(`CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.`);return e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t.toUpperCase()===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|32;else if(t===63)this.dayOfWeek[e]=63;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|vT[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},bT=[31,28,31,30,31,30,31,31,30,31,30,31],J=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Y=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date){if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`)}else if(t==null)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}getLastDayOfMonth(e,t){return t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():bT[t]}getLastWeekday(e,t){let n=this.getLastDayOfMonth(e,t),r=new Date(Date.UTC(e,t,n)).getUTCDay();return r===0?n-2:r===6?n-1:n}getNearestWeekday(e,t,n){let r=this.getLastDayOfMonth(e,t);if(n>r)return-1;let i=new Date(Date.UTC(e,t,n)).getUTCDay();return i===0?n===r?n-2:n+1:i===6?n===1?n+2:n-1:n}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&63&&vT[a-1]&r)return!0;if(r&32){let r=this.getLastDayOfMonth(e,t);for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0){if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else try{let t=gT(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${t}`)}}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.month<0||this.day>bT[this.month]||this.day<1||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}return!1}fromString(e){if(typeof this.tz==`number`){let t=mT(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(mT(e,this.tz))}findNext(e,t,n,r){return this._findMatch(e,t,n,r,1)}_findMatch(e,t,n,r,i){let a=this[t],o;n.lastDayOfMonth&&(o=this.getLastDayOfMonth(this.year,this.month));let s=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0,c=this[t]+r,l=i===1?e=>e<n[t].length:e=>e>=0;for(let u=c;l(u);u+=i){let i=n[t][u];if(t===`day`&&!i){for(let e=0;e<n.nearestWeekdays.length;e++)if(n.nearestWeekdays[e]){let t=this.getNearestWeekday(this.year,this.month,e-r);if(t===-1)continue;if(t===u-r){i=1;break}}}if(t===`day`&&n.lastWeekday){let e=this.getLastWeekday(this.year,this.month);u-r===e&&(i=1)}if(t===`day`&&n.lastDayOfMonth&&u-r==o&&(i=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(s+(u-r-1))%7];if(t&&t&63)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,u-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);n.useAndLogic?i&&=t:!e.domAndDow&&!n.starDOM?i||=t:i&&=t}if(i)return this[t]=u-r,a===this[t]?1:2}return 3}recurse(e,t,n){if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year+1;n<e.year.length&&n<1e4;n++)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=0,this.day=1,this.hour=0,this.minute=0,this.second=0,this.ms=0}if(this.year>=1e4)return null}let r=this.findNext(t,J[n][0],e,J[n][2]);if(r>1){let i=n+1;for(;i<J.length;)this[J[i][0]]=-J[i][2],i++;if(r===3){if(this[J[n][1]]++,this[J[n][0]]=-J[n][2],this.apply(),n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0&&this.year<1e4;)this.year++;if(this.year>=1e4||this.year>=e.year.length)return null}return this.recurse(e,t,0)}if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=J.length?this:(e.starYear?this.year>=3e3:this.year>=1e4)?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}decrement(e,t){return this.second-=t.interval!==void 0&&t.interval>1?t.interval:1,this.ms=0,this.apply(),this.recurseBackward(e,t,0,0)}recurseBackward(e,t,n,r=0){if(r>1e4)return null;if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year-1;n>=0;n--)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=11,this.day=31,this.hour=23,this.minute=59,this.second=59,this.ms=0}if(this.year<0)return null}let i=this.findPrevious(t,J[n][0],e,J[n][2]);if(i>1){let a=n+1;for(;a<J.length;){let t=J[a][0],n=J[a][2],r=this.getMaxPatternValue(t,e,n);this[t]=r,a++}if(i===3){if(this[J[n][1]]--,n===0){let e=this.getLastDayOfMonth(this.year,this.month);this.day>e&&(this.day=e)}if(n===1){if(this.day<=0)this.day=1;else{let e=this.year,t=this.month;for(;t<0;)t+=12,e--;for(;t>11;)t-=12,e++;let n=t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():bT[t];this.day>n&&(this.day=n)}}this.apply();let i=J[n][0],a=J[n][2],o=this.getMaxPatternValue(i,e,a);if(i===`day`){let e=this.getLastDayOfMonth(this.year,this.month);this[i]=Math.min(o,e)}else this[i]=o;if(this.apply(),n===0){let t=J[1][2],n=this.getMaxPatternValue(`day`,e,t),r=this.getLastDayOfMonth(this.year,this.month),i=Math.min(n,r);i!==this.day&&(this.day=i,this.hour=this.getMaxPatternValue(`hour`,e,J[2][2]),this.minute=this.getMaxPatternValue(`minute`,e,J[3][2]),this.second=this.getMaxPatternValue(`second`,e,J[4][2]))}if(n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0;)this.year--;if(this.year<0)return null}return this.recurseBackward(e,t,0,r+1)}if(this.apply())return this.recurseBackward(e,t,n-1,r+1)}return n+=1,n>=J.length?this:this.year<0?null:this.recurseBackward(e,t,n,r+1)}getMaxPatternValue(e,t,n){if(e===`day`&&t.lastDayOfMonth||e===`day`&&!t.starDOW)return this.getLastDayOfMonth(this.year,this.month);for(let r=t[e].length-1;r>=0;r--)if(t[e][r])return r-n;return t[e].length-1-n}findPrevious(e,t,n,r){return this._findMatch(e,t,n,r,-1)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):hT(_T(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}match(e,t){if(!e.starYear&&(this.year<0||this.year>=e.year.length||e.year[this.year]===0))return!1;for(let n=0;n<J.length;n++){let r=J[n][0],i=J[n][2],a=this[r];if(a+i<0||a+i>=e[r].length)return!1;let o=e[r][a+i];if(r===`day`){if(!o){for(let t=0;t<e.nearestWeekdays.length;t++)if(e.nearestWeekdays[t]){let e=this.getNearestWeekday(this.year,this.month,t-i);if(e!==-1&&e===a){o=1;break}}}if(e.lastWeekday&&a===this.getLastWeekday(this.year,this.month)&&(o=1),e.lastDayOfMonth&&a===this.getLastDayOfMonth(this.year,this.month)&&(o=1),!e.starDOW){let n=new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay(),r=e.dayOfWeek[(n+(a-1))%7];r&&r&63&&(r=+!!this.isNthWeekdayOfMonth(this.year,this.month,a,r)),e.useAndLogic?o&&=r:!t.domAndDow&&!e.starDOM?o||=r:o&&=r}}if(!o)return!1}return!0}};function xT(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode!==void 0&&e.domAndDow===void 0?e.domAndDow=!e.legacyMode:e.domAndDow===void 0&&(e.domAndDow=!1),e.legacyMode=!e.domAndDow,e.paused=e.paused!==void 0&&e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch!==void 0&&e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.dayOffset=e.dayOffset===void 0?0:parseInt(e.dayOffset.toString(),10),e.unref=e.unref!==void 0&&e.unref,e.mode=e.mode===void 0?`auto`:e.mode,e.alternativeWeekdays=e.alternativeWeekdays!==void 0&&e.alternativeWeekdays,e.sloppyRanges=e.sloppyRanges!==void 0&&e.sloppyRanges,![`auto`,`5-part`,`6-part`,`7-part`,`5-or-6-parts`,`6-or-7-parts`].includes(e.mode))throw Error(`CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.`);if(e.startAt&&(e.startAt=new Y(e.startAt,e.timezone)),e.stopAt&&(e.stopAt=new Y(e.stopAt,e.timezone)),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);if(e.dayOffset!==void 0&&e.dayOffset!==0&&isNaN(e.dayOffset))throw Error(`CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.`);return e}function ST(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function CT(e){return ST(e)}function wT(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var TT=3e4,ET=[],DT=class{name;options;_states;fn;getTz(){return this.options.timezone||this.options.utcOffset}applyDayOffset(e){if(this.options.dayOffset!==void 0&&this.options.dayOffset!==0){let t=this.options.dayOffset*24*60*60*1e3;return new Date(e.getTime()+t)}return e}constructor(e,t,n){let r,i;if(ST(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(ST(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=xT(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new yT(`* * * * *`,void 0,{mode:`auto`})},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Y(e,this.getTz()):this._states.pattern=new yT(e,this.options.timezone,{mode:this.options.mode,alternativeWeekdays:this.options.alternativeWeekdays,sloppyRanges:this.options.sloppyRanges}),this.name){if(ET.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);ET.push(this)}return i!==void 0&&CT(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?this.applyDayOffset(t.getDate(!1)):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=t||this._states.currentRun||void 0;return this._enumerateRuns(e,n,`next`)}previousRuns(e,t){return this._enumerateRuns(e,t||void 0,`previous`)}_enumerateRuns(e,t,n){let r=[],i=t?new Y(t,this.getTz()):null,a=n===`next`?this._next:this._previous;for(;e--;){let e=a.call(this,i);if(!e)break;let t=e.getDate(!1);r.push(this.applyDayOffset(t)),i=e}return r}match(e){if(this._states.once){let t=new Y(e,this.getTz());t.ms=0;let n=new Y(this._states.once,this.getTz());return n.ms=0,t.getTime()===n.getTime()}let t=new Y(e,this.getTz());return t.ms=0,t.match(this._states.pattern,this.options)}getPattern(){if(!this._states.once)return this._states.pattern?this._states.pattern.pattern:void 0}getOnce(){return this._states.once?this._states.once.getDate():null}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Y||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Y(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=ET.indexOf(this);e>=0&&ET.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>TT&&(t=TT),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&wT(this._states.currentTimeout),this)}async _trigger(e){this._states.blocking=!0,this._states.currentRun=new Y(void 0,this.getTz());try{if(this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){if(ST(this.options.catch))try{this.options.catch(e,this)}catch{}}else this.fn!==void 0&&await this.fn(this,this.options.context)}finally{this._states.previousRun=new Y(e,this.getTz()),this._states.blocking=!1}}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&ST(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Y(e,this.getTz()),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Y(e,this.getTz());return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_previous(e){let t=new Y(e,this.getTz());this.options.stopAt&&t.getTime()>this.options.stopAt.getTime()&&(t=this.options.stopAt);let n=new Y(t,this.getTz());return this._states.once?this._states.once.getTime()<t.getTime()?this._states.once:null:(n=n.decrement(this._states.pattern,this.options),n===null||this.options.startAt&&n.getTime()<this.options.startAt.getTime()?null:n)}_calculatePreviousRun(e,t){let n=new Y(void 0,this.getTz()),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Y(r,this.getTz()).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function OT(e,t){try{return new DT(e.trim(),{domAndDow:!0}).nextRun(t)??null}catch{return null}}var kT=e({FORWARDABLE_TO_LEADER:()=>AT,LickManager:()=>NT,buildActiveLicksError:()=>IT,getLickManager:()=>RT,lickScoopMatches:()=>PT,lickTargetCandidates:()=>FT});const X=y(`lick-manager`),AT=new Set([`navigate`,`discovery`]);function jT(e){if(typeof e!=`object`||!e)return null;let t=e;return typeof t.verb!=`string`||typeof t.target!=`string`?null:ue({verb:t.verb,target:t.target,branch:typeof t.branch==`string`?t.branch:void 0,path:typeof t.path==`string`?t.path:void 0,instruction:typeof t.instruction==`string`?t.instruction:void 0})}function MT(e){return!e.discoveryKind&&!e.discoveryUrl&&!e.discoveryOrigin?null:Pa({origin:e.discoveryOrigin,kind:e.discoveryKind,url:e.discoveryUrl})}var NT=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;forwarder=null;seenNavigateFingerprints=new Set;seenDiscoveryFingerprints=new Set;unitRoster=null;discoveryIgnore=null;async init(){await _b();let e=await bb();for(let t of e)this.webhooks.set(t.id,t);X.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await wb();for(let e of t)this.crontasks.set(e.id,e);X.info(`Loaded crontasks`,{count:this.crontasks.size}),await this.reconcileOrphans(),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),X.info(`Cron scheduler started`)}setUnitRosterProvider(e){this.unitRoster=e}resolveLickTarget(e){let t=this.unitRoster?.();return t?t.some(t=>PT(e,t.name,t.folder))?{status:`resolved`}:{status:`unresolved`,candidates:FT(t)}:{status:`unverifiable`}}setDiscoveryIgnore(e){this.discoveryIgnore=e}isOrphanedLick(e){return e?this.resolveLickTarget(e).status===`unresolved`:!1}async reconcileOrphans(){if(this.unitRoster){for(let e of Array.from(this.webhooks.values()))if(this.isOrphanedLick(e.scoop)){X.warn(`Removing orphaned webhook at init; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.webhooks.delete(e.id);try{await xb(e.id)}catch(t){X.warn(`Failed to delete orphaned webhook from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}for(let e of Array.from(this.crontasks.values()))if(this.isOrphanedLick(e.scoop)){X.warn(`Removing orphaned cron task at init; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.crontasks.delete(e.id);try{await Tb(e.id)}catch(t){X.warn(`Failed to delete orphaned cron task from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}}}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}setForwarder(e){this.forwarder=e}dispatch(e){if(!(e.type===`discovery`&&this.shouldSuppressDiscovery(e))){if(this.forwarder&&AT.has(e.type)){this.forwarder(e);return}this.eventHandler?.(e)}}handleForwardedEvent(e){e.type===`discovery`&&this.shouldSuppressDiscovery(e)||this.isDuplicateFingerprint(e)||this.eventHandler?.(e)}emitEvent(e){e.type===`discovery`&&this.shouldSuppressDiscovery(e)||this.isDuplicateFingerprint(e)||(X.info(`External lick event`,{type:e.type,target:e.targetScoop}),this.dispatch(e))}isDuplicateFingerprint(e){let t=null,n,r;if(e.type===`navigate`)t=jT(e.body),n=this.seenNavigateFingerprints,r=`navigate`;else if(e.type===`discovery`)t=MT(e),n=this.seenDiscoveryFingerprints,r=`discovery`;else return!1;return t===null?!1:n.has(t)?(X.debug(`Suppressing duplicate ${r} lick`,{fingerprint:t}),!0):(n.add(t),!1)}shouldSuppressDiscovery(e){return e.discoverySource===`live-navigation`?this.discoveryIgnore?.(e)?(X.debug(`Suppressing ignored llms.txt discovery`,{origin:e.discoveryOrigin}),!0):!1:(X.debug(`Suppressing discovery without live-navigation provenance`),!0)}async createWebhook(e,t,n){let r=this.generateId(),i={id:r,name:e,createdAt:new Date().toISOString(),filter:n,scoop:t};return n&&this.compileFilter(n,!0),this.webhooks.set(r,i),await vb(i),X.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await xb(e),X.info(`Webhook deleted`,{id:e}),!0):await yb(e)!==null&&(await xb(e),X.info(`Webhook deleted`,{id:e}),!0)}listWebhooks(){return Array.from(this.webhooks.values())}getWebhook(e){return this.webhooks.get(e)}handleWebhookEvent(e,t,n){let r=this.webhooks.get(e);if(!r)return X.warn(`Webhook not found`,{webhookId:e}),`unknown-webhook`;if(this.isOrphanedLick(r.scoop))return X.warn(`Webhook target scoop not found — dropping delivery`,{webhookId:e,name:r.name,scoop:r.scoop}),`unresolved-target`;let i={type:`webhook`,webhookId:e,webhookName:r.name,targetScoop:r.scoop,timestamp:new Date().toISOString(),headers:t,body:n};if(r.filter)try{let t=this.compileFilter(r.filter,!0)(i);if(t===!1)return X.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name}),`filtered`;typeof t==`object`&&t&&(i=t)}catch(t){X.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}return X.info(`Webhook event received`,{webhookId:e,name:r.name,targetScoop:r.scoop}),this.dispatch(i),`delivered`}async createCronTask(e,t,n,r){let i=OT(t,new Date);if(!i)throw Error(`Invalid cron expression`);r&&this.compileFilter(r,!1);let a=this.generateId(),o={id:a,name:e,cron:t,scoop:n,filter:r,nextRun:i.toISOString(),lastRun:null,status:`active`,createdAt:new Date().toISOString()};return this.crontasks.set(a,o),await Sb(o),X.info(`Cron task created`,{id:a,name:e,cron:t,scoop:n}),o}async deleteCronTask(e){return this.crontasks.has(e)?(this.crontasks.delete(e),await Tb(e),X.info(`Cron task deleted`,{id:e}),!0):await Cb(e)!==null&&(await Tb(e),X.info(`Cron task deleted`,{id:e}),!0)}listCronTasks(){return Array.from(this.crontasks.values())}getCronTask(e){return this.crontasks.get(e)}getLicksForScoop(e,t){return{webhooks:Array.from(this.webhooks.values()).filter(n=>PT(n.scoop,e,t)),cronTasks:Array.from(this.crontasks.values()).filter(n=>PT(n.scoop,e,t))}}async getLicksForScoopFromDb(e,t){let[n,r]=await Promise.all([bb(),wb()]);return{webhooks:n.filter(n=>PT(n.scoop,e,t)),cronTasks:r.filter(n=>PT(n.scoop,e,t))}}async deleteIfOrphanedCron(e){if(!this.isOrphanedLick(e.scoop))return!1;X.warn(`Deleting orphaned cron task; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.crontasks.delete(e.id);try{await Tb(e.id)}catch(t){X.warn(`Failed to delete orphaned cron task from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}return!0}async runCronScheduler(){let e=new Date;for(let t of this.crontasks.values())await this.deleteIfOrphanedCron(t)||t.status===`active`&&t.nextRun&&(new Date(t.nextRun)>e||await this.runDueCronTask(t,e))}async runDueCronTask(e,t){let n={time:t.toISOString()};if(e.filter)try{let r=this.compileFilter(e.filter,!1)(null);if(r===!1){X.debug(`Cron task skipped by filter`,{id:e.id,name:e.name}),e.nextRun=OT(e.cron,t)?.toISOString()??null,e.lastRun=t.toISOString(),await Sb(e);return}typeof r==`object`&&r&&(n=r)}catch(t){X.error(`Cron filter error`,{id:e.id,error:t instanceof Error?t.message:String(t)})}let r={type:`cron`,cronId:e.id,cronName:e.name,targetScoop:e.scoop,timestamp:t.toISOString(),body:n};X.info(`Cron task running`,{id:e.id,name:e.name}),this.dispatch(r),e.nextRun=OT(e.cron,t)?.toISOString()??null,e.lastRun=t.toISOString(),await Sb(e)}generateId(){let e=``;for(let t=0;t<12;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return e}compileFilter(e,t){try{return t?Function(`event`,`return (${e})(event);`):Function(`return (${e})();`)}catch(e){throw Error(`Invalid filter function: ${e instanceof Error?e.message:String(e)}`)}}};function PT(e,t,n){return e?e===t||e===n||`${e}-scoop`===n:!1}function FT(e){let t=new Set;for(let n of e)t.add(n.folder),n.name&&n.name!==n.folder&&t.add(n.name);return Array.from(t)}function IT(e,t,n){if(t.length===0&&n.length===0)return null;let r=[];t.length>0&&r.push(`${t.length} active webhook${t.length>1?`s`:``}`),n.length>0&&r.push(`${n.length} active cron task${n.length>1?`s`:``}`);let i=[...t.map(e=>` webhook delete ${e.id}`),...n.map(e=>` crontask delete ${e.id}`)].join(`
|
|
1029
|
+
`);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}let LT=null;function RT(){return LT||=new NT,LT}function zT(e){if(e.kind===`local`)return`mount ${ay(e.path)}`;let t=e.profile==="default"?``:` --profile ${ay(e.profile)}`;return`mount --source ${ay(e.source)}${t} ${ay(e.path)}`}function BT(){return`lick-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}var VT=class{deps;entries=new Map;constructor(e){this.deps=e}hasHandoff(e){return this.entries.get(e)?.kind===`navigate-handoff`}registerNavigate(e){let t=BT(),n=e.body??{},r=typeof n.verb==`string`?n.verb:void 0,i=typeof n.target==`string`?n.target:void 0;return r===`upskill`&&i?this.entries.set(t,{kind:`navigate-upskill`,target:i,branch:typeof n.branch==`string`?n.branch:void 0,path:typeof n.path==`string`?n.path:void 0}):r===`handoff`&&this.entries.set(t,{kind:`navigate-handoff`}),t}registerSessionReload(e){let t=BT(),n=e.body??{},r=Array.isArray(n.mounts)?n.mounts:[];return n.reason===`mount-recovery`?r.length>0&&this.entries.set(t,{kind:`session-reload-mount`,mounts:r}):this.entries.set(t,{kind:`session-reload-plain`}),t}registerUpgrade(e){let t=BT(),n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`;return this.entries.set(t,{kind:`upgrade`,from:n,to:r}),t}registerDiscovery(e){if(e.discoveryKind!==`llms-txt`)return null;let t=ux(e.discoveryOrigin,e.discoveryUrl);if(!t)return null;let n=BT();return this.entries.set(n,{kind:`discovery-llms-txt`,hostname:t}),n}async resolve(e,t){let n=this.entries.get(e);if(!n)return null;switch(n.kind){case`navigate-upskill`:return this.resolveUpskill(e,n,t);case`session-reload-mount`:return this.resolveMountRecovery(e,n,t);case`session-reload-plain`:return this.resolveSessionReloadPlain(e,t);case`upgrade`:return this.resolveUpgrade(e,n,t);case`discovery-llms-txt`:return this.resolveDiscovery(e,n,t);case`navigate-handoff`:return null}}async resolveHandoffByHuman(e,t){return this.hasHandoff(e)?(this.entries.delete(e),await this.deps.persistLickDecision(e,t?`allow`:`deny`),!0):!1}async resolveUpskill(e,t,n){this.entries.delete(e);let r;return n.decision!==`deny`&&(r=await this.runUpskillInstall(t)),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async runUpskillInstall(e){let t=this.deps.getConeShell();if(!t)return`upskill could not run: no cone shell available.`;let n=e=>`'${e.replace(/'/g,`'\\''`)}'`,r=[`upskill`];e.branch&&r.push(`--branch`,n(e.branch)),e.path&&r.push(`--path`,n(e.path)),r.push(n(e.target)),r.push(`--all`);try{let e=await t.executeCommand(r.join(` `)),n=`${e.stdout}${e.stderr}`.trim();return n.length>0?n:`upskill exited ${e.exitCode}.`}catch(e){return`upskill failed: ${e instanceof Error?e.message:String(e)}`}}async resolveMountRecovery(e,t,n){this.entries.delete(e);let r;return n.decision!==`deny`&&(r=await this.runMountRecovery(t.mounts)),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async runMountRecovery(e){let t=this.deps.getConeShell();if(!t)return`mount recovery could not run: no cone shell available.`;let n=[];for(let r of e){let e=zT(r);try{let r=await t.executeCommand(e),i=`${r.stdout}${r.stderr}`.trim();n.push(i.length>0?i:`${e} exited ${r.exitCode}.`)}catch(t){n.push(`${e} failed: ${t instanceof Error?t.message:String(t)}`)}}return n.join(`
|
|
1030
|
+
`)}async resolveSessionReloadPlain(e,t){return t.decision===`deny`?(this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:!1,message:`Session-reload notice acknowledged.`}):{settled:!0,persisted:!1,message:`Nothing to confirm — the reload already completed. Use lick_dismiss to acknowledge and clear this notice.`}}async resolveUpgrade(e,t,n){this.entries.delete(e);let r;return r=n.decision===`deny`?`Upgrade dismissed — workspace files were left unchanged.`:await this.runUpgrade(t),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async resolveDiscovery(e,t,n){if(n.decision!==`deny`)return{settled:!0,persisted:!1,message:`Nothing to confirm — use lick_dismiss to ignore this llms.txt host.`};let r=this.deps.getConeFs();if(!r)throw Error(`llms.txt dismissal could not persist: cone filesystem unavailable.`);let i=await dx(r,t.hostname);return this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:i,message:i?`Dismissed — ${t.hostname} was added to /etc/llmstxtignore.`:`Dismissed — ${t.hostname} is already ignored.`}}async runUpgrade(e){let t=this.deps.getConeShell();if(!t)return`upgrade could not run: no cone shell available.`;let n=`upgrade apply --from=${ay(e.from)} --to=${ay(e.to)}`;try{let e=await t.executeCommand(n),r=`${e.stdout}${e.stderr}`.trim();return r.length>0?r:`upgrade exited ${e.exitCode}.`}catch(e){return`upgrade failed: ${e instanceof Error?e.message:String(e)}`}}},HT=`# /etc/models — which models a scoop may be spawned with
|
|
1031
1031
|
#
|
|
1032
1032
|
# \`agent --model\` and \`scoop_scoop\` accept a \`provider:model\` id, so a scoop can
|
|
1033
1033
|
# run on a provider OTHER than the selected one. That moves spend onto another
|
|
@@ -1060,7 +1060,7 @@ ${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowed
|
|
|
1060
1060
|
# openrouter:*
|
|
1061
1061
|
# -openrouter:openai/o3-pro
|
|
1062
1062
|
# -adobe:claude-opus-5
|
|
1063
|
-
`;const UT=y(`model-policy-file`);var WT=class{fs;watcher;unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/models`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/models`)||(await this.fs.writeFile(be,HT),UT.info(`Seeded default /etc/models policy`))}catch(e){UT.warn(`Failed to seed default model policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(be,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);xe(pe(t))}catch(e){xe(Se()),UT.warn(`Failed to read model policy; falling back to own-catalogue-only`,{error:e instanceof Error?e.message:String(e)})}}};function GT(){try{let e=me();if(!e||!fe(e))return;let t=ve().id;return t?{provider:e,id:t}:void 0}catch{return}}async function KT(e,t,n={}){if(!t)return e(()=>{});let r=n.intervalMs??5e3,i=n.maxBeats??24,a=n.stagePrefix??`shared-fs-mount`;t(`${a}:start`);let o=0,s=0,c=0,l=0,u=()=>{c+=1},d=setInterval(()=>{if(c>l)l=c,s=0;else if(s+=1,s>i){clearInterval(d);return}o+=1,t(`${a}:${o}`)},r);try{return await e(u)}finally{clearInterval(d)}}const qT=y(`scheduler`);var JT=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=setInterval(()=>this.pollTasks(),6e4),this.pollTasks(),qT.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,qT.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await
|
|
1063
|
+
`;const UT=y(`model-policy-file`);var WT=class{fs;watcher;unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/models`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/models`)||(await this.fs.writeFile(be,HT),UT.info(`Seeded default /etc/models policy`))}catch(e){UT.warn(`Failed to seed default model policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(be,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);xe(pe(t))}catch(e){xe(Se()),UT.warn(`Failed to read model policy; falling back to own-catalogue-only`,{error:e instanceof Error?e.message:String(e)})}}};function GT(){try{let e=me();if(!e||!fe(e))return;let t=ve().id;return t?{provider:e,id:t}:void 0}catch{return}}async function KT(e,t,n={}){if(!t)return e(()=>{});let r=n.intervalMs??5e3,i=n.maxBeats??24,a=n.stagePrefix??`shared-fs-mount`;t(`${a}:start`);let o=0,s=0,c=0,l=0,u=()=>{c+=1},d=setInterval(()=>{if(c>l)l=c,s=0;else if(s+=1,s>i){clearInterval(d);return}o+=1,t(`${a}:${o}`)},r);try{return await e(u)}finally{clearInterval(d)}}const qT=y(`scheduler`);var JT=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=setInterval(()=>this.pollTasks(),6e4),this.pollTasks(),qT.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,qT.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await db(i),qT.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await fb(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await db(r),qT.info(`Task updated`,{id:e,updates:Object.keys(t)}),r}async pauseTask(e){return await this.updateTask(e,{status:`paused`})!==null}async resumeTask(e){return await fb(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await fb(e)?(await mb(e),qT.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await pb()).filter(t=>t.groupFolder===e)}async getAllTasks(){return pb()}pollTasks(){this.checkTasks().catch(e=>{qT.error(`Task poll failed`,{error:e instanceof Error?e.message:String(e)})})}async checkTasks(){let e=await pb(),t=new Date;for(let n of e)n.status===`active`&&n.nextRun&&(new Date(n.nextRun)>t||await this.runTask(n))}async runTask(e){let t=this.callbacks.getScoop(e.groupFolder);if(!t){qT.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}qT.info(`Running task`,{id:e.id,groupFolder:e.groupFolder});try{let n=new Date().toISOString(),r=this.calculateNextRun(e.scheduleType,e.scheduleValue),i=e.scheduleType===`once`?`completed`:e.status;await db({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),qT.info(`Task completed`,{id:e.id})}catch(t){qT.error(`Task execution failed`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}calculateNextRun(e,t){let n=new Date;switch(e){case`cron`:return OT(t,n)?.toISOString()??null;case`interval`:{let e=parseInt(t,10);return isNaN(e)||e<=0?null:new Date(n.getTime()+e).toISOString()}case`once`:return new Date(t)>n?t:null;default:return null}}};const Z=y(`scoop-approval-router`);var YT=class{deps;registry;constructor(e){this.deps=e,this.registry=new m({onAutoSettle:(e,t,n)=>this.handleAutoSettle(e,t,n)})}handleAutoSettle(e,t,n){Z.info(`Sudo request auto-settled fail-closed; retiring lick card`,{id:e,reason:t}),this.persistLickDecision(e,`deny`,n).catch(n=>{Z.warn(`Failed to persist auto-settled lick decision`,{id:e,reason:t,error:n instanceof Error?n.message:String(n)})})}getConeSudoBroker(e){return f(e,this)}listPendingSudoRequests(e){let t=this.registry.list();return e===void 0?t:t.filter(t=>t.approverJid===e)}maySettle(e,t){return t===void 0||this.registry.get(e)?.approverJid===t}failScoop(e){return this.registry.failScoop(e)}failAll(){return this.registry.failAll()}settleGrantedRequests(e){let t=this.deps.getSudoManager();if(!t)return 0;let n=this.deps.getScoops(),r=0;for(let i of this.registry.list()){let a=n.get(i.scoopJid);if(!a||e!==void 0&&a.folder!==e||!XT(t.getPolicyForScoop(a.folder),i.request))continue;let{kind:o,detail:s}=i.request;this.registry.resolve(i.id,{decision:`allow`})&&(r++,Z.info(`Sudo request auto-settled: policy now grants it`,{id:i.id,folder:a.folder,kind:o,detail:s.slice(0,80)}),this.persistLickDecision(i.id,`allow`,i.scoopJid).catch(e=>{Z.warn(`Failed to persist auto-granted lick decision`,{id:i.id,error:e instanceof Error?e.message:String(e)})}))}return r}admitIfAlreadyGranted(e,t){let n=this.deps.getScoops().get(e),r=this.deps.getSudoManager();return!n||!r||!XT(r.getPolicyForScoop(n.folder),t)?null:(Z.info(`Sudo request already granted by policy — skipping cone`,{scoopJid:e,folder:n.folder,kind:t.kind,detailPreview:t.detail.slice(0,80)}),{decision:`allow`})}async enqueueSudoRequest(e,t,n={}){let r=this.deps.getScoops(),i=n.approver??this.deps.findApprover(e);if(!i)return Z.warn(`Sudo request received but no approver is registered — failing closed`,{scoopJid:e,kind:t.kind}),{decision:`deny`};if(!r.has(e))return Z.warn(`Sudo request from unknown scoop — failing closed`,{scoopJid:e,kind:t.kind}),{decision:`deny`};if(t.kind===`write`&&Ir(t.detail))return Z.warn(`Refusing sudo request for an unhonoured sudoers path`,{scoopJid:e,detail:t.detail}),{decision:`deny`};let a=this.admitIfAlreadyGranted(e,t);if(a)return a;let{id:o,pending:s}=this.registry.register(e,t,i.jid);Z.info(`Sudo request enqueued for cone`,{id:o,scoopJid:e,kind:t.kind,detailPreview:t.detail.slice(0,80)});let c=r.get(e);this.deps.getLickManager()?.emitEvent({type:`sudo-request`,lickId:o,sudoKind:t.kind,sudoDetail:t.detail,sudoScoopName:t.requester??c?.assistantLabel??c?.name??e,sudoSuggestedPattern:t.suggestedPattern,sudoReason:t.reason,targetScoop:i.name,timestamp:new Date().toISOString(),body:{requestId:o,kind:t.kind,detail:t.detail,suggestedPattern:t.suggestedPattern,reason:t.reason,scoopJid:e}});try{await this.deliverSudoRequestToCone(i,e,o,t)}catch(t){let n=t instanceof Error?t.message:String(t);Z.error(`Failed to deliver sudo request to cone — failing closed`,{id:o,scoopJid:e,error:n}),this.registry.resolve(o,{decision:`deny`})}return s}resolveSudoRequest(e,t,n){if(!this.maySettle(e,n))return Z.warn(`Refusing a settle from a unit the request was not routed to`,{id:e,approverJid:n}),!1;let r=this.registry.resolve(e,t);return r?Z.info(`Sudo request resolved by cone`,{id:e,decision:t.decision}):Z.warn(`Sudo request resolve: unknown / already-settled id`,{id:e,decision:t.decision}),r}async resolveSudoRequestAndPersist(e,t,n){let r=this.registry.get(e);if(!r)return{settled:!1,persisted:!1};if(!this.maySettle(e,n))return Z.warn(`Refusing a settle+persist from a unit the request was not routed to`,{id:e,approverJid:n}),{settled:!1,persisted:!1};let i=r.scoopJid,a=r.approverJid,o=this.resolveSudoRequest(e,t,n);if(!o)return{settled:!1,persisted:!1};let s=this.deps.getScoops().get(r.scoopJid),c=r.request.kind,l=s?.folder,u=this.deps.getSudoManager(),d=!1,f,p;if(t.decision===`always`&&u&&s&&s.parentJid!==null){if(c===`command`||c===`read`||c===`write`){let n=t.pattern?.trim()||r.request.suggestedPattern?.trim()||r.request.detail.trim();try{let e=await u.appendScoopRule(s.folder,c,n);e?(d=!0,f=e):p=`pattern collapsed to empty after sanitization`}catch(t){p=t instanceof Error?t.message:String(t),Z.warn(`Failed to persist always grant`,{id:e,folder:s.folder,kind:c,error:p})}}else p=`cannot persist always grant for kind "${c}" (no matching sudoers directive)`}return await this.persistLickDecision(e,t.decision,i,a),{settled:o,persisted:d,persistedPattern:f,persistError:p,scoopFolder:l,kind:c}}async persistLickDecision(e,t,n,r){let i=t===`deny`?`dismissed`:`confirmed`,a=r??this.registry.get(e)?.approverJid,o=a?this.deps.getScoops().get(a):this.deps.findApprover(n??this.registry.get(e)?.scoopJid);if(o)try{let t=(await this.deps.getMessagesForScoop(o.jid)).find(t=>t.lickId===e||t.id===`sudo-request-${e}`);if(!t){Z.warn(`Lick decision: no stored message found to flip`,{lickId:e});return}t.lickState=i,await this.deps.saveMessage(t),this.deps.onMessageUpdate(o.jid,{messageId:t.id,lickId:e,lickState:i})}catch(t){Z.warn(`Failed to persist lick decision`,{lickId:e,error:t instanceof Error?t.message:String(t)})}}async deliverSudoRequestToCone(e,t,n,r){let i=this.deps.getScoops().get(t),a=r.requester??i?.assistantLabel??t,o=i?.folder??t,s=ZT(a,n,r),c={id:`sudo-request-${n}`,chatJid:e.jid,senderId:o,senderName:a,content:s,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sudo-request`,lickId:n,lickState:`pending`};await this.deps.handleMessage(c)}};function XT(e,t){let{kind:n,detail:r}=t;return n===`command`?Mr(e,r)===`nopasswd-allow`:n===`read`||n===`write`?zr(e,n,r)===`nopasswd-allow`:!1}function ZT(e,t,n){let r=[`[@${e} sudo-request]`,`Lick ID: ${t}`,`Kind: ${n.kind}`,`Detail: ${n.detail}`];return n.reason&&r.push(`Reason given: ${n.reason}`),n.suggestedPattern&&r.push(`Suggested pattern: ${n.suggestedPattern}`),r.push(``,`Use the lick_confirm tool with lick_id="${t}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${t}" and a reason to deny. A denial without a reason tells the scoop nothing it can act on.`),r.join(`
|
|
1064
1064
|
`)}let QT=null;function $T(e){QT=e}function eE(e,t,n){QT?.(e,t,n)}const tE=y(`scoop-completion-service`),nE=`/shared/scoop-notifications`,rE=1e3,iE=2e4;function aE(e){let t=e.replace(/\r\n?/g,`
|
|
1065
1065
|
`);if(t.length===0)return 0;let n=1;for(let e=0;e<t.length;e++)t[e]===`
|
|
1066
1066
|
`&&n++;return t.endsWith(`
|
|
@@ -1145,7 +1145,7 @@ ${n}
|
|
|
1145
1145
|
---
|
|
1146
1146
|
${o?`CONE`:`SCOOP`} MEMORY (${e.name}):
|
|
1147
1147
|
${r}
|
|
1148
|
-
---`);let u=iT(i);return u&&(l+=u),l}const XE=y(`scoop-context`);function ZE(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!tn(t).includes(`xhigh`)?`high`:e}function QE(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(ir.includes(e))return e;XE.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}const $E=y(`scoop-context`);function eD(e,t){let n=GE(t);e.state.model=n;let r=Pn(t),i=QE()??r.level;return e.state.thinkingLevel=ZE(i,n),$E.info(`Model updated on running agent`,{folder:t.folder,model:n.id,thinkingLevel:e.state.thinkingLevel}),n.reasoning?r.effortOverride:void 0}function tD(e,t){if(QE())return e.state.thinkingLevel;let n=ZE(t,e.state.model);return e.state.thinkingLevel=n,n}async function nD(e,t){let n=await tT(t.skillsFs??t.fs,er),r=await VE(t.fs,t.unit.workspace.memoryPath),i=await t.getGlobalMemory();e.state.systemPrompt=YE(t.scoop,t.unit,i,r,n),$E.info(`Skills reloaded`,{folder:t.scoop.folder,skillCount:n.length})}const rD=y(`scoop-context`);var iD=class{deps;attempted=!1;active=!1;escalated=!1;pending=null;constructor(e){this.deps=e}resetForRun(){this.attempted=!1,this.active=!1,this.pending=null,this.escalated=!1}get pendingRecovery(){return this.pending}clearPendingRecovery(e){this.pending===e&&(this.pending=null)}get isActive(){return this.active}get hasAttempted(){return this.attempted}markSettled(){this.active=!1}markAssistantSucceeded(){this.attempted=!1}shouldRecover(e){return!this.deps.isImageRecoveryActive()&&Uo(e)}recover(e,t){let n=this.deps.getTurnSignal(),r=t&&n?AbortSignal.any([t,n]):t??n,i=this.deps.getAgent();if(!i||this.deps.isDisposed()||r?.aborted)return;if(this.attempted){this.escalate(r);return}this.attempted=!0,this.active=!0,rD.warn(`Context overflow detected, attempting recovery`,{folder:this.deps.folder,messageCount:e.length});let a=this.deps.getCompactFn(),o=i.state.messages,s=o[o.length-1],c=s?.role===`assistant`&&Uo(s)?o.slice(0,-1):o;if(i.state.messages=c,!a||!i.state.model||!this.deps.getCompactionApiKey()){this.escalate(r,Error(`Compaction is unavailable`));return}this.pending=this.compactAndResume(i,a,c,r)}async compactAndResume(e,t,n,r){try{let i=await t(n,r,{force:!0});if(this.deps.isDisposed()||r?.aborted||this.deps.getAgent()!==e)return;if(!dn(n,i)){this.escalate(r,Error(`Forced compaction did not reduce the context`));return}e.state.messages=i,this.deps.onResponse(`Context window exceeded — compacting history and continuing...`,!1),await new Promise(t=>{setTimeout(()=>{if(this.deps.isDisposed()||r?.aborted||this.deps.getAgent()!==e){t();return}e.continue().then(t).catch(e=>{!this.deps.isDisposed()&&!r?.aborted&&this.escalate(r,e),t()})},100)})}catch(e){!this.deps.isDisposed()&&!r?.aborted&&this.escalate(r,e)}finally{this.active=!1}}escalate(e,t){if(this.active=!1,this.deps.isDisposed()||e?.aborted||this.escalated)return;this.escalated=!0;let n=t instanceof Error?t.message:t?String(t):void 0;rD.error(`Context overflow recovery exhausted`,{folder:this.deps.folder,error:n}),this.deps.setStatus(`error`),this.deps.onExhausted(`Scoop "${this.deps.scoopName}" context window was exceeded and could not be reduced. Re-delegate with a narrower task.`)}},aD=class{deps;turnCount=0;exceededNote=null;wallClockTimer=null;constructor(e){this.deps=e}arm(){this.turnCount=0,this.exceededNote=null;let e=this.deps.getConfig()?.maxWallClockMs;typeof e==`number`&&Number.isFinite(e)&&e>0&&(this.wallClockTimer=setTimeout(()=>{this.wallClockTimer=null,this.trip(`wall-clock bound (${e} ms) exceeded`)},e))}recordCompletedTurn(){this.turnCount+=1}enforceOnTurnStart(){let e=this.deps.getConfig()?.maxTurns;typeof e==`number`&&e>0&&this.turnCount>=e&&this.trip(`turn bound (${e}) exceeded`)}disarm(){this.wallClockTimer!==null&&(clearTimeout(this.wallClockTimer),this.wallClockTimer=null)}takeExceededNote(){let e=this.exceededNote;return this.exceededNote=null,e}trip(e){this.exceededNote!==null||this.deps.isDisposed()||(this.exceededNote=e,this.deps.onTripped())}};function oD(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function sD(e,t){return!oD(e,t)}function cD(e){let t=e.captureStructuredOutput,n;return n=new
|
|
1148
|
+
---`);let u=iT(i);return u&&(l+=u),l}const XE=y(`scoop-context`);function ZE(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!tn(t).includes(`xhigh`)?`high`:e}function QE(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(ir.includes(e))return e;XE.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}const $E=y(`scoop-context`);function eD(e,t){let n=GE(t);e.state.model=n;let r=Pn(t),i=QE()??r.level;return e.state.thinkingLevel=ZE(i,n),$E.info(`Model updated on running agent`,{folder:t.folder,model:n.id,thinkingLevel:e.state.thinkingLevel}),n.reasoning?r.effortOverride:void 0}function tD(e,t){if(QE())return e.state.thinkingLevel;let n=ZE(t,e.state.model);return e.state.thinkingLevel=n,n}async function nD(e,t){let n=await tT(t.skillsFs??t.fs,er),r=await VE(t.fs,t.unit.workspace.memoryPath),i=await t.getGlobalMemory();e.state.systemPrompt=YE(t.scoop,t.unit,i,r,n),$E.info(`Skills reloaded`,{folder:t.scoop.folder,skillCount:n.length})}const rD=y(`scoop-context`);var iD=class{deps;attempted=!1;active=!1;escalated=!1;pending=null;constructor(e){this.deps=e}resetForRun(){this.attempted=!1,this.active=!1,this.pending=null,this.escalated=!1}get pendingRecovery(){return this.pending}clearPendingRecovery(e){this.pending===e&&(this.pending=null)}get isActive(){return this.active}get hasAttempted(){return this.attempted}markSettled(){this.active=!1}markAssistantSucceeded(){this.attempted=!1}shouldRecover(e){return!this.deps.isImageRecoveryActive()&&Uo(e)}recover(e,t){let n=this.deps.getTurnSignal(),r=t&&n?AbortSignal.any([t,n]):t??n,i=this.deps.getAgent();if(!i||this.deps.isDisposed()||r?.aborted)return;if(this.attempted){this.escalate(r);return}this.attempted=!0,this.active=!0,rD.warn(`Context overflow detected, attempting recovery`,{folder:this.deps.folder,messageCount:e.length});let a=this.deps.getCompactFn(),o=i.state.messages,s=o[o.length-1],c=s?.role===`assistant`&&Uo(s)?o.slice(0,-1):o;if(i.state.messages=c,!a||!i.state.model||!this.deps.getCompactionApiKey()){this.escalate(r,Error(`Compaction is unavailable`));return}this.pending=this.compactAndResume(i,a,c,r)}async compactAndResume(e,t,n,r){try{let i=await t(n,r,{force:!0});if(this.deps.isDisposed()||r?.aborted||this.deps.getAgent()!==e)return;if(!dn(n,i)){this.escalate(r,Error(`Forced compaction did not reduce the context`));return}e.state.messages=i,this.deps.onResponse(`Context window exceeded — compacting history and continuing...`,!1),await new Promise(t=>{setTimeout(()=>{if(this.deps.isDisposed()||r?.aborted||this.deps.getAgent()!==e){t();return}e.continue().then(t).catch(e=>{!this.deps.isDisposed()&&!r?.aborted&&this.escalate(r,e),t()})},100)})}catch(e){!this.deps.isDisposed()&&!r?.aborted&&this.escalate(r,e)}finally{this.active=!1}}escalate(e,t){if(this.active=!1,this.deps.isDisposed()||e?.aborted||this.escalated)return;this.escalated=!0;let n=t instanceof Error?t.message:t?String(t):void 0;rD.error(`Context overflow recovery exhausted`,{folder:this.deps.folder,error:n}),this.deps.setStatus(`error`),this.deps.onExhausted(`Scoop "${this.deps.scoopName}" context window was exceeded and could not be reduced. Re-delegate with a narrower task.`)}},aD=class{deps;turnCount=0;exceededNote=null;wallClockTimer=null;constructor(e){this.deps=e}arm(){this.turnCount=0,this.exceededNote=null;let e=this.deps.getConfig()?.maxWallClockMs;typeof e==`number`&&Number.isFinite(e)&&e>0&&(this.wallClockTimer=setTimeout(()=>{this.wallClockTimer=null,this.trip(`wall-clock bound (${e} ms) exceeded`)},e))}recordCompletedTurn(){this.turnCount+=1}enforceOnTurnStart(){let e=this.deps.getConfig()?.maxTurns;typeof e==`number`&&e>0&&this.turnCount>=e&&this.trip(`turn bound (${e}) exceeded`)}disarm(){this.wallClockTimer!==null&&(clearTimeout(this.wallClockTimer),this.wallClockTimer=null)}takeExceededNote(){let e=this.exceededNote;return this.exceededNote=null,e}trip(e){this.exceededNote!==null||this.deps.isDisposed()||(this.exceededNote=e,this.deps.onTripped())}};function oD(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function sD(e,t){return!oD(e,t)}function cD(e){let t=e.captureStructuredOutput,n;return n=new v_({initialState:{model:e.model,tools:e.tools,systemPrompt:e.systemPrompt,messages:e.messages,thinkingLevel:e.thinkingLevel},getApiKey:e.getApiKey,transformContext:async(t,r)=>{let i=await e.transformContext(t,r);return r?.aborted||!sD(t,i)?t:oD(n.state.messages,t)?(t.splice(0,t.length,...i),n.state.messages=[...i],e.onContextCompacted?.(),t):i},streamFn:e.streamFn,afterToolCall:async e=>{t&&e.toolCall.name===`StructuredOutput`&&t(e.args)}}),n}const lD=y(`scoop-context`);async function uD(e,t,n,r){if(!e)return;let i=n.policy.filesystem.kind===`full-workspace`?[n.workspace.root,`/shared`,`/scoops`,`/home`,`/home/user`,Xn,r,`/mnt`]:[`/scoops/${t.folder}`,`/scoops/${t.folder}/workspace`,`/scoops/${t.folder}/home`,`/scoops/${t.folder}/tmp`,`/shared`,Xn,r];for(let t of i)try{await e.mkdir(t,{recursive:!0})}catch{}let a=n.workspace.memoryPath;try{await e.readFile(a)}catch{let r=`# ${t.assistantLabel} Memory
|
|
1149
1149
|
|
|
1150
1150
|
${n.display.role===`primary`?`Role: Cone (main orchestrator)`:`Scoop: ${t.name}`}
|
|
1151
1151
|
Folder: ${t.folder}
|
|
@@ -1162,15 +1162,15 @@ Created: ${new Date().toISOString()}
|
|
|
1162
1162
|
`),d=Buffer.byteLength(u,`utf-8`);return{content:u,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:d,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function AD(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=DD(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`,u=!1;for(let e=a.length-1;e>=0&&s.length<n;e--){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(s.length>0);if(c+n>r){if(l=`bytes`,s.length===0){let e=jD(t,r);s.unshift(e),c=Buffer.byteLength(e,`utf-8`),u=!0}break}s.unshift(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let d=s.join(`
|
|
1163
1163
|
`),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 jD(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 MD=y(`tool:bash`),ND=40960,PD=1048576,FD=`\0slicc-img:`;function ID(e){let t=hn(e).filter(e=>e.kind===`image`);if(t.length===0)return{text:e,markers:new Map};let n=new Set,r=PD;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=new Map,a=``,o=0;return t.forEach((t,r)=>{if(a+=e.slice(o,t.index),n.has(r)){let e=`${FD}${r}`;i.set(e,t.marker),a+=e}else a+=`[image dropped: a newer image in this command used up the ${PD/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 LD(e){let t=hn(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 RD(e){return e.replaceAll(RegExp(`${FD}\\d+`,`g`),`[image]`)}function zD(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 BD(e,t,n,r){let{text:i,markers:a}=ID(e),o=AD(i,{maxBytes:ND});if(!o.truncated)return zD(i,a);let s=`showing the last ${OD(o.outputBytes)} of ${OD(o.totalBytes)} (${o.totalLines} lines)`,c=`${n}/bash-output-${r()}.txt`;try{return await t.writeFile(c,RD(i)),zD(`${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 MD.warn(`Failed to persist full bash output`,{error:e instanceof Error?e.message:String(e)}),zD(`${o.content}\n\n[Output truncated: ${s}. Re-run piping through \`head\`/\`tail\`/\`grep\`/\`sed -n\` to narrow the output.]`,a)}}const VD=new Set([`grep`,`egrep`,`fgrep`,`rg`]);function HD(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 UD(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=HD(r.name);if(i!==`command`)return i;let a=r.args[0];return a?HD(a):null}function WD(e,t,n,r){if(n!==1||r.trim())return!1;let i;try{i=UD(e.getBash().transform(t).ast)}catch{return!1}return i!==null&&VD.has(i)}function GD(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return e}function KD(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 ${ND/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 ${PD/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.`}function qD(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 JD(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 YD(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 eO(e,n,r);await e.fs.writeFile(t,i)}).catch(e=>MD.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,{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:(e,t)=>{s=e,c=t,u()},flushPersist:()=>l,killedByTimeout:!1}}function XD(e,t){t===`timeout`&&(e.killedByTimeout=!0),e.job?.kill(),e.controller.abort(),e.job?.exit(null)}function ZD(e,t){e.job?.exit(e.job.signal.aborted?null:t)}function QD(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 $D(e,t,n,r={}){let i=0,a=0,o={shell:e,fs:t,tempDir:n,options:r,defaultBackgroundAfter:GD(r.defaultBackgroundAfterSeconds)??600,nextOutputSeq:()=>i+=1,nextJobId:()=>`bg-${a+=1}`};return{name:`bash`,description:KD(o.defaultBackgroundAfter),inputSchema:qD(o.defaultBackgroundAfter),execute:(e,t)=>oO(o,e,t)}}async function eO(e,t,n){let r=e.options.scrubOutput;if(!r||!n)return n;try{return await r(n)}catch(e){return MD.warn(`Background bash output scrub failed; withholding output`,{jobId:t,error:e instanceof Error?e.message:String(e)}),`[output withheld: secret scrub unavailable]`}}function tO(e){return e.ok?e.result.exitCode===124&&/execution aborted/i.test(e.result.stderr):/execution aborted/i.test(e.error)}function nO(e,t){return e===void 0?`--- killed (exit ${t}) ---\n`:`--- killed after ${e}s (exit ${t}) ---\n`}async function rO(e,t,n,r,i,a,o,s){await o.flushPersist();let c=o.killedByTimeout||tO(a),l,u;if(c){let e=o.getTeedOutput();u=124,l=`${e.endsWith(`
|
|
1164
1164
|
`)||e.length===0?e:`${e}\n`}${nO(s,u)}`}else if(a.ok)l=[a.result.stdout,a.result.stderr].filter(Boolean).join(``)||`(exit code: ${a.result.exitCode})`,u=a.result.exitCode;else{let e=o.getTeedOutput();u=1,l=e?`${e.endsWith(`
|
|
1165
|
-
`)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await eO(e,t,l),f;try{await e.fs.writeFile(i,d),f=i}catch(e){MD.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){MD.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=AD(LD(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:new Date().toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:u,resultPath:f??null}})}function iO(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=i===void 0?void 0:i-a,u=l===void 0?void 0:setTimeout(()=>XD(t,`timeout`),l*1e3);return t.settled.then(r=>(u!==void 0&&clearTimeout(u),ZD(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),rO(e,o,s,n,c,r,t,i))).catch(e=>MD.error(`Background bash delivery failed`,{jobId:o,error:e})),MD.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:l}),QD(o,s,r,c,i)}async function aO(e,t,n){MD.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})`,{content:await BD(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!WD(e.shell,t,n.exitCode,n.stderr)}}async function oO(e,t,n){let r=t.command,i=GD(t.timeout),a=GD(t.background_after)??e.defaultBackgroundAfter;MD.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=YD(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?(XD(o,`timeout`),MD.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),JD(c)):t===`elapsed`?iO(e,o,r,c,i,a):(ZD(o,t.ok?t.result.exitCode:1),t.ok?await aO(e,r,t.result):(MD.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const sO={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 cO(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function lO(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:cO(e)&&(t.edits=[e])}catch{}else cO(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 uO(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:sO,prepareArguments:lO,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-
|
|
1165
|
+
`)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await eO(e,t,l),f;try{await e.fs.writeFile(i,d),f=i}catch(e){MD.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){MD.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=AD(LD(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:new Date().toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:u,resultPath:f??null}})}function iO(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=i===void 0?void 0:i-a,u=l===void 0?void 0:setTimeout(()=>XD(t,`timeout`),l*1e3);return t.settled.then(r=>(u!==void 0&&clearTimeout(u),ZD(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),rO(e,o,s,n,c,r,t,i))).catch(e=>MD.error(`Background bash delivery failed`,{jobId:o,error:e})),MD.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:l}),QD(o,s,r,c,i)}async function aO(e,t,n){MD.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})`,{content:await BD(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!WD(e.shell,t,n.exitCode,n.stderr)}}async function oO(e,t,n){let r=t.command,i=GD(t.timeout),a=GD(t.background_after)??e.defaultBackgroundAfter;MD.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=YD(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?(XD(o,`timeout`),MD.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),JD(c)):t===`elapsed`?iO(e,o,r,c,i,a):(ZD(o,t.ok?t.result.exitCode:1),t.ok?await aO(e,r,t.result):(MD.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const sO={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 cO(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function lO(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:cO(e)&&(t.edits=[e])}catch{}else cO(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 uO(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:sO,prepareArguments:lO,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-D6vx5LyF.js`);return i(e,t,n,r)}}}async function dO(e,t,n){if(Tr(_n(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 fO=y(`tool:fs`);function pO(e,t=`/workspace`){return[mO(e),hO(e),uO(e,t)]}function mO(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${ED/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;fO.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
|
|
1166
1166
|
`),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=kD(c.join(`
|
|
1167
|
-
`));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${OD(new TextEncoder().encode(t[o]??``).length)}, exceeds ${OD(ED)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${ED}]`};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} (${OD(ED)} 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 fO.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function hO(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;fO.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await dO(e,n,r);return t?(fO.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 fO.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const gO={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 _O(e,t){return{name:Zr,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:gO,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-
|
|
1167
|
+
`));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${OD(new TextEncoder().encode(t[o]??``).length)}, exceeds ${OD(ED)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${ED}]`};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} (${OD(ED)} 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 fO.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function hO(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;fO.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await dO(e,n,r);return t?(fO.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 fO.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const gO={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 _O(e,t){return{name:Zr,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:gO,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-rXtR1z76.js`);return r(e,t,n)}}}function vO(){return null}const yO=y(`tool:request-secret`);async function bO(e,t){let n=vO();if(n)return n(e);let r=t.callPanelRpc??await xO();return r?r(e):{stored:!1,reason:`unavailable`}}async function xO(){let{getPanelRpcClient:e}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i),t=e();return t?e=>t.call(`secret-request`,e,{timeoutMs:3e5}):null}function SO(e){try{return e.getProvider?.()||void 0}catch(e){yO.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function CO(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 wO(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(`
|
|
1168
1168
|
`)}function TO(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 EO(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:CO(t.domains),persist:t.persist===!0,requester:e.requester,provider:SO(e)},a;try{a=await bO(i,e)}catch(e){let t=e instanceof Error?e.message:String(e);return yO.error(`secret request failed`,{name:n,error:t}),{content:`The secret prompt failed: ${t}`,isError:!0}}if(!a.stored)return{content:TO(a),isError:!0};let o=DO(a.name,a.maskedValue,e);return yO.info(`secret stored via request_secret`,{name:a.name,persisted:a.persisted}),{content:wO(a,o)}}}}function DO(e,t,n){if(!n.setEnv||!t||!d(e))return!1;try{return n.setEnv(e,t),!0}catch(t){return yO.warn(`could not inject the masked value into the shell env`,{name:e,error:t instanceof Error?t.message:String(t)}),!1}}const OO=y(`scoop-management-tools`),kO=`cross_cone`;function AO(e){return Tn(e.getScoops(),e.scoop.jid)}function jO(e){let t=new Set;for(let n of AO(e))n.jid!==e.scoop.jid&&n.parentJid!==null&&t.add(n.jid);return t}function MO(e){let t=kn(e.getScoops());return t!==void 0&&t.jid===e.scoop.jid}function NO(e){let t=e.getScoops(),n=jO(e),r=MO(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=Gn(t,e);a.kind!==`cycle`&&i.push({scoop:e,relation:a.kind===`root`?`foreign`:`inherited`})}return i}function PO(e){return t=>t.folder===e||t.name===e}function FO(e,t){let n=NO(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 IO(e,t){let n=[],r=[];for(let i of e){let e=FO(i,t);e?n.push(e):r.push(i)}return{resolved:n,unknown:r}}function LO(e,t){return Dn(e.getScoops(),t.scoop)?.folder??`unknown`}function RO(e,t){return t.relation===`inherited`?`inherited (its owning cone is gone)`:`owned by cone "${LO(e,t)}"`}function zO(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 ${RO(r,e)}`).join(`; `)}. Pass ${kO}: true to act on it anyway.`,isError:!0}}function BO(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 VO=[`command`,`read`,`write`,`secret`];function HO(e){return`${we(e,{maxLen:50})}-scoop`}function UO(e){return e===void 0?{ok:!0}:rr(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${ir.join(`, `)}.`,isError:!0}}function WO(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 GO(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 KO(e,t){let n=NO(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 qO(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 JO(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),OO.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function YO(e){let{kind:t,detail:n,suggested_pattern:r,reason:i}=e;if(!VO.includes(t))return{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${VO.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`?g(i):``;return{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{},...a?{reason:a}:{}}}}function XO(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(`
|
|
1169
1169
|
`)}async function ZO(e,t){let n=YO(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return OO.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:XO(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function QO(e,t){let{scoop_name:n,prompt:r,cross_cone:i}=e;if(PO(n)(t.scoop))return{content:`Cannot feed yourself.`,isError:!0};let a=FO(n,t);if(!a)return KO([n],t);let o=zO([a],i,`feed "${n}"`,t);if(o)return o;try{await t.onFeedScoop(a.scoop.jid,r),OO.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 (${kO}: 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 $O(e,t){return t.relation===`own`?``:t.relation===`inherited`?` [INHERITED]`:` [FOREIGN: ${LO(e,t)}]`}async function ek(e){let t=new Map(NO(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 qO(n,e.getScoopTabState,r?$O(e,r):``)}).join(`
|
|
1170
1170
|
`)}`}}function tk({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:new Date().toISOString(),config:{...n?{modelId:n}:{},...n&&r?{modelProviderId:r}:{},...nk(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 nk(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function rk(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return OO.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 ik(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,workspaceMode:s,allowedCommands:c,thinking:l,background_after:u,canCreateChildren:d}=e,f=Sn(s);if(!f.ok)return{content:f.error,isError:!0};let p=UO(l);if(!p.ok)return{content:p.content,isError:p.isError};let m=WO(u);if(!m.ok)return{content:m.content,isError:!0};let h=GO(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let g=HO(n),_=AO(t).find(e=>e.jid!==t.scoop.jid&&e.parentJid!==null&&(e.name===n||e.folder===g));if(_)return{content:`A scoop named "${_.name}" (${_.folder}) already exists in your scoops. Use feed_scoop to give it another task, or drop_scoop first.`,isError:!0};let ee=Nn(g,t.getScoops().map(e=>e.folder));try{let e=tk({name:n,folder:ee,model:h.modelId,modelProviderId:h.providerId,visiblePaths:a,writablePaths:o,workspaceMode:f.mode,allowedCommands:c,thinkingLevel:p.level,backgroundAfterSeconds:m.seconds,parentJid:t.scoop.jid,defaultVisibleRoots:$n(nr(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return OO.info(`Scoop created`,{name:n,folder:ee}),i&&t.onFeedScoop?rk(r,i,n,ee,t.onFeedScoop):{content:`Scoop "${n}" created as "${ee}". 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 ak(e,t){let{scoop_name:n,cross_cone:r}=e;if(PO(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=FO(n,t);if(!i)return KO([n],t);let a=zO([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),OO.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 ok(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function sk(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return ok();let{resolved:i,unknown:a}=IO(n,t);return i.length===0?KO(a,t):zO(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),OO.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 ck(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 lk(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return ok();let{resolved:i,unknown:a}=IO(n,t);if(i.length===0)return KO(a,t);let o=zO(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);OO.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(...ck(l,c)),{content:u.join(`
|
|
1171
1171
|
`)}}function uk(e,t){return!Array.isArray(e)||e.length===0?ok():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 dk(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 fk(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=uk(n,r);if(a)return a;let{resolved:o,unknown:s}=IO(n,t);if(o.length===0)return KO(s,t);let c=zO(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 OO.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:dk(f,s,p,r)}}function pk(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 mk(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`?g(a):``,s={...r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`},...o?{note:o}:{}};try{let e=await t.onSudoResolve(n,s);return e.settled?(OO.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:pk(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 hk(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`?g(r):``;try{let e=await t.onSudoResolve(n,{decision:`deny`,...i?{note:i}:{}});return e.settled?(OO.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 gk(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(`
|
|
1172
|
-
`)}`}}async function _k(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),OO.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 vk(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=>JO(t,e)}}function yk(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:[...VO],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=>ZO(t,e)}}function bk(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.`},[kO]:BO(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>QO(t,e)}}function xk(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:()=>ek(e)}}function Sk(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:[...ir],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=>ik(t,e)}}function Ck(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.`},[kO]:BO(`drop`)},required:[`scoop_name`]},execute:t=>ak(t,e)}}function wk(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"]).`},[kO]:BO(`mute`)},required:[`scoop_names`]},execute:t=>sk(t,e)}}function Tk(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"]).`},[kO]:BO(`unmute`)},required:[`scoop_names`]},execute:t=>lk(t,e)}}function Ek(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."},[kO]:BO(`wait on`)},required:[`scoop_names`]},execute:t=>fk(t,e)}}function Dk(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=>mk(t,e)}}function Ok(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=>hk(t,e)}}function kk(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:()=>gk(e)}}function Ak(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=>_k(t,e)}}function jk(e){let t=[],n=En(e.scoop);return wn(e.scoop)||(t.push(vk(e)),e.onSudoRequest&&t.push(yk(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(Sk(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(bk(e)),t.push(xk(e)),e.onDropScoop&&t.push(Ck(e)),e.onMuteScoops&&t.push(wk(e)),e.onUnmuteScoops&&t.push(Tk(e)),e.onScheduleScoopWait&&t.push(Ek(e)),e.onSudoResolve&&(t.push(Dk(e)),t.push(Ok(e))),e.onListSudoRequests&&t.push(kk(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(Ak(e))),t}const Mk=y(`scoop-context`);function Nk(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-Mu-876Hm.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function Pk(e){let{scoop:t,unit:n,callbacks:r}=e,i=jk({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:he,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=pO(e.gatedFs,n.workspace.root),o=_O(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>UC);return t(e.fs)}}),s=[...a,o,$D(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:an(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){Mk.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i,EO({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>TD(GE(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);s.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let c={scrubToolResult:an()},l=Nk(e);return e.processManager?sn(s,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},c,l):sn(s,void 0,c,l)}const Fk=y(`scoop-context`);async function Ik(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();Fk.info(`Filesystem ready`,{folder:t.folder}),await uD(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,skills:l}=await CD({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(o);let u=await Pk({getTurnGuestGates:e.getTurnGuestGates,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:d,globalMemory:f}=await HE(r,n,()=>i.getGlobalMemory());if(!WE(t))return Fk.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let p=KE(t,n),m=YE(t,n,f,d,l),h=await e.sessions.restore(),{streamWithSessionId:g,compactFn:_,getCompactionApiKey:ee}=await fD(p,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>WE(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let te=Pn(t);return{kind:`ready`,agent:cD({model:p,tools:u,systemPrompt:m,messages:h,thinkingLevel:ZE(QE()??te.level,p),getApiKey:()=>WE(t)??void 0,transformContext:_,streamFn:g,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:_,getCompactionApiKey:ee,effortOverride:te.effortOverride,toolCount:u.length}}const Lk=y(`scoop-context`);var Rk=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 Lk.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=SC(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=ln(n);return Lk.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.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return;let n=this.deps.canonical;n&&(this.createdAt||=Date.now(),n.store.syncAgentMessages(n.identity,t,{createdAt:this.createdAt}).catch(e=>{Lk.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})}))}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){Lk.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 zk(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 Bk(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function Vk(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const Hk=y(`scoop-context`);var Uk=class{deps;constructor(e){this.deps=e}async run(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.deps.isDisposed()||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n,r);if(!o||this.deps.isDisposed()||r.aborted||(i=o,await this.handleAttemptError(o,a,r)))return null}return i}reportExhausted(e){let t=e.message;Hk.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 tryAgentPrompt(e,t,n,r){this.deps.beginAttempt();try{if(await e.prompt(t,n),this.deps.isDisposed()||r.aborted)return null;let i=this.deps.overflow.pendingRecovery;if(i!==null&&(await i,this.deps.overflow.clearPendingRecovery(i),this.deps.isDisposed()||r.aborted))return null;let a=this.deps.getStreamError();return a?Error(a):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)&&(Hk.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:kE(r)}),!!(t<3&&(await AE(Wk(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return OE(e)?(Hk.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 Da(e)?(Hk.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Aa(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(!kE(e)||t>=3)return!1;let r=Wk(t);return Hk.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await AE(r,n)&&!this.deps.isDisposed()}fail(e,t){EE(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function Wk(e){return 1e3*2**(e-1)}function Gk(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){Hk.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 Kk=y(`scoop-context`);var qk=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>this.callbacks.onToolStart?.(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:()=>this.sessions.schedule(),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){this.scoop=e,this.unit=Zn(e),this.owner={kind:jn(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.sessions=new Rk({store:r??null,canonical:c?{store:c,identity:br(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 aD({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new LE({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new zE({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new iD({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 Uk({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 yD(this.unit,this.scoop,A(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Jn(this.callbacks.getScoops(),this.scoop)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);let e=await Ik({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,capabilityBroker:this.capabilityBroker,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getTurnGuestGates:()=>this.turnGuestGates,getLickTarget:()=>this.ownLickTarget(),getTmpDir:()=>this.ownTmpDir(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0},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`),Kk.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);Kk.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(JE(this.scoop)),!1)}cleanupPromptState(e,t,n,r){this.runBounds.disarm();let i=this.runBounds.takeExceededNote();i!==null&&this.callbacks.onError(`agent run terminated: ${i}`),(n||r.aborted)&&this.sessions.persistNow(),this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),Bk(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(Gk(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;this.promptAbortController?.abort();let a=new AbortController;this.promptAbortController=a;let o=a.signal;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let s=zk(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:a});this.currentTurnProcess=s,this.runBounds.arm();let c=null;try{if(c=await this.turnRunner.run(i,e,t,o),c&&!this.disposed&&!o.aborted){this.turnRunner.reportExhausted(c);return}!this.disposed&&!o.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(a,s,c,o)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||this.turnGuestGates.push(e)}stop(){Vk(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0)}idleCompactionEnabled(){return CE(this.scoop)?!0:this.unit.parentId===null&&fa(`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-B9i1duyd.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:un,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&&!fa(`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-ZXxxxzvO.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?{transcriptPath:o.transcriptPath}:void 0}async settleLiveSnapshot(e){if(!(this.unit.parentId!==null||!this.fs))try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-ZXxxxzvO.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){Kk.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):[]}getContextFill(){return qE(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=eD(this.agent,this.scoop))}async reloadSkills(){this.agent&&await nD(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?QE()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,tD(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),Vk(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){this.disposed||NE(e,this.eventSink,t)}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||jE(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=y(`scoop-lifecycle-manager`);var Jk=class{deps;units=new Map;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 vE(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=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))??A(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Dn(t.values(),e)??A(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 _r))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(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=Zn(t).policy.filesystem;if(a.kind===`restricted`){let e=Sn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new _r(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:xn(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 qk(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);n.attachContext(l,i),await l.init(),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=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.getContext(e);o||=(await this.createTab(e),this.getContext(e));let s=this.units.get(e);if(s?.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}o=this.getContext(e)}if(!o||!s){Q.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s.tab&&s.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 o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();if(Un(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=Nn(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&&eE(`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}}inheritModel(e){if(An(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Vn(t):void 0)??GT();n&&Mn(e,n)}async unregister(e){let t=this.deps.getScoops();for(let n of Kn(t.values(),e))await this.unregister(n.jid);let n=t.get(e);if(n&&n.parentJid===null&&A(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.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([n?this.deps.getConversationStore()?.delete(yr(n)):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 a=this.deps.approvalRouter.failScoop(e);if(a>0&&Q.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),Q.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){Q.warn(`onScoopUnregistered callback threw`,{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;let r=n.model;Mn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Mn(n,r),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!0}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;zn(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}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Zn(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:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),eE(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},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 On(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:nr(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,wn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(wn(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}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}),eE(`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`),Zn(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(!i)return;let a={id:`scoop-error-${e}-${Date.now()}`,chatJid:i.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(i.jid,a)}catch(e){Q.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{Q.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const $=y(`scoop-message-router`);var Yk=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=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}`);eE(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp: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=cb(ub(sb(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=C_(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(`
|
|
1173
|
-
`);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>w_(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=cb(ub(sb(a),o));this.lastAgentTimestamp.set(e,f),await this.deps.db.setState(`lastAgentTs_${e}`,f);let p=s.some(e=>e.steer),m=new Set,h=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);m.has(t)||(m.add(t),h.push(e.guestGate))}await this.deps.sendPrompt(e,l,d.senderId,d.senderName,u,{steer:p,...h.length>0?{guestGates:h}:{}})}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),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 Xk=y(`orchestrator`),Zk={decision:`deny`};var Qk=class{scoops=new Map;workUnits=new ky(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new uT({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new hE({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 pE({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new sE({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 YT({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=>ab(e),saveMessage:e=>rb(e)});lickRegistry=new VT({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 Yk({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)=>this.callbacks.onError(e,t),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>rb(e),deleteMessage:e=>ib(e),clearMessagesForScoop:e=>nb(e),clearAllMessages:()=>tb(),getMessagesSince:(e,t,n)=>db(e,t,n),setState:(e,t)=>_b(e,t)},isExternalLickChannel:uy});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Jk({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,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>Qy(e),deleteScoop:e=>eb(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>IT(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)},handleMessage:e=>this.handleMessage(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 KT(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new xx({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 px(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new WT(e,t),await this.modelPolicyFile.init(),n(),$y()),n,{stagePrefix:`orchestrator-init`})}async init(e){await vb(),this.sharedFs=await KT(e=>gr.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new D_,this.conversationStore=new NC,this.fsWatcher=new hr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher;let t=await this.initPolicyLayerAndLoadRecords(this.sharedFs,this.fsWatcher,e),n=Object.values(t).find(e=>Rn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Un(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await gb(`lastAgentTs_${e.jid}`);r&&this.messageRouter.setLastAgentTimestamp(e.jid,r)}await this.backfillModels(),await this.migrateConversations(e),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new JT({onTaskRun:async(e,t)=>{Xk.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(),Xk.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let t of this.scoops.values())try{await this.createScoopTab(t.jid)}catch(e){let n=e instanceof Error?e.message:String(e);Xk.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}Er(e=>this.getSessionCostsForCommand(e)),Dr(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>k_);return e()}),this.unregisterExportService=o(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Qv;try{await _C({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){Xk.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(br(r),t).catch(t=>{Xk.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=Rn(e)?null:t??null;try{await Qy(e)}catch(t){Xk.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=>!An(e));if(e.length===0)return;let t=GT(),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?Vn(n):void 0)??t;if(r){Mn(e,r);try{await Qy(e)}catch(t){Xk.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}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=`${Qn.root}/`,r=$n(tr(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: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)}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-CaEocD9T.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:nr,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(Xk.warn(`Guest approval before SudoManager init — failing closed`),Zk)}})}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 Qy(e)}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 A(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 Wn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Dn(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(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await gr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await aT(this.sharedFs).catch(e=>{Xk.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new xx({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 px(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new WT(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),Xk.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 ab(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await Promise.resolve().then(()=>Zx),r=await n(this.sharedFs);return[...t,...r.map(Or)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&Xk.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),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,Xk.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new AC(this.conversationStore):null,t=this.sharedFs;return new PS({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:$S(),snapshotStore:{read:e=>GS(t,e),write:(e,n)=>WS(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.165.0`})}};const $k=y(`workflow-run-manager`),eA=`/shared/workflow-runs`,tA=1e3;function nA(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function rA(e){let t=new Map,n=new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){$k.warn(`observeRun handler threw`,e)}},i=(e,n)=>cA(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=nA(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:new Date().toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(c,d),oA(t,n);let f=i(a.ctx,c),p=sA(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=>$k.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=`${eA}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(eA,{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);$k.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`?aA(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: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=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){$k.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function iA(e){let t=rA(e);return globalThis[p]=t,$k.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function aA(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function oA(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 sA(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 cA(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?lA(n,t,a?.args??[],r):e===`agent`?uA(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function lA(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>tA&&i.logs.splice(0,i.logs.length-tA),r()}return{stdout:``,stderr:``,exitCode:0}}async function uA(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 dA=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function fA(e,t,n){let r=pA(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=gA(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function pA(e){let t=new Map;return mA(t,e.discoveryOrigin),mA(t,e.discoveryUrl),[...t.values()]}function mA(e,t){if(t){hA(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);hA(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!dA.has(e)))hA(e,t,1,`substring`)}catch{}}}function hA(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 gA(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=vA(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)_A(a,e)&&(r+=e.weight*o)}return r}function _A(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 vA(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var yA=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=SA(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:xA,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===xA)throw new j(`ENOTDIR`,`not a directory`,e);let n=CA(t[0]);if(n===null||!this.pidExists(n))throw new j(`ENOENT`,`no such file or directory`,e);return bA.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new j(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=SA(e);if(t.length===1&&t[0]===xA)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new j(`EISDIR`,`is a directory`,e);let n=CA(t[0]);if(n===null||!this.pidExists(n))throw new j(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!bA.includes(r))throw new j(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new j(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=SA(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===xA)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=CA(t[0]);if(n===null||!this.pidExists(n))throw new j(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=CA(t[0]);if(n===null||!this.pidExists(n))throw new j(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!bA.includes(r))throw new j(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new j(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new j(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new j(`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 j(`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:OA(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:kA(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
1172
|
+
`)}`}}async function _k(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),OO.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 vk(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=>JO(t,e)}}function yk(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:[...VO],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=>ZO(t,e)}}function bk(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.`},[kO]:BO(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>QO(t,e)}}function xk(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:()=>ek(e)}}function Sk(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:[...ir],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=>ik(t,e)}}function Ck(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.`},[kO]:BO(`drop`)},required:[`scoop_name`]},execute:t=>ak(t,e)}}function wk(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"]).`},[kO]:BO(`mute`)},required:[`scoop_names`]},execute:t=>sk(t,e)}}function Tk(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"]).`},[kO]:BO(`unmute`)},required:[`scoop_names`]},execute:t=>lk(t,e)}}function Ek(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."},[kO]:BO(`wait on`)},required:[`scoop_names`]},execute:t=>fk(t,e)}}function Dk(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=>mk(t,e)}}function Ok(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=>hk(t,e)}}function kk(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:()=>gk(e)}}function Ak(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=>_k(t,e)}}function jk(e){let t=[],n=En(e.scoop);return wn(e.scoop)||(t.push(vk(e)),e.onSudoRequest&&t.push(yk(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(Sk(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(bk(e)),t.push(xk(e)),e.onDropScoop&&t.push(Ck(e)),e.onMuteScoops&&t.push(wk(e)),e.onUnmuteScoops&&t.push(Tk(e)),e.onScheduleScoopWait&&t.push(Ek(e)),e.onSudoResolve&&(t.push(Dk(e)),t.push(Ok(e))),e.onListSudoRequests&&t.push(kk(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(Ak(e))),t}const Mk=y(`scoop-context`);function Nk(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-Mu-876Hm.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function Pk(e){let{scoop:t,unit:n,callbacks:r}=e,i=jk({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:he,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=pO(e.gatedFs,n.workspace.root),o=_O(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>UC);return t(e.fs)}}),s=[...a,o,$D(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:an(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){Mk.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i,EO({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>TD(GE(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);s.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let c={scrubToolResult:an()},l=Nk(e);return e.processManager?sn(s,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},c,l):sn(s,void 0,c,l)}const Fk=y(`scoop-context`);async function Ik(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();Fk.info(`Filesystem ready`,{folder:t.folder}),await uD(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,skills:l}=await CD({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(o);let u=await Pk({getTurnGuestGates:e.getTurnGuestGates,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:d,globalMemory:f}=await HE(r,n,()=>i.getGlobalMemory());if(!WE(t))return Fk.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let p=KE(t,n),m=YE(t,n,f,d,l),h=await e.sessions.restore(),{streamWithSessionId:g,compactFn:_,getCompactionApiKey:ee}=await fD(p,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>WE(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let te=Pn(t);return{kind:`ready`,agent:cD({model:p,tools:u,systemPrompt:m,messages:h,thinkingLevel:ZE(QE()??te.level,p),getApiKey:()=>WE(t)??void 0,transformContext:_,streamFn:g,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:_,getCompactionApiKey:ee,effortOverride:te.effortOverride,toolCount:u.length}}const Lk=y(`scoop-context`);var Rk=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 Lk.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=xC(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=ln(n);return Lk.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.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return;let n=this.deps.canonical;n&&(this.createdAt||=Date.now(),n.store.syncAgentMessages(n.identity,t,{createdAt:this.createdAt}).catch(e=>{Lk.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})}))}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){Lk.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 zk(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 Bk(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function Vk(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const Hk=y(`scoop-context`);var Uk=class{deps;constructor(e){this.deps=e}async run(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.deps.isDisposed()||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n,r);if(!o||this.deps.isDisposed()||r.aborted||(i=o,await this.handleAttemptError(o,a,r)))return null}return i}reportExhausted(e){let t=e.message;Hk.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 tryAgentPrompt(e,t,n,r){this.deps.beginAttempt();try{if(await e.prompt(t,n),this.deps.isDisposed()||r.aborted)return null;let i=this.deps.overflow.pendingRecovery;if(i!==null&&(await i,this.deps.overflow.clearPendingRecovery(i),this.deps.isDisposed()||r.aborted))return null;let a=this.deps.getStreamError();return a?Error(a):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)&&(Hk.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:kE(r)}),!!(t<3&&(await AE(Wk(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return OE(e)?(Hk.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 Da(e)?(Hk.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Aa(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(!kE(e)||t>=3)return!1;let r=Wk(t);return Hk.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await AE(r,n)&&!this.deps.isDisposed()}fail(e,t){EE(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function Wk(e){return 1e3*2**(e-1)}function Gk(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){Hk.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 Kk=y(`scoop-context`);var qk=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>this.callbacks.onToolStart?.(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:()=>this.sessions.schedule(),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){this.scoop=e,this.unit=Zn(e),this.owner={kind:jn(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.sessions=new Rk({store:r??null,canonical:c?{store:c,identity:br(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 aD({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new LE({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new zE({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new iD({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 Uk({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 yD(this.unit,this.scoop,A(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Jn(this.callbacks.getScoops(),this.scoop)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);let e=await Ik({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,capabilityBroker:this.capabilityBroker,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getTurnGuestGates:()=>this.turnGuestGates,getLickTarget:()=>this.ownLickTarget(),getTmpDir:()=>this.ownTmpDir(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0},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`),Kk.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);Kk.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(JE(this.scoop)),!1)}cleanupPromptState(e,t,n,r){this.runBounds.disarm();let i=this.runBounds.takeExceededNote();i!==null&&this.callbacks.onError(`agent run terminated: ${i}`),(n||r.aborted)&&this.sessions.persistNow(),this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),Bk(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(Gk(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;this.promptAbortController?.abort();let a=new AbortController;this.promptAbortController=a;let o=a.signal;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let s=zk(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:a});this.currentTurnProcess=s,this.runBounds.arm();let c=null;try{if(c=await this.turnRunner.run(i,e,t,o),c&&!this.disposed&&!o.aborted){this.turnRunner.reportExhausted(c);return}!this.disposed&&!o.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(a,s,c,o)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||this.turnGuestGates.push(e)}stop(){Vk(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0)}idleCompactionEnabled(){return CE(this.scoop)?!0:this.unit.parentId===null&&fa(`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-B9i1duyd.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:un,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&&!fa(`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-B70raB09.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?{transcriptPath:o.transcriptPath}:void 0}async settleLiveSnapshot(e){if(!(this.unit.parentId!==null||!this.fs))try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-B70raB09.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){Kk.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):[]}getContextFill(){return qE(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=eD(this.agent,this.scoop))}async reloadSkills(){this.agent&&await nD(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?QE()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,tD(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),Vk(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){this.disposed||NE(e,this.eventSink,t)}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||jE(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=y(`scoop-lifecycle-manager`);var Jk=class{deps;units=new Map;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 vE(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=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))??A(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Dn(t.values(),e)??A(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 _r))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(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=Zn(t).policy.filesystem;if(a.kind===`restricted`){let e=Sn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new _r(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:xn(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 qk(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);n.attachContext(l,i),await l.init(),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=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.getContext(e);o||=(await this.createTab(e),this.getContext(e));let s=this.units.get(e);if(s?.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}o=this.getContext(e)}if(!o||!s){Q.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s.tab&&s.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 o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();if(Un(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=Nn(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&&eE(`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}}inheritModel(e){if(An(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Vn(t):void 0)??GT();n&&Mn(e,n)}async unregister(e){let t=this.deps.getScoops();for(let n of Kn(t.values(),e))await this.unregister(n.jid);let n=t.get(e);if(n&&n.parentJid===null&&A(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.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([n?this.deps.getConversationStore()?.delete(yr(n)):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 a=this.deps.approvalRouter.failScoop(e);if(a>0&&Q.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),Q.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){Q.warn(`onScoopUnregistered callback threw`,{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;let r=n.model;Mn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Mn(n,r),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!0}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;zn(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}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Zn(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:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),eE(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},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 On(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:nr(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,wn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(wn(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}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}),eE(`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`),Zn(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(!i)return;let a={id:`scoop-error-${e}-${Date.now()}`,chatJid:i.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(i.jid,a)}catch(e){Q.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{Q.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const $=y(`scoop-message-router`);var Yk=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=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}`);eE(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp: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=sb(lb(ob(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=S_(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(`
|
|
1173
|
+
`);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>C_(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=sb(lb(ob(a),o));this.lastAgentTimestamp.set(e,f),await this.deps.db.setState(`lastAgentTs_${e}`,f);let p=s.some(e=>e.steer),m=new Set,h=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);m.has(t)||(m.add(t),h.push(e.guestGate))}await this.deps.sendPrompt(e,l,d.senderId,d.senderName,u,{steer:p,...h.length>0?{guestGates:h}:{}})}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),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 Xk=y(`orchestrator`),Zk={decision:`deny`};var Qk=class{scoops=new Map;workUnits=new Oy(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new uT({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new hE({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 pE({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new sE({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 YT({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=>ib(e),saveMessage:e=>nb(e)});lickRegistry=new VT({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 Yk({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)=>this.callbacks.onError(e,t),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>nb(e),deleteMessage:e=>rb(e),clearMessagesForScoop:e=>tb(e),clearAllMessages:()=>eb(),getMessagesSince:(e,t,n)=>ub(e,t,n),setState:(e,t)=>gb(e,t)},isExternalLickChannel:ly});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Jk({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,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>Zy(e),deleteScoop:e=>$y(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>IT(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)},handleMessage:e=>this.handleMessage(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 KT(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new bx({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 fx(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new WT(e,t),await this.modelPolicyFile.init(),n(),Qy()),n,{stagePrefix:`orchestrator-init`})}async init(e){await _b(),this.sharedFs=await KT(e=>gr.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new E_,this.conversationStore=new NC,this.fsWatcher=new hr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher;let t=await this.initPolicyLayerAndLoadRecords(this.sharedFs,this.fsWatcher,e),n=Object.values(t).find(e=>Rn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Un(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await hb(`lastAgentTs_${e.jid}`);r&&this.messageRouter.setLastAgentTimestamp(e.jid,r)}await this.backfillModels(),await this.migrateConversations(e),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new JT({onTaskRun:async(e,t)=>{Xk.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(),Xk.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let t of this.scoops.values())try{await this.createScoopTab(t.jid)}catch(e){let n=e instanceof Error?e.message:String(e);Xk.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}Er(e=>this.getSessionCostsForCommand(e)),Dr(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>O_);return e()}),this.unregisterExportService=o(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Zv;try{await gC({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){Xk.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(br(r),t).catch(t=>{Xk.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=Rn(e)?null:t??null;try{await Zy(e)}catch(t){Xk.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=>!An(e));if(e.length===0)return;let t=GT(),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?Vn(n):void 0)??t;if(r){Mn(e,r);try{await Zy(e)}catch(t){Xk.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}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=`${Qn.root}/`,r=$n(tr(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: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)}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-D1lGElvD.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:nr,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(Xk.warn(`Guest approval before SudoManager init — failing closed`),Zk)}})}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 Zy(e)}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 A(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 Wn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Dn(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(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await gr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await aT(this.sharedFs).catch(e=>{Xk.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new bx({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 fx(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new WT(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),Xk.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 ib(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await Promise.resolve().then(()=>Xx),r=await n(this.sharedFs);return[...t,...r.map(Or)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&Xk.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),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,Xk.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new kC(this.conversationStore):null,t=this.sharedFs;return new NS({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:QS(),snapshotStore:{read:e=>WS(t,e),write:(e,n)=>US(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.166.0`})}};const $k=y(`workflow-run-manager`),eA=`/shared/workflow-runs`,tA=1e3;function nA(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function rA(e){let t=new Map,n=new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){$k.warn(`observeRun handler threw`,e)}},i=(e,n)=>cA(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=nA(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:new Date().toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(c,d),oA(t,n);let f=i(a.ctx,c),p=sA(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=>$k.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=`${eA}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(eA,{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);$k.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`?aA(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: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=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){$k.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function iA(e){let t=rA(e);return globalThis[p]=t,$k.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function aA(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function oA(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 sA(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 cA(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?lA(n,t,a?.args??[],r):e===`agent`?uA(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function lA(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>tA&&i.logs.splice(0,i.logs.length-tA),r()}return{stdout:``,stderr:``,exitCode:0}}async function uA(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 dA=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function fA(e,t,n){let r=pA(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=gA(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function pA(e){let t=new Map;return mA(t,e.discoveryOrigin),mA(t,e.discoveryUrl),[...t.values()]}function mA(e,t){if(t){hA(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);hA(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!dA.has(e)))hA(e,t,1,`substring`)}catch{}}}function hA(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 gA(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=vA(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)_A(a,e)&&(r+=e.weight*o)}return r}function _A(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 vA(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var yA=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=SA(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:xA,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===xA)throw new j(`ENOTDIR`,`not a directory`,e);let n=CA(t[0]);if(n===null||!this.pidExists(n))throw new j(`ENOENT`,`no such file or directory`,e);return bA.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new j(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=SA(e);if(t.length===1&&t[0]===xA)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new j(`EISDIR`,`is a directory`,e);let n=CA(t[0]);if(n===null||!this.pidExists(n))throw new j(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!bA.includes(r))throw new j(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new j(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=SA(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===xA)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=CA(t[0]);if(n===null||!this.pidExists(n))throw new j(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=CA(t[0]);if(n===null||!this.pidExists(n))throw new j(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!bA.includes(r))throw new j(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new j(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new j(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new j(`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 j(`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:OA(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:kA(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
1174
1174
|
`}renderProcFile(e,t){if(e===1)return AA(t);let n=this.pm.get(e);switch(t){case`status`:return wA(n);case`cmdline`:return TA(n);case`cwd`:return EA(n);case`stat`:return DA(n)}}};const bA=[`status`,`cmdline`,`cwd`,`stat`],xA=`table`;function SA(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function CA(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function wA(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${OA(e.status)} (${e.status})`,`Owner:\t${kA(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(`
|
|
1175
1175
|
`)+`
|
|
1176
1176
|
`}function TA(e){return e.argv.join(`\0`)+`\0`}function EA(e){return e.cwd+`
|
|
@@ -1179,7 +1179,7 @@ Created: ${new Date().toISOString()}
|
|
|
1179
1179
|
`)+`
|
|
1180
1180
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
1181
1181
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
1182
|
-
`}}const jA=Math.max(hi,di)+5e3;function MA(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(li(e.nonce)),r=e=>n.postMessage(e),i=new Map,a=e=>{let t=e.data;if(t?.type!==`sync-fs-req`||typeof t.id!=`string`)return;let n=t;if(!fi(n.token))return;let a=i.get(n.id);if(a){r({type:mi,id:n.id}),a.result&&r({type:si,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:mi,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),jA),r({type:si,id:n.id,...e})};(ui(n)?pi(n):ci(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 NA(){return globalThis}function PA(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`mount-recovery`;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 FA(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 IA(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}LA(e,t)}async function LA(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=A(r),a=e.type===`discovery`&&!e.targetScoop?fA(e,i.filter(
|
|
1183
|
-
`,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 UA(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-D4FyZHWP.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-CsCDQ3wI.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 WA(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 tx(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:new Date().toISOString(),body:n})},{...GA(t),isOwnTab:$b(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function GA(e){let t=Ce();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp: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(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(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:()=>nx()}}async function KA(e,t,n,r,i,a){e&&(await JA(e,n,r),i(`mounts-restored`),await qA(e,t,n,r,a),i(`jshd-restored`))}async function qA(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-PqiSHlx3.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 JA(e,t,n){try{let{getAllMountEntries:r,removeMountEntry:i}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:a}=await Promise.resolve().then(()=>ty),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-rytW5wPV.js`),l=await s(e,n),u=await r(),d=c(u,l);for(let e of o(u,l))i(e.targetPath).catch(t=>{n.warn(`failed to purge host-owned mount row`,{path:e.targetPath,error:t instanceof Error?t.message:String(t)})});if(d.length===0)return;let{needsRecovery:f}=await a(d,e,n);if(f.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:f}})}catch(e){n.warn(`mount recovery failed`,e)}}function YA(){wr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-DCwNWWGX.js`);return e()})}function XA(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-DCwNWWGX.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp: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 ZA(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DBtF-C4h.js`),{ScriptCatalog:r}=await import(`./script-catalog-CgT8L-OG.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 QA(e){return e===`node-rest`}function $A(e,t,n,r){import(`./gelatiere-unit-BlRXo_Ch.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!fa(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-ijXRupBc.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function ej(e,t){if(!e)return()=>{};import(`./memory-curation-seam-ZGh8tSbe.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return fa(`memory-v2`)&&import(`./memory-health-CZHaK5wO.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 tj(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}Rv(e,t,e.getSessionStore())}async function nj(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);YA();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await RA(t,n,r,i,e);if(s(`orchestrator-ready`),tj(l,f,o),f)try{await f.mountInternal(`/proc`,new yA(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await zA(l,e,o);s(`lick-manager-ready`),f&&VA({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),NA().__slicc_lickManager=m,$A(l,m,f,o);let h=ej(f,o),{wsBridge:g,wsRegistry:_}=await HA({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});NA().__slicc_wsSubscribers=_;let ee=QA(p.adapter)?await UA(m,o,e.localLickWsUrl??null,f):null,te=WA(n,m,o,e.appPageUrl);await KA(f,c,m,o,s,l),a||await BA(l),s(`cone-bootstrapped`),f&&XA(m,o);let v=null,ne=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:ne}=await ZA(f,n,o));let y=null;f&&e.syncFsChannelNonce&&(y=MA({nonce:e.syncFsChannelNonce}).dispose);let re=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){re||(re=!0,await rj({unsubLeader:u,unsubFollower:d,bshWatchdogStop:v,memoryHealthStop:h,scriptCatalogDispose:ne,lickWsBridgeStop:ee,navigationWatcherStop:te,syncFsResponderDispose:y,sharedFs:f,wsRegistry:_,wsBridge:g,processManager:c,lickManager:m,browser:n,log:o}))}}}async function rj(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)}ij({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function ij(e){let t=NA();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,ni(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[p]}const aj=`x-bypass-llm-proxy`;function oj(e,t,n){return t?(r,i)=>{if(!sj(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(aj)||a.set(aj,`1`),e(r,{...i,headers:a})}:e}function sj(e,t,n){if(lj(e,t))return!0;let r=n?.()??null;return r?cj(e,r,t):!1}function cj(e,t,n){let r=uj(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 lj(e,t){let n=uj(e);try{return new URL(n,t).origin===t}catch{return!0}}function uj(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function dj(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}}}var fj=class{transport;createShell;log;pm;defaultOwner;sessions=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(!pj(e)||e.source!==`panel`)return;let t=e.payload;hj(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`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),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.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=gi(le(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)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?mj(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,mj(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 pj(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function mj(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function hj(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 gj=class extends _{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)}}};function _j(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new fj({transport:t,processManager:i,createShell:(a,o)=>new gj(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Sr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function vj(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function yj(e){if(typeof e!=`string`||!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function bj(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}function xj(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`quota_exceeded`)}function Sj(e){return vj(e)||yj(e)||bj(e)||xj(e)}function Cj(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return Ej(e);if(typeof e==`object`)return Dj(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function wj(e){if(typeof e==`object`&&e&&!(e instanceof Error))return kj(e)??Aj(e);let t=Cj(e);if(t!==void 0)return Tj(t)}function Tj(e){let t=e.trim();if(!t)return e;let n=Oj(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=Oj(t.slice(r,i+1));if(e)return e}return e}function Ej(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function Dj(e){let t=kj(e),n=Aj(e);return n&&t?`${n}: ${t}`:t??n}function Oj(e){if(e.startsWith(`{`))try{return kj(JSON.parse(e))}catch{return}}function kj(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 Aj(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 jj=null,Mj=!1;function Nj(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function Pj(e){return Nj()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function Fj(e={}){if(!Mj&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){h(Ij),$T(Rj),TE(Lj);try{let t=Pj(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(jj=(await import(`./rum-worker-CwmNSpjO.js`)).default,Vj(self)):t===`extension`?(jj=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&Vj(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),Jj(),Uj(),jj=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),Mj=!0,jj&&jj(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function Ij(e){jj?.(`fill`,{source:e})}function Lj(e,t){let n=Bj(t);n!==null&&jj?.(`error`,{source:e,target:n})}function Rj(e,t,n){if(e===`error`){let e=Bj(n);if(e===null)return;jj?.(`error`,{source:`scoop:${t}`,target:e});return}jj?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function zj(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function Bj(e){let t=Cj(e);if(t===void 0)return e==null?void 0:null;if(Sj(t))return null;let n=wj(e)??Tj(t);return Sj(n)?null:Wj(n)}function Vj(e){e.addEventListener(`error`,e=>{let t=e;Lj(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{Lj(`js`,e.reason)})}function Hj(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function Uj(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;Hj(t)&&(Lj(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;Hj(t)&&(Lj(`js`,t),e.stopImmediatePropagation())},!0))}function Wj(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
1182
|
+
`}}const jA=Math.max(hi,di)+5e3;function MA(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(li(e.nonce)),r=e=>n.postMessage(e),i=new Map,a=e=>{let t=e.data;if(t?.type!==`sync-fs-req`||typeof t.id!=`string`)return;let n=t;if(!fi(n.token))return;let a=i.get(n.id);if(a){r({type:mi,id:n.id}),a.result&&r({type:si,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:mi,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),jA),r({type:si,id:n.id,...e})};(ui(n)?pi(n):ci(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 NA(){return globalThis}function PA(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`mount-recovery`;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 FA(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 IA(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}LA(e,t)}async function LA(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=A(r),a=e.type===`discovery`&&!e.targetScoop?fA(e,i.filter(lx),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`&&!lx(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-CZGM2OFA.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=wy(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=PA(e),l=FA(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 RA(e,t,n,r,i){let a=new oi,o=new Qk(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=cn(),c=i.capabilityBroker??l(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),ur(c),NA().__slicc_pm=a,ni(ri()),NA().__slicc_browser=t,await n.bind(o,t);let u=Cr(()=>n.emitTrayRuntimeStatus()),d=ee(()=>n.emitTrayRuntimeStatus());return await o.init(i.onBootProgress),await n.hydrateBuffersFromRecords(),{processManager:a,orchestrator:o,unsubLeader:u,unsubFollower:d,sharedFs:o.getSharedFS(),capabilityBroker:c}}async function zA(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-BULzLcvz.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await Promise.resolve().then(()=>O_);r(()=>a());let{getLickManager:o}=await Promise.resolve().then(()=>kT),s=o();await s.init(),e.setLickManager(s);let c=t.lickEventHandler??IA,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function BA(e){let t=e.getScoops();A(t).length>0||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,parentJid:null,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function VA(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:a}=e;iA({sharedFs:a,getStartingRoot:e=>{let n=A(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=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>ii(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>u().slice(10,22),splitResult:(e,t)=>i(e,t)})}async function HA(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-DsbAqoSN.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-CKHqIv8e.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: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))+`
|
|
1183
|
+
`,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 UA(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-ChigxI36.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-CsCDQ3wI.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 WA(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 ex(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:new Date().toISOString(),body:n})},{...GA(t),isOwnTab:Qb(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function GA(e){let t=Ce();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp: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(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(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:()=>tx()}}async function KA(e,t,n,r,i,a){e&&(await JA(e,n,r),i(`mounts-restored`),await qA(e,t,n,r,a),i(`jshd-restored`))}async function qA(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-DOkDX8BI.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 JA(e,t,n){try{let{getAllMountEntries:r,removeMountEntry:i}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:a}=await Promise.resolve().then(()=>ey),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-rytW5wPV.js`),l=await s(e,n),u=await r(),d=c(u,l);for(let e of o(u,l))i(e.targetPath).catch(t=>{n.warn(`failed to purge host-owned mount row`,{path:e.targetPath,error:t instanceof Error?t.message:String(t)})});if(d.length===0)return;let{needsRecovery:f}=await a(d,e,n);if(f.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:f}})}catch(e){n.warn(`mount recovery failed`,e)}}function YA(){wr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-B5ym__Gu.js`);return e()})}function XA(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-B5ym__Gu.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp: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 ZA(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DBtF-C4h.js`),{ScriptCatalog:r}=await import(`./script-catalog-CgT8L-OG.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 QA(e){return e===`node-rest`}function $A(e,t,n,r){import(`./gelatiere-unit-wvDEO7gH.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!fa(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-C2u47uk0.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function ej(e,t){if(!e)return()=>{};import(`./memory-curation-seam-DUaZFZG9.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return fa(`memory-v2`)&&import(`./memory-health-D7uEvfAx.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 tj(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}Lv(e,t,e.getSessionStore())}async function nj(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);YA();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await RA(t,n,r,i,e);if(s(`orchestrator-ready`),tj(l,f,o),f)try{await f.mountInternal(`/proc`,new yA(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await zA(l,e,o);s(`lick-manager-ready`),f&&VA({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),NA().__slicc_lickManager=m,$A(l,m,f,o);let h=ej(f,o),{wsBridge:g,wsRegistry:_}=await HA({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});NA().__slicc_wsSubscribers=_;let ee=QA(p.adapter)?await UA(m,o,e.localLickWsUrl??null,f):null,te=WA(n,m,o,e.appPageUrl);await KA(f,c,m,o,s,l),a||await BA(l),s(`cone-bootstrapped`),f&&XA(m,o);let v=null,ne=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:ne}=await ZA(f,n,o));let y=null;f&&e.syncFsChannelNonce&&(y=MA({nonce:e.syncFsChannelNonce}).dispose);let re=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){re||(re=!0,await rj({unsubLeader:u,unsubFollower:d,bshWatchdogStop:v,memoryHealthStop:h,scriptCatalogDispose:ne,lickWsBridgeStop:ee,navigationWatcherStop:te,syncFsResponderDispose:y,sharedFs:f,wsRegistry:_,wsBridge:g,processManager:c,lickManager:m,browser:n,log:o}))}}}async function rj(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)}ij({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function ij(e){let t=NA();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,ni(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[p]}const aj=`x-bypass-llm-proxy`;function oj(e,t,n){return t?(r,i)=>{if(!sj(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(aj)||a.set(aj,`1`),e(r,{...i,headers:a})}:e}function sj(e,t,n){if(lj(e,t))return!0;let r=n?.()??null;return r?cj(e,r,t):!1}function cj(e,t,n){let r=uj(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 lj(e,t){let n=uj(e);try{return new URL(n,t).origin===t}catch{return!0}}function uj(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function dj(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}}}var fj=class{transport;createShell;log;pm;defaultOwner;sessions=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(!pj(e)||e.source!==`panel`)return;let t=e.payload;hj(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`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),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.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=gi(le(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)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?mj(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,mj(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 pj(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function mj(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function hj(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 gj=class extends _{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)}}};function _j(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new fj({transport:t,processManager:i,createShell:(a,o)=>new gj(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Sr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function vj(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function yj(e){if(typeof e!=`string`||!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function bj(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}function xj(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`quota_exceeded`)}function Sj(e){return vj(e)||yj(e)||bj(e)||xj(e)}function Cj(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return Ej(e);if(typeof e==`object`)return Dj(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function wj(e){if(typeof e==`object`&&e&&!(e instanceof Error))return kj(e)??Aj(e);let t=Cj(e);if(t!==void 0)return Tj(t)}function Tj(e){let t=e.trim();if(!t)return e;let n=Oj(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=Oj(t.slice(r,i+1));if(e)return e}return e}function Ej(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function Dj(e){let t=kj(e),n=Aj(e);return n&&t?`${n}: ${t}`:t??n}function Oj(e){if(e.startsWith(`{`))try{return kj(JSON.parse(e))}catch{return}}function kj(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 Aj(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 jj=null,Mj=!1;function Nj(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function Pj(e){return Nj()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function Fj(e={}){if(!Mj&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){h(Ij),$T(Rj),TE(Lj);try{let t=Pj(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(jj=(await import(`./rum-worker-CwmNSpjO.js`)).default,Vj(self)):t===`extension`?(jj=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&Vj(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),Jj(),Uj(),jj=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),Mj=!0,jj&&jj(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function Ij(e){jj?.(`fill`,{source:e})}function Lj(e,t){let n=Bj(t);n!==null&&jj?.(`error`,{source:e,target:n})}function Rj(e,t,n){if(e===`error`){let e=Bj(n);if(e===null)return;jj?.(`error`,{source:`scoop:${t}`,target:e});return}jj?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function zj(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function Bj(e){let t=Cj(e);if(t===void 0)return e==null?void 0:null;if(Sj(t))return null;let n=wj(e)??Tj(t);return Sj(n)?null:Wj(n)}function Vj(e){e.addEventListener(`error`,e=>{let t=e;Lj(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{Lj(`js`,e.reason)})}function Hj(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function Uj(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;Hj(t)&&(Lj(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;Hj(t)&&(Lj(`js`,t),e.stopImmediatePropagation())},!0))}function Wj(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
1184
1184
|
`).filter(e=>!zj(e)).join(`
|
|
1185
|
-
`).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 Gj=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function Kj(e){let t=typeof e==`string`?e:wj(e)??Cj(e);if(typeof t!=`string`)return{kind:`absent`};let n=Tj(t);if(n===`[object Object]`)return{kind:`noise`};let r=Wj(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function qj(e){let t=Kj(e.source),n=Kj(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 Jj(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[Gj])return;let t=e.bind(navigator),n=((e,n)=>{try{let r=typeof n==`string`?n:n instanceof ArrayBuffer?new TextDecoder().decode(n):null;if(r&&r.length>0&&r.charCodeAt(0)===123){let n=JSON.parse(r);if(n?.checkpoint===`error`){let r=qj(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[Gj]=!0,navigator.sendBeacon=n}function Yj(e){let t=new Xj(e);return t.start(),{stop:()=>t.dispose()}}var Xj=class{transport;client;writableClient;getWatcher;log;unsubscribe=null;watches=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(!Zj(e)||e.source!==`panel`)return;let t=e.payload;if(Qj(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if($j(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(eM(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 j(`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 j(`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 j(`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(tM(e.type),e.requestId,new j(`EACCES`,`vfs-rpc-host has no writable backend wired`),nM(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 j(`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 j(`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 j(`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=rM(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=rM(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 Zj(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Qj(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 $j(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 eM(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function tM(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 nM(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function rM(e,t){return e instanceof j?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function iM(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=oj(e.bind(globalThis),t,aM)}function aM(){let e=Oe();if(!e)return null;try{return new URL(e).origin}catch{return null}}function oM(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 sM=null,cM=null,lM=null,uM=null,dM=null;const fM=dj(e=>hM(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&fM.handle(e.data)});function pM(e){let t=Ma(e.pageBuildId,`6.165.0-mu61e2g3`);return()=>{t&&Lj(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.165.0-mu61e2g3`)}}function mM(e){iM(),Ne(e.localApiBaseUrl??null),je(e.bridgeToken??null),ti(e.syncFsBridgeEnabled??!1),te(e.pageLoadedAt??null),ke(e.extensionDelegateId??null),oM(e.localStorageSeed??{}),e.flagFloat&&ya(e.flagFloat)}async function hM(e){ka(e.instanceId);let t=pM(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{mM(e),Fj().then(t).catch(()=>{}),await oe(),n(`providers-registered`);let r=Va(e.kernelPort),i=new Vb(r),a=Vb.createCallbacks(i),o=new Ha(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new Zi(o);sM=await nj({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-Bur-XBNy.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=sM.sharedFs?.getWatcher();if(u){let e=null,t=new Set;for(let n of vi)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-BPwAqRch.js`).then(e=>e.i);dM=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=dM,s.setTrayTargetProvider(ea(ie));let f=await _M({host:sM,transport:r,browser:s,instanceId:e.instanceId});f&&(cM=f.stopTerminalHost,lM=f.stopVfsRpcHost,uM=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){gM(e.kernelPort,t)}}function gM(e,t){ja(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 _M(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=_j({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=Yj({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await vM(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function vM(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-B9REkBI_.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-DEK8DT-z.js`).then(e=>e.i),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(cM?.(),cM=null,lM?.(),lM=null,uM?.(),uM=null,dM?.dispose(),dM=null,sM?.dispose())});export{J_ as _,bE as a,fa as b,Qx as c,eS as d,gb as f,kv as g,gv as h,SE as i,$x as l,Ey as m,yE as n,CE as o,_b as p,xE as r,Kw as s,dO as t,tS as u,F_ as v,x_ as y};
|
|
1185
|
+
`).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 Gj=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function Kj(e){let t=typeof e==`string`?e:wj(e)??Cj(e);if(typeof t!=`string`)return{kind:`absent`};let n=Tj(t);if(n===`[object Object]`)return{kind:`noise`};let r=Wj(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function qj(e){let t=Kj(e.source),n=Kj(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 Jj(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[Gj])return;let t=e.bind(navigator),n=((e,n)=>{try{let r=typeof n==`string`?n:n instanceof ArrayBuffer?new TextDecoder().decode(n):null;if(r&&r.length>0&&r.charCodeAt(0)===123){let n=JSON.parse(r);if(n?.checkpoint===`error`){let r=qj(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[Gj]=!0,navigator.sendBeacon=n}function Yj(e){let t=new Xj(e);return t.start(),{stop:()=>t.dispose()}}var Xj=class{transport;client;writableClient;getWatcher;log;unsubscribe=null;watches=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(!Zj(e)||e.source!==`panel`)return;let t=e.payload;if(Qj(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if($j(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(eM(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 j(`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 j(`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 j(`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(tM(e.type),e.requestId,new j(`EACCES`,`vfs-rpc-host has no writable backend wired`),nM(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 j(`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 j(`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 j(`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=rM(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=rM(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 Zj(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Qj(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 $j(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 eM(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function tM(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 nM(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function rM(e,t){return e instanceof j?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function iM(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=oj(e.bind(globalThis),t,aM)}function aM(){let e=Oe();if(!e)return null;try{return new URL(e).origin}catch{return null}}function oM(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 sM=null,cM=null,lM=null,uM=null,dM=null,fM=null;const pM=dj(e=>gM(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&pM.handle(e.data)});function mM(e){let t=Ma(e.pageBuildId,`6.166.0-mu66s1qz`);return()=>{t&&Lj(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.166.0-mu66s1qz`)}}function hM(e){iM(),Ne(e.localApiBaseUrl??null),je(e.bridgeToken??null),ti(e.syncFsBridgeEnabled??!1),te(e.pageLoadedAt??null),ke(e.extensionDelegateId??null),oM(e.localStorageSeed??{}),e.flagFloat&&ya(e.flagFloat)}async function gM(e){ka(e.instanceId);let t=mM(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{hM(e),Fj().then(t).catch(()=>{}),await oe(),n(`providers-registered`);let r=Va(e.kernelPort),i=new Bb(r),a=Bb.createCallbacks(i),o=new Ha(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new Zi(o);sM=await nj({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-Bur-XBNy.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=sM.sharedFs?.getWatcher();if(u){let e=null,t=new Set;for(let n of vi)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-BPwAqRch.js`).then(e=>e.i);fM=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=fM,s.setTrayTargetProvider(ea(ie));let f=await vM({host:sM,transport:r,browser:s,instanceId:e.instanceId});f&&(cM=f.stopTerminalHost,lM=f.stopVfsRpcHost,uM=f.stopSpeechAssetsResponder,dM=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){_M(e.kernelPort,t)}}function _M(e,t){ja(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 vM(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=_j({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=Yj({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await yM(t,e.instanceId),{startComputersHost:o}=await import(`./host-BQ2qKD-D.js`),s=o({transport:e.transport,processManager:e.host.processManager});return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a,stopComputersHost:s.stop}}async function yM(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-BJXemBO4.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-DEK8DT-z.js`).then(e=>e.i),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(cM?.(),cM=null,lM?.(),lM=null,uM?.(),uM=null,dM?.(),dM=null,fM?.dispose(),fM=null,sM?.dispose())});export{q_ as _,bE as a,fa as b,Zx as c,$x as d,hb as f,Ov as g,hv as h,SE as i,Qx as l,Ty as m,yE as n,CE as o,gb as p,xE as r,Kw as s,dO as t,eS as u,P_ as v,b_ as y};
|