sliccy 6.203.0 → 6.203.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/ui/.vite/manifest.json +182 -182
  2. package/dist/ui/assets/__vite-browser-external-BszoxBCp.js +1 -0
  3. package/dist/ui/assets/{account-store-DV19MM14.js → account-store-Ckr93vrT.js} +1 -1
  4. package/dist/ui/assets/{account-store-DPU7N0cx.js → account-store-HGW8p_Gm.js} +1 -1
  5. package/dist/ui/assets/{adobe-JivCmBzw.js → adobe-CRoK1UUH.js} +1 -1
  6. package/dist/ui/assets/{adobe-ChzlrFtS.js → adobe-K0pawRrR.js} +1 -1
  7. package/dist/ui/assets/{agent-panels-CZRnK6r6.js → agent-panels-W_qCuU89.js} +1 -1
  8. package/dist/ui/assets/{almost-bash-shell-headless-BzuFWfJx.js → almost-bash-shell-headless-BVLelv9_.js} +32 -32
  9. package/dist/ui/assets/{apply-layout-DK1tk7At.js → apply-layout-C_MWJTEc.js} +1 -1
  10. package/dist/ui/assets/{apps-BOtYHk2V.js → apps-BV3qh1Xv.js} +1 -1
  11. package/dist/ui/assets/{azure-openai-8WyKNQDc.js → azure-openai-B2MOWr6H.js} +1 -1
  12. package/dist/ui/assets/{azure-openai-B_oKZfwW.js → azure-openai-CmzM246w.js} +1 -1
  13. package/dist/ui/assets/{backend-hostfs-CDnaze3f.js → backend-hostfs-V12rNK3N.js} +1 -1
  14. package/dist/ui/assets/{cdp-TKwtUN29.js → cdp-kHYwsfXY.js} +2 -2
  15. package/dist/ui/assets/{cerebras-Bg9sQEa5.js → cerebras-BnSGOZlZ.js} +1 -1
  16. package/dist/ui/assets/{cerebras-BOCP9MIX.js → cerebras-DdQTNaja.js} +1 -1
  17. package/dist/ui/assets/{composer-speech-DC_sSdYk.js → composer-speech-CParoFER.js} +1 -1
  18. package/dist/ui/assets/{connect-surface-C2tAdJO4.js → connect-surface-B6gwuFE5.js} +1 -1
  19. package/dist/ui/assets/{directed-approval-Cr-jwHvt.js → directed-approval-CpLPsRpu.js} +1 -1
  20. package/dist/ui/assets/{emscripten-vfs-hook-D_oRGXFa.js → emscripten-vfs-hook-Boll1SdT.js} +1 -1
  21. package/dist/ui/assets/{ensure-speech-assets-Le3eCseO.js → ensure-speech-assets-SWXzZ--z.js} +1 -1
  22. package/dist/ui/assets/{frozen-archive-writer-VpFKTRLh.js → frozen-archive-writer-BitG_c4T.js} +1 -1
  23. package/dist/ui/assets/fs-BCsH_3rY.js +2 -0
  24. package/dist/ui/assets/{fs-DnxVqG8S.js → fs-CFKrLJHf.js} +1 -1
  25. package/dist/ui/assets/{gelatiere-store-Dd2SBj-h.js → gelatiere-store-hsjqGmGi.js} +1 -1
  26. package/dist/ui/assets/{gelatiere-unit-i3KpBjAC.js → gelatiere-unit-DraZBew5.js} +1 -1
  27. package/dist/ui/assets/{github-C49eau1p.js → github-CzbB9Uah.js} +2 -2
  28. package/dist/ui/assets/{github-ChsDm6km.js → github-DFa3iFAX.js} +1 -1
  29. package/dist/ui/assets/{github-auth-NOsjs7VX.js → github-auth-DrnKzxZZ.js} +1 -1
  30. package/dist/ui/assets/{github-copilot-DygCcItL.js → github-copilot-CBVnHsdQ.js} +1 -1
  31. package/dist/ui/assets/{github-copilot-InUVaY7X.js → github-copilot-DcTdFt3i.js} +1 -1
  32. package/dist/ui/assets/{github-install-W2R2vdBh.js → github-install-Cd6syyBf.js} +1 -1
  33. package/dist/ui/assets/{github-zip-IVtBM0DQ.js → github-zip-DskcBoh2.js} +1 -1
  34. package/dist/ui/assets/{hear-DoR-Mb8I.js → hear-Dux4OsjD.js} +1 -1
  35. package/dist/ui/assets/{help-Dsyq5Nog.js → help-CnERc5T1.js} +1 -1
  36. package/dist/ui/assets/{installer-XF1rrBlO.js → installer-B3nVVS6-.js} +1 -1
  37. package/dist/ui/assets/{ipk-mamba-VkehwtJJ.js → ipk-mamba-mVsAKL21.js} +1 -1
  38. package/dist/ui/assets/{js-realm-worker-BCxOM4nf.js → js-realm-worker-DBmEtv0k.js} +2 -2
  39. package/dist/ui/assets/{jsh-executor-CwG2QLdu.js → jsh-executor-DUDUxBvJ.js} +2 -2
  40. package/dist/ui/assets/{kernel-worker-B-z88l5w.js → kernel-worker-CN69rnZG.js} +11 -11
  41. package/dist/ui/assets/{lick-ws-bridge-CnZAffru.js → lick-ws-bridge-B0InMC8Z.js} +1 -1
  42. package/dist/ui/assets/{lick-ws-bridge-Dr8ndBaj.js → lick-ws-bridge-Da39Smyv.js} +1 -1
  43. package/dist/ui/assets/{live-session-curation-EtIGz3m_.js → live-session-curation-BIqIx0m8.js} +1 -1
  44. package/dist/ui/assets/{live-session-snapshot-Chxvnh3i.js → live-session-snapshot-BpL-0LSc.js} +1 -1
  45. package/dist/ui/assets/{local-llm-DP9jY8ei.js → local-llm-COFRXxVN.js} +1 -1
  46. package/dist/ui/assets/{local-llm-IPiYDH2F.js → local-llm-DMpJ2CEo.js} +1 -1
  47. package/dist/ui/assets/{main-CCtTYJED.js → main-CdbPSBe0.js} +3 -3
  48. package/dist/ui/assets/{main-cherry-CP8J7wCy.js → main-cherry-BZNKBS64.js} +1 -1
  49. package/dist/ui/assets/{memory-curation-seam-Babzek1S.js → memory-curation-seam-BZfTB-xj.js} +1 -1
  50. package/dist/ui/assets/{memory-health-detJjF2Z.js → memory-health-CV6Pih7i.js} +1 -1
  51. package/dist/ui/assets/{memory-write-execute-DaTYSj3P.js → memory-write-execute-BnZvvvjC.js} +1 -1
  52. package/dist/ui/assets/{merge-folded-cost-into-frozen-COnnhDR_.js → merge-folded-cost-into-frozen-t3zkafLQ.js} +1 -1
  53. package/dist/ui/assets/{mount-DfD8gFP5.js → mount-CMErehEU.js} +1 -1
  54. package/dist/ui/assets/{mount-QjQDkMSN.js → mount-eRgWkp5k.js} +3 -3
  55. package/dist/ui/assets/{new-session-UC6BDORV.js → new-session-CkcYKzZr.js} +2 -2
  56. package/dist/ui/assets/{oauth-bootstrap-WrECDaLR.js → oauth-bootstrap-DpPklXi6.js} +2 -2
  57. package/dist/ui/assets/{onboarding-orchestrator-CkW7uge6.js → onboarding-orchestrator-gPmTutJo.js} +1 -1
  58. package/dist/ui/assets/{openai-codex-DPJ_vCCM.js → openai-codex-B8v50Svz.js} +1 -1
  59. package/dist/ui/assets/{openai-codex-wwvKPu2w.js → openai-codex-DlDGna5_.js} +1 -1
  60. package/dist/ui/assets/{openrouter-DlaUjjFd.js → openrouter-1xtwqOVq.js} +1 -1
  61. package/dist/ui/assets/{openrouter-BrVi5wZp.js → openrouter-ZhMTg6zr.js} +1 -1
  62. package/dist/ui/assets/{openrouter-free-BjAX0noS.js → openrouter-free-CFARCQwv.js} +1 -1
  63. package/dist/ui/assets/{openrouter-free-DlmWYxx3.js → openrouter-free-PzLhalnD.js} +1 -1
  64. package/dist/ui/assets/{openrouter-oauth-CotObMHL.js → openrouter-oauth-CEMbIAX7.js} +1 -1
  65. package/dist/ui/assets/{openrouter-oauth-DEVAARXc.js → openrouter-oauth-CXVleGE4.js} +1 -1
  66. package/dist/ui/assets/{opfs-mount-DbDiMdyl.js → opfs-mount-Bsf3IU0V.js} +1 -1
  67. package/dist/ui/assets/{opfs-mount-C81BQ3Hp.js → opfs-mount-DBwFhBGQ.js} +1 -1
  68. package/dist/ui/assets/{panel-rpc-handlers-BDpfMaFf.js → panel-rpc-handlers-CssTGsvn.js} +2 -2
  69. package/dist/ui/assets/{panelize-shell-CWND8C1O.js → panelize-shell-DVLilBxh.js} +1 -1
  70. package/dist/ui/assets/{pi-edit-execution-DhrrHmSn.js → pi-edit-execution-uvLIX_Ai.js} +1 -1
  71. package/dist/ui/assets/{provider-BHN9xujO.js → provider-CP_LJwJs.js} +2 -2
  72. package/dist/ui/assets/{provider-BInQoZGg.js → provider-DkVl86ly.js} +1 -1
  73. package/dist/ui/assets/{provider-settings-Bu5gz-LR.js → provider-settings-BWMrYTQz.js} +1 -1
  74. package/dist/ui/assets/provider-store-access-DBKNTOVo.js +1 -0
  75. package/dist/ui/assets/provider-store-access-Udi8-SSj.js +1 -0
  76. package/dist/ui/assets/{providers-CxLVqA65.js → providers-CQMZ7t66.js} +2 -2
  77. package/dist/ui/assets/{providers-CVGcOz8C.js → providers-Cf5Htw-U.js} +1 -1
  78. package/dist/ui/assets/{py-realm-worker-Dgg8SPbo.js → py-realm-worker-C_x15yIv.js} +1 -1
  79. package/dist/ui/assets/{pyodide-k1_ckjLA.js → pyodide-DxpNJIMx.js} +2 -2
  80. package/dist/ui/assets/{quick-llm-BJ58ea-a.js → quick-llm-DE2GvAnN.js} +1 -1
  81. package/dist/ui/assets/{realm-inprocess-EJM3lmZg.js → realm-inprocess-D83UW9d-.js} +2 -2
  82. package/dist/ui/assets/{realm-unhandled-rejections-Bhogzq6N.js → realm-unhandled-rejections-DCmYgbjn.js} +1 -1
  83. package/dist/ui/assets/{realm-unhandled-rejections-s-PhYuPd.js → realm-unhandled-rejections-p38FMl-T.js} +1 -1
  84. package/dist/ui/assets/{recovery-screen-DGf55I4c.js → recovery-screen-DtBhGrl5.js} +1 -1
  85. package/dist/ui/assets/{remote-terminal-view-Bp3lGbMV.js → remote-terminal-view-D1BNHazg.js} +2 -2
  86. package/dist/ui/assets/{require-guards-DQMXEhBm.js → require-guards-BWQHXQHI.js} +1 -1
  87. package/dist/ui/assets/{restore-D4J7Iipz.js → restore-D9IIoDiA.js} +1 -1
  88. package/dist/ui/assets/{run-WAB2mNcP.js → run-BB0XJv3f.js} +2 -2
  89. package/dist/ui/assets/{run-DIbAFNVF.js → run-BJNulD7A.js} +2 -2
  90. package/dist/ui/assets/{run-4894R-6V.js → run-Bqnf1Cdy.js} +1 -1
  91. package/dist/ui/assets/{run-CwCKQG5L.js → run-DAAHi5vP.js} +1 -1
  92. package/dist/ui/assets/{run-H7FpUL-C.js → run-DhCM_-DZ.js} +1 -1
  93. package/dist/ui/assets/{run-CsNup5LG.js → run-SIf4I7Q6.js} +1 -1
  94. package/dist/ui/assets/{session-command-memory-B1IiJc6S.js → session-command-memory-QozWyQvx.js} +2 -2
  95. package/dist/ui/assets/{session-jsonl-C5QAPMRG.js → session-jsonl-D5PzFT5b.js} +1 -1
  96. package/dist/ui/assets/{session-jsonl-zVsVHQvd.js → session-jsonl-DRwHOGpT.js} +1 -1
  97. package/dist/ui/assets/{session-search-index-TyG0DYjv.js → session-search-index-6DhtCkCf.js} +1 -1
  98. package/dist/ui/assets/{setup-feature-flags-remote-DyrKcJQ_.js → setup-feature-flags-remote-BYu1rIF_.js} +1 -1
  99. package/dist/ui/assets/{setup-model-catalog-Df-3eMqH.js → setup-model-catalog-Dxvw_5q0.js} +1 -1
  100. package/dist/ui/assets/{sidecar-repair-BTU4PjlG.js → sidecar-repair-BpxW7B4l.js} +1 -1
  101. package/dist/ui/assets/{signed-fetch-COgfkyhb.js → signed-fetch-Qj3nRtnI.js} +1 -1
  102. package/dist/ui/assets/{silent-renew-backoff-DR_6_gkt.js → silent-renew-backoff-DsREO3j9.js} +1 -1
  103. package/dist/ui/assets/slicc-version-C6BuKZ8E.js +1 -0
  104. package/dist/ui/assets/{snapshot-BYRnZgun.js → snapshot-DnbILwky.js} +1 -1
  105. package/dist/ui/assets/{snapshot-features-DSTI8Xk-.js → snapshot-features-BCK9Imrv.js} +1 -1
  106. package/dist/ui/assets/{soundscape-DFt-r2N_.js → soundscape-B358Dt9e.js} +1 -1
  107. package/dist/ui/assets/{speak-CGCALDqP.js → speak-Bo3aKbrD.js} +1 -1
  108. package/dist/ui/assets/{sprinkle-manager-BPEzclVV.js → sprinkle-manager-7LXuXasA.js} +1 -1
  109. package/dist/ui/assets/{sprinkle-renderer-C9P4tF37.js → sprinkle-renderer-CU_JfBSq.js} +1 -1
  110. package/dist/ui/assets/{state-IyXxuFsn.js → state-rKgnMaSb.js} +1 -1
  111. package/dist/ui/assets/{store-BDCbScJg.js → store-BMTk8QVa.js} +1 -1
  112. package/dist/ui/assets/{store-BqhDES-R.js → store-DBXEQFqZ.js} +1 -1
  113. package/dist/ui/assets/{sudo-CSQogkQw.js → sudo-B-Pm_Bnj.js} +1 -1
  114. package/dist/ui/assets/supervisor-DhZJH2cL.js +1 -0
  115. package/dist/ui/assets/{sync-dialog-DyP9oa-d.js → sync-dialog-DkgkVlkn.js} +1 -1
  116. package/dist/ui/assets/{transformers-env-9Kdr8jF9.js → transformers-env-rpxnIWDG.js} +1 -1
  117. package/dist/ui/assets/{tray-leader-DPbQ9-cY.js → tray-leader-DymCPRfM.js} +1 -1
  118. package/dist/ui/assets/{tray-leave-runtime-CTKWa3jj.js → tray-leave-runtime-D01BmoyG.js} +1 -1
  119. package/dist/ui/assets/{tray-sidecar-DMBX7ZXv.js → tray-sidecar-1N4ecoU0.js} +1 -1
  120. package/dist/ui/assets/{upgrade-detection-kNZzwNpV.js → upgrade-detection-D28x8Bra.js} +1 -1
  121. package/dist/ui/assets/{upskill-lick-skip-DeQBgND8.js → upskill-lick-skip-7__195zM.js} +1 -1
  122. package/dist/ui/assets/{voice-reply-B2Ov5r4z.js → voice-reply-NjB3SSJJ.js} +1 -1
  123. package/dist/ui/assets/{wc-attach-PXx7zOo9.js → wc-attach-CWX4iYzw.js} +2 -2
  124. package/dist/ui/assets/{wc-browser-BVPmHApK.js → wc-browser-Ce7h3334.js} +1 -1
  125. package/dist/ui/assets/{wc-computers-GFq20Asc.js → wc-computers-BwKndmef.js} +1 -1
  126. package/dist/ui/assets/{wc-detached-BFgijHFC.js → wc-detached-30u7rePq.js} +1 -1
  127. package/dist/ui/assets/{wc-extension-ClH2hzKe.js → wc-extension-CAPhtP2a.js} +2 -2
  128. package/dist/ui/assets/{wc-follower-DRjxOqlY.js → wc-follower-D5j-A7Ix.js} +3 -3
  129. package/dist/ui/assets/{wc-follower-oauth-Dv4HM0CS.js → wc-follower-oauth-qeotlWSI.js} +1 -1
  130. package/dist/ui/assets/{wc-gelatiere-BcT-4QSH.js → wc-gelatiere-4CwycDyL.js} +1 -1
  131. package/dist/ui/assets/{wc-live-CTO9I9nC.js → wc-live-mY1x8C54.js} +5 -5
  132. package/dist/ui/assets/{wc-nav-23A2dSMz.js → wc-nav-Cw9yrsaO.js} +2 -2
  133. package/dist/ui/assets/{wc-onboarding-C7IxqgPn.js → wc-onboarding-CEGW3hb5.js} +2 -2
  134. package/dist/ui/assets/{wc-permissions-CS69eQxj.js → wc-permissions-BmxmJkbj.js} +2 -2
  135. package/dist/ui/assets/{wc-placeholder-BhMoGONH.js → wc-placeholder-BJGe-e5H.js} +3 -3
  136. package/dist/ui/assets/{wc-secret-request-CS4jusXt.js → wc-secret-request-VI6gOUw8.js} +1 -1
  137. package/dist/ui/assets/{wc-settings-CieLSxcx.js → wc-settings-BpVfU7V0.js} +3 -3
  138. package/dist/ui/assets/{wc-shell-BK14Hdh_.js → wc-shell-DOXgGrMg.js} +33 -33
  139. package/dist/ui/assets/{wc-shortcut-config-B06eYu9d.js → wc-shortcut-config-DUS-IyYG.js} +1 -1
  140. package/dist/ui/assets/{wc-sprinkles-hFRbzywq.js → wc-sprinkles-hACYRDUD.js} +2 -2
  141. package/dist/ui/assets/{wc-transcript-export-DOqtuC95.js → wc-transcript-export-DUEZuxEg.js} +2 -2
  142. package/dist/ui/assets/{wc-tray-zDNVj29T.js → wc-tray-Djy3O6Pk.js} +4 -4
  143. package/dist/ui/assets/welcome-detection-DeDfFn6p.js +1 -0
  144. package/dist/ui/assets/{whisper-session-DO48ERvc.js → whisper-session-Bx2TskIV.js} +2 -2
  145. package/dist/ui/assets/{xai-grok-CqRCInHV.js → xai-grok-B_-F_tKS.js} +1 -1
  146. package/dist/ui/assets/{xai-grok-fxnzs1zt.js → xai-grok-BtkLvzBV.js} +1 -1
  147. package/dist/ui/index.html +3 -3
  148. package/dist/ui/packages/webapp/index.html +3 -3
  149. package/package.json +2 -2
  150. package/dist/ui/assets/__vite-browser-external-C8D44jj0.js +0 -1
  151. package/dist/ui/assets/fs-C5qc-0Vs.js +0 -2
  152. package/dist/ui/assets/provider-store-access-WdcwS_v-.js +0 -1
  153. package/dist/ui/assets/provider-store-access-_wxLVWcl.js +0 -1
  154. package/dist/ui/assets/slicc-version-BgdYERF-.js +0 -1
  155. package/dist/ui/assets/supervisor-Bt6KNGEa.js +0 -1
  156. package/dist/ui/assets/welcome-detection-le5-bkR_.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,c as o,f as s,g as c,h as l,i as u,m as d,o as f,p,r as m,s as h,t as ee,u as g,v as te,x as ne,y as re}from"./almost-bash-shell-headless-BzuFWfJx.js";import{t as _}from"./logger-LESFN7Hj.js";import{r as ie,t as ae}from"./base64-BPBW1Gzr.js";import{i as oe,r as se}from"./handoff-link-B3It6xQY.js";import{a as ce,b as le,f as ue,g as de,h as fe,i as pe,m as me,p as he,v as ge,x as _e,y as ve}from"./account-store-DV19MM14.js";import{n as ye}from"./proxied-fetch-DXaTHROw.js";import{t as be}from"./slugify-BYJ6QVAt.js";import{i as xe,n as Se,t as Ce}from"./archive-redaction-ByV7X5fs.js";import{i as we,r as Te}from"./host-command-guuPK7VN.js";import{o as Ee}from"./snapshot-BYRnZgun.js";import{n as De,r as Oe}from"./panel-rpc-DW7W4w6_.js";import{i as ke,l as Ae,o as je,r as Me}from"./feature-flags-QlgHaQc1.js";import{a as Ne,t as Pe}from"./providers-CVGcOz8C.js";import{c as Fe,d as Ie,o as Le,s as Re,t as ze,u as Be}from"./api-endpoint-D8lUKmPu.js";import{$ as Ve,A as He,At as Ue,B as We,C as Ge,Ct as Ke,D as qe,Dt as v,E as Je,Et as Ye,F as Xe,H as Ze,I as Qe,J as $e,K as et,L as tt,M as nt,Mt as y,N as rt,Nt as it,O as at,Ot as ot,P as st,Q as ct,R as lt,St as ut,T as dt,Tt as b,U as ft,V as pt,W as mt,X as ht,Y as gt,Z as _t,_ as vt,_t as yt,a as bt,at as x,b as xt,bt as St,c as Ct,ct as S,d as wt,dt as Tt,et as Et,f as Dt,ft as Ot,g as kt,gt as At,h as jt,ht as Mt,i as Nt,it as Pt,j as Ft,jt as It,k as Lt,kt as C,l as Rt,lt as zt,m as Bt,mt as Vt,n as Ht,nt as Ut,o as Wt,ot as Gt,p as Kt,pt as w,q as qt,r as Jt,rt as T,s as Yt,st as E,t as Xt,tt as Zt,u as Qt,ut as $t,v as en,vt as tn,w as nn,wt as D,x as rn,xt as an,y as on,yt as sn,z as cn}from"./build-BRNa03GH.js";import{a as ln}from"./models-4WTk3EBD.js";import{o as un,t as dn}from"./compat-uEPf6-XW.js";import{a as fn,r as pn,t as mn}from"./core-VO3EvqHP.js";import{i as hn,n as gn,r as _n,t as vn}from"./context-compaction-Dpr7xgBZ.js";import{t as yn}from"./secrets-bridge-client-BiJrSKN9.js";import{n as bn,t as xn}from"./image-markers-CwM1dvoI.js";import{i as Sn}from"./tool-ui-DRnUkp2g.js";import{c as Cn,t as wn}from"./claude-model-version-ceOteQ2f.js";import{a as Tn,n as En,t as Dn}from"./path-utils-DNJG-zQf.js";import{t as On}from"./merge-file-core-VJlzucJY.js";import{i as kn,n as An,r as jn,t as Mn}from"./workspace-mode-D0kUKBVS.js";import{C as Nn,D as Pn,E as O,O as Fn,S as In,T as Ln,_ as Rn,a as zn,c as Bn,d as Vn,f as Hn,g as Un,h as Wn,l as Gn,m as Kn,n as qn,o as Jn,p as Yn,r as Xn,s as Zn,t as Qn,u as $n,v as er,w as tr,y as nr}from"./record-COQlaFL1.js";import{a as rr,c as ir,d as ar,i as or,l as sr,n as cr,o as lr,r as ur,s as dr,u as fr}from"./descriptor-CKLcFFX3.js";import{n as pr,t as mr}from"./thinking-level-5x0UAu9N.js";import{t as k}from"./types-D8gIX-W-.js";import{i as hr,n as gr}from"./mount-index-CQfmUPuZ.js";import{a as _r,i as vr,n as yr,r as br,s as xr,t as Sr}from"./signed-fetch-COgfkyhb.js";import{n as Cr}from"./mount-table-store-DrF_Ifaz.js";import{t as wr}from"./remote-cache-UwMD8EkX.js";import"./mount-DfD8gFP5.js";import{i as Tr,n as Er,r as Dr}from"./fs-DnxVqG8S.js";import{i as Or,n as kr,t as Ar}from"./key-B2Bki3fU.js";import{n as jr,r as Mr,t as Nr}from"./tray-leader-status-CpkFr6n7.js";import"./tray-runtime-config-CTm013-K.js";import{r as Pr}from"./slicc-version-BgdYERF-.js";import{r as Fr}from"./virtual-device-paths-CS5o4QVz.js";import{a as Ir,i as Lr,r as Rr}from"./cost-command-D0tJNxsl.js";import{_ as zr,a as Br,c as Vr,d as Hr,f as Ur,g as Wr,h as Gr,l as Kr,m as qr,n as Jr,p as Yr,r as Xr,s as Zr,t as Qr,u as $r,v as ei}from"./sudoers-BdBYQPUn.js";import{n as ti,r as ni,t as ri}from"./sudo-fs-CGjo9awW.js";import{t as ii}from"./llm-session-id-BZyXP_j2.js";import{t as ai}from"./src-CUSndb9K.js";import{a as oi,i as si,n as ci,o as li,s as ui}from"./memory-budget-CFfevxz_.js";import{i as di}from"./browser-DuyhpHbR.js";import{t as fi}from"./jsh-discovery-CnvNKojr.js";import{t as pi}from"./process-manager-BkhAohXT.js";import{i as mi,o as hi,r as gi,t as _i}from"./jsh-executor-CwG2QLdu.js";import{C as vi,_ as yi,b as bi,f as xi,h as Si,l as Ci,n as wi,r as Ti,x as Ei}from"./sync-exec-dispatch-BwrIjhDd.js";import{n as Di}from"./just-bash-compat-B-SPHuh_.js";import{t as Oi}from"./lick-target-env-8JxfVcIV.js";const ki=[`/workspace`,`/shared`,`/scoops`,`/home`];var Ai=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 ji(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 Mi=_(`cdp`);function Ni(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 Pi=class{ws=null;nextId=1;_superseded=!1;pending=new Ai;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,Mi.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Mi.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(),Mi.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),Mi.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 ji(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;Mi.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Mi.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;Mi.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,Mi.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Mi.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Mi.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Ni(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}};function Fi(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Ii(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Li=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Ri(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Li.map(e=>zi(i,e,t,r)))).filter(e=>e!==null)}async function zi(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||!Bi(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Bi(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`)}const Vi=3e4;var Hi=class extends Error{constructor(e=`CDP bridge rejected the session token (bridge-token-required). Open SLICC again from Sliccstart to pick up a fresh token.`){super(e),this.name=`CdpBridgeRejectedError`}},Ui=class extends Error{constructor(){super(`CDP reconnect is backing off`),this.name=`CdpReconnectBackoffError`}};function Wi(e,t=Math.random){let n=Math.min(Vi,250*2**Math.min(Math.max(0,e),16)),r=Math.round(n*.2*t());return Math.min(Vi,n+r)}function Gi(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var Ki=class{lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;reconnectAttempt=0;reconnectNotBefore=0;bridgeRejection=null;bridgeRejectedHandler=null;bridgeRejectedNotified=!1;classifyConnectFailure=async()=>`transient`;primeConnectOptions(e){this.lastConnectOptions=e?{...e}:{}}setSupersededHandler(e){this.supersededHandler=e}setBridgeRejectedHandler(e){this.bridgeRejectedHandler=e}setConnectFailureClassifier(e){this.classifyConnectFailure=e}async connect(e,t){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new Hi(this.bridgeRejection);this.lastConnectOptions=t?{...t}:{};try{await e.connect({url:t?.url??Gi(),timeout:t?.timeout,...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t),this.bridgeRejection?new Hi(this.bridgeRejection):e}this.noteReconnectSuccess()}async ensureLocalConnected(e){if(e.superseded===!0){this.notifySuperseded();return}if(e.state===`disconnected`){this.throwIfReconnectPaused();let t=this.lastConnectOptions;try{await e.connect({url:t?.url??Gi(),...t?.timeout===void 0?{}:{timeout:t.timeout},...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t??void 0),this.bridgeRejection?new Hi(this.bridgeRejection):e}this.noteReconnectSuccess()}}async ensureConnected(e){if(e.client.superseded===!0){this.notifySuperseded();return}if(e.client.state===`disconnected`){this.throwIfReconnectPaused();let t=e.client;e.restoreLocalAfterRemoteDrop(),e.clearSessionsForTransport(t),e.getClient().state===`disconnected`&&await this.connect(e.getClient(),this.lastConnectOptions??void 0)}}throwIfReconnectPaused(){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new Hi(this.bridgeRejection);if(Date.now()<this.reconnectNotBefore)throw new Ui}noteReconnectSuccess(){this.reconnectAttempt=0,this.reconnectNotBefore=0,this.supersededNotified=!1}async noteReconnectFailure(e){if(await this.classifyConnectFailure({url:e?.url??``,...e?.protocols===void 0?{}:{protocols:e.protocols}})===`terminal`){this.bridgeRejection=new Hi().message,this.notifyBridgeRejected();return}let t=Wi(this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectNotBefore=Date.now()+t}notifyBridgeRejected(){if(!this.bridgeRejectedNotified){this.bridgeRejectedNotified=!0;try{this.bridgeRejectedHandler?.()}catch{}}}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}},qi=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 Ji(e,t){if(e?.aborted)throw new qi(t)}function Yi(e,t){return e?{signal:e,error:()=>new qi(t)}:void 0}function Xi(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new qi(n));return}let a=()=>{clearTimeout(o),i(new qi(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Zi(e,t,n){return t?t.aborted?Promise.reject(new qi(n)):new Promise((r,i)=>{let a=()=>i(new qi(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var Qi=class{contexts=new Map;for(e,t){let n=`${t}:${e}`,r=this.contexts.get(n);return r||(r=new Map,this.contexts.set(n,r)),r}peek(e,t){return this.contexts.get(`${t}:${e}`)}drop(e){this.contexts.delete(`main:${e}`),this.contexts.delete(`isolated:${e}`)}get size(){return this.contexts.size}};const $i=_(`har-recorder`);var ea=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)}`;Ji(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Ji(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Ji(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}`),$i.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=>{$i.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=>{$i.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 ta(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return $i.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 $i.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)),$i.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 $i.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 ta(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){$i.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return $i.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var na=class{maxSessions;onEvict;sessions=new Map;pinnedTargets=new Map;appliedSends=new Map;constructor(e=32,t){this.maxSessions=e,this.onEvict=t}get size(){return this.sessions.size}get(e){return this.sessions.get(e)}has(e){return this.sessions.has(e)}values(){return this.sessions.values()}entries(){return this.sessions.entries()}snapshot(){return[...this.sessions]}remember(e,t){this.pruneAppliedSends(),this.sessions.set(e,t),this.enforceCap(e)}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}take(e){let t=this.sessions.get(e);return t&&this.sessions.delete(e),t}delete(e){this.sessions.delete(e)}clear(){this.sessions.clear()}pin(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.enforceCap()}}isPinned(e){return this.pinnedTargets.has(e)}enforceCap(e){for(;this.sessions.size>this.maxSessions;){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&&this.onEvict?.(t,n)}}noteApplied(e){this.appliedSends.set(e,(this.appliedSends.get(e)??0)+1)}appliedCount(e){return this.appliedSends.get(e)??0}pruneAppliedSends(){if(this.appliedSends.size<=this.maxSessions*4)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)}findBySessionId(e){for(let[t,n]of this.sessions)if(n.sessionId===e)return[t,n]}findByTargetOrLocalId(e){let t=[];for(let[n,r]of this.sessions)(n===e||r.remote?.localTargetId===e)&&t.push([n,r]);return t}anyOnTransport(e){for(let t of this.sessions.values())if(t.transport===e)return!0;return!1}anyMatchingRemote(e,t){for(let n of this.sessions.values())if(n.remote?.runtimeId===e&&n.remote.localTargetId===t)return!0;return!1}};const ra=`(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,c as o,f as s,g as c,h as l,i as u,m as d,o as f,p,r as m,s as h,t as ee,u as g,v as te,x as ne,y as re}from"./almost-bash-shell-headless-BVLelv9_.js";import{t as _}from"./logger-LESFN7Hj.js";import{r as ie,t as ae}from"./base64-BPBW1Gzr.js";import{i as oe,r as se}from"./handoff-link-B3It6xQY.js";import{a as ce,b as le,f as ue,g as de,h as fe,i as pe,m as me,p as he,v as ge,x as _e,y as ve}from"./account-store-Ckr93vrT.js";import{n as ye}from"./proxied-fetch-DXaTHROw.js";import{t as be}from"./slugify-BYJ6QVAt.js";import{i as xe,n as Se,t as Ce}from"./archive-redaction-ByV7X5fs.js";import{i as we,r as Te}from"./host-command-guuPK7VN.js";import{o as Ee}from"./snapshot-DnbILwky.js";import{n as De,r as Oe}from"./panel-rpc-DW7W4w6_.js";import{i as ke,l as Ae,o as je,r as Me}from"./feature-flags-QlgHaQc1.js";import{a as Ne,t as Pe}from"./providers-Cf5Htw-U.js";import{c as Fe,d as Ie,o as Le,s as Re,t as ze,u as Be}from"./api-endpoint-D8lUKmPu.js";import{$ as Ve,A as He,At as Ue,B as We,C as Ge,Ct as Ke,D as qe,Dt as v,E as Je,Et as Ye,F as Xe,H as Ze,I as Qe,J as $e,K as et,L as tt,M as nt,Mt as y,N as rt,Nt as it,O as at,Ot as ot,P as st,Q as ct,R as lt,St as ut,T as dt,Tt as b,U as ft,V as pt,W as mt,X as ht,Y as gt,Z as _t,_ as vt,_t as yt,a as bt,at as x,b as xt,bt as St,c as Ct,ct as S,d as wt,dt as Tt,et as Et,f as Dt,ft as Ot,g as kt,gt as At,h as jt,ht as Mt,i as Nt,it as Pt,j as Ft,jt as It,k as Lt,kt as C,l as Rt,lt as zt,m as Bt,mt as Vt,n as Ht,nt as Ut,o as Wt,ot as Gt,p as Kt,pt as w,q as qt,r as Jt,rt as T,s as Yt,st as E,t as Xt,tt as Zt,u as Qt,ut as $t,v as en,vt as tn,w as nn,wt as D,x as rn,xt as an,y as on,yt as sn,z as cn}from"./build-BRNa03GH.js";import{a as ln}from"./models-4WTk3EBD.js";import{o as un,t as dn}from"./compat-uEPf6-XW.js";import{a as fn,r as pn,t as mn}from"./core-VO3EvqHP.js";import{i as hn,n as gn,r as _n,t as vn}from"./context-compaction-Dpr7xgBZ.js";import{t as yn}from"./secrets-bridge-client-BiJrSKN9.js";import{n as bn,t as xn}from"./image-markers-CwM1dvoI.js";import{i as Sn}from"./tool-ui-DRnUkp2g.js";import{c as Cn,t as wn}from"./claude-model-version-ceOteQ2f.js";import{a as Tn,n as En,t as Dn}from"./path-utils-DNJG-zQf.js";import{t as On}from"./merge-file-core-VJlzucJY.js";import{i as kn,n as An,r as jn,t as Mn}from"./workspace-mode-D0kUKBVS.js";import{C as Nn,D as Pn,E as O,O as Fn,S as In,T as Ln,_ as Rn,a as zn,c as Bn,d as Vn,f as Hn,g as Un,h as Wn,l as Gn,m as Kn,n as qn,o as Jn,p as Yn,r as Xn,s as Zn,t as Qn,u as $n,v as er,w as tr,y as nr}from"./record-COQlaFL1.js";import{a as rr,c as ir,d as ar,i as or,l as sr,n as cr,o as lr,r as ur,s as dr,u as fr}from"./descriptor-CKLcFFX3.js";import{n as pr,t as mr}from"./thinking-level-5x0UAu9N.js";import{t as k}from"./types-D8gIX-W-.js";import{i as hr,n as gr}from"./mount-index-CQfmUPuZ.js";import{a as _r,i as vr,n as yr,r as br,s as xr,t as Sr}from"./signed-fetch-Qj3nRtnI.js";import{n as Cr}from"./mount-table-store-DrF_Ifaz.js";import{t as wr}from"./remote-cache-UwMD8EkX.js";import"./mount-CMErehEU.js";import{i as Tr,n as Er,r as Dr}from"./fs-CFKrLJHf.js";import{i as Or,n as kr,t as Ar}from"./key-B2Bki3fU.js";import{n as jr,r as Mr,t as Nr}from"./tray-leader-status-CpkFr6n7.js";import"./tray-runtime-config-CTm013-K.js";import{r as Pr}from"./slicc-version-C6BuKZ8E.js";import{r as Fr}from"./virtual-device-paths-CS5o4QVz.js";import{a as Ir,i as Lr,r as Rr}from"./cost-command-D0tJNxsl.js";import{_ as zr,a as Br,c as Vr,d as Hr,f as Ur,g as Wr,h as Gr,l as Kr,m as qr,n as Jr,p as Yr,r as Xr,s as Zr,t as Qr,u as $r,v as ei}from"./sudoers-BdBYQPUn.js";import{n as ti,r as ni,t as ri}from"./sudo-fs-CGjo9awW.js";import{t as ii}from"./llm-session-id-BZyXP_j2.js";import{t as ai}from"./src-CUSndb9K.js";import{a as oi,i as si,n as ci,o as li,s as ui}from"./memory-budget-CFfevxz_.js";import{i as di}from"./browser-DuyhpHbR.js";import{t as fi}from"./jsh-discovery-CnvNKojr.js";import{t as pi}from"./process-manager-BkhAohXT.js";import{i as mi,o as hi,r as gi,t as _i}from"./jsh-executor-DUDUxBvJ.js";import{C as vi,_ as yi,b as bi,f as xi,h as Si,l as Ci,n as wi,r as Ti,x as Ei}from"./sync-exec-dispatch-BwrIjhDd.js";import{n as Di}from"./just-bash-compat-B-SPHuh_.js";import{t as Oi}from"./lick-target-env-8JxfVcIV.js";const ki=[`/workspace`,`/shared`,`/scoops`,`/home`];var Ai=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 ji(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 Mi=_(`cdp`);function Ni(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 Pi=class{ws=null;nextId=1;_superseded=!1;pending=new Ai;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,Mi.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Mi.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(),Mi.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),Mi.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 ji(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;Mi.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Mi.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;Mi.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,Mi.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Mi.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Mi.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Ni(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}};function Fi(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Ii(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Li=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Ri(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Li.map(e=>zi(i,e,t,r)))).filter(e=>e!==null)}async function zi(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||!Bi(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Bi(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`)}const Vi=3e4;var Hi=class extends Error{constructor(e=`CDP bridge rejected the session token (bridge-token-required). Open SLICC again from Sliccstart to pick up a fresh token.`){super(e),this.name=`CdpBridgeRejectedError`}},Ui=class extends Error{constructor(){super(`CDP reconnect is backing off`),this.name=`CdpReconnectBackoffError`}};function Wi(e,t=Math.random){let n=Math.min(Vi,250*2**Math.min(Math.max(0,e),16)),r=Math.round(n*.2*t());return Math.min(Vi,n+r)}function Gi(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var Ki=class{lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;reconnectAttempt=0;reconnectNotBefore=0;bridgeRejection=null;bridgeRejectedHandler=null;bridgeRejectedNotified=!1;classifyConnectFailure=async()=>`transient`;primeConnectOptions(e){this.lastConnectOptions=e?{...e}:{}}setSupersededHandler(e){this.supersededHandler=e}setBridgeRejectedHandler(e){this.bridgeRejectedHandler=e}setConnectFailureClassifier(e){this.classifyConnectFailure=e}async connect(e,t){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new Hi(this.bridgeRejection);this.lastConnectOptions=t?{...t}:{};try{await e.connect({url:t?.url??Gi(),timeout:t?.timeout,...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t),this.bridgeRejection?new Hi(this.bridgeRejection):e}this.noteReconnectSuccess()}async ensureLocalConnected(e){if(e.superseded===!0){this.notifySuperseded();return}if(e.state===`disconnected`){this.throwIfReconnectPaused();let t=this.lastConnectOptions;try{await e.connect({url:t?.url??Gi(),...t?.timeout===void 0?{}:{timeout:t.timeout},...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t??void 0),this.bridgeRejection?new Hi(this.bridgeRejection):e}this.noteReconnectSuccess()}}async ensureConnected(e){if(e.client.superseded===!0){this.notifySuperseded();return}if(e.client.state===`disconnected`){this.throwIfReconnectPaused();let t=e.client;e.restoreLocalAfterRemoteDrop(),e.clearSessionsForTransport(t),e.getClient().state===`disconnected`&&await this.connect(e.getClient(),this.lastConnectOptions??void 0)}}throwIfReconnectPaused(){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new Hi(this.bridgeRejection);if(Date.now()<this.reconnectNotBefore)throw new Ui}noteReconnectSuccess(){this.reconnectAttempt=0,this.reconnectNotBefore=0,this.supersededNotified=!1}async noteReconnectFailure(e){if(await this.classifyConnectFailure({url:e?.url??``,...e?.protocols===void 0?{}:{protocols:e.protocols}})===`terminal`){this.bridgeRejection=new Hi().message,this.notifyBridgeRejected();return}let t=Wi(this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectNotBefore=Date.now()+t}notifyBridgeRejected(){if(!this.bridgeRejectedNotified){this.bridgeRejectedNotified=!0;try{this.bridgeRejectedHandler?.()}catch{}}}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}},qi=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 Ji(e,t){if(e?.aborted)throw new qi(t)}function Yi(e,t){return e?{signal:e,error:()=>new qi(t)}:void 0}function Xi(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new qi(n));return}let a=()=>{clearTimeout(o),i(new qi(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Zi(e,t,n){return t?t.aborted?Promise.reject(new qi(n)):new Promise((r,i)=>{let a=()=>i(new qi(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var Qi=class{contexts=new Map;for(e,t){let n=`${t}:${e}`,r=this.contexts.get(n);return r||(r=new Map,this.contexts.set(n,r)),r}peek(e,t){return this.contexts.get(`${t}:${e}`)}drop(e){this.contexts.delete(`main:${e}`),this.contexts.delete(`isolated:${e}`)}get size(){return this.contexts.size}};const $i=_(`har-recorder`);var ea=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)}`;Ji(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Ji(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Ji(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}`),$i.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=>{$i.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=>{$i.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 ta(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return $i.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 $i.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)),$i.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 $i.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 ta(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){$i.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return $i.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var na=class{maxSessions;onEvict;sessions=new Map;pinnedTargets=new Map;appliedSends=new Map;constructor(e=32,t){this.maxSessions=e,this.onEvict=t}get size(){return this.sessions.size}get(e){return this.sessions.get(e)}has(e){return this.sessions.has(e)}values(){return this.sessions.values()}entries(){return this.sessions.entries()}snapshot(){return[...this.sessions]}remember(e,t){this.pruneAppliedSends(),this.sessions.set(e,t),this.enforceCap(e)}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}take(e){let t=this.sessions.get(e);return t&&this.sessions.delete(e),t}delete(e){this.sessions.delete(e)}clear(){this.sessions.clear()}pin(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.enforceCap()}}isPinned(e){return this.pinnedTargets.has(e)}enforceCap(e){for(;this.sessions.size>this.maxSessions;){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&&this.onEvict?.(t,n)}}noteApplied(e){this.appliedSends.set(e,(this.appliedSends.get(e)??0)+1)}appliedCount(e){return this.appliedSends.get(e)??0}pruneAppliedSends(){if(this.appliedSends.size<=this.maxSessions*4)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)}findBySessionId(e){for(let[t,n]of this.sessions)if(n.sessionId===e)return[t,n]}findByTargetOrLocalId(e){let t=[];for(let[n,r]of this.sessions)(n===e||r.remote?.localTargetId===e)&&t.push([n,r]);return t}anyOnTransport(e){for(let t of this.sessions.values())if(t.transport===e)return!0;return!1}anyMatchingRemote(e,t){for(let n of this.sessions.values())if(n.remote?.runtimeId===e&&n.remote.localTargetId===t)return!0;return!1}};const ra=`(function() {
2
2
  'use strict';
3
3
 
4
4
  // ===== DOM Utilities =====
@@ -874,7 +874,7 @@ 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 ca(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)ca(n,t)}function la(e){let t=e.exceptionDetails;return t?t.exception?.description??t.text:null}function ua(e,t){let n=la(e);if(n!==null)throw Error(`${t}: ${n}`);return e.result?.value}function da(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 fa(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=pa(a,o);t.has(s)||t.set(s,e)}return t}function pa(e,t){return`${e.toLowerCase()}|${t.replace(/\s+/g,` `).trim()}`}function ma(e,t){let n=pa(e.role,e.name),r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)ma(n,t)}function ha(e){let t={role:Ee(e.role,`unknown`),name:Ee(e.name)},n=Ee(e.value);n!==``&&(t.value=n);let r=Ee(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>ha(e)).filter(e=>e.role!==`unknown`)),t}function ga(e){let t=e??{queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0};return{queueDepth:t.queueDepth,totalWaitMs:t.tabWaitMs+t.bridgeWaitMs,tabWaitMs:t.tabWaitMs,bridgeWaitMs:t.bridgeWaitMs,acquisitions:t.acquisitions}}var _a=class{tabLocks=new Map;bridgeLock=Promise.resolve();bridgeHold=null;bridgeWaiters=0;tabLockStats=new Map;getStats(e){if(e!==void 0)return ga(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 ga(t)}countersFor(e){let t=this.tabLockStats.get(e);return t||(t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0},this.tabLockStats.set(e,t)),t}liveOwner(){return this.bridgeHold?.owner}reentrantOwner(e){let t=this.bridgeHold;if(!(!t||e===null||t.targetId!==e))return t.owner}async holdTabLock(e,t,n){Ji(t,`starting a command on tab ${e}`);let r=this.countersFor(e);r.queueDepth+=1;let i;try{i=await this.acquireTabLock(e,r,t)}catch(e){throw--r.queueDepth,e}try{return await n(r)}finally{--r.queueDepth,i()}}async acquireTabLock(e,t,n){let r,i=new Promise(e=>{r=e}),a=this.tabLocks.get(e);this.tabLocks.set(e,i);let o=()=>{this.tabLocks.get(e)===i&&this.tabLocks.delete(e),r()};if(a){let r=Date.now();try{await Zi(a,n,`queued for the lock on tab ${e}`)}catch(e){throw t.tabWaitMs+=Date.now()-r,a.then(o,o),e}t.tabWaitMs+=Date.now()-r}return o}async acquireBridgeLock(e){if(e?.owner!==void 0&&this.bridgeHold?.owner===e.owner)return()=>void 0;let t,n=new Promise(e=>{t=e}),r=this.bridgeLock,i=this.bridgeHold!==null||this.bridgeWaiters>0;if(this.bridgeLock=n,i){this.bridgeWaiters+=1;let t=Date.now();try{await r}finally{--this.bridgeWaiters}e?.counters&&(e.counters.bridgeWaitMs+=Date.now()-t)}let a={release:t,owner:Symbol(`bridge-hold`),targetId:e?.targetId??null};this.bridgeHold=a;let o=!1;return()=>{o||(o=!0,this.bridgeHold===a&&(this.bridgeHold=null),t())}}async runGlobal(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e),targetId:e});try{return await t()}finally{n()}}},va=class{overrides=new Map;get(e){return this.overrides.get(e)}set(e,t){this.overrides.set(e,t)}delete(e){this.overrides.delete(e)}has(e){return this.overrides.has(e)}get size(){return this.overrides.size}};const ya=_(`browser-api`),ba=[`Session with given id not found`,`Target closed`,`No session with given id`,`No tab attached for sessionId`];var xa=class extends Error{};function Sa(e){let t=e instanceof Error?e.message:String(e);return ba.some(e=>t.includes(e))}var Ca=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)}},wa=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;frames=new Qi;sessions=new na(32,(e,t)=>{ya.debug(`Evicting least-recently-used CDP session`,{targetId:e}),this.detachSession(e,t)});_listenedTransports=new Set;_sessionReplacedSubs=new Map;locks=new _a;viewports=new va;connection=new Ki;_onSessionChange;handleJavaScriptDialogOpening=e=>{this.dismissJavaScriptDialog(e)};async dismissJavaScriptDialog(e){let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.transportForSession(t).send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),ya.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){ya.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}handleExecutionContextCreated=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this.frames.for(t,`main`).set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.executionContextId;if(typeof n!=`number`)return;let r=this.frames.peek(t,`main`);if(r)for(let[e,t]of r)t===n&&r.delete(e)};handleExecutionContextsCleared=e=>{let t=this.eventSessionId(e);t&&this.frames.peek(t,`main`)?.clear()};eventSessionId(e){let t=e.sessionId;return typeof t==`string`?t:this.sessionId}handleDetachedFromTarget=e=>{let t=e.sessionId;if(typeof t!=`string`)return;let n=this.sessions.findBySessionId(t);n&&this.forgetSession(n[0],n[1])};handleTargetDestroyed=e=>{let t=e.targetId;if(typeof t!=`string`)return;let n=this.sessions.findByTargetOrLocalId(t)[0];n&&this.forgetSession(n[0],n[1])};constructor(e){this.client=e??new Pi,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 Ca)return e;let t=this._accountedTransports.get(e);return t||(t=new Ca(e,e=>this.noteApplied(e)),this._accountedTransports.set(e,t)),t}noteApplied(e){this.sessions.noteApplied(e)}createHarRecorder(e,t){return new ea(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;return this.locks.holdTabLock(e,r,async n=>{let i=this.sessions.pin(e);try{return n.acquisitions+=1,await this.runOnTab(e,t,r)}finally{i()}})}async runOnTab(e,t,n){try{return await this.attemptOnTab(e,t,n)}catch(r){if(r instanceof xa||!Sa(r))throw r;return ya.warn(`Stale CDP session — re-attaching and retrying once`,{targetId:e,error:r instanceof Error?r.message:String(r)}),this.invalidateSession(e),await this.attemptOnTab(e,t,n)}}async attemptOnTab(e,t,n){let r=await this.attachHandle(e,this.locks.reentrantOwner(e),n);Ji(n,`about to run a command on tab ${e}`);let i=r.sessionId,a=this.sessions.appliedCount(i);try{return await t(r)}catch(t){if(!Sa(t))throw t;let n=this.sessions.appliedCount(i)-a;if(n===0)throw t;this.invalidateSession(e);let r=t instanceof Error?t.message:String(t);throw ya.warn(`CDP session reset mid-command — not replaying`,{targetId:e,applied:n,reason:r}),new xa(`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 sa(this,e,r,this.accountedTransportFor(i?.transport??this.client),n)}handleFor(e,t){return new sa(this,e,t.sessionId,this.accountedTransportFor(t.transport))}getTabLockStats(e){return this.locks.getStats(e)}async runGlobal(e,t){return this.locks.runGlobal(e,t)}viewportOverride(e){return this.viewports.get(e)}recordViewportOverride(e,t){this.viewports.set(e,t)}frameContexts(e,t){return this.frames.for(e,t)}dropFrameContexts(e){this.frames.drop(e)}async reapplyViewportOverride(e,t){let n=this.viewports.get(e);if(n)try{await this.handleFor(e,t).applyViewportOverride(n)}catch(t){ya.warn(`Failed to re-apply viewport override on re-attach`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:e.kind,capabilities:e.capabilities}));return[...e,...r]}async connect(e){await this.connection.connect(this.client,e)}async reconnectIfNeeded(){await this.ensureConnected(),this.client!==this.localClient&&await this.ensureLocalConnected()}primeConnectOptions(e){this.connection.primeConnectOptions(e)}setCdpSupersededHandler(e){this.connection.setSupersededHandler(e)}setCdpBridgeRejectedHandler(e){this.connection.setBridgeRejectedHandler(e)}setCdpConnectFailureClassifier(e){this.connection.setConnectFailureClassifier(e)}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async openWindow(e,t={}){await this.ensureConnected(),await this.ensureLocalConnected(),Da(t);let n=t.focus!==!1,r={url:e||`about:blank`,newWindow:!0,background:!n};t.decorated===!1&&(r.decorated=!1);let i=t.state;i&&i!==`normal`?r.windowState=i:(t.width!==void 0&&(r.width=t.width),t.height!==void 0&&(r.height=t.height),t.left!==void 0&&(r.left=t.left),t.top!==void 0&&(r.top=t.top),i&&(r.windowState=i));let a=(await this.localClient.send(`Target.createTarget`,r)).targetId;if(typeof a!=`string`||!a)throw Error(`Target.createTarget did not return a usable targetId`);return a}async getWindowBounds(e){await this.ensureConnected();let t=ka((await(await this.transportForWindowOps(e)).send(`Browser.getWindowForTarget`,{targetId:Ea(e)})).bounds),n=await this.readDevicePixelRatio(e);return{...t,dpr:n}}async setWindowBounds(e,t){await this.ensureConnected(),Da(t);let n=await this.transportForWindowOps(e),r=Ea(e),i=await n.send(`Browser.getWindowForTarget`,{targetId:r}),a=i.windowId;if(typeof a!=`number`)throw Error(`Browser.getWindowForTarget did not return a windowId`);let o=ka(i.bounds),s=t.state;(t.left!==void 0||t.top!==void 0||t.width!==void 0||t.height!==void 0)&&o.state!==`normal`&&await n.send(`Browser.setWindowBounds`,{windowId:a,bounds:{windowState:`normal`}});let c={};s&&s!==`normal`?c.windowState=s:(t.left!==void 0&&(c.left=t.left),t.top!==void 0&&(c.top=t.top),t.width!==void 0&&(c.width=t.width),t.height!==void 0&&(c.height=t.height),s&&(c.windowState=s)),await n.send(`Browser.setWindowBounds`,{windowId:a,bounds:c});let l=ka((await n.send(`Browser.getWindowBounds`,{windowId:a})).bounds),u=await this.readDevicePixelRatio(e);return{...l,dpr:u}}async readDevicePixelRatio(e){try{let t=await this.withTab(e,e=>e.evaluate(`window.devicePixelRatio`,{awaitPromise:!1,returnByValue:!0}));return typeof t==`number`&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}async transportForWindowOps(e){if(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);return this.trayTargetProvider.createRemoteTransport(n,r)}return await this.ensureLocalConnected(),this.localClient}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.viewports.delete(e),await this.dropSession(e),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let e=this.trayTargetProvider.createRemoteTransport(n,r);try{await e.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}return}}await this.localClient.send(`Target.closeTarget`,{targetId:e})}disconnect(){this.clearSessions(),this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){return this.attachToPageOwned(e,this.locks.reentrantOwner(e))}async attachToPageOwned(e,t,n){let r=await this.locks.acquireBridgeLock({owner:t,targetId:e,counters:this.locks.countersFor(e)});try{await this.ensureConnected();let t=this.sessions.get(e);return t?(this.activateSession(e,t),t.sessionId):await(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)?this.attachRemoteTarget(e,n):this.attachLocalTarget(e,n))}finally{r()}}async selectTab(e){await this.withTab(e,async()=>void 0)}async bringTabToFront(e){await this.withTab(e,e=>e.bringToFront())}async attachRemoteTarget(e,t){let n=e.indexOf(`:`),r=e.substring(0,n),i=e.substring(n+1),a=this.trayTargetProvider?.createRemoteTransport?.(r,i);if(!a)throw Error(`No remote transport for target ${e}`);Ji(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),Ji(t,`about to enable Page on tray tab ${e}`),await a.send(`Page.enable`,{},o.sessionId),Ji(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(),Ji(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),Ji(t,`about to enable Page on tab ${e}`),await this.localClient.send(`Page.enable`,{},n.sessionId),Ji(t,`about to restore the viewport of tab ${e}`),await this.reapplyViewportOverride(e,n),this.notifySessionChange(e,n),n.sessionId}async detach(){let e=this.attachedTargetId;e&&(await this.dropSession(e),this.useLocalTransport())}async wakeCapture(e,t){let n=await this.locks.acquireBridgeLock({owner:this.locks.reentrantOwner(e.targetId),targetId:e.targetId});try{return await this.wakeCaptureLocked(e,t,this.locks.liveOwner())}finally{n()}}async wakeCaptureLocked(e,t,n){let r=e.targetId,i=await this.findFocusedLocalPage(r,n).catch(()=>null),a=await this.attachHandle(r,n);try{return await a.send(`Page.bringToFront`),await a.send(`Page.captureScreenshot`,t)}finally{if(i)try{await(await this.attachHandle(i,n)).send(`Page.bringToFront`),await this.attachToPageOwned(r,n)}catch{}}}async findFocusedLocalPage(e,t){let n=await this.listPages();for(let r of n)if(!(!r.targetId||r.targetId===e)&&!r.targetId.includes(`:`))try{if(await(await this.attachHandle(r.targetId,t)).evaluate(`document.hasFocus()`)===!0)return r.targetId}catch{}return null}async ensureLocalConnected(){await this.connection.ensureLocalConnected(this.localClient)}async ensureConnected(){await this.connection.ensureConnected({client:this.client,restoreLocalAfterRemoteDrop:()=>{this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null)},clearSessionsForTransport:e=>this.clearSessionsForTransport(e),getClient:()=>this.client})}transportForSession(e){return this.sessions.findBySessionId(e)?.[1].transport??this.client}addTransportListeners(e){this._listenedTransports.has(e)||(this._listenedTransports.add(e),e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.on(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.on(`Target.targetDestroyed`,this.handleTargetDestroyed))}releaseLifecycleTransport(e){e!==this.localClient&&this._listenedTransports.has(e)&&(this.sessions.anyOnTransport(e)||(this._listenedTransports.delete(e),e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.off(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.off(`Target.targetDestroyed`,this.handleTargetDestroyed)))}setClient(e){this.addTransportListeners(e),this.client=e}useLocalTransport(){let e=this.remoteTargetInfo;this.remoteTargetInfo=null,this.setClient(this.localClient),e&&(this.sessions.anyMatchingRemote(e.runtimeId,e.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.runtimeId,e.localTargetId))}rememberSession(e,t){this.addTransportListeners(t.transport),this.sessions.remember(e,t)}activateSession(e,t){t.remote?(this.setClient(t.transport),this.remoteTargetInfo={...t.remote}):this.client!==t.transport&&this.useLocalTransport(),this.sessionId=t.sessionId,this.attachedTargetId=e,this.sessions.touch(e,t)}notifySessionChange(e,t){let n=this.accountedTransportFor(t.transport);this._onSessionChange?.(t.sessionId,n,e);let r=this._sessionReplacedSubs.get(e);if(r)for(let i of[...r])try{i(t.sessionId,n,e)}catch(t){ya.warn(`session-replaced subscriber threw`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}forgetSession(e,t){this.unregisterSession(e),this.disposeSessionTransport(t)}unregisterSession(e){let t=this.sessions.get(e);t&&this.dropFrameContexts(t.sessionId),this.sessions.delete(e),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disposeSessionTransport(e){this.releaseLifecycleTransport(e.transport),e.remote&&(this.sessions.anyMatchingRemote(e.remote.runtimeId,e.remote.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.remote.runtimeId,e.remote.localTargetId))}async detachSession(e,t){this.unregisterSession(e);try{await t.transport.send(`Target.detachFromTarget`,{sessionId:t.sessionId})}catch{}finally{this.disposeSessionTransport(t)}}async dropSession(e){let t=this.sessions.get(e);if(!t){this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null);return}await this.detachSession(e,t)}invalidateSession(e){let t=this.sessions.get(e);t&&this.forgetSession(e,t)}clearSessionsForTransport(e){for(let[t,n]of this.sessions.snapshot())n.transport===e&&this.forgetSession(t,n)}clearSessions(){for(let[e,t]of this.sessions.snapshot())this.forgetSession(e,t);this.sessions.clear(),this.sessionId=null,this.attachedTargetId=null}};const Ta=new Set([`normal`,`minimized`,`maximized`,`fullscreen`]);function Ea(e){let t=e.indexOf(`:`);return t>=0?e.substring(t+1):e}function Da(e){let t=e.state;if(!(!t||t===`normal`)){if(!Ta.has(t))throw Error(`window state must be one of ${[...Ta].join(`|`)} (got ${JSON.stringify(t)})`);if(e.left!==void 0||e.top!==void 0||e.width!==void 0||e.height!==void 0)throw Error(`window state '${t}' cannot be combined with left/top/width/height (chrome.windows + CDP both reject the mix)`)}}function Oa(e){return typeof e==`object`&&!!e}function ka(e){let t=Oa(e)?e:{},n=t.windowState??t.state,r=typeof n==`string`&&Ta.has(n)?n:`normal`;return{left:Aa(t.left,0),top:Aa(t.top,0),width:Aa(t.width,0),height:Aa(t.height,0),state:r}}function Aa(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}const ja=_(`panel-rpc-cdp`);var Ma=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=>{ja.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,De)+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){ja.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=>{ja.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=>{ja.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function Na(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 Ma(e,r,i),t.set(a,o)),o},removeRemoteTransport(e,r){let i=n(e,r),a=t.get(i);a&&(a.disconnect(),t.delete(i))},async openRemoteTab(t,n){let r=e();if(!r)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let{targetId:i}=await r.call(`remote-open-tab`,{runtimeId:t,url:n});return i}}}function Pa(e){return`slicc_feature_flags_remote:${e}`}let Fa=null;function Ia(e,t){let n=Ra(t);Fa=e,Me(e,za(n,e)??{})}function La(e,t){if(!Fa||e!==void 0&&e!==Pa(Fa))return!1;let n=Ra(t);return Ae(Fa,za(n,Fa)??{}),!0}function Ra(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 za(e,t){try{let n=e?.getItem(Pa(t));return n?Ba(JSON.parse(n)):null}catch{return null}}function Ba(e){return!Va(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function Va(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ha=_(`stale-asset`),Ua=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Wa(e){return Ua.test(e)}let Ga=null;function Ka(e){if(!e){Ga=null;return}Ga=e}function qa(e=!1){if(!Ga||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Ga,replayTurn:e})}finally{t.close()}}function Ja(e){Wa(e instanceof Error?e.message:String(e))&&qa()}function Ya(e,t){return!e||e===t?!1:(Ha.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),qa(),!0)}var Xa=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new Ai;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 ji(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 Za(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 Qa(e){let t=Za(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var $a=class extends Xa{constructor(e){let t=Za(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 eo(e,t){return e.find(e=>e.folder===t)??e.find(e=>e.folder===`${t}-scoop`)??e.find(e=>e.name===t)}const to=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function no(e){return to.test(e)}function ro(e,t){return`(${e} && ${t})`}function A(e,t){return`(${e} || ${t})`}function io(e){return`!(${e})`}function ao(e){return`Array.isArray(${e})`}function oo(e){return`typeof ${e} === "bigint"`}function so(e){return`typeof ${e} === "boolean"`}function co(e){return`Number.isInteger(${e})`}function lo(e){return`${e} === null`}function uo(e){return`Number.isFinite(${e})`}function fo(e){return ro(po(e),io(ao(e)))}function po(e){return`typeof ${e} === "object" && ${e} !== null`}function mo(e){return`typeof ${e} === "string"`}function ho(e){return`typeof ${e} === "symbol"`}function go(e){return`${e} === undefined`}function _o(e){return`typeof ${e} === "function"`}function vo(e){return`Guard.IsConstructor(${e})`}function yo(e,t){return`${e} === ${t}`}function bo(e,t){return`${e} > ${t}`}function xo(e,t){return`${e} < ${t}`}function So(e,t){return`${e} <= ${t}`}function Co(e,t){return`${e} >= ${t}`}function wo(e,t){return`Guard.IsMinLength(${e}, ${t})`}function To(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Eo(e,t,n,r){return w(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 Do(e){return`Object.entries(${e})`}function Oo(e){return`Object.getOwnPropertyNames(${e})`}function ko(e,t){return w(t,`"__proto__"`)||w(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function Ao(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function jo(e){return`[${e.join(`, `)}]`}function Mo(e,t){return`((${e.join(`, `)}) => ${t})`}function j(e,t){return`${e}(${t.join(`, `)})`}function No(e,t){return`new ${e}(${t.join(`, `)})`}function M(e,t){return`${e}${no(t)?`.${t}`:`[${N(t)}]`}`}function N(e){return v(e)?JSON.stringify(e):`${e}`}function Po(e,t,n){return`(${e} ? ${t} : ${n})`}function Fo(e){return`{ ${e.join(`; `)}; }`}function Io(e,t){return`const ${e} = ${t}`}function Lo(e,t){return`if(${e}) { ${t} }`}function Ro(e){return`return ${e}`}function P(e){return w(e.length,0)?`true`:e.reduce((e,t)=>ro(e,t))}function zo(e){return w(e.length,0)?`false`:e.reduce((e,t)=>A(e,t))}function Bo(e){return`++${e}`}function Vo(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Ho=it;function Uo(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let Wo;function Go(){try{return qo(`null`)(),!0}catch{return!1}}function Ko(){return C(Wo)&&(Wo=Go()),Wo&&Zt().useAcceleration}function qo(...e){return new globalThis.Function(...e)}function Jo(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 Yo=Jo;function Xo(){return Yo}const Zo=[/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],Qo=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function $o(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!Qo.some(t=>t.test(e.errorMessage))&&Zo.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 es(e){return E(e,`~refine`)&&S(e[`~refine`])&&x(e[`~refine`],0,e=>b(e)&&E(e,`check`)&&E(e,`error`)&&Vt(e.check)&&Vt(e.error))}function ts(e){return b(e)&&!S(e)}function ns(e){return $t(e)}function F(e){return ts(e)||ns(e)}function rs(e){return E(e,`additionalItems`)&&F(e.additionalItems)}function is(e){return E(e,`additionalProperties`)&&F(e.additionalProperties)}function as(e){return E(e,`allOf`)&&S(e.allOf)&&e.allOf.every(e=>F(e))}function os(e){return E(e,`$anchor`)&&v(e.$anchor)}function ss(e){return E(e,`anyOf`)&&S(e.anyOf)&&e.anyOf.every(e=>F(e))}function cs(e){return E(e,`const`)}function ls(e){return E(e,`contains`)&&F(e.contains)}function us(e){return E(e,`default`)}function ds(e){return E(e,`dependencies`)&&b(e.dependencies)&&Object.values(e.dependencies).every(e=>F(e)||S(e)&&e.every(e=>v(e)))}function fs(e){return E(e,`dependentRequired`)&&b(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>S(e)&&e.every(e=>v(e)))}function ps(e){return E(e,`dependentSchemas`)&&b(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>F(e))}function ms(e){return E(e,`$dynamicAnchor`)&&v(e.$dynamicAnchor)}function hs(e){return E(e,`$dynamicRef`)&&v(e.$dynamicRef)}function gs(e){return E(e,`else`)&&F(e.else)}function _s(e){return E(e,`enum`)&&S(e.enum)}function vs(e){return E(e,`exclusiveMaximum`)&&(D(e.exclusiveMaximum)||zt(e.exclusiveMaximum))}function ys(e){return E(e,`exclusiveMinimum`)&&(D(e.exclusiveMinimum)||zt(e.exclusiveMinimum))}function bs(e){return E(e,`format`)&&v(e.format)}function xs(e){return E(e,`$id`)&&v(e.$id)}function Ss(e){return E(e,`if`)&&F(e.if)}function Cs(e){return E(e,`items`)&&(F(e.items)||S(e.items)&&e.items.every(e=>F(e)))}function ws(e){return Cs(e)&&S(e.items)}function Ts(e){return E(e,`maximum`)&&(D(e.maximum)||zt(e.maximum))}function Es(e){return E(e,`maxContains`)&&D(e.maxContains)}function Ds(e){return E(e,`maxItems`)&&D(e.maxItems)}function Os(e){return E(e,`maxLength`)&&D(e.maxLength)}function ks(e){return E(e,`maxProperties`)&&D(e.maxProperties)}function As(e){return E(e,`minimum`)&&(D(e.minimum)||zt(e.minimum))}function js(e){return E(e,`minContains`)&&D(e.minContains)}function Ms(e){return E(e,`minItems`)&&D(e.minItems)}function Ns(e){return E(e,`minLength`)&&D(e.minLength)}function Ps(e){return E(e,`minProperties`)&&D(e.minProperties)}function Fs(e){return E(e,`multipleOf`)&&(D(e.multipleOf)||zt(e.multipleOf))}function Is(e){return E(e,`not`)&&F(e.not)}function Ls(e){return E(e,`oneOf`)&&S(e.oneOf)&&e.oneOf.every(e=>F(e))}function Rs(e){return E(e,`pattern`)&&(v(e.pattern)||e.pattern instanceof RegExp)}function zs(e){return E(e,`patternProperties`)&&b(e.patternProperties)&&Object.values(e.patternProperties).every(e=>F(e))}function Bs(e){return E(e,`prefixItems`)&&S(e.prefixItems)&&e.prefixItems.every(e=>F(e))}function Vs(e){return E(e,`properties`)&&b(e.properties)&&Object.values(e.properties).every(e=>F(e))}function Hs(e){return E(e,`propertyNames`)&&(b(e.propertyNames)||F(e.propertyNames))}function Us(e){return E(e,`$recursiveAnchor`)&&$t(e.$recursiveAnchor)}function Ws(e){return Us(e)&&w(e.$recursiveAnchor,!0)}function Gs(e){return E(e,`$recursiveRef`)&&v(e.$recursiveRef)}function Ks(e){return E(e,`$ref`)&&v(e.$ref)}function qs(e){return E(e,`required`)&&S(e.required)&&e.required.every(e=>v(e))}function Js(e){return E(e,`then`)&&F(e.then)}function Ys(e){return E(e,`type`)&&(v(e.type)||S(e.type)&&e.type.every(e=>v(e)))}function Xs(e){return E(e,`uniqueItems`)&&$t(e.uniqueItems)}function Zs(e){return E(e,`unevaluatedItems`)&&F(e.unevaluatedItems)}function Qs(e){return E(e,`unevaluatedProperties`)&&F(e.unevaluatedProperties)}function $s(e){return Zs(e)||Qs(e)||y(e).some(t=>tc(e[t]))}function ec(e){return e.some(e=>tc(e))}function tc(e){return S(e)?ec(e):b(e)?$s(e):!1}function nc(e,t){return tc(t)||y(e).some(t=>tc(e[t]))}var rc=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return j(M(`context`,`Push`),[])}Pop(){return j(M(`context`,`Pop`),[])}AddIndex(e){return j(M(`context`,`AddIndex`),[e])}AddKey(e){return j(M(`context`,`AddKey`),[e])}Merge(e){return j(M(`context`,`Merge`),[e])}},ic=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}},ac=class extends ic{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},oc=class extends ac{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const sc={identifier:`External`,variables:[]};function cc(e){let t=`External[${sc.variables.length}]`;return sc.variables.push(e),t}function lc(){sc.variables=[]}function uc(){return{...sc}}function dc(e,t,n,r){return Eo(cc(n[`~refine`].map(e=>e)),N(0),[`refinement`,`_`],j(M(`refinement`,`check`),[r]))}function fc(e,t,n,r){return x(n[`~refine`],0,(e,t)=>e.check(r))}function pc(e,t,n,r,i,a){return Gt(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let mc=0;function I(){return`var_${mc++}`}function hc(e){return Cs(e)&&S(e.items)}function gc(e,t,n,r){if(!hc(n))return N(!0);let[i,a]=[I(),I()],o=Wf(e,t,n.additionalItems,i),s=xo(a,N(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?A(s,ro(o,c)):A(s,o);return j(M(r,`every`),[Mo([i,a],l)])}function _c(e,t,n,r){return!hc(n)||r.every((r,i)=>sn(i,n.items.length)||Gf(e,t,n.additionalItems,r)&&t.AddIndex(i))}function vc(e,t,n,r,i,a){return!hc(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return sn(o,i.items.length)||Kf(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function yc(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function bc(e){let t=[];return zs(e)&&t.push(...y(e.patternProperties)),Vs(e)&&t.push(...y(e.properties).map(yc)),w(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function xc(e,t,n){return qs(t)&&Vs(t)&&!zs(t)&&w(t.additionalProperties,!1)&&w(y(t.properties).length,t.required.length)}function Sc(e,t,n){return yo(M(j(M(`Object`,`getOwnPropertyNames`),[n]),`length`),N(t.required.length))}function Cc(e,t,n,r){let[i,a]=[I(),I()],o=cc(new RegExp(bc(n))),s=Wf(e,t,n.additionalProperties,`${r}[${i}]`),c=j(M(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?A(c,ro(s,l)):A(c,s);return Eo(Oo(r),N(0),[i,a],u)}function wc(e,t,n,r){return xc(t,n,r)?Sc(t,n,r):Cc(e,t,n,r)}function Tc(e,t,n,r){let i=new RegExp(bc(n));return x(y(r),0,(a,o)=>i.test(a)||Gf(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function Ec(e,t,n,r,i,a){let o=new RegExp(bc(i)),s=[];return Gt(y(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new oc,p=o.test(c)||Kf(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 Dc(e,t,n,r,i){let a=Io(`results`,`[]`),o=n.map((e,t)=>Io(`context_${t}`,No(`CheckContext`,[]))),s=n.map((n,i)=>Io(`condition_${i}`,j(Mo([`context`],R(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>Lo(`condition_${t}`,j(M(`results`,`push`),[`context_${t}`]))),l=Ro(ro(i,t.Merge(`results`)));return j(Mo([],Fo([a,...o,...s,...c,l])),[])}function Oc(e,t,n,r){return Dc(e,t,n.allOf,r,yo(M(`results`,`length`),N(n.allOf.length)))}function kc(e,t,n,r){return P(n.allOf.map(n=>R(e,t,n,r)))}function Ac(e,t,n,r){return t.UseUnevaluated()?Oc(e,t,n,r):kc(e,t,n,r)}function jc(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new ic;return z(e,i,n,r)?[...t,i]:t},[]);return w(i.length,n.allOf.length)&&t.Merge(i)}function Mc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new oc,u=B(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=w(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function Nc(e,t,n,r){return Dc(e,t,n.anyOf,r,bo(M(`results`,`length`),N(0)))}function Pc(e,t,n,r){return zo(n.anyOf.map(n=>R(e,t,n,r)))}function Fc(e,t,n,r){return t.UseUnevaluated()?Nc(e,t,n,r):Pc(e,t,n,r)}function Ic(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new ic;return z(e,i,n,r)?[...t,i]:t},[]);return At(i.length,0)&&t.Merge(i)}function Lc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new oc,l=B(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=At(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 Rc(e,t,n,r){return N(!!n)}function zc(e,t,n,r){return n}function Bc(e,t,n,r,i,a){return zc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function Vc(e,t,n,r){return It(n.const)?yo(r,N(n.const)):Ao(r,cc(n.const))}function Hc(e,t,n,r){return It(n.const)?w(r,n.const):Ot(r,n.const)}function Uc(e,t,n,r,i,a){return Hc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Wc(e){return!(js(e)&&w(e.minContains,0))}function Gc(e,t,n,r){if(!Wc(n))return N(!0);let i=I();return ro(io(yo(M(r,`length`),N(0))),j(M(r,`some`),[Mo([i],R(e,t,n.contains,i))]))}function Kc(e,t,n,r){return!Wc(n)||!w(r.length,0)&&r.some(r=>z(e,t,n.contains,r))}function qc(e,t,n,r,i,a){return Kc(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Jc(e,t,n,r){return A(yo(M(Oo(r),`length`),N(0)),P(T(n.dependencies).map(([n,i])=>{let a=io(ko(r,N(n))),o=R(e,t,i,r);return A(a,S(i)?(e=>P(e.map(e=>ko(r,N(e)))))(i):o)})))}function Yc(e,t,n,r){let i=w(y(r).length,0),a=x(T(n.dependencies),0,([n,i])=>!E(r,n)||(S(i)?i.every(e=>E(r,e)):z(e,t,i,r)));return i||a}function Xc(e,t,n,r,i,a){let o=w(y(a).length,0),s=Gt(T(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!E(a,i)||(S(o)?o.every(e=>E(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):B(e,t,s,r,o,a))});return o||s}function Zc(e,t,n,r){return A(yo(M(Oo(r),`length`),N(0)),P(T(n.dependentRequired).map(([e,t])=>A(io(ko(r,N(e))),P(t.map(e=>ko(r,N(e))))))))}function Qc(e,t,n,r){let i=w(y(r).length,0),a=x(T(n.dependentRequired),0,([e,t])=>!E(r,e)||t.every(e=>E(r,e)));return i||a}function $c(e,t,n,r,i,a){let o=w(y(a).length,0),s=Gt(T(i.dependentRequired),0,([e,i])=>!E(a,e)||Gt(i,0,o=>E(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function el(e,t,n,r){return A(yo(M(Oo(r),`length`),N(0)),P(T(n.dependentSchemas).map(([n,i])=>A(io(ko(r,N(n))),R(e,t,i,r)))))}function tl(e,t,n,r){let i=w(y(r).length,0),a=x(T(n.dependentSchemas),0,([n,i])=>!E(r,n)||z(e,t,i,r));return i||a}function nl(e,t,n,r,i,a){let o=w(y(a).length,0),s=Gt(T(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!E(a,i)||B(e,t,s,r,o,a)});return o||s}function rl(e,t,n,r){return np(e,t,e.DynamicRef(n)??!1,r)}function il(e,t,n,r){let i=e.DynamicRef(n)??!1;return F(i)&&z(e,t,i,r)}function al(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return F(o)&&B(e,t,`#`,r,o,a)}function ol(e,t,n,r){return zo(n.enum.map(e=>It(e)?yo(r,N(e)):Ao(r,cc(e))))}function sl(e,t,n,r){return n.enum.some(e=>It(e)?w(r,e):Ot(r,e))}function cl(e,t,n,r,i,a){return sl(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function ll(e,t,n,r){return xo(r,N(n.exclusiveMaximum))}function ul(e,t,n,r){return sn(r,n.exclusiveMaximum)}function dl(e,t,n,r,i,a){return ul(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function fl(e,t,n,r){return bo(r,N(n.exclusiveMinimum))}function pl(e,t,n,r){return At(r,n.exclusiveMinimum)}function ml(e,t,n,r,i,a){return pl(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const hl=[0,31,28,31,30,31,30,31,31,30,31,30,31],gl=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function _l(e){return e%4==0&&(e%100!=0||e%400==0)}function vl(e){let t=gl.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&&_l(n)?29:hl[r])}const yl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function bl(e,t=!0){let n=yl.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 xl(e,t=!0){let n=e.split(/T/i);return n.length===2&&vl(n[0])&&bl(n[1],t)}const Sl=/^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 Cl(e){return Sl.test(e)}const wl=/^(?!.*\.\.)[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 Tl(e){return wl.test(e)}function El(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 Dl(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)Qe();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=El(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function Ol(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function kl(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function Al(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function jl(e){return Ol(e)||kl(e)||Al(e)}const Ml=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),Nl=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 Pl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function Fl(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function Il(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function Ll(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function Rl(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function zl(e){return e>=1632&&e<=1641}function Bl(e){return e>=1776&&e<=1785}function Vl(e){return Nl.has(e)}function Hl(e){if(e.length===0)return Qe();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||jl(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(Ml.has(n))return!1;(Il(n)||Ll(n)||Rl(n))&&(r=!0),zl(n)&&(i=!0),Bl(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||!Pl(s))return!1;break;case 1523:case 1524:if(o===void 0||!Fl(o))return!1;break;case 8204:if(o===void 0||o<128&&!Vl(o))return!1;break;case 8205:if(o===void 0||!Vl(o))return!1}}return!(e.includes(`・`)&&!r||i&&a)}function Ul(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 Wl(e){return e.toLowerCase().startsWith(`xn--`)}function Gl(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=Dl(t);return n?Hl(n):!1}catch{return!1}}function Kl(e){return e.length===0||e.length>63?!1:Wl(e)?Gl(e):Hl(e)}function ql(e){return e.length===0||e.length>63?!1:Wl(e)?Gl(e):Ul(e)}function Jl(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!ql(t))return!1;return!0}const Yl=/^(?!.*\.\.)[\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 Xl(e){return Yl.test(e)}function Zl(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(!Kl(e))return!1;return!0}function Ql(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 $l(e){return Ql(e,0,e.length)}function eu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function tu(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&&eu(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!Ql(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 nu(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function ru(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))?nu(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:nu(e)}function iu(e){try{return new URL(e),!0}catch{return!1}}const au=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function ou(e){return au.test(e)}const su=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function cu(e){return su.test(e)}function lu(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const uu=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function du(e){return uu.test(e)}const fu=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function pu(e){return fu.test(e)}const mu=/^(?:(?:[^\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 hu(e){return mu.test(e)}function gu(e){return e>=97&&e<=122||e>=65&&e<=90}function _u(e){return gu(e)||e>=48&&e<=57}function vu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function yu(e){return _u(e)||e===43||e===45||e===46}function bu(e){return _u(e)||e===45||e===46||e===95||e===126}function xu(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 Su(e){return bu(e)||xu(e)||e===58||e===64}function Cu(e){let t=e.length;if(t===0||!gu(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!yu(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||!vu(e.charCodeAt(t+1))||!vu(e.charCodeAt(t+2)))return!1;t+=2}else if(!bu(n)&&!xu(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&&!bu(t)&&!xu(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||!vu(e.charCodeAt(n+1))||!vu(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(Su(r)||r===47||r===63||r===35))return!1;n++}return!0}const wu=/^(?: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 Tu(e){return wu.test(e)}const Eu=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Du(e){return Eu.test(e)}const L=new Map;function Ou(){L.clear()}function ku(){return[...L.entries()]}function Au(e,t){L.set(e,t)}function ju(e){return L.has(e)}function Mu(e){return L.get(e)}function Nu(e,t){return L.get(e)?.(t)??!0}function Pu(){Ou(),L.set(`date-time`,xl),L.set(`date`,vl),L.set(`duration`,Cl),L.set(`email`,Tl),L.set(`hostname`,Jl),L.set(`idn-email`,Xl),L.set(`idn-hostname`,Zl),L.set(`ipv4`,$l),L.set(`ipv6`,tu),L.set(`iri-reference`,ru),L.set(`iri`,iu),L.set(`json-pointer-uri-fragment`,ou),L.set(`json-pointer`,cu),L.set(`regex`,lu),L.set(`relative-json-pointer`,du),L.set(`time`,bl),L.set(`uri-reference`,pu),L.set(`uri-template`,hu),L.set(`uri`,Cu),L.set(`url`,Tu),L.set(`uuid`,Du)}Pu();var Fu=e({Clear:()=>Ou,Entries:()=>ku,Get:()=>Mu,Has:()=>ju,IsDate:()=>vl,IsDateTime:()=>xl,IsDuration:()=>Cl,IsEmail:()=>Tl,IsHostname:()=>Jl,IsIPv4:()=>$l,IsIPv6:()=>tu,IsIdnEmail:()=>Xl,IsIdnHostname:()=>Zl,IsIri:()=>iu,IsIriReference:()=>ru,IsJsonPointer:()=>cu,IsJsonPointerUriFragment:()=>ou,IsRegex:()=>lu,IsRelativeJsonPointer:()=>du,IsTime:()=>bl,IsUri:()=>Cu,IsUriReference:()=>pu,IsUriTemplate:()=>hu,IsUrl:()=>Tu,IsUuid:()=>Du,Reset:()=>Pu,Set:()=>Au,Test:()=>Nu});function Iu(e,t,n,r){return j(M(`Format`,`Test`),[N(n.format),r])}function Lu(e,t,n,r){return Nu(n.format,r)}function Ru(e,t,n,r,i,a){return Lu(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function zu(e,t,n,r){let i=!Js(n)||n.then,a=!gs(n)||n.else;return Po(R(e,t,n.if,r),R(e,t,i,r),R(e,t,a,r))}function Bu(e,t,n,r){let i=!Js(n)||n.then,a=!gs(n)||n.else;return z(e,t,n.if,r)?z(e,t,i,r):z(e,t,a,r)}function Vu(e,t,n,r,i,a){let o=!Js(i)||i.then,s=!gs(i)||i.else,c=new oc,l=B(e,c,`${n}/if`,r,i.if,a)?B(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):B(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 Hu(e,t,n,r){return P(n.items.map((n,i)=>{let a=So(M(r,`length`),N(i)),o=Wf(e,t,n,`${r}[${i}]`),s=t.AddIndex(N(i));return A(a,t.UseUnevaluated()?ro(o,s):o)}))}function Uu(e,t,n,r){return x(n.items,0,(n,i)=>tn(r.length,i)||Gf(e,t,n,r[i])&&t.AddIndex(i))}function Wu(e,t,n,r,i,a){return Gt(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return tn(a.length,o)||Kf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Gu(e,t,n,r){let i=Bs(n)?n.prefixItems.length:0,a=Wf(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?ro(a,o):a;return Eo(r,N(i),[`element`,`index`],s)}function Ku(e,t,n,r){let i=Bs(n)?n.prefixItems.length:0;return x(r,i,(r,i)=>Gf(e,t,n.items,r)&&t.AddIndex(i))}function qu(e,t,n,r,i,a){let o=Bs(i)?i.prefixItems.length:0;return Gt(a,o,(a,o)=>Kf(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function Ju(e,t,n,r){return ws(n)?Hu(e,t,n,r):Gu(e,t,n,r)}function Yu(e,t,n,r){return ws(n)?Uu(e,t,n,r):Ku(e,t,n,r)}function Xu(e,t,n,r,i,a){return ws(i)?Wu(e,t,n,r,i,a):qu(e,t,n,r,i,a)}function Zu(e){return ls(e)}function Qu(e,t,n,r){if(!Zu(n))return N(!0);let[i,a]=[I(),I()];return So(j(M(r,`reduce`),[Mo([i,a],Po(R(e,t,n.contains,a),Bo(i),i)),N(0)]),N(n.maxContains))}function $u(e,t,n,r){if(!Zu(n))return!0;let i=r.reduce((r,i)=>z(e,t,n.contains,i)?++r:r,0);return tn(i,n.maxContains)}function ed(e,t,n,r,i,a){let o=js(i)?i.minContains:1;return $u(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function td(e,t,n,r){return So(r,N(n.maximum))}function nd(e,t,n,r){return tn(r,n.maximum)}function rd(e,t,n,r,i,a){return nd(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function id(e,t,n,r){return So(M(r,`length`),N(n.maxItems))}function ad(e,t,n,r){return tn(r.length,n.maxItems)}function od(e,t,n,r,i,a){return ad(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function sd(e,t,n,r){return To(r,N(n.maxLength))}function cd(e,t,n,r){return St(r,n.maxLength)}function ld(e,t,n,r,i,a){return cd(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function ud(e,t,n,r){return So(M(Oo(r),`length`),N(n.maxProperties))}function dd(e,t,n,r){return tn(y(r).length,n.maxProperties)}function fd(e,t,n,r,i,a){return dd(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function pd(e){return ls(e)}function md(e,t,n,r){if(!pd(n))return N(!0);let[i,a]=[I(),I()];return Co(j(M(r,`reduce`),[Mo([i,a],Po(R(e,t,n.contains,a),Bo(i),i)),N(0)]),N(n.minContains))}function hd(e,t,n,r){if(!pd(n))return!0;let i=r.reduce((r,i)=>z(e,t,n.contains,i)?++r:r,0);return Mt(i,n.minContains)}function gd(e,t,n,r,i,a){return hd(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function _d(e,t,n,r){return Co(r,N(n.minimum))}function vd(e,t,n,r){return Mt(r,n.minimum)}function yd(e,t,n,r,i,a){return vd(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function bd(e,t,n,r){return Co(M(r,`length`),N(n.minItems))}function xd(e,t,n,r){return Mt(r.length,n.minItems)}function Sd(e,t,n,r,i,a){return xd(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function Cd(e,t,n,r){return wo(r,N(n.minLength))}function wd(e,t,n,r){return an(r,n.minLength)}function Td(e,t,n,r,i,a){return wd(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function Ed(e,t,n,r){return Co(M(Oo(r),`length`),N(n.minProperties))}function Dd(e,t,n,r){return Mt(y(r).length,n.minProperties)}function Od(e,t,n,r,i,a){return Dd(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function kd(e,t,n,r){return Vo(r,N(n.multipleOf))}function Ad(e,t,n,r){return ut(r,n.multipleOf)}function jd(e,t,n,r,i,a){return Ad(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function Md(e,t,n,r){return Dc(e,t,[n.not],r,io(yo(M(`results`,`length`),N(1))))}function Nd(e,t,n,r){return io(R(e,t,n.not,r))}function Pd(e,t,n,r){return t.UseUnevaluated()?Md(e,t,n,r):Nd(e,t,n,r)}function Fd(e,t,n,r){let i=new ic;return!z(e,i,n.not,r)&&t.Merge([i])}function Id(e,t,n,r,i,a){return Fd(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function Ld(e,t,n,r){return Dc(e,t,n.oneOf,r,yo(M(`results`,`length`),N(1)))}function Rd(e,t,n,r){return yo(j(M(jo(n.oneOf.map(n=>R(e,t,n,r))),`reduce`),[Mo([`count`,`result`],Po(yo(`result`,N(!0)),Bo(`count`),`count`)),N(0)]),N(1))}function zd(e,t,n,r){return t.UseUnevaluated()?Ld(e,t,n,r):Rd(e,t,n,r)}function Bd(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new ic;return z(e,i,n,r)?[...t,i]:t},[]);return w(i.length,1)&&t.Merge(i)}function Vd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new oc,u=B(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=w(c.length,1)&&t.Merge(c);return!l&&w(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 Hd(e,t,n,r){return j(M(cc(v(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function Ud(e,t,n,r){return(v(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function Wd(e,t,n,r,i,a){return Ud(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function Gd(e,t,n,r){return P(T(n.patternProperties).map(([n,i])=>{let[a,o]=[I(),I()],s=io(j(M(cc(new RegExp(n,`u`)),`test`),[a])),c=Wf(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?A(s,ro(c,l)):A(s,c);return Eo(Do(r),N(0),[`[${a}, ${o}]`,`_`],u)}))}function Kd(e,t,n,r){return x(T(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return x(T(r),0,([n,r])=>!a.test(n)||Gf(e,t,i,r)&&t.AddKey(n))})}function qd(e,t,n,r,i,a){return Gt(T(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return Gt(T(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||Kf(e,t,s,a,o,i)&&t.AddKey(n)})})}function Jd(e,t,n,r){return P(n.prefixItems.map((n,i)=>{let a=So(M(r,`length`),N(i)),o=Wf(e,t,n,`${r}[${i}]`),s=t.AddIndex(N(i));return A(a,t.UseUnevaluated()?ro(o,s):o)}))}function Yd(e,t,n,r){return w(r.length,0)||x(n.prefixItems,0,(n,i)=>tn(r.length,i)||Gf(e,t,n,r[i])&&t.AddIndex(i))}function Xd(e,t,n,r,i,a){return w(a.length,0)||Gt(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return tn(a.length,o)||Kf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Zd(e,t){return e.includes(t)||Zt().exactOptionalPropertyTypes}function Qd(e,t){return go(M(e,t))}function $d(e,t){return C(e[t])}function ef(e,t,n,r){let i=qs(n)?n.required:[];return P(T(n.properties).map(([n,a])=>{let o=io(ko(r,N(n))),s=Wf(e,t,a,M(r,n)),c=t.AddKey(N(n)),l=t.UseUnevaluated()?ro(s,c):s,u=i.includes(n)?l:A(o,l);return Zd(i,n)?u:A(Qd(r,n),u)}))}function tf(e,t,n,r){let i=qs(n)?n.required:[];return x(T(n.properties),0,([n,a])=>{let o=!E(r,n)||Gf(e,t,a,r[n])&&t.AddKey(n);return Zd(i,n)?o:$d(r,n)||o})}function nf(e,t,n,r,i,a){let o=qs(i)?i.required:[];return Gt(T(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!E(a,i)||Kf(e,t,c,l,s,a[i])&&t.AddKey(i);return Zd(o,i)?u():$d(a,i)||u()})}function rf(e,t,n,r){let[i,a]=[I(),I()];return Eo(Oo(r),N(0),[i,a],R(e,t,n.propertyNames,i))}function af(e,t,n,r){return x(y(r),0,(r,i)=>z(e,t,n.propertyNames,r))}function of(e,t,n,r,i,a){let o=[];return Gt(y(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=B(e,new oc,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function sf(e,t,n,r){return np(e,t,e.RecursiveRef(n)??!1,r)}function cf(e,t,n,r){let i=e.RecursiveRef(n)??!1;return F(i)&&z(e,t,i,r)}function lf(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return F(o)&&B(e,t,`#`,r,o,a)}function uf(e,t,n,r){let i=Mo([`context`,`value`],np(e,t,n,`value`));return j(Mo([`context`,`value`],Fo([Io(`nextContext`,No(`CheckContext`,[])),Io(`result`,j(i,[`nextContext`,`value`])),Lo(`result`,t.Merge(`[nextContext]`)),Ro(`result`)])),[`context`,r])}function df(e,t,n,r){return np(e,t,n,r)}function ff(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?uf(e,t,i,r):df(e,t,i,r)}function pf(e,t,n,r){let i=e.Ref(n)??!1,a=new ic,o=F(i)&&z(e,a,i,r);return o&&t.Merge([a]),o}function mf(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new oc,c=F(o)&&B(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function hf(e,t,n,r){return P(n.required.map(e=>ko(r,N(e))))}function gf(e,t,n,r){return x(n.required,0,e=>E(r,e))}function _f(e,t,n,r,i,a){let o=[];return Gt(i.required,0,e=>{let t=E(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function vf(e,t,n,r){return w(n,`object`)?fo(r):w(n,`array`)?ao(r):w(n,`boolean`)?so(r):w(n,`integer`)?co(r):w(n,`number`)?uo(r):w(n,`null`)?lo(r):w(n,`string`)?mo(r):w(n,`bigint`)?oo(r):w(n,`constructor`)?vo(r):w(n,`function`)?_o(r):w(n,`symbol`)?ho(r):w(n,`undefined`)||w(n,`void`)?go(r):N(!0)}function yf(e,t,n,r,i){return w(n,`object`)?Ye(i):w(n,`array`)?S(i):w(n,`boolean`)?$t(i):w(n,`integer`)?yt(i):w(n,`number`)?D(i):w(n,`null`)?Ke(i):w(n,`string`)?v(i):w(n,`bigint`)?zt(i):w(n,`constructor`)?Tt(i):w(n,`function`)?Vt(i):w(n,`symbol`)?ot(i):w(n,`undefined`)?C(i):!w(n,`void`)||C(i)}function bf(e,t,n,r){return zo(n.map(n=>vf(e,t,n,r)))}function xf(e,t,n,r,i){return n.some(n=>yf(e,t,n,r,i))}function Sf(e,t,n,r){return S(n.type)?bf(e,t,n.type,r):vf(e,t,n.type,r)}function Cf(e,t,n,r){return S(n.type)?xf(e,t,n.type,n,r):yf(e,t,n.type,n,r)}function wf(e,t,n,r,i,a){return(S(i.type)?xf(e,t,i.type,i,a):yf(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function Tf(e,t,n,r){let[i,a]=[I(),I()],o=j(M(`context`,`GetIndices`),[]),s=j(M(`indices`,`has`),[i]),c=R(e,t,n.unevaluatedItems,a),l=j(M(`context`,`AddIndex`),[i]),u=Eo(r,N(0),[a,i],ro(A(s,c),l));return j(Mo([`context`],Fo([Io(`indices`,o),Ro(u)])),[`context`])}function Ef(e,t,n,r){let i=t.GetIndices();return x(r,0,(r,a)=>(i.has(a)||z(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function Df(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return Gt(a,0,(a,c)=>{let l=new oc,u=(o.has(c)||B(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 Of(e,t,n,r){let[i,a]=[I(),I()],o=j(M(`context`,`GetKeys`),[]),s=j(M(`keys`,`has`),[i]),c=j(M(`context`,`AddKey`),[i]),l=R(e,t,n.unevaluatedProperties,a),u=Eo(Do(r),N(0),[`[${i}, ${a}]`,`_`],A(s,ro(l,c)));return j(Mo([`context`],Fo([Io(`keys`,o),Ro(u)])),[`context`])}function kf(e,t,n,r){let i=t.GetKeys();return x(T(r),0,([r,a])=>i.has(r)||z(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function Af(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return Gt(T(a),0,([a,c])=>{let l=new oc,u=o.has(a)||B(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 jf(e){return!w(e.uniqueItems,!1)}function Mf(e,t,n,r){return jf(n)?yo(M(No(`Set`,[j(M(r,`map`),[M(`Hashing`,`Hash`)])]),`size`),M(r,`length`)):N(!0)}function Nf(e,t,n,r){if(!jf(n))return!0;let i=new Set(r.map(st)).size,a=r.length;return w(i,a)}function Pf(e,t,n,r,i,a){if(!jf(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=st(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return w(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function Ff(e,t){return Ys(e)&&(S(e.type)&&At(e.type.length,0)&&x(e.type,0,e=>w(e,t))||w(e.type,t))}function If(e){return Ff(e,`object`)}function Lf(e){return ts(e)&&(is(e)||ds(e)||fs(e)||ps(e)||Vs(e)||zs(e)||Hs(e)||Ps(e)||ks(e)||qs(e)||Qs(e))}function Rf(e){return Ff(e,`array`)}function zf(e){return ts(e)&&(rs(e)||Cs(e)||ls(e)||Es(e)||Ds(e)||js(e)||Ms(e)||Bs(e)||Zs(e)||Xs(e))}function Bf(e){return Ff(e,`string`)}function Vf(e){return ts(e)&&(Ns(e)||Os(e)||bs(e)||Rs(e))}function Hf(e){return Ff(e,`number`)||Ff(e,`bigint`)}function Uf(e){return ts(e)&&(As(e)||Ts(e)||vs(e)||ys(e)||Fs(e))}function Wf(e,t,n,r){return t.UseUnevaluated()?ro(ro(t.Push(),R(e,t,n,r)),t.Pop()):R(e,t,n,r)}function R(e,t,n,r){e.Push(n);let i=[];if(ns(n))return Rc(e,t,n,r);if(Ys(n)&&i.push(Sf(e,t,n,r)),Lf(n)){let a=[];qs(n)&&a.push(hf(e,t,n,r)),is(n)&&a.push(wc(e,t,n,r)),ds(n)&&a.push(Jc(e,t,n,r)),fs(n)&&a.push(Zc(e,t,n,r)),ps(n)&&a.push(el(e,t,n,r)),zs(n)&&a.push(Gd(e,t,n,r)),Vs(n)&&a.push(ef(e,t,n,r)),Hs(n)&&a.push(rf(e,t,n,r)),Ps(n)&&a.push(Ed(e,t,n,r)),ks(n)&&a.push(ud(e,t,n,r));let o=P(a),s=A(io(fo(r)),o);i.push(If(n)?o:s)}if(zf(n)){let a=[];rs(n)&&a.push(gc(e,t,n,r)),ls(n)&&a.push(Gc(e,t,n,r)),Cs(n)&&a.push(Ju(e,t,n,r)),Es(n)&&a.push(Qu(e,t,n,r)),Ds(n)&&a.push(id(e,t,n,r)),js(n)&&a.push(md(e,t,n,r)),Ms(n)&&a.push(bd(e,t,n,r)),Bs(n)&&a.push(Jd(e,t,n,r)),Xs(n)&&a.push(Mf(e,t,n,r));let o=P(a),s=A(io(ao(r)),o);i.push(Rf(n)?o:s)}if(Vf(n)){let a=[];Os(n)&&a.push(sd(e,t,n,r)),Ns(n)&&a.push(Cd(e,t,n,r)),bs(n)&&a.push(Iu(e,t,n,r)),Rs(n)&&a.push(Hd(e,t,n,r));let o=P(a),s=A(io(mo(r)),o);i.push(Bf(n)?o:s)}if(Uf(n)){let a=[];vs(n)&&a.push(ll(e,t,n,r)),ys(n)&&a.push(fl(e,t,n,r)),Ts(n)&&a.push(td(e,t,n,r)),As(n)&&a.push(_d(e,t,n,r)),Fs(n)&&a.push(kd(e,t,n,r));let o=P(a),s=A(io(A(uo(r),oo(r))),o);i.push(Hf(n)?o:s)}Ks(n)&&i.push(ff(e,t,n,r)),Gs(n)&&i.push(sf(e,t,n,r)),hs(n)&&i.push(rl(e,t,n,r)),cs(n)&&i.push(Vc(e,t,n,r)),_s(n)&&i.push(ol(e,t,n,r)),Ss(n)&&i.push(zu(e,t,n,r)),Is(n)&&i.push(Pd(e,t,n,r)),as(n)&&i.push(Ac(e,t,n,r)),ss(n)&&i.push(Fc(e,t,n,r)),Ls(n)&&i.push(zd(e,t,n,r)),Zs(n)&&i.push(A(io(ao(r)),Tf(e,t,n,r))),Qs(n)&&i.push(A(io(po(r)),Of(e,t,n,r))),es(n)&&i.push(dc(e,t,n,r));let a=P(i);return e.Pop(n),a}function Gf(e,t,n,r){return t.Push()&&z(e,t,n,r)&&t.Pop()}function z(e,t,n,r){e.Push(n);let i=ns(n)?zc(e,t,n,r):(!Ys(n)||Cf(e,t,n,r))&&(!(b(r)&&!S(r))||(!qs(n)||gf(e,t,n,r))&&(!is(n)||Tc(e,t,n,r))&&(!ds(n)||Yc(e,t,n,r))&&(!fs(n)||Qc(e,t,n,r))&&(!ps(n)||tl(e,t,n,r))&&(!zs(n)||Kd(e,t,n,r))&&(!Vs(n)||tf(e,t,n,r))&&(!Hs(n)||af(e,t,n,r))&&(!Ps(n)||Dd(e,t,n,r))&&(!ks(n)||dd(e,t,n,r)))&&(!S(r)||(!rs(n)||_c(e,t,n,r))&&(!ls(n)||Kc(e,t,n,r))&&(!Cs(n)||Yu(e,t,n,r))&&(!Es(n)||$u(e,t,n,r))&&(!Ds(n)||ad(e,t,n,r))&&(!js(n)||hd(e,t,n,r))&&(!Ms(n)||xd(e,t,n,r))&&(!Bs(n)||Yd(e,t,n,r))&&(!Xs(n)||Nf(e,t,n,r)))&&(!v(r)||(!Os(n)||cd(e,t,n,r))&&(!Ns(n)||wd(e,t,n,r))&&(!bs(n)||Lu(e,t,n,r))&&(!Rs(n)||Ud(e,t,n,r)))&&(!(D(r)||zt(r))||(!vs(n)||ul(e,t,n,r))&&(!ys(n)||pl(e,t,n,r))&&(!Ts(n)||nd(e,t,n,r))&&(!As(n)||vd(e,t,n,r))&&(!Fs(n)||Ad(e,t,n,r)))&&(!Ks(n)||pf(e,t,n,r))&&(!Gs(n)||cf(e,t,n,r))&&(!hs(n)||il(e,t,n,r))&&(!cs(n)||Hc(e,t,n,r))&&(!_s(n)||sl(e,t,n,r))&&(!Ss(n)||Bu(e,t,n,r))&&(!Is(n)||Fd(e,t,n,r))&&(!as(n)||jc(e,t,n,r))&&(!ss(n)||Ic(e,t,n,r))&&(!Ls(n)||Bd(e,t,n,r))&&(!Zs(n)||!S(r)||Ef(e,t,n,r))&&(!Qs(n)||!b(r)||kf(e,t,n,r))&&(!es(n)||fc(e,t,n,r));return e.Pop(n),i}function Kf(e,t,n,r,i,a){return t.Push()&&B(e,t,n,r,i,a)&&t.Pop()}function B(e,t,n,r,i,a){e.Push(i);let o=ns(i)?Bc(e,t,n,r,i,a):!!((!Ys(i)||wf(e,t,n,r,i,a))&+(!(b(a)&&!S(a))||!!((!qs(i)||_f(e,t,n,r,i,a))&+(!is(i)||Ec(e,t,n,r,i,a))&(!ds(i)||Xc(e,t,n,r,i,a))&(!fs(i)||$c(e,t,n,r,i,a))&(!ps(i)||nl(e,t,n,r,i,a))&(!zs(i)||qd(e,t,n,r,i,a))&(!Vs(i)||nf(e,t,n,r,i,a))&(!Hs(i)||of(e,t,n,r,i,a))&(!Ps(i)||Od(e,t,n,r,i,a))&(!ks(i)||fd(e,t,n,r,i,a))))&(!S(a)||!!((!rs(i)||vc(e,t,n,r,i,a))&+(!ls(i)||qc(e,t,n,r,i,a))&(!Cs(i)||Xu(e,t,n,r,i,a))&(!Es(i)||ed(e,t,n,r,i,a))&(!Ds(i)||od(e,t,n,r,i,a))&(!js(i)||gd(e,t,n,r,i,a))&(!Ms(i)||Sd(e,t,n,r,i,a))&(!Bs(i)||Xd(e,t,n,r,i,a))&(!Xs(i)||Pf(e,t,n,r,i,a))))&(!v(a)||!!((!Os(i)||ld(e,t,n,r,i,a))&+(!Ns(i)||Td(e,t,n,r,i,a))&(!bs(i)||Ru(e,t,n,r,i,a))&(!Rs(i)||Wd(e,t,n,r,i,a))))&(!(D(a)||zt(a))||!!((!vs(i)||dl(e,t,n,r,i,a))&+(!ys(i)||ml(e,t,n,r,i,a))&(!Ts(i)||rd(e,t,n,r,i,a))&(!As(i)||yd(e,t,n,r,i,a))&(!Fs(i)||jd(e,t,n,r,i,a))))&(!Ks(i)||mf(e,t,n,r,i,a))&(!Gs(i)||lf(e,t,n,r,i,a))&(!hs(i)||al(e,t,n,r,i,a))&(!cs(i)||Uc(e,t,n,r,i,a))&(!_s(i)||cl(e,t,n,r,i,a))&(!Ss(i)||Vu(e,t,n,r,i,a))&(!Is(i)||Id(e,t,n,r,i,a))&(!as(i)||Mc(e,t,n,r,i,a))&(!ss(i)||Lc(e,t,n,r,i,a))&(!Ls(i)||Vd(e,t,n,r,i,a))&(!Zs(i)||!S(a)||Df(e,t,n,r,i,a))&(!Qs(i)||!b(a)||Af(e,t,n,r,i,a)))&&(!es(i)||pc(e,t,n,r,i,a));return e.Pop(i),o}const qf=[0],Jf=new Map,Yf=new Map;function Xf(){return st(qf[0]++)}function Zf(e,t){Jf.has(e)||Jf.set(e,new Map);let n=Jf.get(e);if(n.has(t))return n.get(t);let r=Xf();return n.set(t,r),r}function Qf(e,t,n,r){return e.UseUnevaluated()?j(`check_${n}`,[`context`,r]):j(`check_${n}`,[r])}function $f(e,t,n,r){let i=R(e,t,n,`value`);return t.UseUnevaluated()?Io(`check_${r}`,Mo([`context`,`value`],i)):Io(`check_${r}`,Mo([`value`],i))}function ep(){qf[0]=0,Jf.clear(),Yf.clear()}function tp(){return[...Yf.values()]}function np(e,t,n,r){let i=Zf(n,e.BaseURL().href),a=Qf(t,n,i,r);return Yf.has(i)?a:(Yf.set(i,``),Yf.set(i,$f(e,t,n,i)),a)}function rp(e,t){return b(t)&&!Ue(e)?t[e]:void 0}function ip(e,t){return e.reduce((e,t)=>rp(t,e),t)}function ap(e){if(w(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 op(e,t){return ip(ap(t),e)}function sp(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(w(r.pathname,i.pathname))return n.hash.startsWith(`#`)?up(e,t,n):e}function cp(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return w(r.href,i.href)?e:void 0}function lp(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return w(r.href,i.href)?e:void 0}function up(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 op(e,r)}function dp(e,t,n){if(xs(e)){let r=sp(e,t,n);if(!C(r))return r}if(os(e)){let r=cp(e,t,n);if(!C(r))return r}if(ms(e)){let r=lp(e,t,n);if(!C(r))return r}return up(e,t,n)}function fp(e,t,n){return e.reduce((e,r)=>{let i=mp(r,t,n);return C(i)?e:i},void 0)}function pp(e,t,n){return y(e).reduce((r,i)=>{let a=mp(e[i],t,n);return C(a)?r:a},void 0)}function mp(e,t,n){let r=ts(e)&&xs(e)?new URL(e.$id,t.href):t;if(ts(e)){let t=dp(e,r,n);if(!C(t))return t}if(S(e))return fp(e,r,n);if(b(e))return pp(e,r,n)}function hp(e,t){let n=new URL(`http://unknown/`),r=xs(e)?new URL(e.$id,n.href):n;return mp(e,r,new URL(t,r.href))}function gp(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?hp(t,n.$dynamicRef):hp(e,n.$dynamicRef);if(!C(i))return!ts(i)||!ms(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var _p=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)},vp,yp,bp,xp,Sp,Cp=class{constructor(e,t){vp.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){ts(e)&&(xs(e)&&(this.ids.push(e),_p(this,vp,`m`,yp).call(this,e)),os(e)&&this.anchors.push(e),Ws(e)&&this.recursiveAnchors.push(e),ms(e)&&this.dynamicAnchors.push(e))}Pop(e){ts(e)&&(xs(e)&&(this.ids.pop(),_p(this,vp,`m`,bp).call(this,e)),os(e)&&this.anchors.pop(),Ws(e)&&this.recursiveAnchors.pop(),ms(e)&&this.dynamicAnchors.pop())}Ref(e){return _p(this,vp,`m`,xp).call(this,e)??_p(this,vp,`m`,Sp).call(this,e)}RecursiveRef(e){return Ws(this.Base())?hp(this.recursiveAnchors[0],e.$recursiveRef):hp(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return gp(t,this.Base(),e,this.dynamicAnchors)}};vp=new WeakSet,yp=function e(t,n=!0){if(!ts(t))return;let r=t;if(!(!n&&xs(r))){!n&&ms(r)&&this.dynamicAnchors.push(r);for(let t of y(r))_p(this,vp,`m`,e).call(this,r[t],!1)}},bp=function e(t,n=!0){if(!ts(t))return;let r=t;if(!(!n&&xs(r))){!n&&ms(r)&&this.dynamicAnchors.pop();for(let t of y(r))_p(this,vp,`m`,e).call(this,r[t],!1)}},xp=function(e){return E(this.context,e.$ref)?this.context[e.$ref]:void 0},Sp=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?hp(this.Base(),e.$ref):hp(t,e.$ref)};function wp(e){return`${e.Functions().join(`;
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 ca(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)ca(n,t)}function la(e){let t=e.exceptionDetails;return t?t.exception?.description??t.text:null}function ua(e,t){let n=la(e);if(n!==null)throw Error(`${t}: ${n}`);return e.result?.value}function da(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 fa(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=pa(a,o);t.has(s)||t.set(s,e)}return t}function pa(e,t){return`${e.toLowerCase()}|${t.replace(/\s+/g,` `).trim()}`}function ma(e,t){let n=pa(e.role,e.name),r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)ma(n,t)}function ha(e){let t={role:Ee(e.role,`unknown`),name:Ee(e.name)},n=Ee(e.value);n!==``&&(t.value=n);let r=Ee(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>ha(e)).filter(e=>e.role!==`unknown`)),t}function ga(e){let t=e??{queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0};return{queueDepth:t.queueDepth,totalWaitMs:t.tabWaitMs+t.bridgeWaitMs,tabWaitMs:t.tabWaitMs,bridgeWaitMs:t.bridgeWaitMs,acquisitions:t.acquisitions}}var _a=class{tabLocks=new Map;bridgeLock=Promise.resolve();bridgeHold=null;bridgeWaiters=0;tabLockStats=new Map;getStats(e){if(e!==void 0)return ga(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 ga(t)}countersFor(e){let t=this.tabLockStats.get(e);return t||(t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0},this.tabLockStats.set(e,t)),t}liveOwner(){return this.bridgeHold?.owner}reentrantOwner(e){let t=this.bridgeHold;if(!(!t||e===null||t.targetId!==e))return t.owner}async holdTabLock(e,t,n){Ji(t,`starting a command on tab ${e}`);let r=this.countersFor(e);r.queueDepth+=1;let i;try{i=await this.acquireTabLock(e,r,t)}catch(e){throw--r.queueDepth,e}try{return await n(r)}finally{--r.queueDepth,i()}}async acquireTabLock(e,t,n){let r,i=new Promise(e=>{r=e}),a=this.tabLocks.get(e);this.tabLocks.set(e,i);let o=()=>{this.tabLocks.get(e)===i&&this.tabLocks.delete(e),r()};if(a!=null){let r=Date.now();try{await Zi(a,n,`queued for the lock on tab ${e}`)}catch(e){throw t.tabWaitMs+=Date.now()-r,a.then(o,o),e}t.tabWaitMs+=Date.now()-r}return o}async acquireBridgeLock(e){if(e?.owner!==void 0&&this.bridgeHold?.owner===e.owner)return()=>void 0;let t,n=new Promise(e=>{t=e}),r=this.bridgeLock,i=this.bridgeHold!==null||this.bridgeWaiters>0;if(this.bridgeLock=n,i){this.bridgeWaiters+=1;let t=Date.now();try{await r}finally{--this.bridgeWaiters}e?.counters&&(e.counters.bridgeWaitMs+=Date.now()-t)}let a={release:t,owner:Symbol(`bridge-hold`),targetId:e?.targetId??null};this.bridgeHold=a;let o=!1;return()=>{o||(o=!0,this.bridgeHold===a&&(this.bridgeHold=null),t())}}async runGlobal(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e),targetId:e});try{return await t()}finally{n()}}},va=class{overrides=new Map;get(e){return this.overrides.get(e)}set(e,t){this.overrides.set(e,t)}delete(e){this.overrides.delete(e)}has(e){return this.overrides.has(e)}get size(){return this.overrides.size}};const ya=_(`browser-api`),ba=[`Session with given id not found`,`Target closed`,`No session with given id`,`No tab attached for sessionId`];var xa=class extends Error{};function Sa(e){let t=e instanceof Error?e.message:String(e);return ba.some(e=>t.includes(e))}var Ca=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)}},wa=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;frames=new Qi;sessions=new na(32,(e,t)=>{ya.debug(`Evicting least-recently-used CDP session`,{targetId:e}),this.detachSession(e,t)});_listenedTransports=new Set;_sessionReplacedSubs=new Map;locks=new _a;viewports=new va;connection=new Ki;_onSessionChange;handleJavaScriptDialogOpening=e=>{this.dismissJavaScriptDialog(e)};async dismissJavaScriptDialog(e){let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.transportForSession(t).send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),ya.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){ya.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}handleExecutionContextCreated=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this.frames.for(t,`main`).set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.executionContextId;if(typeof n!=`number`)return;let r=this.frames.peek(t,`main`);if(r)for(let[e,t]of r)t===n&&r.delete(e)};handleExecutionContextsCleared=e=>{let t=this.eventSessionId(e);t&&this.frames.peek(t,`main`)?.clear()};eventSessionId(e){let t=e.sessionId;return typeof t==`string`?t:this.sessionId}handleDetachedFromTarget=e=>{let t=e.sessionId;if(typeof t!=`string`)return;let n=this.sessions.findBySessionId(t);n&&this.forgetSession(n[0],n[1])};handleTargetDestroyed=e=>{let t=e.targetId;if(typeof t!=`string`)return;let n=this.sessions.findByTargetOrLocalId(t)[0];n&&this.forgetSession(n[0],n[1])};constructor(e){this.client=e??new Pi,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 Ca)return e;let t=this._accountedTransports.get(e);return t||(t=new Ca(e,e=>this.noteApplied(e)),this._accountedTransports.set(e,t)),t}noteApplied(e){this.sessions.noteApplied(e)}createHarRecorder(e,t){return new ea(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;return this.locks.holdTabLock(e,r,async n=>{let i=this.sessions.pin(e);try{return n.acquisitions+=1,await this.runOnTab(e,t,r)}finally{i()}})}async runOnTab(e,t,n){try{return await this.attemptOnTab(e,t,n)}catch(r){if(r instanceof xa||!Sa(r))throw r;return ya.warn(`Stale CDP session — re-attaching and retrying once`,{targetId:e,error:r instanceof Error?r.message:String(r)}),this.invalidateSession(e),await this.attemptOnTab(e,t,n)}}async attemptOnTab(e,t,n){let r=await this.attachHandle(e,this.locks.reentrantOwner(e),n);Ji(n,`about to run a command on tab ${e}`);let i=r.sessionId,a=this.sessions.appliedCount(i);try{return await t(r)}catch(t){if(!Sa(t))throw t;let n=this.sessions.appliedCount(i)-a;if(n===0)throw t;this.invalidateSession(e);let r=t instanceof Error?t.message:String(t);throw ya.warn(`CDP session reset mid-command — not replaying`,{targetId:e,applied:n,reason:r}),new xa(`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 sa(this,e,r,this.accountedTransportFor(i?.transport??this.client),n)}handleFor(e,t){return new sa(this,e,t.sessionId,this.accountedTransportFor(t.transport))}getTabLockStats(e){return this.locks.getStats(e)}async runGlobal(e,t){return this.locks.runGlobal(e,t)}viewportOverride(e){return this.viewports.get(e)}recordViewportOverride(e,t){this.viewports.set(e,t)}frameContexts(e,t){return this.frames.for(e,t)}dropFrameContexts(e){this.frames.drop(e)}async reapplyViewportOverride(e,t){let n=this.viewports.get(e);if(n)try{await this.handleFor(e,t).applyViewportOverride(n)}catch(t){ya.warn(`Failed to re-apply viewport override on re-attach`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:e.kind,capabilities:e.capabilities}));return[...e,...r]}async connect(e){await this.connection.connect(this.client,e)}async reconnectIfNeeded(){await this.ensureConnected(),this.client!==this.localClient&&await this.ensureLocalConnected()}primeConnectOptions(e){this.connection.primeConnectOptions(e)}setCdpSupersededHandler(e){this.connection.setSupersededHandler(e)}setCdpBridgeRejectedHandler(e){this.connection.setBridgeRejectedHandler(e)}setCdpConnectFailureClassifier(e){this.connection.setConnectFailureClassifier(e)}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async openWindow(e,t={}){await this.ensureConnected(),await this.ensureLocalConnected(),Da(t);let n=t.focus!==!1,r={url:e||`about:blank`,newWindow:!0,background:!n};t.decorated===!1&&(r.decorated=!1);let i=t.state;i&&i!==`normal`?r.windowState=i:(t.width!==void 0&&(r.width=t.width),t.height!==void 0&&(r.height=t.height),t.left!==void 0&&(r.left=t.left),t.top!==void 0&&(r.top=t.top),i&&(r.windowState=i));let a=(await this.localClient.send(`Target.createTarget`,r)).targetId;if(typeof a!=`string`||!a)throw Error(`Target.createTarget did not return a usable targetId`);return a}async getWindowBounds(e){await this.ensureConnected();let t=ka((await(await this.transportForWindowOps(e)).send(`Browser.getWindowForTarget`,{targetId:Ea(e)})).bounds),n=await this.readDevicePixelRatio(e);return{...t,dpr:n}}async setWindowBounds(e,t){await this.ensureConnected(),Da(t);let n=await this.transportForWindowOps(e),r=Ea(e),i=await n.send(`Browser.getWindowForTarget`,{targetId:r}),a=i.windowId;if(typeof a!=`number`)throw Error(`Browser.getWindowForTarget did not return a windowId`);let o=ka(i.bounds),s=t.state;(t.left!==void 0||t.top!==void 0||t.width!==void 0||t.height!==void 0)&&o.state!==`normal`&&await n.send(`Browser.setWindowBounds`,{windowId:a,bounds:{windowState:`normal`}});let c={};s&&s!==`normal`?c.windowState=s:(t.left!==void 0&&(c.left=t.left),t.top!==void 0&&(c.top=t.top),t.width!==void 0&&(c.width=t.width),t.height!==void 0&&(c.height=t.height),s&&(c.windowState=s)),await n.send(`Browser.setWindowBounds`,{windowId:a,bounds:c});let l=ka((await n.send(`Browser.getWindowBounds`,{windowId:a})).bounds),u=await this.readDevicePixelRatio(e);return{...l,dpr:u}}async readDevicePixelRatio(e){try{let t=await this.withTab(e,e=>e.evaluate(`window.devicePixelRatio`,{awaitPromise:!1,returnByValue:!0}));return typeof t==`number`&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}async transportForWindowOps(e){if(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);return this.trayTargetProvider.createRemoteTransport(n,r)}return await this.ensureLocalConnected(),this.localClient}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.viewports.delete(e),await this.dropSession(e),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let e=this.trayTargetProvider.createRemoteTransport(n,r);try{await e.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}return}}await this.localClient.send(`Target.closeTarget`,{targetId:e})}disconnect(){this.clearSessions(),this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){return this.attachToPageOwned(e,this.locks.reentrantOwner(e))}async attachToPageOwned(e,t,n){let r=await this.locks.acquireBridgeLock({owner:t,targetId:e,counters:this.locks.countersFor(e)});try{await this.ensureConnected();let t=this.sessions.get(e);return t?(this.activateSession(e,t),t.sessionId):await(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)?this.attachRemoteTarget(e,n):this.attachLocalTarget(e,n))}finally{r()}}async selectTab(e){await this.withTab(e,async()=>void 0)}async bringTabToFront(e){await this.withTab(e,e=>e.bringToFront())}async attachRemoteTarget(e,t){let n=e.indexOf(`:`),r=e.substring(0,n),i=e.substring(n+1),a=this.trayTargetProvider?.createRemoteTransport?.(r,i);if(!a)throw Error(`No remote transport for target ${e}`);Ji(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),Ji(t,`about to enable Page on tray tab ${e}`),await a.send(`Page.enable`,{},o.sessionId),Ji(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(),Ji(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),Ji(t,`about to enable Page on tab ${e}`),await this.localClient.send(`Page.enable`,{},n.sessionId),Ji(t,`about to restore the viewport of tab ${e}`),await this.reapplyViewportOverride(e,n),this.notifySessionChange(e,n),n.sessionId}async detach(){let e=this.attachedTargetId;e&&(await this.dropSession(e),this.useLocalTransport())}async wakeCapture(e,t){let n=await this.locks.acquireBridgeLock({owner:this.locks.reentrantOwner(e.targetId),targetId:e.targetId});try{return await this.wakeCaptureLocked(e,t,this.locks.liveOwner())}finally{n()}}async wakeCaptureLocked(e,t,n){let r=e.targetId,i=await this.findFocusedLocalPage(r,n).catch(()=>null),a=await this.attachHandle(r,n);try{return await a.send(`Page.bringToFront`),await a.send(`Page.captureScreenshot`,t)}finally{if(i)try{await(await this.attachHandle(i,n)).send(`Page.bringToFront`),await this.attachToPageOwned(r,n)}catch{}}}async findFocusedLocalPage(e,t){let n=await this.listPages();for(let r of n)if(!(!r.targetId||r.targetId===e)&&!r.targetId.includes(`:`))try{if(await(await this.attachHandle(r.targetId,t)).evaluate(`document.hasFocus()`)===!0)return r.targetId}catch{}return null}async ensureLocalConnected(){await this.connection.ensureLocalConnected(this.localClient)}async ensureConnected(){await this.connection.ensureConnected({client:this.client,restoreLocalAfterRemoteDrop:()=>{this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null)},clearSessionsForTransport:e=>this.clearSessionsForTransport(e),getClient:()=>this.client})}transportForSession(e){return this.sessions.findBySessionId(e)?.[1].transport??this.client}addTransportListeners(e){this._listenedTransports.has(e)||(this._listenedTransports.add(e),e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.on(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.on(`Target.targetDestroyed`,this.handleTargetDestroyed))}releaseLifecycleTransport(e){e!==this.localClient&&this._listenedTransports.has(e)&&(this.sessions.anyOnTransport(e)||(this._listenedTransports.delete(e),e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.off(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.off(`Target.targetDestroyed`,this.handleTargetDestroyed)))}setClient(e){this.addTransportListeners(e),this.client=e}useLocalTransport(){let e=this.remoteTargetInfo;this.remoteTargetInfo=null,this.setClient(this.localClient),e&&(this.sessions.anyMatchingRemote(e.runtimeId,e.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.runtimeId,e.localTargetId))}rememberSession(e,t){this.addTransportListeners(t.transport),this.sessions.remember(e,t)}activateSession(e,t){t.remote?(this.setClient(t.transport),this.remoteTargetInfo={...t.remote}):this.client!==t.transport&&this.useLocalTransport(),this.sessionId=t.sessionId,this.attachedTargetId=e,this.sessions.touch(e,t)}notifySessionChange(e,t){let n=this.accountedTransportFor(t.transport);this._onSessionChange?.(t.sessionId,n,e);let r=this._sessionReplacedSubs.get(e);if(r)for(let i of[...r])try{i(t.sessionId,n,e)}catch(t){ya.warn(`session-replaced subscriber threw`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}forgetSession(e,t){this.unregisterSession(e),this.disposeSessionTransport(t)}unregisterSession(e){let t=this.sessions.get(e);t&&this.dropFrameContexts(t.sessionId),this.sessions.delete(e),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disposeSessionTransport(e){this.releaseLifecycleTransport(e.transport),e.remote&&(this.sessions.anyMatchingRemote(e.remote.runtimeId,e.remote.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.remote.runtimeId,e.remote.localTargetId))}async detachSession(e,t){this.unregisterSession(e);try{await t.transport.send(`Target.detachFromTarget`,{sessionId:t.sessionId})}catch{}finally{this.disposeSessionTransport(t)}}async dropSession(e){let t=this.sessions.get(e);if(!t){this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null);return}await this.detachSession(e,t)}invalidateSession(e){let t=this.sessions.get(e);t&&this.forgetSession(e,t)}clearSessionsForTransport(e){for(let[t,n]of this.sessions.snapshot())n.transport===e&&this.forgetSession(t,n)}clearSessions(){for(let[e,t]of this.sessions.snapshot())this.forgetSession(e,t);this.sessions.clear(),this.sessionId=null,this.attachedTargetId=null}};const Ta=new Set([`normal`,`minimized`,`maximized`,`fullscreen`]);function Ea(e){let t=e.indexOf(`:`);return t>=0?e.substring(t+1):e}function Da(e){let t=e.state;if(!(!t||t===`normal`)){if(!Ta.has(t))throw Error(`window state must be one of ${[...Ta].join(`|`)} (got ${JSON.stringify(t)})`);if(e.left!==void 0||e.top!==void 0||e.width!==void 0||e.height!==void 0)throw Error(`window state '${t}' cannot be combined with left/top/width/height (chrome.windows + CDP both reject the mix)`)}}function Oa(e){return typeof e==`object`&&!!e}function ka(e){let t=Oa(e)?e:{},n=t.windowState??t.state,r=typeof n==`string`&&Ta.has(n)?n:`normal`;return{left:Aa(t.left,0),top:Aa(t.top,0),width:Aa(t.width,0),height:Aa(t.height,0),state:r}}function Aa(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}const ja=_(`panel-rpc-cdp`);var Ma=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=>{ja.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,De)+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){ja.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=>{ja.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=>{ja.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function Na(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 Ma(e,r,i),t.set(a,o)),o},removeRemoteTransport(e,r){let i=n(e,r),a=t.get(i);a&&(a.disconnect(),t.delete(i))},async openRemoteTab(t,n){let r=e();if(!r)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let{targetId:i}=await r.call(`remote-open-tab`,{runtimeId:t,url:n});return i}}}function Pa(e){return`slicc_feature_flags_remote:${e}`}let Fa=null;function Ia(e,t){let n=Ra(t);Fa=e,Me(e,za(n,e)??{})}function La(e,t){if(!Fa||e!==void 0&&e!==Pa(Fa))return!1;let n=Ra(t);return Ae(Fa,za(n,Fa)??{}),!0}function Ra(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 za(e,t){try{let n=e?.getItem(Pa(t));return n?Ba(JSON.parse(n)):null}catch{return null}}function Ba(e){return!Va(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function Va(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ha=_(`stale-asset`),Ua=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Wa(e){return Ua.test(e)}let Ga=null;function Ka(e){if(!e){Ga=null;return}Ga=e}function qa(e=!1){if(!Ga||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Ga,replayTurn:e})}finally{t.close()}}function Ja(e){Wa(e instanceof Error?e.message:String(e))&&qa()}function Ya(e,t){return!e||e===t?!1:(Ha.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),qa(),!0)}var Xa=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new Ai;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 ji(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 Za(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 Qa(e){let t=Za(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var $a=class extends Xa{constructor(e){let t=Za(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 eo(e,t){return e.find(e=>e.folder===t)??e.find(e=>e.folder===`${t}-scoop`)??e.find(e=>e.name===t)}const to=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function no(e){return to.test(e)}function ro(e,t){return`(${e} && ${t})`}function A(e,t){return`(${e} || ${t})`}function io(e){return`!(${e})`}function ao(e){return`Array.isArray(${e})`}function oo(e){return`typeof ${e} === "bigint"`}function so(e){return`typeof ${e} === "boolean"`}function co(e){return`Number.isInteger(${e})`}function lo(e){return`${e} === null`}function uo(e){return`Number.isFinite(${e})`}function fo(e){return ro(po(e),io(ao(e)))}function po(e){return`typeof ${e} === "object" && ${e} !== null`}function mo(e){return`typeof ${e} === "string"`}function ho(e){return`typeof ${e} === "symbol"`}function go(e){return`${e} === undefined`}function _o(e){return`typeof ${e} === "function"`}function vo(e){return`Guard.IsConstructor(${e})`}function yo(e,t){return`${e} === ${t}`}function bo(e,t){return`${e} > ${t}`}function xo(e,t){return`${e} < ${t}`}function So(e,t){return`${e} <= ${t}`}function Co(e,t){return`${e} >= ${t}`}function wo(e,t){return`Guard.IsMinLength(${e}, ${t})`}function To(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Eo(e,t,n,r){return w(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 Do(e){return`Object.entries(${e})`}function Oo(e){return`Object.getOwnPropertyNames(${e})`}function ko(e,t){return w(t,`"__proto__"`)||w(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function Ao(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function jo(e){return`[${e.join(`, `)}]`}function Mo(e,t){return`((${e.join(`, `)}) => ${t})`}function j(e,t){return`${e}(${t.join(`, `)})`}function No(e,t){return`new ${e}(${t.join(`, `)})`}function M(e,t){return`${e}${no(t)?`.${t}`:`[${N(t)}]`}`}function N(e){return v(e)?JSON.stringify(e):`${e}`}function Po(e,t,n){return`(${e} ? ${t} : ${n})`}function Fo(e){return`{ ${e.join(`; `)}; }`}function Io(e,t){return`const ${e} = ${t}`}function Lo(e,t){return`if(${e}) { ${t} }`}function Ro(e){return`return ${e}`}function P(e){return w(e.length,0)?`true`:e.reduce((e,t)=>ro(e,t))}function zo(e){return w(e.length,0)?`false`:e.reduce((e,t)=>A(e,t))}function Bo(e){return`++${e}`}function Vo(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Ho=it;function Uo(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let Wo;function Go(){try{return qo(`null`)(),!0}catch{return!1}}function Ko(){return C(Wo)&&(Wo=Go()),Wo&&Zt().useAcceleration}function qo(...e){return new globalThis.Function(...e)}function Jo(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 Yo=Jo;function Xo(){return Yo}const Zo=[/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],Qo=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function $o(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!Qo.some(t=>t.test(e.errorMessage))&&Zo.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 es(e){return E(e,`~refine`)&&S(e[`~refine`])&&x(e[`~refine`],0,e=>b(e)&&E(e,`check`)&&E(e,`error`)&&Vt(e.check)&&Vt(e.error))}function ts(e){return b(e)&&!S(e)}function ns(e){return $t(e)}function F(e){return ts(e)||ns(e)}function rs(e){return E(e,`additionalItems`)&&F(e.additionalItems)}function is(e){return E(e,`additionalProperties`)&&F(e.additionalProperties)}function as(e){return E(e,`allOf`)&&S(e.allOf)&&e.allOf.every(e=>F(e))}function os(e){return E(e,`$anchor`)&&v(e.$anchor)}function ss(e){return E(e,`anyOf`)&&S(e.anyOf)&&e.anyOf.every(e=>F(e))}function cs(e){return E(e,`const`)}function ls(e){return E(e,`contains`)&&F(e.contains)}function us(e){return E(e,`default`)}function ds(e){return E(e,`dependencies`)&&b(e.dependencies)&&Object.values(e.dependencies).every(e=>F(e)||S(e)&&e.every(e=>v(e)))}function fs(e){return E(e,`dependentRequired`)&&b(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>S(e)&&e.every(e=>v(e)))}function ps(e){return E(e,`dependentSchemas`)&&b(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>F(e))}function ms(e){return E(e,`$dynamicAnchor`)&&v(e.$dynamicAnchor)}function hs(e){return E(e,`$dynamicRef`)&&v(e.$dynamicRef)}function gs(e){return E(e,`else`)&&F(e.else)}function _s(e){return E(e,`enum`)&&S(e.enum)}function vs(e){return E(e,`exclusiveMaximum`)&&(D(e.exclusiveMaximum)||zt(e.exclusiveMaximum))}function ys(e){return E(e,`exclusiveMinimum`)&&(D(e.exclusiveMinimum)||zt(e.exclusiveMinimum))}function bs(e){return E(e,`format`)&&v(e.format)}function xs(e){return E(e,`$id`)&&v(e.$id)}function Ss(e){return E(e,`if`)&&F(e.if)}function Cs(e){return E(e,`items`)&&(F(e.items)||S(e.items)&&e.items.every(e=>F(e)))}function ws(e){return Cs(e)&&S(e.items)}function Ts(e){return E(e,`maximum`)&&(D(e.maximum)||zt(e.maximum))}function Es(e){return E(e,`maxContains`)&&D(e.maxContains)}function Ds(e){return E(e,`maxItems`)&&D(e.maxItems)}function Os(e){return E(e,`maxLength`)&&D(e.maxLength)}function ks(e){return E(e,`maxProperties`)&&D(e.maxProperties)}function As(e){return E(e,`minimum`)&&(D(e.minimum)||zt(e.minimum))}function js(e){return E(e,`minContains`)&&D(e.minContains)}function Ms(e){return E(e,`minItems`)&&D(e.minItems)}function Ns(e){return E(e,`minLength`)&&D(e.minLength)}function Ps(e){return E(e,`minProperties`)&&D(e.minProperties)}function Fs(e){return E(e,`multipleOf`)&&(D(e.multipleOf)||zt(e.multipleOf))}function Is(e){return E(e,`not`)&&F(e.not)}function Ls(e){return E(e,`oneOf`)&&S(e.oneOf)&&e.oneOf.every(e=>F(e))}function Rs(e){return E(e,`pattern`)&&(v(e.pattern)||e.pattern instanceof RegExp)}function zs(e){return E(e,`patternProperties`)&&b(e.patternProperties)&&Object.values(e.patternProperties).every(e=>F(e))}function Bs(e){return E(e,`prefixItems`)&&S(e.prefixItems)&&e.prefixItems.every(e=>F(e))}function Vs(e){return E(e,`properties`)&&b(e.properties)&&Object.values(e.properties).every(e=>F(e))}function Hs(e){return E(e,`propertyNames`)&&(b(e.propertyNames)||F(e.propertyNames))}function Us(e){return E(e,`$recursiveAnchor`)&&$t(e.$recursiveAnchor)}function Ws(e){return Us(e)&&w(e.$recursiveAnchor,!0)}function Gs(e){return E(e,`$recursiveRef`)&&v(e.$recursiveRef)}function Ks(e){return E(e,`$ref`)&&v(e.$ref)}function qs(e){return E(e,`required`)&&S(e.required)&&e.required.every(e=>v(e))}function Js(e){return E(e,`then`)&&F(e.then)}function Ys(e){return E(e,`type`)&&(v(e.type)||S(e.type)&&e.type.every(e=>v(e)))}function Xs(e){return E(e,`uniqueItems`)&&$t(e.uniqueItems)}function Zs(e){return E(e,`unevaluatedItems`)&&F(e.unevaluatedItems)}function Qs(e){return E(e,`unevaluatedProperties`)&&F(e.unevaluatedProperties)}function $s(e){return Zs(e)||Qs(e)||y(e).some(t=>tc(e[t]))}function ec(e){return e.some(e=>tc(e))}function tc(e){return S(e)?ec(e):b(e)?$s(e):!1}function nc(e,t){return tc(t)||y(e).some(t=>tc(e[t]))}var rc=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return j(M(`context`,`Push`),[])}Pop(){return j(M(`context`,`Pop`),[])}AddIndex(e){return j(M(`context`,`AddIndex`),[e])}AddKey(e){return j(M(`context`,`AddKey`),[e])}Merge(e){return j(M(`context`,`Merge`),[e])}},ic=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}},ac=class extends ic{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},oc=class extends ac{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const sc={identifier:`External`,variables:[]};function cc(e){let t=`External[${sc.variables.length}]`;return sc.variables.push(e),t}function lc(){sc.variables=[]}function uc(){return{...sc}}function dc(e,t,n,r){return Eo(cc(n[`~refine`].map(e=>e)),N(0),[`refinement`,`_`],j(M(`refinement`,`check`),[r]))}function fc(e,t,n,r){return x(n[`~refine`],0,(e,t)=>e.check(r))}function pc(e,t,n,r,i,a){return Gt(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let mc=0;function I(){return`var_${mc++}`}function hc(e){return Cs(e)&&S(e.items)}function gc(e,t,n,r){if(!hc(n))return N(!0);let[i,a]=[I(),I()],o=Wf(e,t,n.additionalItems,i),s=xo(a,N(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?A(s,ro(o,c)):A(s,o);return j(M(r,`every`),[Mo([i,a],l)])}function _c(e,t,n,r){return!hc(n)||r.every((r,i)=>sn(i,n.items.length)||Gf(e,t,n.additionalItems,r)&&t.AddIndex(i))}function vc(e,t,n,r,i,a){return!hc(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return sn(o,i.items.length)||Kf(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function yc(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function bc(e){let t=[];return zs(e)&&t.push(...y(e.patternProperties)),Vs(e)&&t.push(...y(e.properties).map(yc)),w(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function xc(e,t,n){return qs(t)&&Vs(t)&&!zs(t)&&w(t.additionalProperties,!1)&&w(y(t.properties).length,t.required.length)}function Sc(e,t,n){return yo(M(j(M(`Object`,`getOwnPropertyNames`),[n]),`length`),N(t.required.length))}function Cc(e,t,n,r){let[i,a]=[I(),I()],o=cc(new RegExp(bc(n))),s=Wf(e,t,n.additionalProperties,`${r}[${i}]`),c=j(M(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?A(c,ro(s,l)):A(c,s);return Eo(Oo(r),N(0),[i,a],u)}function wc(e,t,n,r){return xc(t,n,r)?Sc(t,n,r):Cc(e,t,n,r)}function Tc(e,t,n,r){let i=new RegExp(bc(n));return x(y(r),0,(a,o)=>i.test(a)||Gf(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function Ec(e,t,n,r,i,a){let o=new RegExp(bc(i)),s=[];return Gt(y(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new oc,p=o.test(c)||Kf(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 Dc(e,t,n,r,i){let a=Io(`results`,`[]`),o=n.map((e,t)=>Io(`context_${t}`,No(`CheckContext`,[]))),s=n.map((n,i)=>Io(`condition_${i}`,j(Mo([`context`],R(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>Lo(`condition_${t}`,j(M(`results`,`push`),[`context_${t}`]))),l=Ro(ro(i,t.Merge(`results`)));return j(Mo([],Fo([a,...o,...s,...c,l])),[])}function Oc(e,t,n,r){return Dc(e,t,n.allOf,r,yo(M(`results`,`length`),N(n.allOf.length)))}function kc(e,t,n,r){return P(n.allOf.map(n=>R(e,t,n,r)))}function Ac(e,t,n,r){return t.UseUnevaluated()?Oc(e,t,n,r):kc(e,t,n,r)}function jc(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new ic;return z(e,i,n,r)?[...t,i]:t},[]);return w(i.length,n.allOf.length)&&t.Merge(i)}function Mc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new oc,u=B(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=w(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function Nc(e,t,n,r){return Dc(e,t,n.anyOf,r,bo(M(`results`,`length`),N(0)))}function Pc(e,t,n,r){return zo(n.anyOf.map(n=>R(e,t,n,r)))}function Fc(e,t,n,r){return t.UseUnevaluated()?Nc(e,t,n,r):Pc(e,t,n,r)}function Ic(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new ic;return z(e,i,n,r)?[...t,i]:t},[]);return At(i.length,0)&&t.Merge(i)}function Lc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new oc,l=B(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=At(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 Rc(e,t,n,r){return N(!!n)}function zc(e,t,n,r){return n}function Bc(e,t,n,r,i,a){return zc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function Vc(e,t,n,r){return It(n.const)?yo(r,N(n.const)):Ao(r,cc(n.const))}function Hc(e,t,n,r){return It(n.const)?w(r,n.const):Ot(r,n.const)}function Uc(e,t,n,r,i,a){return Hc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Wc(e){return!(js(e)&&w(e.minContains,0))}function Gc(e,t,n,r){if(!Wc(n))return N(!0);let i=I();return ro(io(yo(M(r,`length`),N(0))),j(M(r,`some`),[Mo([i],R(e,t,n.contains,i))]))}function Kc(e,t,n,r){return!Wc(n)||!w(r.length,0)&&r.some(r=>z(e,t,n.contains,r))}function qc(e,t,n,r,i,a){return Kc(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Jc(e,t,n,r){return A(yo(M(Oo(r),`length`),N(0)),P(T(n.dependencies).map(([n,i])=>{let a=io(ko(r,N(n))),o=R(e,t,i,r);return A(a,S(i)?(e=>P(e.map(e=>ko(r,N(e)))))(i):o)})))}function Yc(e,t,n,r){let i=w(y(r).length,0),a=x(T(n.dependencies),0,([n,i])=>!E(r,n)||(S(i)?i.every(e=>E(r,e)):z(e,t,i,r)));return i||a}function Xc(e,t,n,r,i,a){let o=w(y(a).length,0),s=Gt(T(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!E(a,i)||(S(o)?o.every(e=>E(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):B(e,t,s,r,o,a))});return o||s}function Zc(e,t,n,r){return A(yo(M(Oo(r),`length`),N(0)),P(T(n.dependentRequired).map(([e,t])=>A(io(ko(r,N(e))),P(t.map(e=>ko(r,N(e))))))))}function Qc(e,t,n,r){let i=w(y(r).length,0),a=x(T(n.dependentRequired),0,([e,t])=>!E(r,e)||t.every(e=>E(r,e)));return i||a}function $c(e,t,n,r,i,a){let o=w(y(a).length,0),s=Gt(T(i.dependentRequired),0,([e,i])=>!E(a,e)||Gt(i,0,o=>E(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function el(e,t,n,r){return A(yo(M(Oo(r),`length`),N(0)),P(T(n.dependentSchemas).map(([n,i])=>A(io(ko(r,N(n))),R(e,t,i,r)))))}function tl(e,t,n,r){let i=w(y(r).length,0),a=x(T(n.dependentSchemas),0,([n,i])=>!E(r,n)||z(e,t,i,r));return i||a}function nl(e,t,n,r,i,a){let o=w(y(a).length,0),s=Gt(T(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!E(a,i)||B(e,t,s,r,o,a)});return o||s}function rl(e,t,n,r){return np(e,t,e.DynamicRef(n)??!1,r)}function il(e,t,n,r){let i=e.DynamicRef(n)??!1;return F(i)&&z(e,t,i,r)}function al(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return F(o)&&B(e,t,`#`,r,o,a)}function ol(e,t,n,r){return zo(n.enum.map(e=>It(e)?yo(r,N(e)):Ao(r,cc(e))))}function sl(e,t,n,r){return n.enum.some(e=>It(e)?w(r,e):Ot(r,e))}function cl(e,t,n,r,i,a){return sl(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function ll(e,t,n,r){return xo(r,N(n.exclusiveMaximum))}function ul(e,t,n,r){return sn(r,n.exclusiveMaximum)}function dl(e,t,n,r,i,a){return ul(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function fl(e,t,n,r){return bo(r,N(n.exclusiveMinimum))}function pl(e,t,n,r){return At(r,n.exclusiveMinimum)}function ml(e,t,n,r,i,a){return pl(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const hl=[0,31,28,31,30,31,30,31,31,30,31,30,31],gl=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function _l(e){return e%4==0&&(e%100!=0||e%400==0)}function vl(e){let t=gl.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&&_l(n)?29:hl[r])}const yl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function bl(e,t=!0){let n=yl.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 xl(e,t=!0){let n=e.split(/T/i);return n.length===2&&vl(n[0])&&bl(n[1],t)}const Sl=/^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 Cl(e){return Sl.test(e)}const wl=/^(?!.*\.\.)[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 Tl(e){return wl.test(e)}function El(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 Dl(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)Qe();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=El(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function Ol(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function kl(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function Al(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function jl(e){return Ol(e)||kl(e)||Al(e)}const Ml=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),Nl=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 Pl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function Fl(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function Il(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function Ll(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function Rl(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function zl(e){return e>=1632&&e<=1641}function Bl(e){return e>=1776&&e<=1785}function Vl(e){return Nl.has(e)}function Hl(e){if(e.length===0)return Qe();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||jl(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(Ml.has(n))return!1;(Il(n)||Ll(n)||Rl(n))&&(r=!0),zl(n)&&(i=!0),Bl(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||!Pl(s))return!1;break;case 1523:case 1524:if(o===void 0||!Fl(o))return!1;break;case 8204:if(o===void 0||o<128&&!Vl(o))return!1;break;case 8205:if(o===void 0||!Vl(o))return!1}}return!(e.includes(`・`)&&!r||i&&a)}function Ul(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 Wl(e){return e.toLowerCase().startsWith(`xn--`)}function Gl(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=Dl(t);return n?Hl(n):!1}catch{return!1}}function Kl(e){return e.length===0||e.length>63?!1:Wl(e)?Gl(e):Hl(e)}function ql(e){return e.length===0||e.length>63?!1:Wl(e)?Gl(e):Ul(e)}function Jl(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!ql(t))return!1;return!0}const Yl=/^(?!.*\.\.)[\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 Xl(e){return Yl.test(e)}function Zl(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(!Kl(e))return!1;return!0}function Ql(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 $l(e){return Ql(e,0,e.length)}function eu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function tu(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&&eu(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!Ql(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 nu(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function ru(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))?nu(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:nu(e)}function iu(e){try{return new URL(e),!0}catch{return!1}}const au=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function ou(e){return au.test(e)}const su=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function cu(e){return su.test(e)}function lu(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const uu=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function du(e){return uu.test(e)}const fu=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function pu(e){return fu.test(e)}const mu=/^(?:(?:[^\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 hu(e){return mu.test(e)}function gu(e){return e>=97&&e<=122||e>=65&&e<=90}function _u(e){return gu(e)||e>=48&&e<=57}function vu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function yu(e){return _u(e)||e===43||e===45||e===46}function bu(e){return _u(e)||e===45||e===46||e===95||e===126}function xu(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 Su(e){return bu(e)||xu(e)||e===58||e===64}function Cu(e){let t=e.length;if(t===0||!gu(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!yu(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||!vu(e.charCodeAt(t+1))||!vu(e.charCodeAt(t+2)))return!1;t+=2}else if(!bu(n)&&!xu(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&&!bu(t)&&!xu(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||!vu(e.charCodeAt(n+1))||!vu(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(Su(r)||r===47||r===63||r===35))return!1;n++}return!0}const wu=/^(?: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 Tu(e){return wu.test(e)}const Eu=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Du(e){return Eu.test(e)}const L=new Map;function Ou(){L.clear()}function ku(){return[...L.entries()]}function Au(e,t){L.set(e,t)}function ju(e){return L.has(e)}function Mu(e){return L.get(e)}function Nu(e,t){return L.get(e)?.(t)??!0}function Pu(){Ou(),L.set(`date-time`,xl),L.set(`date`,vl),L.set(`duration`,Cl),L.set(`email`,Tl),L.set(`hostname`,Jl),L.set(`idn-email`,Xl),L.set(`idn-hostname`,Zl),L.set(`ipv4`,$l),L.set(`ipv6`,tu),L.set(`iri-reference`,ru),L.set(`iri`,iu),L.set(`json-pointer-uri-fragment`,ou),L.set(`json-pointer`,cu),L.set(`regex`,lu),L.set(`relative-json-pointer`,du),L.set(`time`,bl),L.set(`uri-reference`,pu),L.set(`uri-template`,hu),L.set(`uri`,Cu),L.set(`url`,Tu),L.set(`uuid`,Du)}Pu();var Fu=e({Clear:()=>Ou,Entries:()=>ku,Get:()=>Mu,Has:()=>ju,IsDate:()=>vl,IsDateTime:()=>xl,IsDuration:()=>Cl,IsEmail:()=>Tl,IsHostname:()=>Jl,IsIPv4:()=>$l,IsIPv6:()=>tu,IsIdnEmail:()=>Xl,IsIdnHostname:()=>Zl,IsIri:()=>iu,IsIriReference:()=>ru,IsJsonPointer:()=>cu,IsJsonPointerUriFragment:()=>ou,IsRegex:()=>lu,IsRelativeJsonPointer:()=>du,IsTime:()=>bl,IsUri:()=>Cu,IsUriReference:()=>pu,IsUriTemplate:()=>hu,IsUrl:()=>Tu,IsUuid:()=>Du,Reset:()=>Pu,Set:()=>Au,Test:()=>Nu});function Iu(e,t,n,r){return j(M(`Format`,`Test`),[N(n.format),r])}function Lu(e,t,n,r){return Nu(n.format,r)}function Ru(e,t,n,r,i,a){return Lu(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function zu(e,t,n,r){let i=!Js(n)||n.then,a=!gs(n)||n.else;return Po(R(e,t,n.if,r),R(e,t,i,r),R(e,t,a,r))}function Bu(e,t,n,r){let i=!Js(n)||n.then,a=!gs(n)||n.else;return z(e,t,n.if,r)?z(e,t,i,r):z(e,t,a,r)}function Vu(e,t,n,r,i,a){let o=!Js(i)||i.then,s=!gs(i)||i.else,c=new oc,l=B(e,c,`${n}/if`,r,i.if,a)?B(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):B(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 Hu(e,t,n,r){return P(n.items.map((n,i)=>{let a=So(M(r,`length`),N(i)),o=Wf(e,t,n,`${r}[${i}]`),s=t.AddIndex(N(i));return A(a,t.UseUnevaluated()?ro(o,s):o)}))}function Uu(e,t,n,r){return x(n.items,0,(n,i)=>tn(r.length,i)||Gf(e,t,n,r[i])&&t.AddIndex(i))}function Wu(e,t,n,r,i,a){return Gt(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return tn(a.length,o)||Kf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Gu(e,t,n,r){let i=Bs(n)?n.prefixItems.length:0,a=Wf(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?ro(a,o):a;return Eo(r,N(i),[`element`,`index`],s)}function Ku(e,t,n,r){let i=Bs(n)?n.prefixItems.length:0;return x(r,i,(r,i)=>Gf(e,t,n.items,r)&&t.AddIndex(i))}function qu(e,t,n,r,i,a){let o=Bs(i)?i.prefixItems.length:0;return Gt(a,o,(a,o)=>Kf(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function Ju(e,t,n,r){return ws(n)?Hu(e,t,n,r):Gu(e,t,n,r)}function Yu(e,t,n,r){return ws(n)?Uu(e,t,n,r):Ku(e,t,n,r)}function Xu(e,t,n,r,i,a){return ws(i)?Wu(e,t,n,r,i,a):qu(e,t,n,r,i,a)}function Zu(e){return ls(e)}function Qu(e,t,n,r){if(!Zu(n))return N(!0);let[i,a]=[I(),I()];return So(j(M(r,`reduce`),[Mo([i,a],Po(R(e,t,n.contains,a),Bo(i),i)),N(0)]),N(n.maxContains))}function $u(e,t,n,r){if(!Zu(n))return!0;let i=r.reduce((r,i)=>z(e,t,n.contains,i)?++r:r,0);return tn(i,n.maxContains)}function ed(e,t,n,r,i,a){let o=js(i)?i.minContains:1;return $u(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function td(e,t,n,r){return So(r,N(n.maximum))}function nd(e,t,n,r){return tn(r,n.maximum)}function rd(e,t,n,r,i,a){return nd(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function id(e,t,n,r){return So(M(r,`length`),N(n.maxItems))}function ad(e,t,n,r){return tn(r.length,n.maxItems)}function od(e,t,n,r,i,a){return ad(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function sd(e,t,n,r){return To(r,N(n.maxLength))}function cd(e,t,n,r){return St(r,n.maxLength)}function ld(e,t,n,r,i,a){return cd(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function ud(e,t,n,r){return So(M(Oo(r),`length`),N(n.maxProperties))}function dd(e,t,n,r){return tn(y(r).length,n.maxProperties)}function fd(e,t,n,r,i,a){return dd(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function pd(e){return ls(e)}function md(e,t,n,r){if(!pd(n))return N(!0);let[i,a]=[I(),I()];return Co(j(M(r,`reduce`),[Mo([i,a],Po(R(e,t,n.contains,a),Bo(i),i)),N(0)]),N(n.minContains))}function hd(e,t,n,r){if(!pd(n))return!0;let i=r.reduce((r,i)=>z(e,t,n.contains,i)?++r:r,0);return Mt(i,n.minContains)}function gd(e,t,n,r,i,a){return hd(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function _d(e,t,n,r){return Co(r,N(n.minimum))}function vd(e,t,n,r){return Mt(r,n.minimum)}function yd(e,t,n,r,i,a){return vd(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function bd(e,t,n,r){return Co(M(r,`length`),N(n.minItems))}function xd(e,t,n,r){return Mt(r.length,n.minItems)}function Sd(e,t,n,r,i,a){return xd(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function Cd(e,t,n,r){return wo(r,N(n.minLength))}function wd(e,t,n,r){return an(r,n.minLength)}function Td(e,t,n,r,i,a){return wd(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function Ed(e,t,n,r){return Co(M(Oo(r),`length`),N(n.minProperties))}function Dd(e,t,n,r){return Mt(y(r).length,n.minProperties)}function Od(e,t,n,r,i,a){return Dd(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function kd(e,t,n,r){return Vo(r,N(n.multipleOf))}function Ad(e,t,n,r){return ut(r,n.multipleOf)}function jd(e,t,n,r,i,a){return Ad(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function Md(e,t,n,r){return Dc(e,t,[n.not],r,io(yo(M(`results`,`length`),N(1))))}function Nd(e,t,n,r){return io(R(e,t,n.not,r))}function Pd(e,t,n,r){return t.UseUnevaluated()?Md(e,t,n,r):Nd(e,t,n,r)}function Fd(e,t,n,r){let i=new ic;return!z(e,i,n.not,r)&&t.Merge([i])}function Id(e,t,n,r,i,a){return Fd(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function Ld(e,t,n,r){return Dc(e,t,n.oneOf,r,yo(M(`results`,`length`),N(1)))}function Rd(e,t,n,r){return yo(j(M(jo(n.oneOf.map(n=>R(e,t,n,r))),`reduce`),[Mo([`count`,`result`],Po(yo(`result`,N(!0)),Bo(`count`),`count`)),N(0)]),N(1))}function zd(e,t,n,r){return t.UseUnevaluated()?Ld(e,t,n,r):Rd(e,t,n,r)}function Bd(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new ic;return z(e,i,n,r)?[...t,i]:t},[]);return w(i.length,1)&&t.Merge(i)}function Vd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new oc,u=B(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=w(c.length,1)&&t.Merge(c);return!l&&w(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 Hd(e,t,n,r){return j(M(cc(v(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function Ud(e,t,n,r){return(v(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function Wd(e,t,n,r,i,a){return Ud(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function Gd(e,t,n,r){return P(T(n.patternProperties).map(([n,i])=>{let[a,o]=[I(),I()],s=io(j(M(cc(new RegExp(n,`u`)),`test`),[a])),c=Wf(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?A(s,ro(c,l)):A(s,c);return Eo(Do(r),N(0),[`[${a}, ${o}]`,`_`],u)}))}function Kd(e,t,n,r){return x(T(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return x(T(r),0,([n,r])=>!a.test(n)||Gf(e,t,i,r)&&t.AddKey(n))})}function qd(e,t,n,r,i,a){return Gt(T(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return Gt(T(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||Kf(e,t,s,a,o,i)&&t.AddKey(n)})})}function Jd(e,t,n,r){return P(n.prefixItems.map((n,i)=>{let a=So(M(r,`length`),N(i)),o=Wf(e,t,n,`${r}[${i}]`),s=t.AddIndex(N(i));return A(a,t.UseUnevaluated()?ro(o,s):o)}))}function Yd(e,t,n,r){return w(r.length,0)||x(n.prefixItems,0,(n,i)=>tn(r.length,i)||Gf(e,t,n,r[i])&&t.AddIndex(i))}function Xd(e,t,n,r,i,a){return w(a.length,0)||Gt(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return tn(a.length,o)||Kf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Zd(e,t){return e.includes(t)||Zt().exactOptionalPropertyTypes}function Qd(e,t){return go(M(e,t))}function $d(e,t){return C(e[t])}function ef(e,t,n,r){let i=qs(n)?n.required:[];return P(T(n.properties).map(([n,a])=>{let o=io(ko(r,N(n))),s=Wf(e,t,a,M(r,n)),c=t.AddKey(N(n)),l=t.UseUnevaluated()?ro(s,c):s,u=i.includes(n)?l:A(o,l);return Zd(i,n)?u:A(Qd(r,n),u)}))}function tf(e,t,n,r){let i=qs(n)?n.required:[];return x(T(n.properties),0,([n,a])=>{let o=!E(r,n)||Gf(e,t,a,r[n])&&t.AddKey(n);return Zd(i,n)?o:$d(r,n)||o})}function nf(e,t,n,r,i,a){let o=qs(i)?i.required:[];return Gt(T(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!E(a,i)||Kf(e,t,c,l,s,a[i])&&t.AddKey(i);return Zd(o,i)?u():$d(a,i)||u()})}function rf(e,t,n,r){let[i,a]=[I(),I()];return Eo(Oo(r),N(0),[i,a],R(e,t,n.propertyNames,i))}function af(e,t,n,r){return x(y(r),0,(r,i)=>z(e,t,n.propertyNames,r))}function of(e,t,n,r,i,a){let o=[];return Gt(y(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=B(e,new oc,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function sf(e,t,n,r){return np(e,t,e.RecursiveRef(n)??!1,r)}function cf(e,t,n,r){let i=e.RecursiveRef(n)??!1;return F(i)&&z(e,t,i,r)}function lf(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return F(o)&&B(e,t,`#`,r,o,a)}function uf(e,t,n,r){let i=Mo([`context`,`value`],np(e,t,n,`value`));return j(Mo([`context`,`value`],Fo([Io(`nextContext`,No(`CheckContext`,[])),Io(`result`,j(i,[`nextContext`,`value`])),Lo(`result`,t.Merge(`[nextContext]`)),Ro(`result`)])),[`context`,r])}function df(e,t,n,r){return np(e,t,n,r)}function ff(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?uf(e,t,i,r):df(e,t,i,r)}function pf(e,t,n,r){let i=e.Ref(n)??!1,a=new ic,o=F(i)&&z(e,a,i,r);return o&&t.Merge([a]),o}function mf(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new oc,c=F(o)&&B(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function hf(e,t,n,r){return P(n.required.map(e=>ko(r,N(e))))}function gf(e,t,n,r){return x(n.required,0,e=>E(r,e))}function _f(e,t,n,r,i,a){let o=[];return Gt(i.required,0,e=>{let t=E(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function vf(e,t,n,r){return w(n,`object`)?fo(r):w(n,`array`)?ao(r):w(n,`boolean`)?so(r):w(n,`integer`)?co(r):w(n,`number`)?uo(r):w(n,`null`)?lo(r):w(n,`string`)?mo(r):w(n,`bigint`)?oo(r):w(n,`constructor`)?vo(r):w(n,`function`)?_o(r):w(n,`symbol`)?ho(r):w(n,`undefined`)||w(n,`void`)?go(r):N(!0)}function yf(e,t,n,r,i){return w(n,`object`)?Ye(i):w(n,`array`)?S(i):w(n,`boolean`)?$t(i):w(n,`integer`)?yt(i):w(n,`number`)?D(i):w(n,`null`)?Ke(i):w(n,`string`)?v(i):w(n,`bigint`)?zt(i):w(n,`constructor`)?Tt(i):w(n,`function`)?Vt(i):w(n,`symbol`)?ot(i):w(n,`undefined`)?C(i):!w(n,`void`)||C(i)}function bf(e,t,n,r){return zo(n.map(n=>vf(e,t,n,r)))}function xf(e,t,n,r,i){return n.some(n=>yf(e,t,n,r,i))}function Sf(e,t,n,r){return S(n.type)?bf(e,t,n.type,r):vf(e,t,n.type,r)}function Cf(e,t,n,r){return S(n.type)?xf(e,t,n.type,n,r):yf(e,t,n.type,n,r)}function wf(e,t,n,r,i,a){return(S(i.type)?xf(e,t,i.type,i,a):yf(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function Tf(e,t,n,r){let[i,a]=[I(),I()],o=j(M(`context`,`GetIndices`),[]),s=j(M(`indices`,`has`),[i]),c=R(e,t,n.unevaluatedItems,a),l=j(M(`context`,`AddIndex`),[i]),u=Eo(r,N(0),[a,i],ro(A(s,c),l));return j(Mo([`context`],Fo([Io(`indices`,o),Ro(u)])),[`context`])}function Ef(e,t,n,r){let i=t.GetIndices();return x(r,0,(r,a)=>(i.has(a)||z(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function Df(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return Gt(a,0,(a,c)=>{let l=new oc,u=(o.has(c)||B(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 Of(e,t,n,r){let[i,a]=[I(),I()],o=j(M(`context`,`GetKeys`),[]),s=j(M(`keys`,`has`),[i]),c=j(M(`context`,`AddKey`),[i]),l=R(e,t,n.unevaluatedProperties,a),u=Eo(Do(r),N(0),[`[${i}, ${a}]`,`_`],A(s,ro(l,c)));return j(Mo([`context`],Fo([Io(`keys`,o),Ro(u)])),[`context`])}function kf(e,t,n,r){let i=t.GetKeys();return x(T(r),0,([r,a])=>i.has(r)||z(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function Af(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return Gt(T(a),0,([a,c])=>{let l=new oc,u=o.has(a)||B(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 jf(e){return!w(e.uniqueItems,!1)}function Mf(e,t,n,r){return jf(n)?yo(M(No(`Set`,[j(M(r,`map`),[M(`Hashing`,`Hash`)])]),`size`),M(r,`length`)):N(!0)}function Nf(e,t,n,r){if(!jf(n))return!0;let i=new Set(r.map(st)).size,a=r.length;return w(i,a)}function Pf(e,t,n,r,i,a){if(!jf(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=st(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return w(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function Ff(e,t){return Ys(e)&&(S(e.type)&&At(e.type.length,0)&&x(e.type,0,e=>w(e,t))||w(e.type,t))}function If(e){return Ff(e,`object`)}function Lf(e){return ts(e)&&(is(e)||ds(e)||fs(e)||ps(e)||Vs(e)||zs(e)||Hs(e)||Ps(e)||ks(e)||qs(e)||Qs(e))}function Rf(e){return Ff(e,`array`)}function zf(e){return ts(e)&&(rs(e)||Cs(e)||ls(e)||Es(e)||Ds(e)||js(e)||Ms(e)||Bs(e)||Zs(e)||Xs(e))}function Bf(e){return Ff(e,`string`)}function Vf(e){return ts(e)&&(Ns(e)||Os(e)||bs(e)||Rs(e))}function Hf(e){return Ff(e,`number`)||Ff(e,`bigint`)}function Uf(e){return ts(e)&&(As(e)||Ts(e)||vs(e)||ys(e)||Fs(e))}function Wf(e,t,n,r){return t.UseUnevaluated()?ro(ro(t.Push(),R(e,t,n,r)),t.Pop()):R(e,t,n,r)}function R(e,t,n,r){e.Push(n);let i=[];if(ns(n))return Rc(e,t,n,r);if(Ys(n)&&i.push(Sf(e,t,n,r)),Lf(n)){let a=[];qs(n)&&a.push(hf(e,t,n,r)),is(n)&&a.push(wc(e,t,n,r)),ds(n)&&a.push(Jc(e,t,n,r)),fs(n)&&a.push(Zc(e,t,n,r)),ps(n)&&a.push(el(e,t,n,r)),zs(n)&&a.push(Gd(e,t,n,r)),Vs(n)&&a.push(ef(e,t,n,r)),Hs(n)&&a.push(rf(e,t,n,r)),Ps(n)&&a.push(Ed(e,t,n,r)),ks(n)&&a.push(ud(e,t,n,r));let o=P(a),s=A(io(fo(r)),o);i.push(If(n)?o:s)}if(zf(n)){let a=[];rs(n)&&a.push(gc(e,t,n,r)),ls(n)&&a.push(Gc(e,t,n,r)),Cs(n)&&a.push(Ju(e,t,n,r)),Es(n)&&a.push(Qu(e,t,n,r)),Ds(n)&&a.push(id(e,t,n,r)),js(n)&&a.push(md(e,t,n,r)),Ms(n)&&a.push(bd(e,t,n,r)),Bs(n)&&a.push(Jd(e,t,n,r)),Xs(n)&&a.push(Mf(e,t,n,r));let o=P(a),s=A(io(ao(r)),o);i.push(Rf(n)?o:s)}if(Vf(n)){let a=[];Os(n)&&a.push(sd(e,t,n,r)),Ns(n)&&a.push(Cd(e,t,n,r)),bs(n)&&a.push(Iu(e,t,n,r)),Rs(n)&&a.push(Hd(e,t,n,r));let o=P(a),s=A(io(mo(r)),o);i.push(Bf(n)?o:s)}if(Uf(n)){let a=[];vs(n)&&a.push(ll(e,t,n,r)),ys(n)&&a.push(fl(e,t,n,r)),Ts(n)&&a.push(td(e,t,n,r)),As(n)&&a.push(_d(e,t,n,r)),Fs(n)&&a.push(kd(e,t,n,r));let o=P(a),s=A(io(A(uo(r),oo(r))),o);i.push(Hf(n)?o:s)}Ks(n)&&i.push(ff(e,t,n,r)),Gs(n)&&i.push(sf(e,t,n,r)),hs(n)&&i.push(rl(e,t,n,r)),cs(n)&&i.push(Vc(e,t,n,r)),_s(n)&&i.push(ol(e,t,n,r)),Ss(n)&&i.push(zu(e,t,n,r)),Is(n)&&i.push(Pd(e,t,n,r)),as(n)&&i.push(Ac(e,t,n,r)),ss(n)&&i.push(Fc(e,t,n,r)),Ls(n)&&i.push(zd(e,t,n,r)),Zs(n)&&i.push(A(io(ao(r)),Tf(e,t,n,r))),Qs(n)&&i.push(A(io(po(r)),Of(e,t,n,r))),es(n)&&i.push(dc(e,t,n,r));let a=P(i);return e.Pop(n),a}function Gf(e,t,n,r){return t.Push()&&z(e,t,n,r)&&t.Pop()}function z(e,t,n,r){e.Push(n);let i=ns(n)?zc(e,t,n,r):(!Ys(n)||Cf(e,t,n,r))&&(!(b(r)&&!S(r))||(!qs(n)||gf(e,t,n,r))&&(!is(n)||Tc(e,t,n,r))&&(!ds(n)||Yc(e,t,n,r))&&(!fs(n)||Qc(e,t,n,r))&&(!ps(n)||tl(e,t,n,r))&&(!zs(n)||Kd(e,t,n,r))&&(!Vs(n)||tf(e,t,n,r))&&(!Hs(n)||af(e,t,n,r))&&(!Ps(n)||Dd(e,t,n,r))&&(!ks(n)||dd(e,t,n,r)))&&(!S(r)||(!rs(n)||_c(e,t,n,r))&&(!ls(n)||Kc(e,t,n,r))&&(!Cs(n)||Yu(e,t,n,r))&&(!Es(n)||$u(e,t,n,r))&&(!Ds(n)||ad(e,t,n,r))&&(!js(n)||hd(e,t,n,r))&&(!Ms(n)||xd(e,t,n,r))&&(!Bs(n)||Yd(e,t,n,r))&&(!Xs(n)||Nf(e,t,n,r)))&&(!v(r)||(!Os(n)||cd(e,t,n,r))&&(!Ns(n)||wd(e,t,n,r))&&(!bs(n)||Lu(e,t,n,r))&&(!Rs(n)||Ud(e,t,n,r)))&&(!(D(r)||zt(r))||(!vs(n)||ul(e,t,n,r))&&(!ys(n)||pl(e,t,n,r))&&(!Ts(n)||nd(e,t,n,r))&&(!As(n)||vd(e,t,n,r))&&(!Fs(n)||Ad(e,t,n,r)))&&(!Ks(n)||pf(e,t,n,r))&&(!Gs(n)||cf(e,t,n,r))&&(!hs(n)||il(e,t,n,r))&&(!cs(n)||Hc(e,t,n,r))&&(!_s(n)||sl(e,t,n,r))&&(!Ss(n)||Bu(e,t,n,r))&&(!Is(n)||Fd(e,t,n,r))&&(!as(n)||jc(e,t,n,r))&&(!ss(n)||Ic(e,t,n,r))&&(!Ls(n)||Bd(e,t,n,r))&&(!Zs(n)||!S(r)||Ef(e,t,n,r))&&(!Qs(n)||!b(r)||kf(e,t,n,r))&&(!es(n)||fc(e,t,n,r));return e.Pop(n),i}function Kf(e,t,n,r,i,a){return t.Push()&&B(e,t,n,r,i,a)&&t.Pop()}function B(e,t,n,r,i,a){e.Push(i);let o=ns(i)?Bc(e,t,n,r,i,a):!!((!Ys(i)||wf(e,t,n,r,i,a))&+(!(b(a)&&!S(a))||!!((!qs(i)||_f(e,t,n,r,i,a))&+(!is(i)||Ec(e,t,n,r,i,a))&(!ds(i)||Xc(e,t,n,r,i,a))&(!fs(i)||$c(e,t,n,r,i,a))&(!ps(i)||nl(e,t,n,r,i,a))&(!zs(i)||qd(e,t,n,r,i,a))&(!Vs(i)||nf(e,t,n,r,i,a))&(!Hs(i)||of(e,t,n,r,i,a))&(!Ps(i)||Od(e,t,n,r,i,a))&(!ks(i)||fd(e,t,n,r,i,a))))&(!S(a)||!!((!rs(i)||vc(e,t,n,r,i,a))&+(!ls(i)||qc(e,t,n,r,i,a))&(!Cs(i)||Xu(e,t,n,r,i,a))&(!Es(i)||ed(e,t,n,r,i,a))&(!Ds(i)||od(e,t,n,r,i,a))&(!js(i)||gd(e,t,n,r,i,a))&(!Ms(i)||Sd(e,t,n,r,i,a))&(!Bs(i)||Xd(e,t,n,r,i,a))&(!Xs(i)||Pf(e,t,n,r,i,a))))&(!v(a)||!!((!Os(i)||ld(e,t,n,r,i,a))&+(!Ns(i)||Td(e,t,n,r,i,a))&(!bs(i)||Ru(e,t,n,r,i,a))&(!Rs(i)||Wd(e,t,n,r,i,a))))&(!(D(a)||zt(a))||!!((!vs(i)||dl(e,t,n,r,i,a))&+(!ys(i)||ml(e,t,n,r,i,a))&(!Ts(i)||rd(e,t,n,r,i,a))&(!As(i)||yd(e,t,n,r,i,a))&(!Fs(i)||jd(e,t,n,r,i,a))))&(!Ks(i)||mf(e,t,n,r,i,a))&(!Gs(i)||lf(e,t,n,r,i,a))&(!hs(i)||al(e,t,n,r,i,a))&(!cs(i)||Uc(e,t,n,r,i,a))&(!_s(i)||cl(e,t,n,r,i,a))&(!Ss(i)||Vu(e,t,n,r,i,a))&(!Is(i)||Id(e,t,n,r,i,a))&(!as(i)||Mc(e,t,n,r,i,a))&(!ss(i)||Lc(e,t,n,r,i,a))&(!Ls(i)||Vd(e,t,n,r,i,a))&(!Zs(i)||!S(a)||Df(e,t,n,r,i,a))&(!Qs(i)||!b(a)||Af(e,t,n,r,i,a)))&&(!es(i)||pc(e,t,n,r,i,a));return e.Pop(i),o}const qf=[0],Jf=new Map,Yf=new Map;function Xf(){return st(qf[0]++)}function Zf(e,t){Jf.has(e)||Jf.set(e,new Map);let n=Jf.get(e);if(n.has(t))return n.get(t);let r=Xf();return n.set(t,r),r}function Qf(e,t,n,r){return e.UseUnevaluated()?j(`check_${n}`,[`context`,r]):j(`check_${n}`,[r])}function $f(e,t,n,r){let i=R(e,t,n,`value`);return t.UseUnevaluated()?Io(`check_${r}`,Mo([`context`,`value`],i)):Io(`check_${r}`,Mo([`value`],i))}function ep(){qf[0]=0,Jf.clear(),Yf.clear()}function tp(){return[...Yf.values()]}function np(e,t,n,r){let i=Zf(n,e.BaseURL().href),a=Qf(t,n,i,r);return Yf.has(i)?a:(Yf.set(i,``),Yf.set(i,$f(e,t,n,i)),a)}function rp(e,t){return b(t)&&!Ue(e)?t[e]:void 0}function ip(e,t){return e.reduce((e,t)=>rp(t,e),t)}function ap(e){if(w(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 op(e,t){return ip(ap(t),e)}function sp(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(w(r.pathname,i.pathname))return n.hash.startsWith(`#`)?up(e,t,n):e}function cp(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return w(r.href,i.href)?e:void 0}function lp(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return w(r.href,i.href)?e:void 0}function up(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 op(e,r)}function dp(e,t,n){if(xs(e)){let r=sp(e,t,n);if(!C(r))return r}if(os(e)){let r=cp(e,t,n);if(!C(r))return r}if(ms(e)){let r=lp(e,t,n);if(!C(r))return r}return up(e,t,n)}function fp(e,t,n){return e.reduce((e,r)=>{let i=mp(r,t,n);return C(i)?e:i},void 0)}function pp(e,t,n){return y(e).reduce((r,i)=>{let a=mp(e[i],t,n);return C(a)?r:a},void 0)}function mp(e,t,n){let r=ts(e)&&xs(e)?new URL(e.$id,t.href):t;if(ts(e)){let t=dp(e,r,n);if(!C(t))return t}if(S(e))return fp(e,r,n);if(b(e))return pp(e,r,n)}function hp(e,t){let n=new URL(`http://unknown/`),r=xs(e)?new URL(e.$id,n.href):n;return mp(e,r,new URL(t,r.href))}function gp(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?hp(t,n.$dynamicRef):hp(e,n.$dynamicRef);if(!C(i))return!ts(i)||!ms(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var _p=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)},vp,yp,bp,xp,Sp,Cp=class{constructor(e,t){vp.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){ts(e)&&(xs(e)&&(this.ids.push(e),_p(this,vp,`m`,yp).call(this,e)),os(e)&&this.anchors.push(e),Ws(e)&&this.recursiveAnchors.push(e),ms(e)&&this.dynamicAnchors.push(e))}Pop(e){ts(e)&&(xs(e)&&(this.ids.pop(),_p(this,vp,`m`,bp).call(this,e)),os(e)&&this.anchors.pop(),Ws(e)&&this.recursiveAnchors.pop(),ms(e)&&this.dynamicAnchors.pop())}Ref(e){return _p(this,vp,`m`,xp).call(this,e)??_p(this,vp,`m`,Sp).call(this,e)}RecursiveRef(e){return Ws(this.Base())?hp(this.recursiveAnchors[0],e.$recursiveRef):hp(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return gp(t,this.Base(),e,this.dynamicAnchors)}};vp=new WeakSet,yp=function e(t,n=!0){if(!ts(t))return;let r=t;if(!(!n&&xs(r))){!n&&ms(r)&&this.dynamicAnchors.push(r);for(let t of y(r))_p(this,vp,`m`,e).call(this,r[t],!1)}},bp=function e(t,n=!0){if(!ts(t))return;let r=t;if(!(!n&&xs(r))){!n&&ms(r)&&this.dynamicAnchors.pop();for(let t of y(r))_p(this,vp,`m`,e).call(this,r[t],!1)}},xp=function(e){return E(this.context,e.$ref)?this.context[e.$ref]:void 0},Sp=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?hp(this.Base(),e.$ref):hp(t,e.$ref)};function wp(e){return`${e.Functions().join(`;
878
878
  `)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function Tp(e,t){return qo(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(ic,it,Fu,Xe,e.External().variables)}function Ep(e){let t=new Cp(e.Context(),e.Schema()),n=new ic;return r=>z(t,n,e.Schema(),r)}function Dp(e,t){return Ko()?Tp(e,t):Ep(e)}var Op=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)}},kp=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=wp(this),t=Dp(this,e);return new Op(Ko(),e,t)}};function Ap(...e){let[t,n]=Uo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});lc(),ep();let r=new Cp(t,n),i=new rc(nc(t,n)),a=np(r,i,n,`value`),o=tp();return new kp(t,n,uc(),o,a,i.UseUnevaluated())}function jp(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=Zt(),a=Xo(),o=[];return[B(new Cp(t,n),new ac(e=>{if(!Mt(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function Mp(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return z(new Cp(t,n),new ic,n,r)}function Np(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Mp(t,n,r)}function Pp(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=jp(t,n,r);return a}var Fp=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 Ip(e,t,n){return S(n)?n.map(n=>qp(e,t.items,n)):n}function Lp(e,t,n){return qp({...e,...t.$defs},$e(t.$ref),n)}function Rp(e,t){let n=E(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=Jt(e,t),i=Ht(r);return Ze(i)?Nt(i,n):i}function zp(e,t,n){return qp(e,Rp(e,t),n)}function Bp(e){return E(e,`additionalProperties`)?e.additionalProperties:void 0}function Vp(e,t,n){if(!b(n)||S(n))return n;let r=Bp(t);for(let i of y(n)){if(E(t.properties,i)){n[i]=qp(e,t.properties[i],n[i]);continue}if($t(r)&&w(r,!0)||Et(r)&&Np(e,r,n[i])){n[i]=qp(e,r,n[i]);continue}delete n[i]}return n}function Hp(e,t,n){if(!b(n))return n;let r=Bp(t),[i,a]=[new RegExp(wt(t)),Dt(t)];for(let t of y(n)){if(i.test(t)){n[t]=qp(e,a,n[t]);continue}if($t(r)&&w(r,!0)||Et(r)&&Np(e,r,n[t])){n[t]=qp(e,r,n[t]);continue}delete n[t]}return n}function Up(e,t,n){return E(e,t.$ref)?qp(e,e[t.$ref],n):n}function Wp(e,t,n){if(!S(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;i<r;i++)n[i]=qp(e,t.items[i],n[i]);return At(n.length,r)?n.slice(0,r):n}function Gp(e){return Ut(e)}function Kp(e,t,n){for(let r of t.anyOf){let t=qp(e,r,Gp(n));if(Np(e,r,t))return t}return n}function qp(e,t,n){return ct(t)?Ip(e,t,n):We(t)?Lp(e,t,n):lt(t)?zp(e,t,n):Ze(t)?Vp(e,t,n):Ct(t)?Hp(e,t,n):qt(t)?Up(e,t,n):Kt(t)?Wp(e,t,n):kt(t)?Kp(e,t,n):n}function Jp(e,t){for(let n of Ho.Keys(e))Ho.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function Yp(e){let t={};for(let n of Ho.Keys(e))t[n]=Qp(e[n]);return t}function Xp(e){return Zp(Xt(e))}function Zp(e){return e.map(e=>Qp(e))}function Qp(e){return Jp(e,ct(e)?Ve(Qp(e.items),_t(e)):lt(e)?tt(Zp(e.allOf)):kt(e)?vt(Xp(e.anyOf)):Ze(e)?ft(Yp(e.properties)):Ct(e)?Rt(Qt(e),Qp(Dt(e))):Kt(e)?Bt(Zp(e.items)):e)}function $p(e){return Qp(e)}function em(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return qp(t,Zt().unionPrioritySort?$p(n):n,r)}function tm(e){return b(e)&&E(e,`value`)}function V(e){return{value:e}}function nm(e){return S(e)?V(e):V([e])}function rm(e){return w(e,!0)?V(BigInt(1)):V(BigInt(0))}const im=/^-?(0|[1-9]\d*)n$/,am=/^-?(0|[1-9]\d*)\.\d+$/,om=/^-?(0|[1-9]\d*)$/;function sm(e){return im.test(e)}function cm(e){return am.test(e)}function lm(e){return om.test(e)}function um(e){let t=e.toLowerCase();return sm(e)?V(BigInt(e.slice(0,e.length-1))):cm(e)?V(BigInt(e.split(`.`)[0])):lm(e)?V(BigInt(e)):w(t,`false`)?V(BigInt(0)):w(t,`true`)?V(BigInt(1)):void 0}function dm(e){return zt(e)?V(e):$t(e)?rm(e):D(e)?V(BigInt(Math.trunc(e))):Ke(e)?V(BigInt(0)):v(e)?um(e):C(e)?V(BigInt(0)):void 0}function fm(e){return w(e,BigInt(0))?V(!1):w(e,BigInt(1))?V(!0):void 0}function pm(e){return w(e,0)?V(!1):w(e,1)?V(!0):void 0}function mm(e){return w(e.toLowerCase(),`false`)?V(!1):w(e.toLowerCase(),`true`)?V(!0):w(e,`0`)?V(!1):w(e,`1`)?V(!0):void 0}function hm(e){return zt(e)?fm(e):$t(e)?V(e):D(e)?pm(e):Ke(e)?V(!1):v(e)?mm(e):C(e)?V(!1):void 0}function gm(e){return w(e,BigInt(0))?V(null):void 0}function _m(e){return w(e,!1)?V(null):void 0}function vm(e){return w(e,0)?V(null):void 0}function ym(e){let t=e.toLowerCase();return w(t,`undefined`)||w(t,`null`)||w(e,``)||w(e,`0`)?V(null):void 0}function bm(e){return zt(e)?gm(e):$t(e)?_m(e):D(e)?vm(e):Ke(e)?V(null):v(e)?ym(e):C(e)?V(null):void 0}const xm=BigInt(2**53-1),Sm=BigInt(-(2**53-1));function Cm(e){return e<=xm&&e>=Sm?V(Number(e)):void 0}function wm(e){return V(+!!e)}function Tm(e){let t=+e;if(D(t))return V(t);let n=e.toLowerCase();if(w(n,`false`))return V(0);if(w(n,`true`))return V(1);let r=dm(e);if(tm(r))return r.value<=xm&&r.value>=Sm?V(Number(r.value)):void 0}function Em(e){return zt(e)?Cm(e):$t(e)?wm(e):D(e)?V(e):Ke(e)?V(0):v(e)?Tm(e):C(e)?V(0):void 0}function Dm(e){return zt(e)||$t(e)||D(e)?V(e.toString()):Ke(e)?V(`null`):v(e)?V(e):C(e)?V(``):void 0}function Om(e){return w(e,BigInt(0))?V(void 0):void 0}function km(e){return w(e,!1)?V(void 0):void 0}function Am(e){return w(e,0)?V(void 0):void 0}function jm(e){let t=e.toLowerCase();return w(t,`undefined`)||w(t,`null`)||w(e,``)||w(e,`0`)?V(void 0):void 0}function Mm(e){return zt(e)?Om(e):$t(e)?km(e):D(e)?Am(e):Ke(e)?V(void 0):v(e)?jm(e):C(e)?V(e):void 0}function Nm(e,t,n){return nm(n).value.map(n=>oh(e,t.items,n))}function Pm(e,t,n){let r=dm(n);return tm(r)?r.value:n}function Fm(e,t,n){let r=hm(n);return tm(r)?r.value:n}function Im(e,t,n){return oh({...e,...t.$defs},$e(t.$ref),n)}function Lm(e,t,n){return oh(e,Ht(t),n)}function Rm(e,t,n){let r=Em(n);return tm(r)?Math.trunc(r.value):n}function zm(e,t,n){let r=Jt(e,t);return oh(e,Ht(r),n)}function Bm(e,t,n){let r=dm(n);return tm(r)&&w(t.const,r.value)?r.value:n}function Vm(e,t,n){let r=hm(n);return tm(r)&&w(t.const,r.value)?r.value:n}function Hm(e,t,n){let r=Em(n);return tm(r)&&w(t.const,r.value)?r.value:n}function Um(e,t,n){let r=Dm(n);return tm(r)&&w(t.const,r.value)?r.value:n}function Wm(e,t,n){return w(t.const,n)?n:dt(t)?Bm(e,t,n):Je(t)?Vm(e,t,n):qe(t)?Hm(e,t,n):at(t)?Um(e,t,n):Qe()}function Gm(e,t,n){let r=bm(n);return tm(r)?r.value:n}function Km(e,t,n){let r=Em(n);return tm(r)?r.value:n}function qm(e,t,n,r){let i=y(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=oh(e,n,r[t]));return r}function Jm(e,t,n){return mt(e)&&C(n[t])}function Ym(e,t,n){let r=Pt(t.properties),i=y(n);for(let[t,a]of r)for(let r of i)!t.test(r)||Jm(a,r,n)||(n[r]=oh(e,a,n[r]));return E(t,`additionalProperties`)&&b(t.additionalProperties)?qm(e,r,t.additionalProperties,n):n}function Xm(e,t,n){return Ye(n)?Ym(e,t,n):n}function Zm(e,t,n){let r=Pt(t.patternProperties),i=y(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=oh(e,a,n[r]));return E(t,`additionalProperties`)&&b(t.additionalProperties)?qm(e,r,t.additionalProperties,n):n}function Qm(e,t,n){return Ye(n)?Zm(e,t,n):n}function $m(e,t,n){return E(e,t.$ref)?oh(e,e[t.$ref],n):n}function eh(e,t,n){let r=Dm(n);return tm(r)?r.value:n}function th(e,t,n){return oh(e,Ht(t),n)}function nh(e,t,n){if(!S(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=oh(e,t.items[r],n[r]);return n}function rh(e,t,n){let r=Mm(n);return tm(r)?r.value:n}function ih(e,t,n){if(t.anyOf.some(t=>Np(e,t,n)))return n;let r=t.anyOf.map(t=>oh(e,t,Gp(n))).find(n=>Np(e,t,n));return C(r)?n:r}function ah(e,t,n){return tm(Mm(n))?void 0:n}function oh(e,t,n){return ct(t)?Nm(e,t,n):nt(t)?Pm(e,t,n):Ft(t)?Fm(e,t,n):We(t)?Im(e,t,n):cn(t)?Lm(e,t,n):He(t)?Rm(e,t,n):lt(t)?zm(e,t,n):nn(t)?Wm(e,t,n):Ge(t)?Gm(e,t,n):rn(t)?Km(e,t,n):Ze(t)?Xm(e,t,n):Ct(t)?Qm(e,t,n):qt(t)?$m(e,t,n):en(t)?eh(e,t,n):bt(t)?th(e,t,n):Kt(t)?nh(e,t,n):Yt(t)?rh(e,t,n):kt(t)?ih(e,t,n):Wt(t)?ah(e,t,n):n}function sh(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return oh(t,n,r)}function ch(e,t,n){if(!S(n))return n;for(let r=0;r<n.length;r++)n[r]=_h(e,t.items,n[r]);return n}function lh(e,t,n){return _h({...e,...t.$defs},$e(t.$ref),n)}function uh(e,t){return C(t)?Vt(e.default)?e.default():Gp(e.default):t}function dh(e,t,n){let r=Jt(e,t);return _h(e,Ht(r),n)}function fh(e,t,n){if(!b(n))return n;let r=y(t.properties);for(let i of r){let r=_h(e,t.properties[i],n[i]);C(r)&&(mt(t.properties[i])||!E(t.properties[i],`default`))||(n[i]=r)}if(!is(t)||$t(t.additionalProperties))return n;for(let i of y(n))r.includes(i)||(n[i]=_h(e,t.additionalProperties,n[i]));return n}function ph(e,t,n){if(!b(n))return n;let[r,i]=[new RegExp(wt(t)),Dt(t)];for(let t of y(n))r.test(t)&&us(i)&&(n[t]=_h(e,i,n[t]));if(!is(t))return n;for(let i of y(n))r.test(i)||(n[i]=_h(e,t.additionalProperties,n[i]));return n}function mh(e,t,n){return E(e,t.$ref)?_h(e,e[t.$ref],n):n}function hh(e,t,n){if(!S(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]=_h(e,r[t],n[t]));return n}function gh(e,t,n){for(let r of t.anyOf){let t=_h(e,r,Gp(n));if(Np(e,r,t))return t}return n}function _h(e,t,n){let r=us(t)?uh(t,n):n;return ct(t)?ch(e,t,r):We(t)?lh(e,t,r):lt(t)?dh(e,t,r):Ze(t)?fh(e,t,r):Ct(t)?ph(e,t,r):qt(t)?mh(e,t,r):Kt(t)?hh(e,t,r):kt(t)?gh(e,t,r):r}function vh(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return _h(t,n,r)}function yh(e){return(...t)=>{let[n,r,i]=Uo(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function bh(e,t,n){return t[`~codec`].decode(n)}function xh(e,t,n){return t[`~codec`].encode(n)}function H(e,t,n,r){return rt(n)?w(e,`Decode`)?bh(t,n,r):xh(t,n,r):r}function Sh(e,t,n,r){if(!S(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 Ch(e,t,n,r){let i=H(e,t,n,r);if(!S(i))return i;for(let r=0;r<i.length;r++)i[r]=U(e,t,n.items,i[r]);return i}function wh(e,t,n,r){return w(e,`Decode`)?Sh(e,t,n,r):Ch(e,t,n,r)}function Th(e,t,n,r){return r=U(e,{...t,...n.$defs},$e(n.$ref),r),H(e,t,n,r)}function Eh(e){return e.reduce((e,t)=>({...e,...t}),{})}function Dh(e,t){for(let n of t)if(!Ot(e,n))return n;return e}function Oh(e,t,n,r){if(w(n.allOf.length,0))return H(e,t,n,r);let i=n.allOf.map(n=>U(e,t,n,em(n,Gp(r))));return H(e,t,n,i.every(e=>b(e))?Eh(i):Dh(r,i))}function kh(e,t,n,r){if(w(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,em(n,Gp(i))));return a.every(e=>b(e))?Eh(a):Dh(i,a)}function Ah(e,t,n,r){return w(e,`Decode`)?Oh(e,t,n,r):kh(e,t,n,r)}function jh(e,t,n,r){if(!Ye(r))return r;for(let i of y(n.properties))!E(r,i)||Jm(n.properties[i],i,r)||(r[i]=U(e,t,n.properties[i],r[i]));return H(e,t,n,r)}function Mh(e,t,n,r){let i=H(e,t,n,r);if(!Ye(i))return i;for(let r of y(n.properties))!E(i,r)||Jm(n.properties[r],r,i)||(i[r]=U(e,t,n.properties[r],i[r]));return i}function Nh(e,t,n,r){return w(e,`Decode`)?jh(e,t,n,r):Mh(e,t,n,r)}function Ph(e,t,n,r){if(!Ye(r))return r;let i=new RegExp(wt(n));for(let a of y(r))i.test(a)&&(r[a]=U(e,t,Dt(n),r[a]));return H(e,t,n,r)}function Fh(e,t,n,r){let i=H(e,t,n,r);if(!Ye(i))return i;let a=new RegExp(wt(n));for(let r of y(i))a.test(r)&&(i[r]=U(e,t,Dt(n),i[r]));return i}function Ih(e,t,n,r){return w(e,`Decode`)?Ph(e,t,n,r):Fh(e,t,n,r)}function Lh(e,t,n,r){return E(t,n.$ref)?U(e,t,t[n.$ref],r):r}function Rh(e,t,n,r){return w(e,`Decode`)?H(e,t,n,Lh(e,t,n,r)):Lh(e,t,n,H(e,t,n,r))}function zh(e,t,n,r){if(!S(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 Bh(e,t,n,r){let i=H(e,t,n,r);if(!S(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 Vh(e,t,n,r){return w(e,`Decode`)?zh(e,t,n,r):Bh(e,t,n,r)}function Hh(e,t,n,r){for(let i of n.anyOf)if(Np(t,i,r))return H(e,t,n,U(e,t,i,r));return r}function Uh(e,t,n,r){let i=H(e,t,n,r);for(let r of n.anyOf){let n=U(e,t,r,Gp(i));if(Np(t,r,n))return n}return i}function Wh(e,t,n,r){return w(e,`Decode`)?Hh(e,t,n,r):Uh(e,t,n,r)}function U(e,t,n,r){return ct(n)?wh(e,t,n,r):We(n)?Th(e,t,n,r):lt(n)?Ah(e,t,n,r):Ze(n)?Nh(e,t,n,r):Ct(n)?Ih(e,t,n,r):qt(n)?Rh(e,t,n,r):Kt(n)?Vh(e,t,n,r):kt(n)?Wh(e,t,n,r):H(e,t,n,r)}var Gh=class extends Fp{constructor(e,t){super(`Decode`,e,t)}};function Kh(e,t,n){if(!Np(e,t,n))throw new Gh(n,Pp(e,t,n));return n}function qh(e,t,n){return U(`Decode`,e,Zt().unionPrioritySort?$p(t):t,n)}const Jh=yh([(e,t,n)=>Gp(n),(e,t,n)=>vh(e,t,n),(e,t,n)=>sh(e,t,n),(e,t,n)=>em(e,t,n),(e,t,n)=>Kh(e,t,n),(e,t,n)=>qh(e,t,n)]);function Yh(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Jh(t,n,r)}var Xh=class extends Fp{constructor(e,t){super(`Encode`,e,t)}};function Zh(e,t,n){if(!Np(e,t,n))throw new Xh(n,Pp(e,t,n));return n}function Qh(e,t,n){return U(`Encode`,e,Zt().unionPrioritySort?$p(t):t,n)}const $h=yh([(e,t,n)=>Gp(n),(e,t,n)=>Qh(e,t,n),(e,t,n)=>vh(e,t,n),(e,t,n)=>sh(e,t,n),(e,t,n)=>em(e,t,n),(e,t,n)=>Zh(e,t,n)]);function eg(...e){let[t,n,r]=Uo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return $h(t,n,r)}function tg(e,t){return rt(t)||lg(e,t.items)}function ng(e,t){return rt(t)||og({...e,...t.$defs},$e(t.$ref))}function rg(e,t){return rt(t)||t.allOf.some(t=>lg(e,t))}function ig(e,t){return rt(t)||y(t.properties).some(n=>lg(e,t.properties[n]))}function ag(e,t){return rt(t)||lg(e,Dt(t))}function og(e,t){return!ug.has(t.$ref)&&(ug.add(t.$ref),rt(t)||E(e,t.$ref)&&lg(e,e[t.$ref]))}function sg(e,t){return rt(t)||t.items.some(t=>lg(e,t))}function cg(e,t){return rt(t)||t.anyOf.some(t=>lg(e,t))}function lg(e,t){return ct(t)?tg(e,t):We(t)?ng(e,t):lt(t)?rg(e,t):Ze(t)?ig(e,t):Ct(t)?ag(e,t):qt(t)?og(e,t):Kt(t)?sg(e,t):kt(t)?cg(e,t):rt(t)}const ug=new Set;function dg(...e){let[t,n]=Uo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return ug.clear(),lg(t,n)}var fg=class extends Error{constructor(e,t){super(t),this.type=e}};function pg(e,t){return Vt(t.default)?t.default(t):b(t.default)?Gp(t.default):t.default}function mg(e,t){if(Xs(t)&&!us(t))throw new fg(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=Ms(t)?t.minItems:0;return Array.from({length:n},()=>Fg(e,t.items))}function hg(e,t){return ys(t)?BigInt(t.exclusiveMinimum)+BigInt(1):As(t)?BigInt(t.minimum):BigInt(0)}function gg(e,t){return!1}function _g(e,t){let n=Fg(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function vg(e,t){return Fg({...e,...t.$defs},$e(t.$ref))}function yg(e,t){return Fg(e,Ht(t))}function bg(e,t){let n=Fg(e,t.returnType);return()=>n}function xg(e,t){return ys(t)&&D(t.exclusiveMinimum)?t.exclusiveMinimum+1:As(t)?t.minimum:0}function Sg(e,t){let n=Jt(e,t);return Fg(e,Ht(n))}function Cg(e,t){return t.const}function wg(e,t){throw new fg(t,`Cannot create TNever types`)}function Tg(e,t){return null}function Eg(e,t){return ys(t)&&D(t.exclusiveMinimum)?t.exclusiveMinimum+1:As(t)?t.minimum:0}function Dg(e,t){return(C(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:Fg(e,t.properties[r])}),{})}function Og(e,t){if(Ps(t)&&!us(t))throw new fg(t,`Record with the minProperties constraint must have a default annotation`);return{}}function kg(e,t){return E(e,t.$ref)?Fg(e,e[t.$ref]):(()=>{throw new fg(t,`Unable to deref Ref`)})()}function Ag(e,t){if((Rs(t)||bs(t))&&!us(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=Ns(t)?t.minLength:0;return``.padEnd(n)}function jg(e,t){return Symbol()}function Mg(e,t){let n=jt(t.pattern);if(en(n))throw new fg(t,`Unable to create TemplateLiteral due to infinite type expansion`);return Fg(e,n)}function Ng(e,t){return Array.from({length:t.minItems},(n,r)=>Fg(e,t.items[r]))}function Pg(e,t){if(w(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return Fg(e,t.anyOf[0])}function Fg(e,t){return us(t)?pg(e,t):ct(t)?mg(e,t):nt(t)?hg(e,t):Ft(t)?gg(e,t):ht(t)?_g(e,t):We(t)?vg(e,t):cn(t)?yg(e,t):gt(t)?bg(e,t):He(t)?xg(e,t):lt(t)?Sg(e,t):nn(t)?Cg(e,t):et(t)?wg(e,t):Ge(t)?Tg(e,t):rn(t)?Eg(e,t):Ze(t)?Dg(e,t):Ct(t)?Og(e,t):qt(t)?kg(e,t):en(t)?Ag(e,t):xt(t)?jg(e,t):bt(t)?Mg(e,t):Kt(t)?Ng(e,t):Yt(t)?void 0:kt(t)?Pg(e,t):(Wt(t),void 0)}function Ig(...e){let[t,n]=Uo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Fg(t,n)}var Lg=class extends Fp{constructor(e,t){super(`Parse`,e,t)}};function Rg(e,t,n){if(!Np(e,t,n))throw new Lg(n,Pp(e,t,n));return n}const zg=yh([(e,t,n)=>Gp(n),(e,t,n)=>vh(e,t,n),(e,t,n)=>sh(e,t,n),(e,t,n)=>em(e,t,n),(e,t,n)=>Rg(e,t,n)]),Bg=ft({type:Lt(`insert`),path:on(),value:pt()}),Vg=Object({type:Lt(`update`),path:on(),value:pt()}),Hg=ft({type:Lt(`delete`),path:on()});vt([Bg,Vg,Hg]);var Ug=class{constructor(e,t){this.hasCodec=dg(e,t),this.buildResult=Ap(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(Zt().correctiveParse)return zg(this.Context(),this.Type(),e);throw new Lg(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:Pp(this.Context(),this.Type(),e)}Clean(e){return em(this.Context(),this.Type(),e)}Convert(e){return sh(this.Context(),this.Type(),e)}Create(){return Ig(this.Context(),this.Type())}Default(e){return vh(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Yh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?eg(this.Context(),this.Type(),e):this.Parse(e)}};function Wg(...e){let[t,n]=Uo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new Ug(t,n)}const Gg=new WeakMap,Kg=Symbol.for(`TypeBox.Kind`);function qg(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function Jg(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 Yg(e){try{return n_(e)}catch{return}}function Xg(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 Zg(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]=e_(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=e_(i,t.additionalProperties))}function Qg(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=e_(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=e_(e[n],t.items)}function $g(e,t){for(let n of t)if(Yg(n)?.Check(e))return e;for(let n of t){let t=e_(structuredClone(e),n);if(Yg(n)?.Check(t))return t}return e}function e_(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=e_(n,e);Array.isArray(t.anyOf)&&(n=$g(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=$g(n,t.oneOf));let r=qg(t),i=r.length>1&&r.some(e=>Jg(n,e));if(r.length>0&&!i)for(let e of r){let t=Xg(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&Zg(n,t),r.includes(`array`)&&Array.isArray(n)&&Qg(n,t),n}function t_(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&&t_(e[n],r)}else if(t.items)for(let n of e)t_(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`&&Yg(i)?.Check(null)===!1?delete n[e]:t_(n[e],i))}function n_(e){let t=e,n=Gg.get(t);if(n)return n;let r=Wg(e);return Gg.set(t,r),r}function r_(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 i_(e,t){let n=structuredClone(t.arguments);t_(n,e.parameters),sh(e.parameters,n);let r=n_(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Kg)){let t=e_(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=>` - ${r_(e)}: ${e.message}`).join(`
879
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 a_(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function o_(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 c_(s,o,n,i,r,a??a_()),o}async function s_(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 c_(o,a,t,r,n,i??a_()),a}async function c_(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 l_(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 u_(u,i):await d_(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 l_(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 u_(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:y_(`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 b_(e,t);let i=x_(e);await S_(i,t),n.push(i)}return{messages:n,terminate:!1}}async function d_(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?f_(e,t,a,n,r,i):p_(e,t,a,n,r,i)}async function f_(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 g_(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await v_(e,t,n,await __(n,i,a),r,i),await b_(l,a);let u=x_(l);if(await S_(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:m_(o)}}async function p_(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 g_(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await b_(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{let o=await __(n,i,a),s=await v_(e,t,n,o,r,i);return await b_(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=x_(e);await S_(t,a),c.push(t)}return{messages:c,terminate:m_(s)}}function m_(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function h_(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function g_(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:y_(`Tool ${n.name} not found`),isError:!0};try{let o=i_(a,h_(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:y_(`Operation aborted`),isError:!0};if(a?.block){let e=y_(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:y_(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:y_(e instanceof Error?e.message:String(e)),isError:!0}}}async function __(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:y_(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function v_(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=y_(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function y_(e){return{content:[{type:`text`,text:e}],details:{}}}async function b_(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function x_(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 S_(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function C_(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const w_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},T_={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_(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??T_,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 D_=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=[]}},O_=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=E_(t.initialState),this.convertToLlm=t.convertToLlm??C_,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??a_(),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 D_(t.steeringMode??`one-at-a-time`),this.followUpQueue=new D_(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 o_(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await s_(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:w_,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 k_(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 A_(e){let t=e.mimeType||`application/octet-stream`;return`${e.name} (${t}, ${k_(e.size)})`}function j_(e){let t=A_(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
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 M_(e,t){if(!t?.length)return e;let n=t.map(j_),r=e.trim();return r?`${r}\n\n${n.join(`
@@ -988,7 +988,7 @@ Write /etc/models
988
988
  `)}\n`}var zx=class{fs;watcher;broker;onPolicyReload;policy=Vr();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??p(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`&&Ur(this.policy,e.detail)===`nopasswd-allow`)return Nx.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 Nx.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(Zr(e.kind),n)}catch(n){return Nx.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=[Br(),this.policy];return n&&r.push(n),t&&r.push(t),qr(...r)}registerScoopConfig(e,t){this.scoopConfigPolicies.set(e,Gr(Rx(t??void 0))),this.onPolicyReload(e)}async initScoopPolicy(e,t){this.registerScoopConfig(e,t);let n=$r(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=Wr(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=ei(e);if(!a)return Nx.warn(`Unspellable scoop folder; not persisting`,{folder:e}),null;let o=await this.readTextOrEmpty(a),s=`NOPASSWD ${i} ${r}`;if(o.split(`
989
989
  `).some(e=>e.trim()===s))return Nx.info(`Per-scoop grant already present; skipping duplicate append`,{folder:e,kind:t,pattern:r}),r;try{await this.fs.mkdir(Jr,{recursive:!0})}catch{}let c=o?o.endsWith(`
990
990
  `)?o:`${o}\n`:Lx;return await this.fs.writeFile(a,`${c}${s}\n`),await this.reloadScoopPolicy(e),Nx.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 k&&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=ei(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(Xr)];try{let t=(await this.fs.readDir(Jr)).filter(e=>e.type===`file`).filter(e=>zr(e.name)===null).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${Jr}/${n}`))}catch{}this.policy=qr(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return Vr();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return Gr(n)}catch(t){return Nx.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),Vr()}}async ensureDefaults(){try{await this.fs.mkdir(Jr,{recursive:!0})}catch{}await this.seedWhenAbsent(Xr,()=>Mx),await this.seedWhenAbsent(Qr,async()=>(await import(`./approver-agent-CivzfuZ7.js`)).DEFAULT_APPROVALS_MD)}async seedWhenAbsent(e,t){try{if(await this.fs.exists(e))return;await this.fs.writeFile(e,await t()),Nx.info(`Seeded bundled policy default`,{path:e})}catch(t){Nx.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=Wr(t);if(!n)return;let r=``;try{if(await this.fs.exists(ri)){let e=await this.fs.readFile(ri,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof k&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(Jr,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
991
- `)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(ri,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,Px,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=Fx(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 Bx(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Vx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hx(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++)Hx(e[r],`${t}/${r}`,n);return}if(Vx(e))for(let[r,i]of Object.entries(e))Hx(i,`${t}/${Bx(r)}`,n)}function Ux(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=Ux(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(Vx(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=Ux(o,`${t}/${Bx(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function Wx(e,t,n){if(Vx(e))return Ux(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}return e}function Gx(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 Kx(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new a(`redaction-unavailable`);let o=0,s=i;for(;s<e.length;){let t=e[s].length;if(s>i&&o+t>1048576)break;o+=t,s++}let c=e.slice(i,s),l;try{l=await t.redact(c,n)}catch{throw new a(`redaction-unavailable`)}if(l.length!==c.length)throw new a(`redaction-unavailable`);r.push(...l),i=s}return r}function qx(e,t,n,r){let i=[],a=Gx(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Gx(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}=xe(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 Jx(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 Yx(e,t,n,r){if(r?.aborted)throw new a(`redaction-unavailable`);let{privacy:i,...o}=e,s=[];Hx(o,``,s);let c=s.filter(e=>!ne(e.pointer)),l=[...t.entries()],u=await Kx([...c.map(e=>e.value),...l.map(([,e])=>e)],n,r),d=[],f={},p=1,m=new Map,h=[];for(let e=0;e<c.length;e++){let t=c[e],n=qx(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)}Jx(h,d,f);let ee=new Map,g=c.length,te=[];for(let e=0;e<l.length;e++){let[t,n]=l[e],r=qx(n,u[g+e],{kind:`attachment`,attachmentId:t},p);p=r.nextId,ee.set(t,r.finalText),te.push(r)}Jx(te,d,f);let re=Wx(e,``,m);return{document:{...re,privacy:{...re.privacy,redactionCounts:f,redactions:d}},textAttachments:ee}}function Xx(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 Zx(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 Qx={"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 $x(e,t){return Qx[e]??(t===`text-redacted`?`.txt`:`.bin`)}function eS(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${$x(t,n)}`}function tS(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 nS(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 rS(e,t,n,r,i){let a=Xx(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(tS(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=tS(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 iS(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:tS(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(rS(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function aS(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 oS(e,t,n,r,i,a,o){let s=aS(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(rS(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function sS(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=oS(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 cS(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,eS(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 lS(e,t,n,r,i){let{rawAttachments:o,textMap:s}=cS(e,n),c,l;try{let e=await Yx({...t,attachments:o},s,r,i);c=e.document,l=e.textAttachments}catch(e){throw e instanceof a?e:new a(`attachment-unreadable`)}let u=new Map;for(let t of e){if(u.has(t.attachmentId))throw new a(`schema-invalid`);u.set(t.attachmentId,t)}let d=new Map,f=await Promise.all(c.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=u.get(e.id);if(t===void 0)throw new a(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(l.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await Zx(n);return d.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...c,attachments:f},bundleFiles:d}}async function uS(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}=iS(nS(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}=sS(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],ee=t;f.size>0&&(ee={...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:g,bundleFiles:te}=await lS(h,ee,s,r,i),ne=[...g.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{...g,session:{...g.session,completeness:{status:ne.length>0?`partial`:g.session.completeness.status,missing:ne}}},bundleFiles:te}}function dS(e){return qn(e)}function fS(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 pS(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:Nn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!Nn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=dS(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function mS(e,t,n={}){let r=e=>n.rootJid===void 0?e:Fn(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 a(`transfer-aborted`);let i=fS(n,e),[o,s]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new a(`transfer-aborted`);let c=r(e.listScoops());if(i===fS(c,e))return pS(c,o,s,e)}}var hS=e({SESSIONS_DIR:()=>gS,SESSIONS_INDEX_PATH:()=>_S,parseFrozenArchive:()=>yS,readSessionsIndex:()=>vS});const gS=`/sessions`,_S=`/sessions/index.json`;async function vS(e){try{let t=await e.readFile(_S,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function yS(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,bS(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=xS(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:CS(t),...r})}function bS(e){let t={},n=SS(e,`cost`),r=SS(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=xS(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=Number(e.match(/^curatedThrough:\s*(\d+)\s*$/m)?.[1]);Number.isFinite(c)&&c>0&&(t.curatedThrough=c);let l=e.match(/^id:\s*(\S+)\s*$/m)?.[1];l&&(t.id=l);let u=e.match(/^sidecar:\s*(\S+)\s*$/m)?.[1];return u&&(t.sidecar=u),t}function xS(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 SS(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function CS(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 wS(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function TS(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function ES(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(TS(t,r++));return n}function DS(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=TS(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 OS(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=TS(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 kS(e,t,n){let r=wS(t,n),i=ES(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 AS(e,t,n){let r=wS(t,n),{blocks:i,excluded:a,images:o}=DS(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 jS(e,t,n){let r=wS(t,n),{blocks:i,images:a}=OS(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`?kS(e,t,n):e.role===`assistant`?AS(e,t,n):e.role===`toolResult`?jS(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function NS(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 PS(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:NS(e),excludedReasoningBlocks:t,canonicalImages:n}}const FS=(()=>{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 IS(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^FS[(t^e[n])&255];return~t>>>0}const LS=new TextEncoder;function K(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function RS(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 zS(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),RS(r,14,n),RS(r,18,t),RS(r,22,t),K(r,26,e.length),K(r,28,0),r.set(e,30),r}function BS(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),RS(i,16,n),RS(i,20,t),RS(i,24,t),K(i,28,e.length),K(i,30,0),K(i,32,0),K(i,34,0),K(i,36,0),RS(i,38,0),RS(i,42,r),i.set(e,46),i}function VS(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),RS(r,12,t),RS(r,16,n),K(r,20,0),r}function HS(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 US(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${be(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*WS(e,t,n,r,i){if(n?.aborted)throw i(new a(`transfer-aborted`)),new a(`transfer-aborted`);let o=()=>i(new a(`transfer-aborted`));n?.addEventListener(`abort`,o,{once:!0});let s=ai.create(),c=0,l=0,u=[],d=!1;function*f(e){s.update(e),c+=e.byteLength,l+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),o=LS.encode(`transcript.json`),p=IS(i),m=zS(o,i.length,p);if(u.push({nameBytes:o,size:i.length,crc:p,localOffset:l}),n?.aborted||(yield*f(m),n?.aborted))throw new a(`transfer-aborted`);yield*f(i);for(let[e,r]of t){if(n?.aborted)throw new a(`transfer-aborted`);let t=LS.encode(e),i=IS(r),o=zS(t,r.length,i);if(u.push({nameBytes:t,size:r.length,crc:i,localOffset:l}),yield*f(o),n?.aborted)throw new a(`transfer-aborted`);yield*f(r)}let h=l;for(let e of u){if(n?.aborted)throw new a(`transfer-aborted`);yield*f(BS(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new a(`transfer-aborted`);yield*f(VS(u.length,l-h,h)),d=!0,r({byteLength:c,sha256:s.hex()})}catch(e){throw d=!0,i(e),e}finally{n?.removeEventListener(`abort`,o),d||(d=!0,i(new a(`transfer-aborted`)))}}function GS(e,t,n){for(let e of t.keys())if(!HS(e))throw new a(`schema-invalid`);if(t.size+1>65535)throw new a(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new a(`schema-invalid`);let r,i,o=new Promise((e,t)=>{r=e,i=t});return{filename:US(e),chunks:WS(e,t,n,r,i),completion:o}}function KS(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:re},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function qS(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 JS(e){let t=n(e);if(!t.ok)throw new a(`schema-invalid`,t.error)}function YS(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 XS(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 ZS(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 QS=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),JS(i.document),r?.({phase:`packaging`}),GS(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await mS(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=PS(n.sources),{document:i,bundleFiles:a}=await uS({document:KS(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});JS(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 mS(this.deps.collection,e),r=PS(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=KS(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),uS({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 Yx(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new a(`redaction-unavailable`)}let o=YS(r.attachments,i,e.attachments),s=await XS(r.attachments,o);return{document:{...r,attachments:s},bundleFiles:o}}async buildLegacyPartial(e,t,n){let r=(await vS(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new a(`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 a(`session-not-found`)}let{loadFrozenArchive:o}=await import(`./session-jsonl-C5QAPMRG.js`),{title:s,messages:c}=await o(this.deps.vfs,i,r.filename),l=`legacy-cone`,u=qS(c,l),d=ZS(i),f={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:re},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`}),uS({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 a(`attachment-unreadable`);return t}};const $S=`/sessions/data`,eC=`document.json`;async function tC(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 nC(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new a(`session-not-found`)}function rC(e){return`${$S}/${e}`}function iC(e){return`${$S}/.tmp-${e}`}async function aC(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function oC(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 oC(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function sC(e,t,n){await aC(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 sC(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function cC(e,t,n){nC(t);let r=iC(t),i=rC(t),o=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!o.has(e))throw new a(`schema-invalid`);await oC(e,i),await aC(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await tC(r),i=o.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let a={...n.document,attachments:t},s=JSON.stringify(a,null,2);if(await e.writeFile(`${r}/${eC}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await aC(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await sC(e,r,i),await e.flush()}catch(t){throw await oC(e,r),t}await oC(e,r)}async function lC(e,t){nC(t);let r=rC(t),i=`${r}/${eC}`,o;try{let t=await e.readFile(i,{encoding:`utf-8`});o=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new a(`session-not-found`)}let s;try{s=JSON.parse(o)}catch{throw new a(`schema-invalid`)}if(!n(s).ok)throw new a(`schema-invalid`);let c=new Map;for(let t of s.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 a(`transfer-corrupt`)}if(await tC(i)!==t.sha256)throw new a(`transfer-corrupt`);c.set(t.path,i)}return{document:s,attachments:c}}function uC(e){return`error`in e}function dC(){throw new a(`redaction-unavailable`)}function fC(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&dC(),e.texts}function pC(){return{async redact(e){let t;try{t=await fetch(Re(`/api/secrets/redact-export`),{method:`POST`,headers:ze({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{dC()}t.ok||dC();let n;try{n=await t.json()}catch{dC()}return fC(n,e.length)}}}function mC(){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{dC()}return typeof t==`object`&&t&&uC(t)&&dC(),fC(t,e.length)}}}function hC(){return{async redact(e){let t;try{t=await yn(`secrets.redact-export`,{texts:e})}catch{dC()}return t??dC(),typeof t==`object`&&t&&uC(t)&&dC(),fC(t,e.length)}}}function gC(){return{async redact(e){dC()}}}function _C(){let e=fn();return e===`connect`?gC():e===`extension-direct`?mC():e===`extension-delegate`?hC():pC()}const vC=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function yC(e){return`e${e}`}function bC(e){let t=[];for(let n of e){let e=CC(n),r=TC(n);if(e===`assistant`){let e=t.length,i=yC(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:OC(n),message:n,model:DC(n)});for(let e of kC(n)){let n=t.length;t.push({id:yC(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:yC(i),seq:i,kind:`tool-result`,timestamp:r,text:OC(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=OC(n),a=e===`user`?SC(i):null,o=t.length,s=yC(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):vC.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 xC(e){let t=[];for(let n of e){let e=t.length,r=yC(e),i=EC(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:yC(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&J_(n.channel)?n.channel:SC(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):vC.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 SC(e){for(let t of gv(e)){let e=(t.sender?_v(t.sender):null)??vv(t.body);if(e)return e}return null}function CC(e){return e.role??``}function wC(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 TC(e){return wC(e.timestamp)}function EC(e){return wC(e.timestamp)}function DC(e){let t=e.model;return typeof t==`string`?t:void 0}function OC(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 kC(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 AC(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function jC(e){return e!==null&&e.version<=2}const MC=_(`work-unit-conversation`);var NC=class extends Error{};const PC=`conversations`;async function FC(e){let t=e.now??(()=>Date.now()),n=await LC(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=kr(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await IC(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 NC){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 IC(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 NC(`canonical record unreadable: ${i.reason}`);let a=Ar(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:bC(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:xC(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function LC(e,t){let n=await e.getMigrationState(PC);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:PC,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var RC=e({applyAttachmentOverlays:()=>HC,interleaveMarkers:()=>UC,toAgentMessages:()=>BC,toChatMessages:()=>VC});const zC=new Set([`summarized`,`fallback`]);function BC(e){if(!jC(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 VC(e,t={}){if(!jC(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 UC(t,e.markers)}let n=e.projectionPrefix??[],r=BC(e);if(r.length===0)return UC([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>nv),a=HC(i(r,t),e.attachments);return UC([...n,...a],e.markers)}function HC(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 UC(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||zC.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=WC(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(GC(r[a++]));i.push(t)}for(;a<r.length;)i.push(GC(r[a++]));return i}function WC(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 GC(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 KC(e){return{id:e.legacyKeys.chatSessionId,messages:await VC(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function qC(e){return{id:e.workUnitId,messages:BC(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var JC=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(qC)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(KC))}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(fr({parentJid:null,folder:e}).root);return t?KC(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const YC=_(`work-unit-conversation`),XC=`conversations`,ZC=`migrations`;var QC=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 aw((await this.getDb()).transaction(XC,`readonly`).objectStore(XC).get(e));return t?jC(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(YC.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(YC.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return YC.warn(`Conversation record read failed`,{key:e,error:sw(t)}),{status:`error`,reason:sw(t)}}}async save(e){let t=e.version>2?e.version:AC(e),n={...e,version:t},r=(await this.getDb()).transaction(XC,`readwrite`);return r.objectStore(XC).put(n),await ow(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(XC,`readwrite`);t.objectStore(XC).delete(e),await ow(t)}catch(t){YC.warn(`Conversation record delete failed`,{key:e,error:sw(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`){YC.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){YC.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:sw(n)})}}async loadAll(){try{return(await aw((await this.getDb()).transaction(XC,`readonly`).objectStore(XC).getAll())).filter(e=>jC(e)&&Array.isArray(e.entries))}catch(e){return YC.warn(`Conversation record listing failed`,{error:sw(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await aw((await this.getDb()).transaction(XC,`readonly`).objectStore(XC).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)!jC(e)||!Array.isArray(e.entries)||(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return YC.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:sw(t)}),null}}async listKeys(){try{return(await aw((await this.getDb()).transaction(XC,`readonly`).objectStore(XC).getAllKeys())).map(String)}catch(e){return YC.warn(`Conversation key listing failed`,{error:sw(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=bC(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=$C(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return YC.warn(`Conversation record write failed`,{key:e.key,error:sw(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?ew(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 YC.warn(`Conversation marker write failed`,{key:e,error:sw(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 aw((await this.getDb()).transaction(ZC,`readonly`).objectStore(ZC).get(e))??null}catch(t){return YC.warn(`Migration state read failed`,{id:e,error:sw(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(ZC,`readwrite`);t.objectStore(ZC).put(e),await ow(t)}catch(t){YC.warn(`Migration state write failed`,{id:e.id,error:sw(t)})}}async clearAll(){let e=(await this.getDb()).transaction([XC,ZC],`readwrite`);e.objectStore(XC).clear(),e.objectStore(ZC).clear(),await ow(e)}getDb(){return this.dbPromise||(this.dbPromise=iw(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 $C(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??[],...tw(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&nw(a,t))return null;let o=t.length>a.length&&nw(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 ew(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 tw(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function nw(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!rw(e[n],t[n]))return!1;return!0}function rw(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 iw(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(XC)||e.createObjectStore(XC,{keyPath:`key`}),e.objectStoreNames.contains(ZC)||e.createObjectStore(ZC,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function aw(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function ow(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function sw(e){return e instanceof Error?e.message:String(e)}var cw=e({CONE_MEMORY_PATH:()=>dw,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>uw,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>fw,applyConeMemoryBudget:()=>_w,readSessionCount:()=>hw,restructureConeMemory:()=>gw,splitConeMemory:()=>mw});const lw=_(`cone-memory-budget`),uw=1.25,dw=cr.memoryPath,fw=`/sessions/index.json`,pw=/^## Auto-extracted/m;function mw(e){let t=pw.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function hw(e){try{let t=await e.readFile(fw,{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 gw(e){let{header:t,autoExtracted:n}=mw(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
+ `)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(ri,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,Px,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=Fx(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 Bx(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Vx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hx(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++)Hx(e[r],`${t}/${r}`,n);return}if(Vx(e))for(let[r,i]of Object.entries(e))Hx(i,`${t}/${Bx(r)}`,n)}function Ux(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=Ux(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(Vx(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=Ux(o,`${t}/${Bx(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function Wx(e,t,n){if(Vx(e))return Ux(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}return e}function Gx(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 Kx(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new a(`redaction-unavailable`);let o=0,s=i;for(;s<e.length;){let t=e[s].length;if(s>i&&o+t>1048576)break;o+=t,s++}let c=e.slice(i,s),l;try{l=await t.redact(c,n)}catch{throw new a(`redaction-unavailable`)}if(l.length!==c.length)throw new a(`redaction-unavailable`);r.push(...l),i=s}return r}function qx(e,t,n,r){let i=[],a=Gx(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Gx(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}=xe(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 Jx(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 Yx(e,t,n,r){if(r?.aborted)throw new a(`redaction-unavailable`);let{privacy:i,...o}=e,s=[];Hx(o,``,s);let c=s.filter(e=>!ne(e.pointer)),l=[...t.entries()],u=await Kx([...c.map(e=>e.value),...l.map(([,e])=>e)],n,r),d=[],f={},p=1,m=new Map,h=[];for(let e=0;e<c.length;e++){let t=c[e],n=qx(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)}Jx(h,d,f);let ee=new Map,g=c.length,te=[];for(let e=0;e<l.length;e++){let[t,n]=l[e],r=qx(n,u[g+e],{kind:`attachment`,attachmentId:t},p);p=r.nextId,ee.set(t,r.finalText),te.push(r)}Jx(te,d,f);let re=Wx(e,``,m);return{document:{...re,privacy:{...re.privacy,redactionCounts:f,redactions:d}},textAttachments:ee}}function Xx(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 Zx(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 Qx={"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 $x(e,t){return Qx[e]??(t===`text-redacted`?`.txt`:`.bin`)}function eS(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${$x(t,n)}`}function tS(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 nS(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 rS(e,t,n,r,i){let a=Xx(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(tS(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=tS(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 iS(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:tS(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(rS(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function aS(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 oS(e,t,n,r,i,a,o){let s=aS(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(rS(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function sS(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=oS(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 cS(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,eS(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 lS(e,t,n,r,i){let{rawAttachments:o,textMap:s}=cS(e,n),c,l;try{let e=await Yx({...t,attachments:o},s,r,i);c=e.document,l=e.textAttachments}catch(e){throw e instanceof a?e:new a(`attachment-unreadable`)}let u=new Map;for(let t of e){if(u.has(t.attachmentId))throw new a(`schema-invalid`);u.set(t.attachmentId,t)}let d=new Map,f=await Promise.all(c.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=u.get(e.id);if(t===void 0)throw new a(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(l.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await Zx(n);return d.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...c,attachments:f},bundleFiles:d}}async function uS(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}=iS(nS(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}=sS(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],ee=t;f.size>0&&(ee={...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:g,bundleFiles:te}=await lS(h,ee,s,r,i),ne=[...g.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{...g,session:{...g.session,completeness:{status:ne.length>0?`partial`:g.session.completeness.status,missing:ne}}},bundleFiles:te}}function dS(e){return qn(e)}function fS(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 pS(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:Nn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!Nn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=dS(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function mS(e,t,n={}){let r=e=>n.rootJid===void 0?e:Fn(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 a(`transfer-aborted`);let i=fS(n,e),[o,s]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new a(`transfer-aborted`);let c=r(e.listScoops());if(i===fS(c,e))return pS(c,o,s,e)}}var hS=e({SESSIONS_DIR:()=>gS,SESSIONS_INDEX_PATH:()=>_S,parseFrozenArchive:()=>yS,readSessionsIndex:()=>vS});const gS=`/sessions`,_S=`/sessions/index.json`;async function vS(e){try{let t=await e.readFile(_S,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function yS(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,bS(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=xS(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:CS(t),...r})}function bS(e){let t={},n=SS(e,`cost`),r=SS(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=xS(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=Number(e.match(/^curatedThrough:\s*(\d+)\s*$/m)?.[1]);Number.isFinite(c)&&c>0&&(t.curatedThrough=c);let l=e.match(/^id:\s*(\S+)\s*$/m)?.[1];l&&(t.id=l);let u=e.match(/^sidecar:\s*(\S+)\s*$/m)?.[1];return u&&(t.sidecar=u),t}function xS(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 SS(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function CS(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 wS(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function TS(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function ES(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(TS(t,r++));return n}function DS(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=TS(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 OS(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=TS(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 kS(e,t,n){let r=wS(t,n),i=ES(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 AS(e,t,n){let r=wS(t,n),{blocks:i,excluded:a,images:o}=DS(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 jS(e,t,n){let r=wS(t,n),{blocks:i,images:a}=OS(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`?kS(e,t,n):e.role===`assistant`?AS(e,t,n):e.role===`toolResult`?jS(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function NS(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 PS(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:NS(e),excludedReasoningBlocks:t,canonicalImages:n}}const FS=(()=>{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 IS(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^FS[(t^e[n])&255];return~t>>>0}const LS=new TextEncoder;function K(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function RS(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 zS(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),RS(r,14,n),RS(r,18,t),RS(r,22,t),K(r,26,e.length),K(r,28,0),r.set(e,30),r}function BS(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),RS(i,16,n),RS(i,20,t),RS(i,24,t),K(i,28,e.length),K(i,30,0),K(i,32,0),K(i,34,0),K(i,36,0),RS(i,38,0),RS(i,42,r),i.set(e,46),i}function VS(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),RS(r,12,t),RS(r,16,n),K(r,20,0),r}function HS(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 US(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${be(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*WS(e,t,n,r,i){if(n?.aborted)throw i(new a(`transfer-aborted`)),new a(`transfer-aborted`);let o=()=>i(new a(`transfer-aborted`));n?.addEventListener(`abort`,o,{once:!0});let s=ai.create(),c=0,l=0,u=[],d=!1;function*f(e){s.update(e),c+=e.byteLength,l+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),o=LS.encode(`transcript.json`),p=IS(i),m=zS(o,i.length,p);if(u.push({nameBytes:o,size:i.length,crc:p,localOffset:l}),n?.aborted||(yield*f(m),n?.aborted))throw new a(`transfer-aborted`);yield*f(i);for(let[e,r]of t){if(n?.aborted)throw new a(`transfer-aborted`);let t=LS.encode(e),i=IS(r),o=zS(t,r.length,i);if(u.push({nameBytes:t,size:r.length,crc:i,localOffset:l}),yield*f(o),n?.aborted)throw new a(`transfer-aborted`);yield*f(r)}let h=l;for(let e of u){if(n?.aborted)throw new a(`transfer-aborted`);yield*f(BS(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new a(`transfer-aborted`);yield*f(VS(u.length,l-h,h)),d=!0,r({byteLength:c,sha256:s.hex()})}catch(e){throw d=!0,i(e),e}finally{n?.removeEventListener(`abort`,o),d||(d=!0,i(new a(`transfer-aborted`)))}}function GS(e,t,n){for(let e of t.keys())if(!HS(e))throw new a(`schema-invalid`);if(t.size+1>65535)throw new a(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new a(`schema-invalid`);let r,i,o=new Promise((e,t)=>{r=e,i=t});return{filename:US(e),chunks:WS(e,t,n,r,i),completion:o}}function KS(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:re},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function qS(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 JS(e){let t=n(e);if(!t.ok)throw new a(`schema-invalid`,t.error)}function YS(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 XS(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 ZS(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 QS=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),JS(i.document),r?.({phase:`packaging`}),GS(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await mS(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=PS(n.sources),{document:i,bundleFiles:a}=await uS({document:KS(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});JS(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 mS(this.deps.collection,e),r=PS(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=KS(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),uS({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 Yx(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new a(`redaction-unavailable`)}let o=YS(r.attachments,i,e.attachments),s=await XS(r.attachments,o);return{document:{...r,attachments:s},bundleFiles:o}}async buildLegacyPartial(e,t,n){let r=(await vS(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new a(`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 a(`session-not-found`)}let{loadFrozenArchive:o}=await import(`./session-jsonl-D5PzFT5b.js`),{title:s,messages:c}=await o(this.deps.vfs,i,r.filename),l=`legacy-cone`,u=qS(c,l),d=ZS(i),f={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:re},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`}),uS({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 a(`attachment-unreadable`);return t}};const $S=`/sessions/data`,eC=`document.json`;async function tC(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 nC(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new a(`session-not-found`)}function rC(e){return`${$S}/${e}`}function iC(e){return`${$S}/.tmp-${e}`}async function aC(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function oC(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 oC(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function sC(e,t,n){await aC(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 sC(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function cC(e,t,n){nC(t);let r=iC(t),i=rC(t),o=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!o.has(e))throw new a(`schema-invalid`);await oC(e,i),await aC(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await tC(r),i=o.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let a={...n.document,attachments:t},s=JSON.stringify(a,null,2);if(await e.writeFile(`${r}/${eC}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await aC(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await sC(e,r,i),await e.flush()}catch(t){throw await oC(e,r),t}await oC(e,r)}async function lC(e,t){nC(t);let r=rC(t),i=`${r}/${eC}`,o;try{let t=await e.readFile(i,{encoding:`utf-8`});o=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new a(`session-not-found`)}let s;try{s=JSON.parse(o)}catch{throw new a(`schema-invalid`)}if(!n(s).ok)throw new a(`schema-invalid`);let c=new Map;for(let t of s.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 a(`transfer-corrupt`)}if(await tC(i)!==t.sha256)throw new a(`transfer-corrupt`);c.set(t.path,i)}return{document:s,attachments:c}}function uC(e){return`error`in e}function dC(){throw new a(`redaction-unavailable`)}function fC(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&dC(),e.texts}function pC(){return{async redact(e){let t;try{t=await fetch(Re(`/api/secrets/redact-export`),{method:`POST`,headers:ze({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{dC()}t.ok||dC();let n;try{n=await t.json()}catch{dC()}return fC(n,e.length)}}}function mC(){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{dC()}return typeof t==`object`&&t&&uC(t)&&dC(),fC(t,e.length)}}}function hC(){return{async redact(e){let t;try{t=await yn(`secrets.redact-export`,{texts:e})}catch{dC()}return t??dC(),typeof t==`object`&&t&&uC(t)&&dC(),fC(t,e.length)}}}function gC(){return{async redact(e){dC()}}}function _C(){let e=fn();return e===`connect`?gC():e===`extension-direct`?mC():e===`extension-delegate`?hC():pC()}const vC=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function yC(e){return`e${e}`}function bC(e){let t=[];for(let n of e){let e=CC(n),r=TC(n);if(e===`assistant`){let e=t.length,i=yC(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:OC(n),message:n,model:DC(n)});for(let e of kC(n)){let n=t.length;t.push({id:yC(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:yC(i),seq:i,kind:`tool-result`,timestamp:r,text:OC(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=OC(n),a=e===`user`?SC(i):null,o=t.length,s=yC(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):vC.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 xC(e){let t=[];for(let n of e){let e=t.length,r=yC(e),i=EC(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:yC(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&J_(n.channel)?n.channel:SC(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):vC.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 SC(e){for(let t of gv(e)){let e=(t.sender?_v(t.sender):null)??vv(t.body);if(e)return e}return null}function CC(e){return e.role??``}function wC(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 TC(e){return wC(e.timestamp)}function EC(e){return wC(e.timestamp)}function DC(e){let t=e.model;return typeof t==`string`?t:void 0}function OC(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 kC(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 AC(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function jC(e){return e!==null&&e.version<=2}const MC=_(`work-unit-conversation`);var NC=class extends Error{};const PC=`conversations`;async function FC(e){let t=e.now??(()=>Date.now()),n=await LC(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=kr(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await IC(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 NC){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 IC(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 NC(`canonical record unreadable: ${i.reason}`);let a=Ar(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:bC(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:xC(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function LC(e,t){let n=await e.getMigrationState(PC);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:PC,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var RC=e({applyAttachmentOverlays:()=>HC,interleaveMarkers:()=>UC,toAgentMessages:()=>BC,toChatMessages:()=>VC});const zC=new Set([`summarized`,`fallback`]);function BC(e){if(!jC(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 VC(e,t={}){if(!jC(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 UC(t,e.markers)}let n=e.projectionPrefix??[],r=BC(e);if(r.length===0)return UC([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>nv),a=HC(i(r,t),e.attachments);return UC([...n,...a],e.markers)}function HC(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 UC(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||zC.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=WC(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(GC(r[a++]));i.push(t)}for(;a<r.length;)i.push(GC(r[a++]));return i}function WC(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 GC(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 KC(e){return{id:e.legacyKeys.chatSessionId,messages:await VC(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function qC(e){return{id:e.workUnitId,messages:BC(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var JC=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(qC)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(KC))}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(fr({parentJid:null,folder:e}).root);return t?KC(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const YC=_(`work-unit-conversation`),XC=`conversations`,ZC=`migrations`;var QC=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 aw((await this.getDb()).transaction(XC,`readonly`).objectStore(XC).get(e));return t?jC(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(YC.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(YC.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return YC.warn(`Conversation record read failed`,{key:e,error:sw(t)}),{status:`error`,reason:sw(t)}}}async save(e){let t=e.version>2?e.version:AC(e),n={...e,version:t},r=(await this.getDb()).transaction(XC,`readwrite`);return r.objectStore(XC).put(n),await ow(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(XC,`readwrite`);t.objectStore(XC).delete(e),await ow(t)}catch(t){YC.warn(`Conversation record delete failed`,{key:e,error:sw(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`){YC.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){YC.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:sw(n)})}}async loadAll(){try{return(await aw((await this.getDb()).transaction(XC,`readonly`).objectStore(XC).getAll())).filter(e=>jC(e)&&Array.isArray(e.entries))}catch(e){return YC.warn(`Conversation record listing failed`,{error:sw(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await aw((await this.getDb()).transaction(XC,`readonly`).objectStore(XC).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)!jC(e)||!Array.isArray(e.entries)||(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return YC.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:sw(t)}),null}}async listKeys(){try{return(await aw((await this.getDb()).transaction(XC,`readonly`).objectStore(XC).getAllKeys())).map(String)}catch(e){return YC.warn(`Conversation key listing failed`,{error:sw(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=bC(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=$C(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return YC.warn(`Conversation record write failed`,{key:e.key,error:sw(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?ew(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 YC.warn(`Conversation marker write failed`,{key:e,error:sw(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 aw((await this.getDb()).transaction(ZC,`readonly`).objectStore(ZC).get(e))??null}catch(t){return YC.warn(`Migration state read failed`,{id:e,error:sw(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(ZC,`readwrite`);t.objectStore(ZC).put(e),await ow(t)}catch(t){YC.warn(`Migration state write failed`,{id:e.id,error:sw(t)})}}async clearAll(){let e=(await this.getDb()).transaction([XC,ZC],`readwrite`);e.objectStore(XC).clear(),e.objectStore(ZC).clear(),await ow(e)}getDb(){return this.dbPromise||(this.dbPromise=iw(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 $C(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??[],...tw(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&nw(a,t))return null;let o=t.length>a.length&&nw(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 ew(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 tw(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function nw(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!rw(e[n],t[n]))return!1;return!0}function rw(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 iw(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(XC)||e.createObjectStore(XC,{keyPath:`key`}),e.objectStoreNames.contains(ZC)||e.createObjectStore(ZC,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function aw(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function ow(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function sw(e){return e instanceof Error?e.message:String(e)}var cw=e({CONE_MEMORY_PATH:()=>dw,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>uw,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>fw,applyConeMemoryBudget:()=>_w,readSessionCount:()=>hw,restructureConeMemory:()=>gw,splitConeMemory:()=>mw});const lw=_(`cone-memory-budget`),uw=1.25,dw=cr.memoryPath,fw=`/sessions/index.json`,pw=/^## Auto-extracted/m;function mw(e){let t=pw.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function hw(e){try{let t=await e.readFile(fw,{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 gw(e){let{header:t,autoExtracted:n}=mw(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.
992
992
 
993
993
  <auto-extracted>
994
994
  ${n}
@@ -1005,7 +1005,7 @@ Rules:
1005
1005
  `}${o}\n`}async function _w(e){if(!e.model||!e.apiKey)return{restructured:!1,reason:`no-llm`};let t=e.memoryPath??dw,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 hw(e.vfs),i=oi(r),a=i*uw;if(n.length<=a)return{restructured:!1,reason:`under-threshold`};lw.info(`Cone memory over threshold — restructuring`,{size:n.length,budget:i,threshold:a,sessionCount:r});try{let r=await gw({currentContent:n,budget:i,model:e.model,apiKey:e.apiKey,headers:e.headers,signal:e.signal});return await e.vfs.writeFile(t,r),lw.info(`Cone memory restructured`,{before:n.length,after:r.length}),{restructured:!0}}catch(e){return lw.warn(`Cone memory restructure failed — leaving appended content in place`,{error:e instanceof Error?e.message:String(e)}),{restructured:!1,reason:`error`}}}const vw=`.skill`,yw=`/workspace/skills`,bw=`SKILL.md`,xw=_(`skills-discovery`),Sw=[`native`,`agents`,`claude`,`marketplace`,`plugin`],Cw=new Map([[`.agents`,`agents`],[`.claude`,`claude`]]),ww=new Set([`.git`,`.slicc`,`node_modules`]),Tw=2e4,Ew=[`mkdir`,`mount`,`rename`,`rm`,`unmount`,`writeFile`],Dw=new WeakMap,Ow=new WeakSet,kw=new WeakMap,Aw=new WeakMap,jw=new Set([`.agents`,`.claude`,`.claude-plugin`]),Mw=new Set([`mount`,`rename`,`rm`,`unmount`]);async function Nw(e,t=yw){let n=await Hw(e,t),r=await zw(e),i=await Pw(e);return[...Sw.flatMap(e=>(e===`native`?n:e===`plugin`?i:r.filter(t=>t.source===e)).sort((e,t)=>e.path.localeCompare(t.path)))]}async function Pw(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 Yw(e,t);for(let r of i){if(r.type!==`directory`)continue;let i=`${t}/${r.name}`,a=`${i}/${bw}`;await Jw(e,a)&&n.push({source:`plugin`,sourceRoot:t,path:i,skillFilePath:a})}}return n}function Fw(e){return e.map(e=>({...e}))}function Iw(e){Dw.delete(e),Aw.delete(e),kw.set(e,(kw.get(e)??0)+1)}function Lw(e){let t=e.split(`/`);for(let e of t)if(jw.has(e))return!0;return t[t.length-1]===`SKILL.md`||t.includes(`skills`)}function Rw(e,t){if(Mw.has(e))return!0;let n=t[0];return typeof n==`string`&&Lw(n)}async function zw(e){if(Bw(e))return Fw(await Kw(e));qw(e);let t=e,n=Dw.get(t);if(n)return Fw(n);let r=kw.get(t)??0,i=Aw.get(t);if(i&&i.generation===r)return Fw(await i.promise);let a=Kw(e).then(e=>((kw.get(t)??0)===r&&Dw.set(t,e),e)),o;return o=a.finally(()=>{Aw.get(t)?.promise===o&&Aw.delete(t)}),Aw.set(t,{generation:r,promise:o}),Fw(await o)}function Bw(e){try{return e[ti]===!0}catch{return!1}}function Vw(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 Yw(e,t),r=[];for(let i of n){if(i.type!==`directory`)continue;let n=`${t}/${i.name}`,a=`${n}/${bw}`;await Jw(e,a)&&r.push({source:`native`,sourceRoot:t,path:n,skillFilePath:a})}return r}async function Uw(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 Ww(e,t,n){let r=await Uw(e,`${t}/marketplace.json`),i=[];for(let t of r){let r=`${t}/skills`,a=await Yw(e,r);for(let t of a){if(t.type!==`directory`)continue;let a=`${r}/${t.name}`,o=`${a}/${bw}`;!await Jw(e,o)||n.has(a)||(n.add(a),i.push({source:`marketplace`,sourceRoot:r,path:a,skillFilePath:o}))}}return i}async function Gw(e,t,n,r){let i=`${t}/skills`,a=await Yw(e,i),o=[];for(let t of a){if(t.type!==`directory`)continue;let a=`${i}/${t.name}`,s=`${a}/${bw}`;!await Jw(e,s)||r.has(a)||(r.add(a),o.push({source:n,sourceRoot:i,path:a,skillFilePath:s}))}return o}async function Kw(e){let t=[],n=new Set,r=new Set([`/`]),i=[{path:`/`,depth:0}];for(let a=0;a<i.length;a+=1){if(a>=Tw){xw.warn(`skills discovery: directory budget exhausted; walk truncated`,{budget:Tw});break}let{path:o,depth:s}=i[a],c=await Yw(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=Cw.get(a.name);if(l){let r=await Gw(e,c,l,n);t.push(...r)}if(a.name===`.claude-plugin`){let r=await Ww(e,c,n);t.push(...r);continue}!ww.has(a.name)&&s<24&&!r.has(c)&&(r.add(c),i.push({path:c,depth:s+1}))}}return t}function qw(e){if(Bw(e))return;let t=e;if(Ow.has(t))return;Ow.add(t);let n=e;for(let r of Ew){let i=n[r];if(typeof i==`function`)try{n[r]=async(...n)=>{let a=await i.apply(e,n);return Rw(r,n)&&Iw(t),a}}catch{}}}async function Jw(e,t){try{return await e.stat(t),!0}catch{return!1}}async function Yw(e,t){try{return[...await e.readDir(t)].sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}async function Xw(e,t=`/workspace/skills`){let n=await Nw(e,t),r=[];for(let t of n){let n=t.path.split(`/`).pop()??t.path,i=``;if(t.skillFilePath)try{i=$w(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}=Vw(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 Zw(e,t,n=`/workspace/skills`){return(await Xw(e,n)).find(e=>e.name===t)||null}async function Qw(e,t,n=`/workspace/skills`){let r=await Zw(e,t,n);if(!r?.skillFilePath)return null;try{return await e.readTextFile(r.skillFilePath)}catch{return null}}function $w(e){let t=e.replace(/^\uFEFF/,``).replace(/\r\n?/g,`
1006
1006
  `).trimStart().match(/^---\s*\n([\s\S]*?)\n---/);if(!t)return null;for(let e of t[1].split(`
1007
1007
  `)){let t=e.match(/^description:\s*(.*)$/);if(t)return t[1].trim()}return null}const eT=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function tT(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 nT=class extends Error{};function rT(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 iT(e){if(!eT.test(e))throw Error(`Invalid skill: skill name "${e}" must be a simple directory name.`)}function aT(e){let t=[];for(let[n,r]of Object.entries(e)){let e=rT(n);e&&(tT(e)||t.push({originalPath:n,path:e,bytes:r}))}return t}function oT(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 ${bw}.`);if(t.length>1)throw Error(`Skill archive contains multiple ${bw} files.`);return t[0]}function sT(e){let t=0,n=0;return di(e,{filter(e){if(t++,t>1e3)throw new nT(`Skill archives may contain at most 1000 entries.`);if(n+=e.originalSize,n>52428800)throw new nT(`Skill archives must expand to 50 MB or smaller after extraction.`);return!0}})}function cT(e){let t=`${Date.now()}-${Math.random().toString(16).slice(2,8)}`;return Dn(yw,`.${e}.tmp-${t}`)}function lT(e,t){return t===`SKILL.md`?e.replace(/\.skill$/i,``):t.slice(0,-9).split(`/`).pop()??``}function uT(e){if(!e.name.toLowerCase().endsWith(`.skill`))throw Error(`Only ${vw} archives can be installed with drag and drop.`);if(e.size>52428800)throw Error(`Skill archives must be 50 MB or smaller.`)}async function dT(e){try{return sT(new Uint8Array(await e.arrayBuffer()))}catch(e){if(e instanceof nT)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Invalid .skill archive: ${t}`)}}function fT(e){return e.path===`SKILL.md`?``:e.path.slice(0,-9)}function pT(e,t){return t&&(e===t||!e.startsWith(`${t}/`))?null:(t?e.slice(t.length+1):e)||null}async function mT(e,t,n,r){let i=Dn(t,n),{dir:a}=Tn(i);a!==`/`&&await e.mkdir(a,{recursive:!0}),await e.writeFile(i,r)}async function hT(e,t,n,r){let i=0;for(let a of t){let t=pT(a.path,n);t&&(await mT(e,r,t,a.bytes),i++)}return i}async function gT(e,t){await e.exists(t)&&await e.rm(t,{recursive:!0})}async function _T(e,t){let n=Dn(yw,t);if(await e.exists(n))throw Error(`Skill "${t}" already exists at ${n}.`);return n}async function vT(e,t){uT(t);let n=aT(await dT(t)),r=oT(n),i=lT(t.name,r.path);iT(i);let a=await _T(e,i),o=cT(i),s=fT(r);await e.mkdir(o,{recursive:!0});try{let t=await hT(e,n,s,o);return await e.rename(o,a),{skillName:i,destinationPath:a,fileCount:t}}catch(t){throw await gT(e,o),t}}var yT=e({MAX_SKILL_ARCHIVE_SIZE_BYTES:()=>52428800,SKILLS_DIR:()=>`skills`,SKILL_ARCHIVE_EXTENSION:()=>vw,SKILL_FILE:()=>bw,WORKSPACE_SKILLS_PATH:()=>yw,discoverSkillCandidates:()=>Nw,discoverSkills:()=>Xw,getSkillInfo:()=>Zw,installSkillFromDrop:()=>vT,readSkillInstructions:()=>Qw,resolveSkillNameCollisions:()=>Vw});const bT=_(`skills`),xT=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-Dc_zsP8N.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-Dc_zsP8N.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-B9cGngY_.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-BbKu0tAh.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-B4YYagrM.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-Jawax3MO.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-CVh4bFFa.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-nuxIaHgr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-BGRdm7JZ.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-CG7Xvjv7.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-CX_QtSBf.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-DiQ9SvKe.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-nEVBLbup.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-B8Oawe6a.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/theme/SKILL.md":()=>import(`./SKILL-CTFXwGP5.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-9iH3AJo5.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)}),ST=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function CT(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 wT={};function TT(){let e={};for(let[t,n]of Object.entries(xT))e[t]=n;for(let[t,n]of Object.entries(ST))e[t]=async()=>CT(await n());for(let[t,n]of Object.entries(wT)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function ET(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){bT.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 DT(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(`
1008
- `)){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}}const OT=new WeakMap;function kT(e,t,n,r){let i=e.get(t);i||(i=new Map,e.set(t,i));let a=i.get(n);if(a)return a;let o;return o=r().finally(()=>{i.get(n)===o&&i.delete(n)}),i.set(n,o),o}async function AT(e,t){let n=await jT(e,t),r=await MT(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=ET([...i,...r,...a]);return bT.info(`Skills loaded`,{count:o.length,dir:t}),o}async function jT(e,t){let n=await Xw(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=DT(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}),bT.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{bT.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function MT(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}=DT(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}),bT.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{bT.debug(`Standalone skills directory not found`,{dir:t})}return n}function NT(e){return e.length===0?``:`
1008
+ `)){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}}const OT=new WeakMap;function kT(e,t,n,r){let i=e.get(t);i||(i=new Map,e.set(t,i));let a=i.get(n);if(a!=null)return a;let o;return o=r().finally(()=>{i.get(n)===o&&i.delete(n)}),i.set(n,o),o}async function AT(e,t){let n=await jT(e,t),r=await MT(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=ET([...i,...r,...a]);return bT.info(`Skills loaded`,{count:o.length,dir:t}),o}async function jT(e,t){let n=await Xw(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=DT(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}),bT.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{bT.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function MT(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}=DT(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}),bT.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{bT.debug(`Standalone skills directory not found`,{dir:t})}return n}function NT(e){return e.length===0?``:`
1009
1009
  ---
1010
1010
  AVAILABLE SKILLS
1011
1011
 
@@ -1167,15 +1167,15 @@ Created: ${new Date().toISOString()}
1167
1167
  `),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 DO(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 OO=_(`tool:bash`),kO=40960,AO=1048576,jO=`\0slicc-img:`;function MO(e){let t=xn(e).filter(e=>e.kind===`image`);if(t.length===0)return{text:e,markers:new Map};let n=new Set,r=AO;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=`${jO}${r}`;i.set(e,t.marker),a+=e}else a+=`[image dropped: a newer image in this command used up the ${AO/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 NO(e){let t=xn(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 PO(e){return e.replaceAll(RegExp(`${jO}\\d+`,`g`),`[image]`)}function FO(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 IO(e,t,n,r){let{text:i,markers:a}=MO(e),o=EO(i,{maxBytes:kO});if(!o.truncated)return FO(i,a);let s=`showing the last ${wO(o.outputBytes)} of ${wO(o.totalBytes)} (${o.totalLines} lines)`,c=`${n}/bash-output-${r()}.txt`;try{return await t.writeFile(c,PO(i)),FO(`${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 OO.warn(`Failed to persist full bash output`,{error:e instanceof Error?e.message:String(e)}),FO(`${o.content}\n\n[Output truncated: ${s}. Re-run piping through \`head\`/\`tail\`/\`grep\`/\`sed -n\` to narrow the output.]`,a)}}const LO=new Set([`grep`,`egrep`,`fgrep`,`rg`]);function RO(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 zO(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=RO(r.name);if(i!==`command`)return i;let a=r.args[0];return a?RO(a):null}function BO(e,t,n,r){if(n!==1||r.trim())return!1;let i;try{i=zO(e.getBash().transform(t).ast)}catch{return!1}return i!==null&&LO.has(i)}function VO(e,t){let n=e.options.annotateResult?.();return n?`${t.endsWith(`
1168
1168
  `)||t.length===0?t:`${t}\n`}${n}\n`:t}function HO(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return e}function UO(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 ${kO/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 ${AO/1024}KB of images per command reaches you as pictures, not base64. A command still running after background_after seconds (default ${e}) is detached: you get a job id at once and a Background Command lick delivers its exit code and output later, so a stuck command never wedges the turn. A pipeline reports the last stage's exit (bash default); when any stage is non-zero the result includes \`pipeline: 1 0\` with each stage's code.`}function WO(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 GO(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 KO(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 QO(e,n,r);await e.fs.writeFile(t,i)}).catch(e=>OO.warn(`Failed to tee background bash output`,{jobId:n,outputPath:t,error:e instanceof Error?e.message:String(e)}))};return{job:i,controller:r,settled:e.shell.executeCommand(t,r.signal,i?.pid,void 0,{capturePipeStatus:!0,onOutput:e=>{o.push(e),u()}}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e instanceof Error?e.message:String(e)})),releaseTurnSignal:()=>n?.removeEventListener(`abort`,a),getTeedOutput:()=>o.join(``),startPersisting:(t,n)=>{s=t,c=n,l=l.then(()=>e.swept).then(()=>void 0),u()},flushPersist:()=>l,killedByTimeout:!1}}function qO(e,t){t===`timeout`&&(e.killedByTimeout=!0),e.job?.kill(),e.controller.abort(),e.job?.exit(null)}function JO(e,t){e.job?.exit(e.job.signal.aborted?null:t)}function YO(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 XO(e,t,n,r={}){let i=0,a=0,o=import(`./bash-job-journal-DEe5YuRn.js`),s=o.then(({createBashJobJournal:e})=>e(t,n,void 0,(e,t)=>OO.warn(e,{tempDir:n,error:t instanceof Error?t.message:String(t)}))),c={shell:e,fs:t,tempDir:n,options:r,defaultBackgroundAfter:HO(r.defaultBackgroundAfterSeconds)??600,nextOutputSeq:()=>i+=1,nextJobId:()=>`bg-${a+=1}`,journal:s,swept:Promise.resolve()};return c.swept=Promise.all([o,s]).then(([{KERNEL_RESTART_EXIT_CODE:e},t])=>t.sweep((t,n)=>ZO(c,t,n,e))).catch(e=>OO.warn(`Could not sweep orphaned bash jobs`,{tempDir:n,error:e})),{name:`bash`,description:UO(c.defaultBackgroundAfter),inputSchema:WO(c.defaultBackgroundAfter),execute:(e,t)=>ik(c,e,t)}}function ZO(e,t,n,r){let i={type:`bash`,bashJobId:t.jobId,bashCommand:t.command,bashExitCode:r,...t.pid===void 0?{}:{bashJobPid:t.pid},resultPath:t.outputPath,preview:n,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:new Date().toISOString(),body:{jobId:t.jobId,pid:t.pid??null,command:t.command,exitCode:r,resultPath:t.outputPath,killedByKernelRestart:!0}};OO.warn(`Background bash job was killed by a kernel restart`,{jobId:t.jobId,command:t.command,startedAt:t.startedAt});let a=n=>{if(e.options.fireLick?.(i)===!1){if(n<=1){OO.warn(`No lick sink for a kernel-restart job report; output file still has it`,{jobId:t.jobId,outputPath:t.outputPath});return}setTimeout(()=>a(n-1),2e3)}};a(30)}async function QO(e,t,n){let r=e.options.scrubOutput;if(!r||!n)return n;try{return await r(n)}catch(e){return OO.warn(`Background bash output scrub failed; withholding output`,{jobId:t,error:e instanceof Error?e.message:String(e)}),`[output withheld: secret scrub unavailable]`}}function $O(e){return e.ok?e.result.exitCode===124&&/execution aborted/i.test(e.result.stderr):/execution aborted/i.test(e.error)}function ek(e,t){return e===void 0?`--- killed (exit ${t}) ---\n`:`--- killed after ${e}s (exit ${t}) ---\n`}async function tk(e,t,n,r,i,a,s,c){await s.flushPersist();let l=s.killedByTimeout||$O(a),u,d;if(l){let e=s.getTeedOutput();d=124,u=`${e.endsWith(`
1169
1169
  `)||e.length===0?e:`${e}\n`}${ek(c,d)}`}else if(a.ok)u=o([a.result.stdout,a.result.stderr].filter(Boolean).join(``)||`(exit code: ${a.result.exitCode})`,a.result.pipeStatus),d=a.result.exitCode;else{let e=s.getTeedOutput();d=1,u=e?`${e.endsWith(`
1170
- `)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let f=await QO(e,t,VO(e,u)),p;try{await e.fs.writeFile(i,f),p=i}catch(e){OO.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){OO.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:d});return}let m=EO(NO(f),{maxBytes:2048});e.options.fireLick({type:`bash`,bashJobId:t,bashCommand:r,bashExitCode:d,...n===void 0?{}:{bashJobPid:n},resultPath:p,preview:m.content,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:new Date().toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:d,resultPath:p??null}})}function nk(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=Promise.all([e.journal,e.swept]).then(([e])=>e.record({jobId:o,pid:s,command:n,outputPath:c,startedAt:new Date().toISOString()})),u=()=>l.then(()=>e.journal).then(e=>e.clear(o)).catch(e=>OO.warn(`Could not journal a detached bash job`,{jobId:o,error:e})),d=i===void 0?void 0:i-a,f=d===void 0?void 0:setTimeout(()=>qO(t,`timeout`),d*1e3);return t.settled.then(r=>(f!==void 0&&clearTimeout(f),JO(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),tk(e,o,s,n,c,r,t,i))).catch(e=>OO.error(`Background bash delivery failed`,{jobId:o,error:e})).then(u),OO.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:d}),YO(o,s,r,c,i)}async function rk(e,t,n){OO.debug(`Result`,{exitCode:n.exitCode,stdoutLength:n.stdout.length,stderrLength:n.stderr.length});let r=``;return n.stdout&&(r+=n.stdout),n.stderr&&(r+=n.stderr),r||=`(exit code: ${n.exitCode})`,r=VO(e,o(r,n.pipeStatus)),{content:await IO(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!BO(e.shell,t,n.exitCode,n.stderr)}}async function ik(e,t,n){let r=t.command,i=HO(t.timeout),a=HO(t.background_after)??e.defaultBackgroundAfter;OO.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=KO(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?(qO(o,`timeout`),OO.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),GO(c)):t===`elapsed`?nk(e,o,r,c,i,a):(JO(o,t.ok?t.result.exitCode:1),t.ok?await rk(e,r,t.result):(OO.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const ak={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 ok(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function sk(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:ok(e)&&(t.edits=[e])}catch{}else ok(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 ck(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:ak,prepareArguments:sk,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-DhrrHmSn.js`);return i(e,t,n,r)}}}async function lk(e,t,n){if(Fr(En(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 uk=_(`tool:fs`);function dk(e,t=`/workspace`){return[fk(e),pk(e),ck(e,t)]}function fk(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${SO/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;uk.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
1170
+ `)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let f=await QO(e,t,VO(e,u)),p;try{await e.fs.writeFile(i,f),p=i}catch(e){OO.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){OO.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:d});return}let m=EO(NO(f),{maxBytes:2048});e.options.fireLick({type:`bash`,bashJobId:t,bashCommand:r,bashExitCode:d,...n===void 0?{}:{bashJobPid:n},resultPath:p,preview:m.content,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:new Date().toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:d,resultPath:p??null}})}function nk(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=Promise.all([e.journal,e.swept]).then(([e])=>e.record({jobId:o,pid:s,command:n,outputPath:c,startedAt:new Date().toISOString()})),u=()=>l.then(()=>e.journal).then(e=>e.clear(o)).catch(e=>OO.warn(`Could not journal a detached bash job`,{jobId:o,error:e})),d=i===void 0?void 0:i-a,f=d===void 0?void 0:setTimeout(()=>qO(t,`timeout`),d*1e3);return t.settled.then(r=>(f!==void 0&&clearTimeout(f),JO(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),tk(e,o,s,n,c,r,t,i))).catch(e=>OO.error(`Background bash delivery failed`,{jobId:o,error:e})).then(u),OO.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:d}),YO(o,s,r,c,i)}async function rk(e,t,n){OO.debug(`Result`,{exitCode:n.exitCode,stdoutLength:n.stdout.length,stderrLength:n.stderr.length});let r=``;return n.stdout&&(r+=n.stdout),n.stderr&&(r+=n.stderr),r||=`(exit code: ${n.exitCode})`,r=VO(e,o(r,n.pipeStatus)),{content:await IO(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!BO(e.shell,t,n.exitCode,n.stderr)}}async function ik(e,t,n){let r=t.command,i=HO(t.timeout),a=HO(t.background_after)??e.defaultBackgroundAfter;OO.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=KO(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?(qO(o,`timeout`),OO.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),GO(c)):t===`elapsed`?nk(e,o,r,c,i,a):(JO(o,t.ok?t.result.exitCode:1),t.ok?await rk(e,r,t.result):(OO.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const ak={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 ok(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function sk(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:ok(e)&&(t.edits=[e])}catch{}else ok(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 ck(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:ak,prepareArguments:sk,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-uvLIX_Ai.js`);return i(e,t,n,r)}}}async function lk(e,t,n){if(Fr(En(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 uk=_(`tool:fs`);function dk(e,t=`/workspace`){return[fk(e),pk(e),ck(e,t)]}function fk(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${SO/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;uk.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
1171
1171
  `),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=TO(c.join(`
1172
- `));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${wO(new TextEncoder().encode(t[o]??``).length)}, exceeds ${wO(SO)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${SO}]`};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} (${wO(SO)} 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 uk.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function pk(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;uk.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await lk(e,n,r);return t?(uk.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 uk.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const mk={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 hk(e,t){return{name:si,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:mk,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-DaTYSj3P.js`);return r(e,t,n)}}}function gk(){return null}const _k=_(`tool:request-secret`);async function vk(e,t){let n=gk();if(n)return n(e);let r=t.callPanelRpc??await yk();return r?r(e):{stored:!1,reason:`unavailable`}}async function yk(){let{getPanelRpcClient:e}=await import(`./panel-rpc-DW7W4w6_.js`).then(e=>e.a),t=e();return t?e=>t.call(`secret-request`,e,{timeoutMs:3e5}):null}function bk(e){try{return e.getProvider?.()||void 0}catch(e){_k.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function xk(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 Sk(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(`
1172
+ `));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${wO(new TextEncoder().encode(t[o]??``).length)}, exceeds ${wO(SO)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${SO}]`};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} (${wO(SO)} 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 uk.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function pk(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;uk.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await lk(e,n,r);return t?(uk.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 uk.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const mk={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 hk(e,t){return{name:si,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:mk,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-BnZvvvjC.js`);return r(e,t,n)}}}function gk(){return null}const _k=_(`tool:request-secret`);async function vk(e,t){let n=gk();if(n)return n(e);let r=t.callPanelRpc??await yk();return r?r(e):{stored:!1,reason:`unavailable`}}async function yk(){let{getPanelRpcClient:e}=await import(`./panel-rpc-DW7W4w6_.js`).then(e=>e.a),t=e();return t?e=>t.call(`secret-request`,e,{timeoutMs:3e5}):null}function bk(e){try{return e.getProvider?.()||void 0}catch(e){_k.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function xk(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 Sk(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(`
1173
1173
  `)}function Ck(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 wk(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:xk(t.domains),persist:t.persist===!0,requester:e.requester,provider:bk(e)},a;try{a=await vk(i,e)}catch(e){let t=e instanceof Error?e.message:String(e);return _k.error(`secret request failed`,{name:n,error:t}),{content:`The secret prompt failed: ${t}`,isError:!0}}if(!a.stored)return{content:Ck(a),isError:!0};let o=Tk(a.name,a.maskedValue,e);return _k.info(`secret stored via request_secret`,{name:a.name,persisted:a.persisted}),{content:Sk(a,o)}}}}function Tk(e,t,n){if(!n.setEnv||!t||!g(e))return!1;try{return n.setEnv(e,t),!0}catch(t){return _k.warn(`could not inject the masked value into the shell env`,{name:e,error:t instanceof Error?t.message:String(t)}),!1}}const Ek=_(`scoop-management-tools`),Dk=`cross_cone`;function Ok(e){return Fn(e.getScoops(),e.scoop.jid)}function kk(e){let t=new Set;for(let n of Ok(e))n.jid!==e.scoop.jid&&n.parentJid!==null&&t.add(n.jid);return t}function Ak(e){let t=zn(e.getScoops());return t!==void 0&&t.jid===e.scoop.jid}function jk(e){let t=e.getScoops(),n=kk(e),r=Ak(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=tr(t,e);a.kind!==`cycle`&&i.push({scoop:e,relation:a.kind===`root`?`foreign`:`inherited`})}return i}function Mk(e){return t=>t.folder===e||t.name===e}function Nk(e,t){let n=jk(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 Pk(e,t){let n=[],r=[];for(let i of e){let e=Nk(i,t);e?n.push(e):r.push(i)}return{resolved:n,unknown:r}}function Fk(e,t){return Ln(e.getScoops(),t.scoop)?.folder??`unknown`}function Ik(e,t){return t.relation===`inherited`?`inherited (its owning cone is gone)`:`owned by cone "${Fk(e,t)}"`}function Lk(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 ${Ik(r,e)}`).join(`; `)}. Pass ${Dk}: true to act on it anyway.`,isError:!0}}function Rk(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 zk=[`command`,`read`,`write`,`secret`];function Bk(e){return`${be(e,{maxLen:50})}-scoop`}function Vk(e){return e===void 0?{ok:!0}:pr(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${mr.join(`, `)}.`,isError:!0}}function Hk(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 Uk(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 Wk(e,t){let n=jk(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 Gk(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 Kk(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),Ek.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function qk(e){let{kind:t,detail:n,suggested_pattern:r,reason:i}=e;if(!zk.includes(t))return{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${zk.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`?h(i):``;return{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{},...a?{reason:a}:{}}}}function Jk(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(`
1174
1174
  `)}async function Yk(e,t){let n=qk(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return Ek.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:Jk(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function Xk(e,t){let{scoop_name:n,prompt:r,cross_cone:i}=e;if(Mk(n)(t.scoop))return{content:`Cannot feed yourself.`,isError:!0};let a=Nk(n,t);if(!a)return Wk([n],t);let o=Lk([a],i,`feed "${n}"`,t);if(o)return o;try{await t.onFeedScoop(a.scoop.jid,r),Ek.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 (${Dk}: 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 Zk(e,t){return t.relation===`own`?``:t.relation===`inherited`?` [INHERITED]`:` [FOREIGN: ${Fk(e,t)}]`}async function Qk(e){let t=new Map(jk(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 Gk(n,e.getScoopTabState,r?Zk(e,r):``)}).join(`
1175
1175
  `)}`}}function $k({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}:{},...eA(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 eA(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function tA(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return Ek.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 nA(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=jn(s);if(!f.ok)return{content:f.error,isError:!0};let p=Vk(l);if(!p.ok)return{content:p.content,isError:p.isError};let m=Hk(u);if(!m.ok)return{content:m.content,isError:!0};let h=Uk(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let ee=Bk(n),g=Ok(t).find(e=>e.jid!==t.scoop.jid&&e.parentJid!==null&&(e.name===n||e.folder===ee));if(g)return{content:`A scoop named "${g.name}" (${g.folder}) already exists in your scoops. Use feed_scoop to give it another task, or drop_scoop first.`,isError:!0};let te=Un(ee,t.getScoops().map(e=>e.folder));try{let e=$k({name:n,folder:te,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:lr(fr(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return Ek.info(`Scoop created`,{name:n,folder:te}),i&&t.onFeedScoop?tA(r,i,n,te,t.onFeedScoop):{content:`Scoop "${n}" created as "${te}". 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 rA(e,t){let{scoop_name:n,cross_cone:r}=e;if(Mk(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=Nk(n,t);if(!i)return Wk([n],t);let a=Lk([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),Ek.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 iA(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function aA(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return iA();let{resolved:i,unknown:a}=Pk(n,t);return i.length===0?Wk(a,t):Lk(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),Ek.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 oA(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 sA(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return iA();let{resolved:i,unknown:a}=Pk(n,t);if(i.length===0)return Wk(a,t);let o=Lk(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);Ek.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(...oA(l,c)),{content:u.join(`
1176
1176
  `)}}function cA(e,t){return!Array.isArray(e)||e.length===0?iA():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 lA(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 uA(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=cA(n,r);if(a)return a;let{resolved:o,unknown:s}=Pk(n,t);if(o.length===0)return Wk(s,t);let c=Lk(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 Ek.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:lA(f,s,p,r)}}function dA(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 fA(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`?h(a):``,s={...r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`},...o?{note:o}:{}};try{let e=await t.onSudoResolve(n,s);return e.settled?(Ek.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:dA(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 pA(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`?h(r):``;try{let e=await t.onSudoResolve(n,{decision:`deny`,...i?{note:i}:{}});return e.settled?(Ek.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 mA(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(`
1177
- `)}`}}async function hA(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),Ek.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 gA(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=>Kk(t,e)}}function _A(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:[...zk],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=>Yk(t,e)}}function vA(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.`},[Dk]:Rk(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>Xk(t,e)}}function yA(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:()=>Qk(e)}}function bA(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:[...mr],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=>nA(t,e)}}function xA(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.`},[Dk]:Rk(`drop`)},required:[`scoop_name`]},execute:t=>rA(t,e)}}function SA(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"]).`},[Dk]:Rk(`mute`)},required:[`scoop_names`]},execute:t=>aA(t,e)}}function CA(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"]).`},[Dk]:Rk(`unmute`)},required:[`scoop_names`]},execute:t=>sA(t,e)}}function wA(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."},[Dk]:Rk(`wait on`)},required:[`scoop_names`]},execute:t=>uA(t,e)}}function TA(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=>fA(t,e)}}function EA(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=>pA(t,e)}}function DA(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:()=>mA(e)}}function OA(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=>hA(t,e)}}function kA(e){let t=[],n=In(e.scoop);return Nn(e.scoop)||(t.push(gA(e)),e.onSudoRequest&&t.push(_A(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(bA(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(vA(e)),t.push(yA(e)),e.onDropScoop&&t.push(xA(e)),e.onMuteScoops&&t.push(SA(e)),e.onUnmuteScoops&&t.push(CA(e)),e.onScheduleScoopWait&&t.push(wA(e)),e.onSudoResolve&&(t.push(TA(e)),t.push(EA(e))),e.onListSudoRequests&&t.push(DA(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(OA(e))),t}const AA=_(`scoop-context`);function jA(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-BzUxTS0o.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function MA(e){let{scoop:t,unit:n,callbacks:r}=e,i=kA({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:de,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=dk(e.gatedFs,n.workspace.root),o=e.blindReads??null,s=hk(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>cw);return t(e.fs)},...o?{blindPaths:()=>o.outsidePaths()}:{}}),c=[...a,s,XO(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:pn(),...o?{annotateResult:()=>o.takeNote()}:{},fireLick:e=>{let n=globalThis.__slicc_lick_handler;return n?(n(e),!0):(AA.warn(`No lick handler for background bash completion`,{folder:t.folder}),!1)}}),...i,wk({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>xO(AD(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);c.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let l={scrubToolResult:pn()},u=jA(e);return e.processManager?mn(c,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},l,u):mn(c,void 0,l,u)}const NA=_(`scoop-context`);async function PA(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();NA.info(`Filesystem ready`,{folder:t.folder}),await YD(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,blindReads:l,skills:u}=await yO({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 d=await MA({getTurnGuestGates:e.getTurnGuestGates,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,blindReads:l,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:f,globalMemory:p}=await DD(r,n,()=>i.getGlobalMemory());if(!kD(t))return NA.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let m=jD(t,n),h=PD(t,n,p,f,u),ee=await e.sessions.restore(),{streamWithSessionId:g,compactFn:te,getCompactionApiKey:ne}=await ZD(m,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>kD(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let re=Wn(t);return{kind:`ready`,agent:qD({model:m,tools:d,systemPrompt:h,messages:ee,thinkingLevel:ID(LD()??re.level,m),getApiKey:()=>kD(t)??void 0,transformContext:te,streamFn:g,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:te,getCompactionApiKey:ne,effortOverride:re.effortOverride,toolCount:d.length}}const FA=_(`scoop-context`);var IA=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 FA.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=BC(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=hn(n);return FA.info(`Restored conversation from the canonical work-unit record`,{folder:this.deps.folder,messageCount:r.length,droppedOrphans:n.length-r.length}),r}persistNow(e){this.flush(e)}flush(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return Promise.resolve();let n=this.deps.canonical;return n?(this.createdAt||=Date.now(),n.store.syncAgentMessages(n.identity,t,{createdAt:this.createdAt}).then(()=>void 0,e=>{FA.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})})):Promise.resolve()}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){FA.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 LA(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 RA(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function zA(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const BA=_(`scoop-context`);var VA=class{deps;constructor(e){this.deps=e}async run(e,t){let n=null;for(let r=1;r<=3;r++){if(this.deps.isDisposed()||t.aborted)return null;let i=await this.tryAttempt(e,t);if(!i||this.deps.isDisposed()||t.aborted||(n=i,await this.handleAttemptError(i,r,t)))return null}return n}reportExhausted(e){let t=e.message;BA.error(`Agent error after retries exhausted`,{folder:this.deps.folder,error:t,maxRetries:3}),this.fail(`Scoop "${this.deps.scoopName}" failed after 3 attempts: ${t}`,t)}async tryAttempt(e,t){this.deps.beginAttempt();try{if(await e(),this.deps.isDisposed()||t.aborted)return null;let n=this.deps.overflow.pendingRecovery;if(n!==null&&(await n,this.deps.overflow.clearPendingRecovery(n),this.deps.isDisposed()||t.aborted))return null;let r=this.deps.getStreamError();return r?Error(r):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handleAttemptError(e,t,n){let r=e.message;return this.handleStaleAssetError(r)||this.handleNonRetryableError(r)?!0:!await this.handleRetryableError(r,t,n)&&(BA.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:mD(r)}),!!(t<3&&(await hD(HA(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return pD(e)?(BA.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 Wa(e)?(BA.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),qa(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(!mD(e)||t>=3)return!1;let r=HA(t);return BA.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await hD(r,n)&&!this.deps.isDisposed()}fail(e,t){iD(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function HA(e){return 1e3*2**(e-1)}function UA(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){BA.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 WA=_(`scoop-context`);var GA=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;forceReleaseTimer=null;turnEpoch=0;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;turnJournal;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>(this.callbacks.onToolStart?.(e,t,n),this.makeToolCallDurable(e,t,n)),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:e=>this.checkpoint(e),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s,c,l,u){this.scoop=e,this.unit=sr(e),this.owner={kind:Vn(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.capabilityBroker=l??null,this.turnJournal=u??null,this.sessions=new IA({store:r??null,canonical:c?{store:c,identity:Ar(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 WD({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new SD({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new wD({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new UD({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 VA({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 mO(this.unit,this.scoop,O(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return ir(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 PA({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`),WA.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);WA.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(ND(this.scoop)),!1)}cleanupPromptState(e,t,n,r,i){if(i!==void 0&&i!==this.turnEpoch){this.currentTurnProcess!==t&&RA(this.processManager,t,{lastError:n,aborted:!0});return}this.runBounds.disarm();let a=this.runBounds.takeExceededNote();a!==null&&this.callbacks.onError(`agent run terminated: ${a}`),(n||r.aborted)&&this.sessions.persistNow(),this.disarmForceRelease(),this.isProcessing=!1,this.turnJournal?.end(this.scoop.jid),!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),RA(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(UA(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder})){for(let e of r)this.addTurnGuestGate(e);return}this.turnGuestGates=[...r];let i=this.agent;await this.runTurn(e,0,()=>i.prompt(e,t))}async resumeTurn(e,t=[]){if(!await this.ensureAgentReady()||this.isBusy)return;this.turnGuestGates=[...t];let n=this.agent;await this.runTurn(`(resumed after reload)`,e,()=>{let e=n.state.messages,t=e[e.length-1];return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)&&(n.state.messages=e.slice(0,-1)),n.continue()})}settleInterruptedToolCalls(e){let t=this.agent;if(!t||e.length===0)return;let n=Date.now(),r=e.map(e=>({role:`toolResult`,toolCallId:e.toolCallId,toolName:e.toolName,content:[{type:`text`,text:e.text}],isError:!0,timestamp:n}));t.state.messages=[...t.state.messages,...r],this.sessions.persistNow();for(let t of e)this.callbacks.onToolEnd?.(t.toolName,t.text,!0,t.toolCallId)}reportError(e){this.callbacks.onError(e)}hasAgent(){return this.agent!==null}async runTurn(e,t,n){this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal,a=++this.turnEpoch;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let o=LA(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:r});this.currentTurnProcess=o,this.runBounds.arm(),this.turnJournal?.begin(this.scoop.jid,this.scoop.folder,t,this.turnGuestGates);let s=null;try{if(s=await this.turnRunner.run(n,i),s&&!this.disposed&&!i.aborted){this.turnRunner.reportExhausted(s);return}a===this.turnEpoch&&!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,o,s,i,a)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||(this.turnGuestGates.push(e),this.turnJournal?.setGuestGates(this.scoop.jid,this.turnGuestGates))}stop(){zA(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.armForceRelease()}disarmForceRelease(){this.forceReleaseTimer!==null&&(clearTimeout(this.forceReleaseTimer),this.forceReleaseTimer=null)}armForceRelease(){this.disarmForceRelease();let e=this.turnEpoch,t=this.currentTurnProcess;this.forceReleaseTimer=setTimeout(()=>{this.forceReleaseTimer=null,!(this.disposed||this.turnEpoch!==e||!this.isProcessing)&&(t&&this.processManager&&(this.processManager.signal(t.pid,`SIGKILL`),this.processManager.exit(t.pid,null)),this.bashJobs.reapAll(),this.shell?.cancelActiveCommand(),this.agent?.abort?.(),!(this.turnEpoch!==e||!this.isProcessing)&&(this.isProcessing=!1,this.status===`processing`&&this.setStatus(`ready`)))},2e3)}clearMessages(){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 jx(this.scoop)?!0:this.unit.parentId===null&&ke(`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-CwYw083A.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:gn,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&&!ke(`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-Chxvnh3i.js`),a=this.unit.parentId===null,o=await i({vfs:this.fs,cone:{folder:this.scoop.folder,label:this.scoop.assistantLabel},messages:e,trigger:t,...a?{}:{sessionsDir:r(this.scoop.folder,this.scoop.jid)},stillValid:()=>!this.disposed&&n===this.sessionGeneration});return o&&a&&this.scheduleLiveDeltaCuration(),o?{transcriptPath:o.transcriptPath}:void 0}scheduleLiveDeltaCuration(){let e=this.fs;if(!e)return;let t={folder:this.scoop.folder,...this.scoop.jid?{jid:this.scoop.jid}:{}};import(`./live-session-curation-EtIGz3m_.js`).then(e=>e.r).then(n=>n.scheduleLiveDeltaCuration({vfs:e,cone:t})).catch(e=>{WA.warn(`Live delta curation failed to start`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}async settleLiveSnapshot(e){if(!(this.unit.parentId!==null||!this.fs))try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-Chxvnh3i.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){WA.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 MD(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=zD(this.agent,this.scoop))}async reloadSkills(){this.agent&&await VD(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){if(!this.agent)return WA.info(`Thinking level stored for a deferred agent`,{requested:e}),`off`;if(LD())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=BD(this.agent,e);return WA.info(`Thinking level applied`,{requested:e,resolved:n,model:this.agent.state.model?.id,provider:this.agent.state.model?.provider,reasoning:this.agent.state.model?.reasoning===!0}),n}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}streamThinking(){if(!this.agent)return null;let e=this.agent.state.thinkingLevel;return{level:e,...e!==`off`&&this.activeEffortOverride===`max`?{effortOverride:`max`}:{}}}dispose(){this.sessions.persistNow(),this.turnJournal?.end(this.scoop.jid),this.disposed=!0,this.disarmForceRelease(),this.idleCompaction?.cancel(),this.runBounds.disarm(),zA(this.processManager,this.currentTurnProcess,`SIGTERM`,this.promptAbortController),this.bashJobs.reapAll(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}handleAgentEvent(e,t){if(!this.disposed)return vD(e,this.eventSink,t)}async makeToolCallDurable(e,t,n){let r=Promise.all([this.sessions.flush(),n?this.turnJournal?.toolStarted(this.scoop.jid,n,e,t):null]),i,a=new Promise(e=>{i=setTimeout(()=>e(`timeout`),2e3)});try{await Promise.race([r,a])===`timeout`&&WA.warn(`Tool call not yet durable; running it anyway`,{folder:this.scoop.folder,toolName:e})}finally{clearTimeout(i)}}checkpoint(e){let t=e?.role;if(t===`user`)this.sessions.persistNow();else if(t===`toolResult`){let{toolCallId:t}=e;this.sessions.flush().then(()=>this.turnJournal?.toolEnded(this.scoop.jid,t))}else this.sessions.schedule()}setStatus(e){this.disposed||(this.status=e,e===`ready`?this.armIdleCompaction():this.idleCompaction?.cancel(),this.callbacks.onStatusChange(e))}handleAssistantMessageEnd(e){e.errorMessage||this.overflow.markAssistantSucceeded();let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}handleAgentEndEvent(e,t){this.disposed||t?.aborted||gD(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 Z=_(`scoop-lifecycle-manager`);var KA=class{deps;units=new Map;tabCreates=new Map;gelatiereModelSync=Promise.resolve();constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new tD(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))??O(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Ln(t.values(),e)??O(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Z.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 Dr))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}createTab(e){let t=this.tabCreates.get(e);if(t)return t;let n;return n=this.openTab(e).finally(()=>{this.tabCreates.get(e)===n&&this.tabCreates.delete(e)}),this.tabCreates.set(e,n),n}async openTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)Z.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Z.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=sr(t).policy.filesystem;if(a.kind===`restricted`){let e=jn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new Dr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:An(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 GA(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0,this.deps.getTurnJournal?.()??void 0);if(n.attachContext(l,i),await l.init(),this.units.get(e)!==n||n.context!==l)return;n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{Z.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),Z.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);Z.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),Z.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 Z.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.deps.getScoops().get(e);if(o&&jx(o)&&(await this.syncGelatiereModel(),!Zn(o)))throw Error(`The gelatiere cannot run until the leading cone has a model`);let s=this.getContext(e);s||=(await this.createTab(e),this.getContext(e));let c=this.units.get(e);if(c?.tab?.status===`initializing`){if(Z.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Z.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}s=this.getContext(e)}if(!s||!c){Z.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),c.tab&&c.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),Z.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await s.prompt(t,i,a)}async resumeTurn(e,t,n){let r=this.getContext(e),i=this.units.get(e);!r||!i||r.isBusy||(this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),i.tab&&i.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),await r.resumeTurn(t,n))}async register(e){let t=this.deps.getScoops(),n=zn(t.values())?.jid;if($n(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=Un(e.folder,n);r!==e.folder&&(Z.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),Z.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&jE(`spawn`,e.folder)}catch(n){Z.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){Z.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=>{Z.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}zn(t.values())?.jid!==n&&await this.syncGelatiereModel().catch(t=>{Z.warn(`Failed to follow the new leading cone after registration`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}inheritModel(e){if(jx(e)){let t=zn(this.deps.getScoops().values());Hn(e,t?Zn(t):void 0);return}if(Bn(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Zn(t):void 0)??xE();n&&Hn(e,n)}async unregister(e){let t=this.deps.getScoops(),n=zn(t.values())?.jid===e;for(let n of nr(t.values(),e))await this.unregister(n.jid);let r=t.get(e);if(r&&r.parentJid===null&&O(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let i=this.deps.getLickManager();if(r&&i){let{webhooks:e,cronTasks:t}=await i.getLicksForScoopFromDb(r.name,r.folder),n=this.deps.buildActiveLicksError(r.folder,e,t);if(n)throw n}this.deps.costTracker.snapshot(e);let a=globalThis.__slicc_wsSubscribers;a&&a.dropForScoop(e).catch(t=>{Z.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),await Promise.all([r?this.deps.getConversationStore()?.delete(kr(r)):void 0,this.deps.getSessionStore()?.delete(e).catch(t=>{Z.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})})]),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let o=this.deps.approvalRouter.failScoop(e);if(o>0&&Z.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:o}),r&&this.deps.getSudoManager()?.forgetScoopPolicies(r.folder),Z.info(`Scoop unregistered`,{jid:e}),r)try{this.deps.callbacks.onScoopUnregistered?.(r)}catch(t){Z.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}n&&await this.syncGelatiereModel().catch(t=>{Z.warn(`Failed to follow the replacement leading cone after root removal`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;if(jx(n))return await this.syncGelatiereModel(),!1;let r=zn(this.deps.getScoops().values())?.jid===e,i=n.model;Hn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Hn(n,i),this.getContext(e)?.updateModel(),Z.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return r&&await this.syncGelatiereModel().catch(t=>{Z.warn(`Failed to synchronize gelatiere after leading model change`,{jid:e,error:t instanceof Error?t.message:String(t)})}),!0}syncGelatiereModel(){let e=this.gelatiereModelSync.then(()=>this.applyGelatiereModel());return this.gelatiereModelSync=e.then(()=>void 0,()=>void 0),e}async applyGelatiereModel(){let e=this.deps.getScoops(),t=[...e.values()].find(jx);if(!t)return!1;let n=zn(e.values()),r=n?Zn(n):void 0,i=Zn(t),a=r?i?.provider===r.provider&&i.id===r.id:Bn(t)===void 0;if(!a){let e=t.model?{...t.model}:void 0,i=t.config?{...t.config}:void 0;Hn(t,r);try{await this.deps.db.saveScoop(t)}catch(n){throw t.model=e,t.config=i,n}Z.info(`Gelatiere model synchronized with leading cone`,{jid:t.jid,leadingJid:n?.jid,model:r?`${r.provider}:${r.id}`:void 0})}return r&&this.getContext(t.jid)?.updateModel(),!a}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();Z.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=>{Z.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Z.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;Yn(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Z.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}streamThinking(e){return this.getContext(e)?.streamThinking()??null}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=sr(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:n=>this.handleScoopTurnError(e,t,n),onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Rn(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:fr(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,Nn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(Nn(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleScoopTurnError(e,t,n){this.deps.getScoops().has(e)&&(this.deps.completionService.recordFailure(e,n),this.units.get(e)?.transition(`error`,{error:n}),jE(`error`,t.folder,n),this.deps.callbacks.onError(e,n),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,n),this.dispatch(e,`onStatusChange`,`error`))}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(Z.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),jE(`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`),sr(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(i)try{this.deps.callbacks.onError(i.jid,`[@${r.assistantLabel} FAILED]: ${t}`,{endTurn:!1})}catch(e){Z.error(`Failed to record fatal error for scoop owner`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}}};const Q=_(`scoop-message-router`);var qA=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(Q.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){Q.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}`);jE(`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),Q.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);Q.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){Q.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){Q.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(Q.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){Q.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{Q.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);Q.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);Q.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,Q.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){Q.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){Q.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){Q.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(Q.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){Q.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){Q.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=xb(Cb(bb(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){Q.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=M_(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(`
1178
- `);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>N_(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=xb(Cb(bb(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);Q.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),await this.deps.settleFoldedCost?.(e),t&&await t.clearSession(n).catch(t=>{Q.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=>{Q.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),Q.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=>{Q.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=>{Q.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(),Q.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 $=_(`orchestrator`),JA={decision:`deny`};var YA=class{scoops=new Map;workUnits=new Hy(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new BT({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;onConversationsReady=null;turnJournal=null;interruptedTurns=null;bootRestoreTail=Promise.resolve();fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new QE({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 XE({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts(),mergeFoldedIntoFrozen:(e,t)=>this.mergeFoldedCostIntoFrozen(e,t)});completionService=new RE({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 TE({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=>vb(e),saveMessage:e=>gb(e)});lickRegistry=new _E({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 qA({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),recordSentAttachments:(e,t)=>this.recordSentAttachments(e,t),onError:(e,t,n)=>this.callbacks.onError(e,t,n),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),settleFoldedCost:e=>this.costTracker.settleFolded(e),db:{saveMessage:e=>gb(e),deleteMessage:e=>_b(e),clearMessagesForScoop:e=>hb(e),clearAllMessages:()=>mb(),getMessagesSince:(e,t,n)=>wb(e,t,n),setState:(e,t)=>Ab(e,t)},isExternalLickChannel:xy});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new KA({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getConversationStore:()=>this.conversationStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,getCapabilityBroker:()=>this.capabilityBroker,getTurnJournal:()=>this.turnJournal,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>db(e),deleteScoop:e=>pb(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>fE(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t,n)=>this.scheduleScoopWait(e,t,n),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t,n)=>this.resolveActionableLick(e,t,n),approveDirectedOrUser:e=>this.approveDirectedOrUser(e),listPendingSudoRequests:e=>this.listPendingSudoRequests(e)}})}setProcessManager(e){this.processManager=e}setCapabilityBroker(e){this.capabilityBroker=e}getCapabilityBroker(){return this.capabilityBroker}getProcessManager(){return this.processManager}async initPolicyLayerAndLoadRecords(e,t,n){return SE(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new zx({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 Ex(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new bE(e,t),await this.modelPolicyFile.init(),n(),fb()),n,{stagePrefix:`orchestrator-init`})}setOnConversationsReady(e){this.onConversationsReady=e}async openSharedFilesystem(e,t){let n=await SE(e=>Er.create({dbName:`slicc-fs`,onRepairProgress:e}),e);this.sharedFs=n,this.sessionStore=new I_,this.conversationStore=new QC;let{TurnJournal:r}=await import(`./turn-journal-C1eVrq7Y.js`);this.turnJournal=new r,this.interruptedTurns=await this.turnJournal.readAll();let i=new Tr;return this.fsWatcher=i,n.setWatcher(i),globalThis.__slicc_fs_watcher=i,t?.onSharedFsReady&&await t.onSharedFsReady(n),{sharedFs:n,fsWatcher:i}}async init(e,t){await jb();let{sharedFs:n,fsWatcher:r}=await this.openSharedFilesystem(e,t),i=await this.initPolicyLayerAndLoadRecords(n,r,e),a=Object.values(i).find(e=>Jn(e))?.jid;for(let e of Object.values(i)){await this.backfillParent(e,a),$n(e),this.migrateScoopConfig(e,Object.values(i)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await kb(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.backfillModels(),await this.migrateConversations(e),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new wE({onTaskRun:async(e,t)=>{$.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(),$.info(`Orchestrator initialized`,{scoopCount:this.scoops.size}),e?.(`conversations-ready`),await this.onConversationsReady?.(),await this.restoreScoopContexts(e),Ir(e=>this.getSessionCostsForCommand(e)),Lr(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>R_);return e()}),this.unregisterExportService=s(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}whenBootRestoresSettled(){return this.bootRestoreTail}async restoreScoopContexts(e){let t=[],n=[];for(let e of this.scoops.values())e.parentJid===null?t.push(e):n.push(e);await OE(t,4,t=>this.restoreScoopContext(t,e));let r=OE(n,4,t=>this.restoreScoopContext(t,e)).catch(e=>{$.warn(`Background scoop restore failed`,{error:e instanceof Error?e.message:String(e)})});this.bootRestoreTail=this.bootRestoreTail.then(()=>r)}async restoreScoopContext(e,t){try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);$.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,root:e.parentJid===null,error:n}),e.parentJid!==null&&this.lifecycle.markTabError(e.jid,n)}finally{t?.(`scoop-restored:${e.jid}`)}}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new ly;try{await FC({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){$.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(Ar(r),t).catch(t=>{$.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=Jn(e)?null:t??null;try{await db(e)}catch(t){$.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=>!Bn(e)&&!jx(e));if(e.length>0){let t=xE(),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?Zn(n):void 0)??t;if(r){Hn(e,r);try{await db(e)}catch(t){$.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}try{await this.lifecycle.syncGelatiereModel()}catch(e){$.warn(`Failed to repair gelatiere model on boot; will retry next boot`,{error:e instanceof Error?e.message:String(e)})}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${cr.root}/`,r=lr(dr(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)}notifyScoopOutcome(e,t){return this.completionService.notifyWithOutcome(e,t)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-Cr-jwHvt.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:fr,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):($.warn(`Guest approval before SudoManager init — failing closed`),JA)}})}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 db(e),e.parentJid===null&&await this.lifecycle.syncGelatiereModel().catch(t=>{$.warn(`Failed to follow a persisted root leadership change`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}reinitLiveUnit(e){return this.lifecycle.reinitAfterPromote(e)}async rekeyConversation(e,t){await this.conversationStore?.rekey(e,t)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return O(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 er(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Ln(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){await this.bootRestoreTail,this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await Er.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await PT(this.sharedFs).catch(e=>{$.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new zx({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 Ex(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new bE(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),$.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 vb(e)}async recoverInterruptedWork(e){await this.bootRestoreTail;let t=this.interruptedTurns;this.interruptedTurns=null;let n=this.turnJournal;if(!t||t.length===0||!n)return[];let{recoverInterruptedWork:r}=await import(`./interrupted-work-recovery-DkaikSRv.js`);return r(t,{journal:n,getScoop:e=>this.scoops.get(e),getUnit:e=>this.lifecycle.getContext(e),resumeTurn:(e,t,n)=>this.lifecycle.resumeTurn(e,t,n),emitLick:e})}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}syncGelatiereModel(){return this.lifecycle.syncGelatiereModel()}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}streamThinking(e){return this.lifecycle.streamThinking(e)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){for(let t of Pn(this.scoops.values(),e))this.lifecycle.getContext(t)?.stop(),this.clearQueuedMessages(t).catch(e=>{$.warn(`Failed to clear queued messages on stop`,{jid:t,error:e instanceof Error?e.message:String(e)})})}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async mergeFoldedCostIntoFrozen(e,t){let n=this.scoops.get(e);if(!n||!this.sharedFs)return!1;try{let{mergeFoldedCostIntoLatestFrozen:e}=await import(`./merge-folded-cost-into-frozen-COnnhDR_.js`);return await e(this.sharedFs,n,t)}catch(t){return $.warn(`Failed to merge folded agent spend into frozen session`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await Promise.resolve().then(()=>hS),r=await n(this.sharedFs);return[...t,...r.map(Rr)]}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&&$.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.bootRestoreTail,await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,$.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new JC(this.conversationStore):null,t=this.sharedFs;return new QS({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:_C(),snapshotStore:{read:e=>lC(t,e),write:(e,n)=>cC(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.203.0`})}};const XA=_(`workflow-run-manager`),ZA=`/shared/workflow-runs`,QA=1e3;function $A(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function ej(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){XA.warn(`observeRun handler threw`,e)}},i=(e,n)=>aj(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=$A(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),rj(t,n);let f=i(a.ctx,c),p=ij(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=>XA.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=`${ZA}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(ZA,{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);XA.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`?nj(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){XA.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function tj(e){let t=ej(e);return globalThis[f]=t,XA.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function nj(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function rj(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 ij(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 aj(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?oj(n,t,a?.args??[],r):e===`agent`?sj(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function oj(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>QA&&i.logs.splice(0,i.logs.length-QA),r()}return{stdout:``,stderr:``,exitCode:0}}async function sj(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 cj=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function lj(e,t,n){let r=uj(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=pj(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function uj(e){let t=new Map;return dj(t,e.discoveryOrigin),dj(t,e.discoveryUrl),[...t.values()]}function dj(e,t){if(t){fj(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);fj(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!cj.has(e)))fj(e,t,1,`substring`)}catch{}}}function fj(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 pj(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=hj(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)mj(a,e)&&(r+=e.weight*o)}return r}function mj(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 hj(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}function gj(e,t,n=e=>console.warn(`Early conversation hydration failed`,e)){e.setOnConversationsReady(async()=>{try{await t.hydrateBuffersFromRecords(),t.publishHydratedTranscripts()}catch(e){n(e)}})}var _j=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=bj(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:yj,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===yj)throw new k(`ENOTDIR`,`not a directory`,e);let n=xj(t[0]);if(n===null||!this.pidExists(n))throw new k(`ENOENT`,`no such file or directory`,e);return vj.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new k(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=bj(e);if(t.length===1&&t[0]===yj)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new k(`EISDIR`,`is a directory`,e);let n=xj(t[0]);if(n===null||!this.pidExists(n))throw new k(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!vj.includes(r))throw new k(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new k(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=bj(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===yj)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=xj(t[0]);if(n===null||!this.pidExists(n))throw new k(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=xj(t[0]);if(n===null||!this.pidExists(n))throw new k(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!vj.includes(r))throw new k(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new k(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new k(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new k(`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 k(`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:Ej(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:Dj(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
1177
+ `)}`}}async function hA(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),Ek.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 gA(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=>Kk(t,e)}}function _A(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:[...zk],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=>Yk(t,e)}}function vA(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.`},[Dk]:Rk(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>Xk(t,e)}}function yA(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:()=>Qk(e)}}function bA(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:[...mr],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=>nA(t,e)}}function xA(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.`},[Dk]:Rk(`drop`)},required:[`scoop_name`]},execute:t=>rA(t,e)}}function SA(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"]).`},[Dk]:Rk(`mute`)},required:[`scoop_names`]},execute:t=>aA(t,e)}}function CA(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"]).`},[Dk]:Rk(`unmute`)},required:[`scoop_names`]},execute:t=>sA(t,e)}}function wA(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."},[Dk]:Rk(`wait on`)},required:[`scoop_names`]},execute:t=>uA(t,e)}}function TA(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=>fA(t,e)}}function EA(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=>pA(t,e)}}function DA(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:()=>mA(e)}}function OA(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=>hA(t,e)}}function kA(e){let t=[],n=In(e.scoop);return Nn(e.scoop)||(t.push(gA(e)),e.onSudoRequest&&t.push(_A(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(bA(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(vA(e)),t.push(yA(e)),e.onDropScoop&&t.push(xA(e)),e.onMuteScoops&&t.push(SA(e)),e.onUnmuteScoops&&t.push(CA(e)),e.onScheduleScoopWait&&t.push(wA(e)),e.onSudoResolve&&(t.push(TA(e)),t.push(EA(e))),e.onListSudoRequests&&t.push(DA(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(OA(e))),t}const AA=_(`scoop-context`);function jA(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-BzUxTS0o.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function MA(e){let{scoop:t,unit:n,callbacks:r}=e,i=kA({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:de,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=dk(e.gatedFs,n.workspace.root),o=e.blindReads??null,s=hk(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>cw);return t(e.fs)},...o?{blindPaths:()=>o.outsidePaths()}:{}}),c=[...a,s,XO(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:pn(),...o?{annotateResult:()=>o.takeNote()}:{},fireLick:e=>{let n=globalThis.__slicc_lick_handler;return n?(n(e),!0):(AA.warn(`No lick handler for background bash completion`,{folder:t.folder}),!1)}}),...i,wk({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>xO(AD(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);c.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let l={scrubToolResult:pn()},u=jA(e);return e.processManager?mn(c,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},l,u):mn(c,void 0,l,u)}const NA=_(`scoop-context`);async function PA(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();NA.info(`Filesystem ready`,{folder:t.folder}),await YD(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,blindReads:l,skills:u}=await yO({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 d=await MA({getTurnGuestGates:e.getTurnGuestGates,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,blindReads:l,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:f,globalMemory:p}=await DD(r,n,()=>i.getGlobalMemory());if(!kD(t))return NA.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let m=jD(t,n),h=PD(t,n,p,f,u),ee=await e.sessions.restore(),{streamWithSessionId:g,compactFn:te,getCompactionApiKey:ne}=await ZD(m,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>kD(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let re=Wn(t);return{kind:`ready`,agent:qD({model:m,tools:d,systemPrompt:h,messages:ee,thinkingLevel:ID(LD()??re.level,m),getApiKey:()=>kD(t)??void 0,transformContext:te,streamFn:g,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:te,getCompactionApiKey:ne,effortOverride:re.effortOverride,toolCount:d.length}}const FA=_(`scoop-context`);var IA=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 FA.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=BC(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=hn(n);return FA.info(`Restored conversation from the canonical work-unit record`,{folder:this.deps.folder,messageCount:r.length,droppedOrphans:n.length-r.length}),r}persistNow(e){this.flush(e)}flush(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return Promise.resolve();let n=this.deps.canonical;return n?(this.createdAt||=Date.now(),n.store.syncAgentMessages(n.identity,t,{createdAt:this.createdAt}).then(()=>void 0,e=>{FA.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})})):Promise.resolve()}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){FA.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 LA(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 RA(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function zA(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const BA=_(`scoop-context`);var VA=class{deps;constructor(e){this.deps=e}async run(e,t){let n=null;for(let r=1;r<=3;r++){if(this.deps.isDisposed()||t.aborted)return null;let i=await this.tryAttempt(e,t);if(!i||this.deps.isDisposed()||t.aborted||(n=i,await this.handleAttemptError(i,r,t)))return null}return n}reportExhausted(e){let t=e.message;BA.error(`Agent error after retries exhausted`,{folder:this.deps.folder,error:t,maxRetries:3}),this.fail(`Scoop "${this.deps.scoopName}" failed after 3 attempts: ${t}`,t)}async tryAttempt(e,t){this.deps.beginAttempt();try{if(await e(),this.deps.isDisposed()||t.aborted)return null;let n=this.deps.overflow.pendingRecovery;if(n!==null&&(await n,this.deps.overflow.clearPendingRecovery(n),this.deps.isDisposed()||t.aborted))return null;let r=this.deps.getStreamError();return r?Error(r):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handleAttemptError(e,t,n){let r=e.message;return this.handleStaleAssetError(r)||this.handleNonRetryableError(r)?!0:!await this.handleRetryableError(r,t,n)&&(BA.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:mD(r)}),!!(t<3&&(await hD(HA(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return pD(e)?(BA.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 Wa(e)?(BA.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),qa(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(!mD(e)||t>=3)return!1;let r=HA(t);return BA.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await hD(r,n)&&!this.deps.isDisposed()}fail(e,t){iD(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function HA(e){return 1e3*2**(e-1)}function UA(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){BA.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 WA=_(`scoop-context`);var GA=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;forceReleaseTimer=null;turnEpoch=0;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;turnJournal;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>(this.callbacks.onToolStart?.(e,t,n),this.makeToolCallDurable(e,t,n)),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:e=>this.checkpoint(e),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s,c,l,u){this.scoop=e,this.unit=sr(e),this.owner={kind:Vn(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.capabilityBroker=l??null,this.turnJournal=u??null,this.sessions=new IA({store:r??null,canonical:c?{store:c,identity:Ar(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 WD({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new SD({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new wD({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new UD({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 VA({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 mO(this.unit,this.scoop,O(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return ir(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 PA({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`),WA.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);WA.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(ND(this.scoop)),!1)}cleanupPromptState(e,t,n,r,i){if(i!==void 0&&i!==this.turnEpoch){this.currentTurnProcess!==t&&RA(this.processManager,t,{lastError:n,aborted:!0});return}this.runBounds.disarm();let a=this.runBounds.takeExceededNote();a!==null&&this.callbacks.onError(`agent run terminated: ${a}`),(n||r.aborted)&&this.sessions.persistNow(),this.disarmForceRelease(),this.isProcessing=!1,this.turnJournal?.end(this.scoop.jid),!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),RA(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(UA(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder})){for(let e of r)this.addTurnGuestGate(e);return}this.turnGuestGates=[...r];let i=this.agent;await this.runTurn(e,0,()=>i.prompt(e,t))}async resumeTurn(e,t=[]){if(!await this.ensureAgentReady()||this.isBusy)return;this.turnGuestGates=[...t];let n=this.agent;await this.runTurn(`(resumed after reload)`,e,()=>{let e=n.state.messages,t=e[e.length-1];return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)&&(n.state.messages=e.slice(0,-1)),n.continue()})}settleInterruptedToolCalls(e){let t=this.agent;if(!t||e.length===0)return;let n=Date.now(),r=e.map(e=>({role:`toolResult`,toolCallId:e.toolCallId,toolName:e.toolName,content:[{type:`text`,text:e.text}],isError:!0,timestamp:n}));t.state.messages=[...t.state.messages,...r],this.sessions.persistNow();for(let t of e)this.callbacks.onToolEnd?.(t.toolName,t.text,!0,t.toolCallId)}reportError(e){this.callbacks.onError(e)}hasAgent(){return this.agent!==null}async runTurn(e,t,n){this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal,a=++this.turnEpoch;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let o=LA(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:r});this.currentTurnProcess=o,this.runBounds.arm(),this.turnJournal?.begin(this.scoop.jid,this.scoop.folder,t,this.turnGuestGates);let s=null;try{if(s=await this.turnRunner.run(n,i),s&&!this.disposed&&!i.aborted){this.turnRunner.reportExhausted(s);return}a===this.turnEpoch&&!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,o,s,i,a)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||(this.turnGuestGates.push(e),this.turnJournal?.setGuestGates(this.scoop.jid,this.turnGuestGates))}stop(){zA(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.armForceRelease()}disarmForceRelease(){this.forceReleaseTimer!==null&&(clearTimeout(this.forceReleaseTimer),this.forceReleaseTimer=null)}armForceRelease(){this.disarmForceRelease();let e=this.turnEpoch,t=this.currentTurnProcess;this.forceReleaseTimer=setTimeout(()=>{this.forceReleaseTimer=null,!(this.disposed||this.turnEpoch!==e||!this.isProcessing)&&(t&&this.processManager&&(this.processManager.signal(t.pid,`SIGKILL`),this.processManager.exit(t.pid,null)),this.bashJobs.reapAll(),this.shell?.cancelActiveCommand(),this.agent?.abort?.(),!(this.turnEpoch!==e||!this.isProcessing)&&(this.isProcessing=!1,this.status===`processing`&&this.setStatus(`ready`)))},2e3)}clearMessages(){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 jx(this.scoop)?!0:this.unit.parentId===null&&ke(`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-CwYw083A.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:gn,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&&!ke(`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-BpL-0LSc.js`),a=this.unit.parentId===null,o=await i({vfs:this.fs,cone:{folder:this.scoop.folder,label:this.scoop.assistantLabel},messages:e,trigger:t,...a?{}:{sessionsDir:r(this.scoop.folder,this.scoop.jid)},stillValid:()=>!this.disposed&&n===this.sessionGeneration});return o&&a&&this.scheduleLiveDeltaCuration(),o?{transcriptPath:o.transcriptPath}:void 0}scheduleLiveDeltaCuration(){let e=this.fs;if(!e)return;let t={folder:this.scoop.folder,...this.scoop.jid?{jid:this.scoop.jid}:{}};import(`./live-session-curation-BIqIx0m8.js`).then(e=>e.r).then(n=>n.scheduleLiveDeltaCuration({vfs:e,cone:t})).catch(e=>{WA.warn(`Live delta curation failed to start`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}async settleLiveSnapshot(e){if(!(this.unit.parentId!==null||!this.fs))try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-BpL-0LSc.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){WA.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 MD(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=zD(this.agent,this.scoop))}async reloadSkills(){this.agent&&await VD(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){if(!this.agent)return WA.info(`Thinking level stored for a deferred agent`,{requested:e}),`off`;if(LD())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=BD(this.agent,e);return WA.info(`Thinking level applied`,{requested:e,resolved:n,model:this.agent.state.model?.id,provider:this.agent.state.model?.provider,reasoning:this.agent.state.model?.reasoning===!0}),n}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}streamThinking(){if(!this.agent)return null;let e=this.agent.state.thinkingLevel;return{level:e,...e!==`off`&&this.activeEffortOverride===`max`?{effortOverride:`max`}:{}}}dispose(){this.sessions.persistNow(),this.turnJournal?.end(this.scoop.jid),this.disposed=!0,this.disarmForceRelease(),this.idleCompaction?.cancel(),this.runBounds.disarm(),zA(this.processManager,this.currentTurnProcess,`SIGTERM`,this.promptAbortController),this.bashJobs.reapAll(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}handleAgentEvent(e,t){if(!this.disposed)return vD(e,this.eventSink,t)}async makeToolCallDurable(e,t,n){let r=Promise.all([this.sessions.flush(),n?this.turnJournal?.toolStarted(this.scoop.jid,n,e,t):null]),i,a=new Promise(e=>{i=setTimeout(()=>e(`timeout`),2e3)});try{await Promise.race([r,a])===`timeout`&&WA.warn(`Tool call not yet durable; running it anyway`,{folder:this.scoop.folder,toolName:e})}finally{clearTimeout(i)}}checkpoint(e){let t=e?.role;if(t===`user`)this.sessions.persistNow();else if(t===`toolResult`){let{toolCallId:t}=e;this.sessions.flush().then(()=>this.turnJournal?.toolEnded(this.scoop.jid,t))}else this.sessions.schedule()}setStatus(e){this.disposed||(this.status=e,e===`ready`?this.armIdleCompaction():this.idleCompaction?.cancel(),this.callbacks.onStatusChange(e))}handleAssistantMessageEnd(e){e.errorMessage||this.overflow.markAssistantSucceeded();let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}handleAgentEndEvent(e,t){this.disposed||t?.aborted||gD(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 Z=_(`scoop-lifecycle-manager`);var KA=class{deps;units=new Map;tabCreates=new Map;gelatiereModelSync=Promise.resolve();constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new tD(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))??O(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Ln(t.values(),e)??O(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Z.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 Dr))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}createTab(e){let t=this.tabCreates.get(e);if(t!=null)return t;let n;return n=this.openTab(e).finally(()=>{this.tabCreates.get(e)===n&&this.tabCreates.delete(e)}),this.tabCreates.set(e,n),n}async openTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)Z.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Z.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=sr(t).policy.filesystem;if(a.kind===`restricted`){let e=jn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new Dr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:An(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 GA(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0,this.deps.getTurnJournal?.()??void 0);if(n.attachContext(l,i),await l.init(),this.units.get(e)!==n||n.context!==l)return;n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{Z.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),Z.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);Z.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),Z.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 Z.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.deps.getScoops().get(e);if(o&&jx(o)&&(await this.syncGelatiereModel(),!Zn(o)))throw Error(`The gelatiere cannot run until the leading cone has a model`);let s=this.getContext(e);s||=(await this.createTab(e),this.getContext(e));let c=this.units.get(e);if(c?.tab?.status===`initializing`){if(Z.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Z.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}s=this.getContext(e)}if(!s||!c){Z.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),c.tab&&c.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),Z.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await s.prompt(t,i,a)}async resumeTurn(e,t,n){let r=this.getContext(e),i=this.units.get(e);!r||!i||r.isBusy||(this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),i.tab&&i.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),await r.resumeTurn(t,n))}async register(e){let t=this.deps.getScoops(),n=zn(t.values())?.jid;if($n(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=Un(e.folder,n);r!==e.folder&&(Z.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),Z.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&jE(`spawn`,e.folder)}catch(n){Z.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){Z.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=>{Z.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}zn(t.values())?.jid!==n&&await this.syncGelatiereModel().catch(t=>{Z.warn(`Failed to follow the new leading cone after registration`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}inheritModel(e){if(jx(e)){let t=zn(this.deps.getScoops().values());Hn(e,t?Zn(t):void 0);return}if(Bn(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Zn(t):void 0)??xE();n&&Hn(e,n)}async unregister(e){let t=this.deps.getScoops(),n=zn(t.values())?.jid===e;for(let n of nr(t.values(),e))await this.unregister(n.jid);let r=t.get(e);if(r&&r.parentJid===null&&O(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let i=this.deps.getLickManager();if(r&&i){let{webhooks:e,cronTasks:t}=await i.getLicksForScoopFromDb(r.name,r.folder),n=this.deps.buildActiveLicksError(r.folder,e,t);if(n)throw n}this.deps.costTracker.snapshot(e);let a=globalThis.__slicc_wsSubscribers;a&&a.dropForScoop(e).catch(t=>{Z.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),await Promise.all([r?this.deps.getConversationStore()?.delete(kr(r)):void 0,this.deps.getSessionStore()?.delete(e).catch(t=>{Z.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})})]),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let o=this.deps.approvalRouter.failScoop(e);if(o>0&&Z.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:o}),r&&this.deps.getSudoManager()?.forgetScoopPolicies(r.folder),Z.info(`Scoop unregistered`,{jid:e}),r)try{this.deps.callbacks.onScoopUnregistered?.(r)}catch(t){Z.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}n&&await this.syncGelatiereModel().catch(t=>{Z.warn(`Failed to follow the replacement leading cone after root removal`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;if(jx(n))return await this.syncGelatiereModel(),!1;let r=zn(this.deps.getScoops().values())?.jid===e,i=n.model;Hn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Hn(n,i),this.getContext(e)?.updateModel(),Z.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return r&&await this.syncGelatiereModel().catch(t=>{Z.warn(`Failed to synchronize gelatiere after leading model change`,{jid:e,error:t instanceof Error?t.message:String(t)})}),!0}syncGelatiereModel(){let e=this.gelatiereModelSync.then(()=>this.applyGelatiereModel());return this.gelatiereModelSync=e.then(()=>void 0,()=>void 0),e}async applyGelatiereModel(){let e=this.deps.getScoops(),t=[...e.values()].find(jx);if(!t)return!1;let n=zn(e.values()),r=n?Zn(n):void 0,i=Zn(t),a=r?i?.provider===r.provider&&i.id===r.id:Bn(t)===void 0;if(!a){let e=t.model?{...t.model}:void 0,i=t.config?{...t.config}:void 0;Hn(t,r);try{await this.deps.db.saveScoop(t)}catch(n){throw t.model=e,t.config=i,n}Z.info(`Gelatiere model synchronized with leading cone`,{jid:t.jid,leadingJid:n?.jid,model:r?`${r.provider}:${r.id}`:void 0})}return r&&this.getContext(t.jid)?.updateModel(),!a}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();Z.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=>{Z.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Z.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;Yn(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Z.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}streamThinking(e){return this.getContext(e)?.streamThinking()??null}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=sr(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:n=>this.handleScoopTurnError(e,t,n),onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Rn(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:fr(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,Nn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(Nn(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleScoopTurnError(e,t,n){this.deps.getScoops().has(e)&&(this.deps.completionService.recordFailure(e,n),this.units.get(e)?.transition(`error`,{error:n}),jE(`error`,t.folder,n),this.deps.callbacks.onError(e,n),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,n),this.dispatch(e,`onStatusChange`,`error`))}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(Z.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),jE(`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`),sr(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(i)try{this.deps.callbacks.onError(i.jid,`[@${r.assistantLabel} FAILED]: ${t}`,{endTurn:!1})}catch(e){Z.error(`Failed to record fatal error for scoop owner`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}}};const Q=_(`scoop-message-router`);var qA=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(Q.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){Q.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}`);jE(`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),Q.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);Q.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){Q.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){Q.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(Q.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){Q.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{Q.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);Q.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);Q.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,Q.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){Q.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){Q.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){Q.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(Q.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){Q.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){Q.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=xb(Cb(bb(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){Q.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=M_(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(`
1178
+ `);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>N_(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=xb(Cb(bb(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);Q.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),await this.deps.settleFoldedCost?.(e),t&&await t.clearSession(n).catch(t=>{Q.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=>{Q.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),Q.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=>{Q.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=>{Q.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(),Q.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 $=_(`orchestrator`),JA={decision:`deny`};var YA=class{scoops=new Map;workUnits=new Hy(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new BT({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;onConversationsReady=null;turnJournal=null;interruptedTurns=null;bootRestoreTail=Promise.resolve();fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new QE({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 XE({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts(),mergeFoldedIntoFrozen:(e,t)=>this.mergeFoldedCostIntoFrozen(e,t)});completionService=new RE({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 TE({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=>vb(e),saveMessage:e=>gb(e)});lickRegistry=new _E({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 qA({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),recordSentAttachments:(e,t)=>this.recordSentAttachments(e,t),onError:(e,t,n)=>this.callbacks.onError(e,t,n),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),settleFoldedCost:e=>this.costTracker.settleFolded(e),db:{saveMessage:e=>gb(e),deleteMessage:e=>_b(e),clearMessagesForScoop:e=>hb(e),clearAllMessages:()=>mb(),getMessagesSince:(e,t,n)=>wb(e,t,n),setState:(e,t)=>Ab(e,t)},isExternalLickChannel:xy});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new KA({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getConversationStore:()=>this.conversationStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,getCapabilityBroker:()=>this.capabilityBroker,getTurnJournal:()=>this.turnJournal,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>db(e),deleteScoop:e=>pb(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>fE(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t,n)=>this.scheduleScoopWait(e,t,n),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t,n)=>this.resolveActionableLick(e,t,n),approveDirectedOrUser:e=>this.approveDirectedOrUser(e),listPendingSudoRequests:e=>this.listPendingSudoRequests(e)}})}setProcessManager(e){this.processManager=e}setCapabilityBroker(e){this.capabilityBroker=e}getCapabilityBroker(){return this.capabilityBroker}getProcessManager(){return this.processManager}async initPolicyLayerAndLoadRecords(e,t,n){return SE(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new zx({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 Ex(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new bE(e,t),await this.modelPolicyFile.init(),n(),fb()),n,{stagePrefix:`orchestrator-init`})}setOnConversationsReady(e){this.onConversationsReady=e}async openSharedFilesystem(e,t){let n=await SE(e=>Er.create({dbName:`slicc-fs`,onRepairProgress:e}),e);this.sharedFs=n,this.sessionStore=new I_,this.conversationStore=new QC;let{TurnJournal:r}=await import(`./turn-journal-C1eVrq7Y.js`);this.turnJournal=new r,this.interruptedTurns=await this.turnJournal.readAll();let i=new Tr;return this.fsWatcher=i,n.setWatcher(i),globalThis.__slicc_fs_watcher=i,t?.onSharedFsReady&&await t.onSharedFsReady(n),{sharedFs:n,fsWatcher:i}}async init(e,t){await jb();let{sharedFs:n,fsWatcher:r}=await this.openSharedFilesystem(e,t),i=await this.initPolicyLayerAndLoadRecords(n,r,e),a=Object.values(i).find(e=>Jn(e))?.jid;for(let e of Object.values(i)){await this.backfillParent(e,a),$n(e),this.migrateScoopConfig(e,Object.values(i)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await kb(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.backfillModels(),await this.migrateConversations(e),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new wE({onTaskRun:async(e,t)=>{$.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(),$.info(`Orchestrator initialized`,{scoopCount:this.scoops.size}),e?.(`conversations-ready`),await this.onConversationsReady?.(),await this.restoreScoopContexts(e),Ir(e=>this.getSessionCostsForCommand(e)),Lr(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>R_);return e()}),this.unregisterExportService=s(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}whenBootRestoresSettled(){return this.bootRestoreTail}async restoreScoopContexts(e){let t=[],n=[];for(let e of this.scoops.values())e.parentJid===null?t.push(e):n.push(e);await OE(t,4,t=>this.restoreScoopContext(t,e));let r=OE(n,4,t=>this.restoreScoopContext(t,e)).catch(e=>{$.warn(`Background scoop restore failed`,{error:e instanceof Error?e.message:String(e)})});this.bootRestoreTail=this.bootRestoreTail.then(()=>r)}async restoreScoopContext(e,t){try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);$.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,root:e.parentJid===null,error:n}),e.parentJid!==null&&this.lifecycle.markTabError(e.jid,n)}finally{t?.(`scoop-restored:${e.jid}`)}}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new ly;try{await FC({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){$.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(Ar(r),t).catch(t=>{$.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=Jn(e)?null:t??null;try{await db(e)}catch(t){$.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=>!Bn(e)&&!jx(e));if(e.length>0){let t=xE(),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?Zn(n):void 0)??t;if(r){Hn(e,r);try{await db(e)}catch(t){$.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}try{await this.lifecycle.syncGelatiereModel()}catch(e){$.warn(`Failed to repair gelatiere model on boot; will retry next boot`,{error:e instanceof Error?e.message:String(e)})}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${cr.root}/`,r=lr(dr(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)}notifyScoopOutcome(e,t){return this.completionService.notifyWithOutcome(e,t)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-CpLPsRpu.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:fr,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):($.warn(`Guest approval before SudoManager init — failing closed`),JA)}})}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 db(e),e.parentJid===null&&await this.lifecycle.syncGelatiereModel().catch(t=>{$.warn(`Failed to follow a persisted root leadership change`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}reinitLiveUnit(e){return this.lifecycle.reinitAfterPromote(e)}async rekeyConversation(e,t){await this.conversationStore?.rekey(e,t)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return O(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 er(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Ln(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){await this.bootRestoreTail,this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await Er.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await PT(this.sharedFs).catch(e=>{$.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new zx({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 Ex(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new bE(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),$.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 vb(e)}async recoverInterruptedWork(e){await this.bootRestoreTail;let t=this.interruptedTurns;this.interruptedTurns=null;let n=this.turnJournal;if(!t||t.length===0||!n)return[];let{recoverInterruptedWork:r}=await import(`./interrupted-work-recovery-DkaikSRv.js`);return r(t,{journal:n,getScoop:e=>this.scoops.get(e),getUnit:e=>this.lifecycle.getContext(e),resumeTurn:(e,t,n)=>this.lifecycle.resumeTurn(e,t,n),emitLick:e})}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}syncGelatiereModel(){return this.lifecycle.syncGelatiereModel()}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}streamThinking(e){return this.lifecycle.streamThinking(e)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){for(let t of Pn(this.scoops.values(),e))this.lifecycle.getContext(t)?.stop(),this.clearQueuedMessages(t).catch(e=>{$.warn(`Failed to clear queued messages on stop`,{jid:t,error:e instanceof Error?e.message:String(e)})})}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async mergeFoldedCostIntoFrozen(e,t){let n=this.scoops.get(e);if(!n||!this.sharedFs)return!1;try{let{mergeFoldedCostIntoLatestFrozen:e}=await import(`./merge-folded-cost-into-frozen-t3zkafLQ.js`);return await e(this.sharedFs,n,t)}catch(t){return $.warn(`Failed to merge folded agent spend into frozen session`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await Promise.resolve().then(()=>hS),r=await n(this.sharedFs);return[...t,...r.map(Rr)]}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&&$.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.bootRestoreTail,await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,$.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new JC(this.conversationStore):null,t=this.sharedFs;return new QS({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:_C(),snapshotStore:{read:e=>lC(t,e),write:(e,n)=>cC(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.203.2`})}};const XA=_(`workflow-run-manager`),ZA=`/shared/workflow-runs`,QA=1e3;function $A(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function ej(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){XA.warn(`observeRun handler threw`,e)}},i=(e,n)=>aj(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=$A(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),rj(t,n);let f=i(a.ctx,c),p=ij(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=>XA.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=`${ZA}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(ZA,{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);XA.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`?nj(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){XA.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function tj(e){let t=ej(e);return globalThis[f]=t,XA.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function nj(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function rj(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 ij(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 aj(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?oj(n,t,a?.args??[],r):e===`agent`?sj(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function oj(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>QA&&i.logs.splice(0,i.logs.length-QA),r()}return{stdout:``,stderr:``,exitCode:0}}async function sj(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 cj=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function lj(e,t,n){let r=uj(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=pj(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function uj(e){let t=new Map;return dj(t,e.discoveryOrigin),dj(t,e.discoveryUrl),[...t.values()]}function dj(e,t){if(t){fj(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);fj(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!cj.has(e)))fj(e,t,1,`substring`)}catch{}}}function fj(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 pj(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=hj(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)mj(a,e)&&(r+=e.weight*o)}return r}function mj(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 hj(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}function gj(e,t,n=e=>console.warn(`Early conversation hydration failed`,e)){e.setOnConversationsReady(async()=>{try{await t.hydrateBuffersFromRecords(),t.publishHydratedTranscripts()}catch(e){n(e)}})}var _j=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=bj(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:yj,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===yj)throw new k(`ENOTDIR`,`not a directory`,e);let n=xj(t[0]);if(n===null||!this.pidExists(n))throw new k(`ENOENT`,`no such file or directory`,e);return vj.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new k(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=bj(e);if(t.length===1&&t[0]===yj)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new k(`EISDIR`,`is a directory`,e);let n=xj(t[0]);if(n===null||!this.pidExists(n))throw new k(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!vj.includes(r))throw new k(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new k(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=bj(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===yj)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=xj(t[0]);if(n===null||!this.pidExists(n))throw new k(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=xj(t[0]);if(n===null||!this.pidExists(n))throw new k(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!vj.includes(r))throw new k(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new k(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new k(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new k(`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 k(`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:Ej(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:Dj(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
1179
1179
  `}renderProcFile(e,t){if(e===1)return Oj(t);let n=this.pm.get(e);switch(t){case`status`:return Sj(n);case`cmdline`:return Cj(n);case`cwd`:return wj(n);case`stat`:return Tj(n)}}};const vj=[`status`,`cmdline`,`cwd`,`stat`],yj=`table`;function bj(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function xj(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Sj(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${Ej(e.status)} (${e.status})`,`Owner:\t${Dj(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(`
1180
1180
  `)+`
1181
1181
  `}function Cj(e){return e.argv.join(`\0`)+`\0`}function wj(e){return e.cwd+`
@@ -1184,7 +1184,7 @@ Created: ${new Date().toISOString()}
1184
1184
  `)+`
1185
1185
  `;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
1186
1186
  `;case`stat`:return`1 (kernel-host) R 0 - 0 -
1187
- `}}const kj=Math.max(Si,Ci)+5e3;function Aj(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(bi(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(!vi(n.token))return;let a=i.get(n.id);if(a){r({type:xi,id:n.id}),a.result&&r({type:yi,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:xi,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),kj),r({type:yi,id:n.id,...e})};(Ti(n)?wi(n):Ei(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 jj(){return globalThis}function Mj(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 wy(e);case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`bash`:return e.bashJobId??`bash`;case`jshd`:return e.jshdName??`jshd`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Nj(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 Pj(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Fj(e,t)}async function Fj(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=O(r),a=e.type===`discovery`&&!e.targetScoop?lj(e,i.filter(Cx),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?eo(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Cx(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-DeQBgND8.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=Ry(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=Mj(e),l=Nj(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 Ij(e,t,n,r,i){let a=new pi,o=new YA(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=fn(),l=i.capabilityBroker??c(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(l),br(l),jj().__slicc_pm=a,mi(gi()),jj().__slicc_browser=t,await n.bind(o,t);let u=Mr(()=>n.emitTrayRuntimeStatus()),d=we(()=>n.emitTrayRuntimeStatus());gj(o,n);let f=i.logger??console;return await o.init(i.onBootProgress,{onSharedFsReady:async e=>{try{let{applyConfiguredHostMounts:t}=await import(`./auto-mount-table-Dlq8aO5D.js`);await t(e,f)}catch(e){f.warn(`Configured host mounts failed`,e)}i.onBootProgress?.(`host-mounts-applied`)}}),await n.hydrateBuffersFromRecords(),n.publishHydratedTranscripts(),{processManager:a,orchestrator:o,unsubLeader:u,unsubFollower:d,sharedFs:o.getSharedFS(),capabilityBroker:l}}async function Lj(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-D0tJNxsl.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await Promise.resolve().then(()=>R_);r(()=>a());let{getLickManager:o}=await Promise.resolve().then(()=>aE),s=o();await s.init(),e.setLickManager(s);let c=t.lickEventHandler??Pj,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function Rj(e){let t=e.getScoops();O(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 zj(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:a}=e;tj({sharedFs:a,getStartingRoot:e=>{let n=O(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)=>_i(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>u().slice(10,22),splitResult:(e,t)=>i(e,t)})}async function Bj(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))+`
1188
- `,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 Vj(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-Dr8ndBaj.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-Bqk2Qgbz.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 Hj(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 mx(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})},{...Uj(t),isOwnTab:fx(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Uj(e){let t=ye();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:()=>hx()}}async function Wj(e,t,n){try{let r=await e.recoverInterruptedWork(e=>t.emitEvent(e));r.length>0&&n.info(`Recovered work interrupted by a reload`,{outcomes:r})}catch(e){n.warn(`Reload recovery failed`,e)}}async function Gj(e,t,n,r,i,a){e&&(await qj(e,n,r),i(`mounts-restored`),await Kj(e,t,n,r,a),i(`jshd-restored`))}async function Kj(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-D4J7Iipz.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 qj(e,t,n){try{let{getAllMountEntries:r}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>fy),{applyConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-Dlq8aO5D.js`),s=await a(e,n),c=o(await r(),s);if(c.length===0)return;let{needsRecovery:l}=await i(c,e,n);if(l.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:l}})}catch(e){n.warn(`mount recovery failed`,e)}}function Jj(){Pr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-kNZzwNpV.js`);return e()})}function Yj(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-kNZzwNpV.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 Xj(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-xbXqblUt.js`),{ScriptCatalog:r}=await import(`./script-catalog-ByM8lrb_.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 Zj(e){return e===`node-rest`}function Qj(e,t,n,r){import(`./gelatiere-unit-i3KpBjAC.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!ke(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-Dd2SBj-h.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function $j(e,t){if(!e)return()=>{};import(`./memory-curation-seam-Babzek1S.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return ke(`memory-v2`)&&import(`./memory-health-detJjF2Z.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 eM(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}Yv(e,t,e.getSessionStore())}async function tM(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Jj();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Ij(t,n,r,i,e);if(s(`orchestrator-ready`),eM(l,f,o),f)try{await f.mountInternal(`/proc`,new _j(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await Lj(l,e,o);s(`lick-manager-ready`),f&&zj({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),jj().__slicc_lickManager=m,Qj(l,m,f,o);let h=$j(f,o),{wsBridge:ee,wsRegistry:g}=await Bj({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});jj().__slicc_wsSubscribers=g;let te=Zj(p.adapter)?await Vj(m,o,e.localLickWsUrl??null,f):null,ne=Hj(n,m,o,e.appPageUrl);await Gj(f,c,m,o,s,l),a||await Rj(l),s(`cone-bootstrapped`),Wj(l,m,o),f&&Yj(m,o);let re=null,_=null;f&&({bshWatchdogStop:re,scriptCatalogDispose:_}=await Xj(f,n,o));let ie=null;f&&e.syncFsChannelNonce&&(ie=Aj({nonce:e.syncFsChannelNonce}).dispose);let ae=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){ae||(ae=!0,await nM({unsubLeader:u,unsubFollower:d,bshWatchdogStop:re,memoryHealthStop:h,scriptCatalogDispose:_,lickWsBridgeStop:te,navigationWatcherStop:ne,syncFsResponderDispose:ie,sharedFs:f,wsRegistry:g,wsBridge:ee,processManager:c,lickManager:m,browser:n,log:o}))}}}async function nM(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)}rM({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function rM(e){let t=jj();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,mi(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[f]}const iM=`x-bypass-llm-proxy`;function aM(e,t,n){return t?(r,i)=>{if(!oM(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(iM)||a.set(iM,`1`),e(r,{...i,headers:a})}:e}function oM(e,t,n){if(cM(e,t))return!0;let r=n?.()??null;return r?sM(e,r,t):!1}function sM(e,t,n){let r=lM(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 cM(e,t){let n=lM(e);try{return new URL(n,t).origin===t}catch{return!0}}function lM(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function uM(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 dM=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(!fM(e)||e.source!==`panel`)return;let t=e.payload;mM(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=Di(ae(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?pM(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,pM(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 fM(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function pM(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function mM(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 hM=class extends ee{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};const gM={maxExecutionTimeMs:1/0,maxCommandCount:1/0,maxLoopIterations:1/0,maxParserTokens:1/0,maxParseIterations:1/0};function _M(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new dM({transport:t,processManager:i,createShell:(a,o)=>new hM(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Nr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s,executionLimits:gM}),logger:o});return{host:c,stop:c.start()}}function vM(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return xM(e);if(typeof e==`object`)return SM(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function yM(e){if(typeof e==`object`&&e&&!(e instanceof Error))return wM(e)??TM(e);let t=vM(e);if(t!==void 0)return bM(t)}function bM(e){let t=e.trim();if(!t)return e;let n=CM(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=CM(t.slice(r,i+1));if(e)return e}return e}function xM(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function SM(e){let t=wM(e),n=TM(e);return n&&t?`${n}: ${t}`:t??n}function CM(e){if(e.startsWith(`{`))try{return wM(JSON.parse(e))}catch{return}}function wM(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 TM(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 EM=null,DM=!1;function OM(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function kM(e){return OM()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function AM(e={}){if(!DM&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){m(jM),AE(NM),rD(MM);try{let t=kM(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(EM=(await import(`./rum-worker-CwmNSpjO.js`)).default,IM(self)):t===`extension`?(EM=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&IM(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),UM(),RM(),EM=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),DM=!0,EM&&EM(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function jM(e){EM?.(`fill`,{source:e})}function MM(e,t){let n=FM(t);n!==null&&EM?.(`error`,{source:e,target:n})}function NM(e,t,n){if(e===`error`){let e=FM(n);if(e===null)return;EM?.(`error`,{source:`scoop:${t}`,target:e});return}EM?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function PM(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function FM(e){let t=vM(e);if(t===void 0)return e==null?void 0:null;if(dD(t))return null;let n=yM(e)??bM(t);return dD(n)?null:zM(n)}function IM(e){e.addEventListener(`error`,e=>{let t=e;MM(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{MM(`js`,e.reason)})}function LM(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function RM(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;LM(t)&&(MM(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;LM(t)&&(MM(`js`,t),e.stopImmediatePropagation())},!0))}function zM(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
1187
+ `}}const kj=Math.max(Si,Ci)+5e3;function Aj(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(bi(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(!vi(n.token))return;let a=i.get(n.id);if(a){r({type:xi,id:n.id}),a.result&&r({type:yi,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:xi,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),kj),r({type:yi,id:n.id,...e})};(Ti(n)?wi(n):Ei(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 jj(){return globalThis}function Mj(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 wy(e);case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`bash`:return e.bashJobId??`bash`;case`jshd`:return e.jshdName??`jshd`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Nj(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 Pj(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Fj(e,t)}async function Fj(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=O(r),a=e.type===`discovery`&&!e.targetScoop?lj(e,i.filter(Cx),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?eo(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Cx(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-7__195zM.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=Ry(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=Mj(e),l=Nj(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 Ij(e,t,n,r,i){let a=new pi,o=new YA(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=fn(),l=i.capabilityBroker??c(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(l),br(l),jj().__slicc_pm=a,mi(gi()),jj().__slicc_browser=t,await n.bind(o,t);let u=Mr(()=>n.emitTrayRuntimeStatus()),d=we(()=>n.emitTrayRuntimeStatus());gj(o,n);let f=i.logger??console;return await o.init(i.onBootProgress,{onSharedFsReady:async e=>{try{let{applyConfiguredHostMounts:t}=await import(`./auto-mount-table-Dlq8aO5D.js`);await t(e,f)}catch(e){f.warn(`Configured host mounts failed`,e)}i.onBootProgress?.(`host-mounts-applied`)}}),await n.hydrateBuffersFromRecords(),n.publishHydratedTranscripts(),{processManager:a,orchestrator:o,unsubLeader:u,unsubFollower:d,sharedFs:o.getSharedFS(),capabilityBroker:l}}async function Lj(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-D0tJNxsl.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await Promise.resolve().then(()=>R_);r(()=>a());let{getLickManager:o}=await Promise.resolve().then(()=>aE),s=o();await s.init(),e.setLickManager(s);let c=t.lickEventHandler??Pj,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function Rj(e){let t=e.getScoops();O(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 zj(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:a}=e;tj({sharedFs:a,getStartingRoot:e=>{let n=O(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)=>_i(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>u().slice(10,22),splitResult:(e,t)=>i(e,t)})}async function Bj(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))+`
1188
+ `,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 Vj(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-Da39Smyv.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-Bqk2Qgbz.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 Hj(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 mx(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})},{...Uj(t),isOwnTab:fx(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Uj(e){let t=ye();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:()=>hx()}}async function Wj(e,t,n){try{let r=await e.recoverInterruptedWork(e=>t.emitEvent(e));r.length>0&&n.info(`Recovered work interrupted by a reload`,{outcomes:r})}catch(e){n.warn(`Reload recovery failed`,e)}}async function Gj(e,t,n,r,i,a){e&&(await qj(e,n,r),i(`mounts-restored`),await Kj(e,t,n,r,a),i(`jshd-restored`))}async function Kj(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-D9IIoDiA.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 qj(e,t,n){try{let{getAllMountEntries:r}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>fy),{applyConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-Dlq8aO5D.js`),s=await a(e,n),c=o(await r(),s);if(c.length===0)return;let{needsRecovery:l}=await i(c,e,n);if(l.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:l}})}catch(e){n.warn(`mount recovery failed`,e)}}function Jj(){Pr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-D28x8Bra.js`);return e()})}function Yj(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-D28x8Bra.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 Xj(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-xbXqblUt.js`),{ScriptCatalog:r}=await import(`./script-catalog-ByM8lrb_.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 Zj(e){return e===`node-rest`}function Qj(e,t,n,r){import(`./gelatiere-unit-DraZBew5.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!ke(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-hsjqGmGi.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function $j(e,t){if(!e)return()=>{};import(`./memory-curation-seam-BZfTB-xj.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return ke(`memory-v2`)&&import(`./memory-health-CV6Pih7i.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 eM(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}Yv(e,t,e.getSessionStore())}async function tM(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Jj();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Ij(t,n,r,i,e);if(s(`orchestrator-ready`),eM(l,f,o),f)try{await f.mountInternal(`/proc`,new _j(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await Lj(l,e,o);s(`lick-manager-ready`),f&&zj({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),jj().__slicc_lickManager=m,Qj(l,m,f,o);let h=$j(f,o),{wsBridge:ee,wsRegistry:g}=await Bj({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});jj().__slicc_wsSubscribers=g;let te=Zj(p.adapter)?await Vj(m,o,e.localLickWsUrl??null,f):null,ne=Hj(n,m,o,e.appPageUrl);await Gj(f,c,m,o,s,l),a||await Rj(l),s(`cone-bootstrapped`),Wj(l,m,o),f&&Yj(m,o);let re=null,_=null;f&&({bshWatchdogStop:re,scriptCatalogDispose:_}=await Xj(f,n,o));let ie=null;f&&e.syncFsChannelNonce&&(ie=Aj({nonce:e.syncFsChannelNonce}).dispose);let ae=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){ae||(ae=!0,await nM({unsubLeader:u,unsubFollower:d,bshWatchdogStop:re,memoryHealthStop:h,scriptCatalogDispose:_,lickWsBridgeStop:te,navigationWatcherStop:ne,syncFsResponderDispose:ie,sharedFs:f,wsRegistry:g,wsBridge:ee,processManager:c,lickManager:m,browser:n,log:o}))}}}async function nM(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)}rM({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function rM(e){let t=jj();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,mi(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[f]}const iM=`x-bypass-llm-proxy`;function aM(e,t,n){return t?(r,i)=>{if(!oM(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(iM)||a.set(iM,`1`),e(r,{...i,headers:a})}:e}function oM(e,t,n){if(cM(e,t))return!0;let r=n?.()??null;return r?sM(e,r,t):!1}function sM(e,t,n){let r=lM(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 cM(e,t){let n=lM(e);try{return new URL(n,t).origin===t}catch{return!0}}function lM(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function uM(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 dM=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(!fM(e)||e.source!==`panel`)return;let t=e.payload;mM(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=Di(ae(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?pM(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,pM(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 fM(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function pM(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function mM(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 hM=class extends ee{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};const gM={maxExecutionTimeMs:1/0,maxCommandCount:1/0,maxLoopIterations:1/0,maxParserTokens:1/0,maxParseIterations:1/0};function _M(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new dM({transport:t,processManager:i,createShell:(a,o)=>new hM(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Nr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s,executionLimits:gM}),logger:o});return{host:c,stop:c.start()}}function vM(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return xM(e);if(typeof e==`object`)return SM(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function yM(e){if(typeof e==`object`&&e&&!(e instanceof Error))return wM(e)??TM(e);let t=vM(e);if(t!==void 0)return bM(t)}function bM(e){let t=e.trim();if(!t)return e;let n=CM(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=CM(t.slice(r,i+1));if(e)return e}return e}function xM(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function SM(e){let t=wM(e),n=TM(e);return n&&t?`${n}: ${t}`:t??n}function CM(e){if(e.startsWith(`{`))try{return wM(JSON.parse(e))}catch{return}}function wM(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 TM(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 EM=null,DM=!1;function OM(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function kM(e){return OM()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function AM(e={}){if(!DM&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){m(jM),AE(NM),rD(MM);try{let t=kM(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(EM=(await import(`./rum-worker-CwmNSpjO.js`)).default,IM(self)):t===`extension`?(EM=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&IM(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),UM(),RM(),EM=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),DM=!0,EM&&EM(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function jM(e){EM?.(`fill`,{source:e})}function MM(e,t){let n=FM(t);n!==null&&EM?.(`error`,{source:e,target:n})}function NM(e,t,n){if(e===`error`){let e=FM(n);if(e===null)return;EM?.(`error`,{source:`scoop:${t}`,target:e});return}EM?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function PM(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function FM(e){let t=vM(e);if(t===void 0)return e==null?void 0:null;if(dD(t))return null;let n=yM(e)??bM(t);return dD(n)?null:zM(n)}function IM(e){e.addEventListener(`error`,e=>{let t=e;MM(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{MM(`js`,e.reason)})}function LM(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function RM(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;LM(t)&&(MM(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;LM(t)&&(MM(`js`,t),e.stopImmediatePropagation())},!0))}function zM(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
1189
1189
  `).filter(e=>!PM(e)).join(`
1190
- `).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 BM=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function VM(e){let t=typeof e==`string`?e:yM(e)??vM(e);if(typeof t!=`string`)return{kind:`absent`};let n=bM(t);if(n===`[object Object]`)return{kind:`noise`};let r=zM(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function HM(e){let t=VM(e.source),n=VM(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 UM(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[BM])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=HM(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[BM]=!0,navigator.sendBeacon=n}function WM(e){let t=new GM(e);return t.start(),{stop:()=>t.dispose()}}var GM=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(!KM(e)||e.source!==`panel`)return;let t=e.payload;if(qM(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(JM(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(YM(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 k(`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 k(`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 k(`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(XM(e.type),e.requestId,new k(`EACCES`,`vfs-rpc-host has no writable backend wired`),ZM(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 k(`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 k(`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 k(`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=QM(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=QM(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 KM(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function qM(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 JM(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 YM(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function XM(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 ZM(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function QM(e,t){return e instanceof k?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function $M(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=aM(e.bind(globalThis),t,eN)}function eN(){let e=Le();if(!e)return null;try{return new URL(e).origin}catch{return null}}function tN(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 nN=null,rN=null,iN=null,aN=null,oN=null,sN=null;const cN=uM(e=>dN(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&cN.handle(e.data)});function lN(e){let t=Ya(e.pageBuildId,`6.203.0-mukh5pyk`);return()=>{t&&MM(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.203.0-mukh5pyk`)}}function uN(e){$M(),Ie(e.localApiBaseUrl??null),Fe(e.bridgeToken??null),hi(e.syncFsBridgeEnabled??!1),t(e.pageLoadedAt??null),Be(e.extensionDelegateId??null),tN(e.localStorageSeed??{}),e.flagFloat&&Ia(e.flagFloat)}async function dN(e){Ka(e.instanceId);let t=lN(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{uN(e),AM().then(t).catch(()=>{}),await Ne(),n(`providers-registered`);let r=Qa(e.kernelPort),i=new ex(r),a=ex.createCallbacks(i),o=new $a(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new wa(o);nN=await tM({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=nN.sharedFs?.getWatcher();if(u){let e=null,t=new Set;for(let n of ki)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-DW7W4w6_.js`).then(e=>e.a);sN=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=sN,s.setTrayTargetProvider(Na(Oe));let f=await pN({host:nN,transport:r,browser:s,instanceId:e.instanceId});f&&(rN=f.stopTerminalHost,iN=f.stopVfsRpcHost,aN=f.stopSpeechAssetsResponder,oN=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){fN(e.kernelPort,t)}}function fN(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 pN(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=_M({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=WM({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await mN(t,e.instanceId),{startComputersHost:o}=await import(`./host-ClT6wiGS.js`),s=o({transport:e.transport,processManager:e.host.processManager});return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a,stopComputersHost:s.stop}}async function mN(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-Le3eCseO.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-DXaTHROw.js`).then(e=>e.a),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(rN?.(),rN=null,iN?.(),iN=null,aN?.(),aN=null,oN?.(),oN=null,sN?.dispose(),sN=null,nN?.dispose())});export{Bv as _,_S as a,A_ as b,Dx as c,Ox as d,jx as f,Tv as g,zy as h,gS as i,kx as l,Ab as m,rO as n,yS as o,kb as p,yT as r,vS as s,lk as t,Ax as u,rv as v,W_ as y};
1190
+ `).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 BM=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function VM(e){let t=typeof e==`string`?e:yM(e)??vM(e);if(typeof t!=`string`)return{kind:`absent`};let n=bM(t);if(n===`[object Object]`)return{kind:`noise`};let r=zM(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function HM(e){let t=VM(e.source),n=VM(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 UM(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[BM])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=HM(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[BM]=!0,navigator.sendBeacon=n}function WM(e){let t=new GM(e);return t.start(),{stop:()=>t.dispose()}}var GM=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(!KM(e)||e.source!==`panel`)return;let t=e.payload;if(qM(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(JM(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(YM(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 k(`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 k(`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 k(`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(XM(e.type),e.requestId,new k(`EACCES`,`vfs-rpc-host has no writable backend wired`),ZM(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 k(`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 k(`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 k(`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=QM(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=QM(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 KM(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function qM(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 JM(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 YM(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function XM(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 ZM(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function QM(e,t){return e instanceof k?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function $M(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=aM(e.bind(globalThis),t,eN)}function eN(){let e=Le();if(!e)return null;try{return new URL(e).origin}catch{return null}}function tN(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 nN=null,rN=null,iN=null,aN=null,oN=null,sN=null;const cN=uM(e=>dN(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&cN.handle(e.data)});function lN(e){let t=Ya(e.pageBuildId,`6.203.2-mukl8xbr`);return()=>{t&&MM(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.203.2-mukl8xbr`)}}function uN(e){$M(),Ie(e.localApiBaseUrl??null),Fe(e.bridgeToken??null),hi(e.syncFsBridgeEnabled??!1),t(e.pageLoadedAt??null),Be(e.extensionDelegateId??null),tN(e.localStorageSeed??{}),e.flagFloat&&Ia(e.flagFloat)}async function dN(e){Ka(e.instanceId);let t=lN(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{uN(e),AM().then(t).catch(()=>{}),await Ne(),n(`providers-registered`);let r=Qa(e.kernelPort),i=new ex(r),a=ex.createCallbacks(i),o=new $a(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new wa(o);nN=await tM({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=nN.sharedFs?.getWatcher();if(u){let e=null,t=new Set;for(let n of ki)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-DW7W4w6_.js`).then(e=>e.a);sN=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=sN,s.setTrayTargetProvider(Na(Oe));let f=await pN({host:nN,transport:r,browser:s,instanceId:e.instanceId});f&&(rN=f.stopTerminalHost,iN=f.stopVfsRpcHost,aN=f.stopSpeechAssetsResponder,oN=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){fN(e.kernelPort,t)}}function fN(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 pN(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=_M({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=WM({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await mN(t,e.instanceId),{startComputersHost:o}=await import(`./host-ClT6wiGS.js`),s=o({transport:e.transport,processManager:e.host.processManager});return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a,stopComputersHost:s.stop}}async function mN(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-SWXzZ--z.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-DXaTHROw.js`).then(e=>e.a),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(rN?.(),rN=null,iN?.(),iN=null,aN?.(),aN=null,oN?.(),oN=null,sN?.dispose(),sN=null,nN?.dispose())});export{Bv as _,_S as a,A_ as b,Dx as c,Ox as d,jx as f,Tv as g,zy as h,gS as i,kx as l,Ab as m,rO as n,yS as o,kb as p,yT as r,vS as s,lk as t,Ax as u,rv as v,W_ as y};