sliccy 6.180.0 → 6.181.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/dist/ui/.vite/manifest.json +217 -189
  2. package/dist/ui/assets/account-store-0RMtbmqz.js +1 -0
  3. package/dist/ui/assets/account-store-J3ybiSNw.js +2 -0
  4. package/dist/ui/assets/adobe-DEXpooxf.js +1 -0
  5. package/dist/ui/assets/adobe-YOeKKYUk.js +2 -0
  6. package/dist/ui/assets/{agent-panels-D9q2my7u.js → agent-panels-B4hlhzVG.js} +1 -1
  7. package/dist/ui/assets/{almost-bash-shell-headless-FNia8qKH.js → almost-bash-shell-headless-BR1Hr6tM.js} +30 -30
  8. package/dist/ui/assets/{apply-layout-CY0ZMc2P.js → apply-layout-BgFVMSBx.js} +1 -1
  9. package/dist/ui/assets/{apps-30Hsl8Yx.js → apps-oyrUmtWx.js} +1 -1
  10. package/dist/ui/assets/{azure-openai-CDmJiho_.js → azure-openai-B6qTFVGv.js} +1 -1
  11. package/dist/ui/assets/{azure-openai-9tspjkO5.js → azure-openai-Ytc_MWDd.js} +1 -1
  12. package/dist/ui/assets/{backend-hostfs-Zq8eFtjc.js → backend-hostfs-CEXlx0cW.js} +1 -1
  13. package/dist/ui/assets/{cdp-C42JpbnT.js → cdp-DVWJozRc.js} +1 -1
  14. package/dist/ui/assets/{cerebras-CFf6FV04.js → cerebras-BT44OLPt.js} +1 -1
  15. package/dist/ui/assets/{cerebras-D2OPqUBP.js → cerebras-brHRFUH2.js} +1 -1
  16. package/dist/ui/assets/{composer-speech-Bi2POadn.js → composer-speech-BZQtz7u1.js} +1 -1
  17. package/dist/ui/assets/{connect-surface-DQTvGzL6.js → connect-surface-D7cq2QI7.js} +1 -1
  18. package/dist/ui/assets/core-B3ULTK7V.js +62 -0
  19. package/dist/ui/assets/core-aQUekdF7.js +36 -0
  20. package/dist/ui/assets/{directed-approval-DsTXqsDu.js → directed-approval-DvAxEX5J.js} +1 -1
  21. package/dist/ui/assets/{emscripten-vfs-hook-Bg1EUSS-.js → emscripten-vfs-hook-agmT6Hsz.js} +1 -1
  22. package/dist/ui/assets/{ensure-speech-assets-0UZlYzUX.js → ensure-speech-assets-CQ05z2Xw.js} +1 -1
  23. package/dist/ui/assets/feature-flags-BftQitIZ.js +1 -0
  24. package/dist/ui/assets/feature-flags-ysThCqxC.js +1 -0
  25. package/dist/ui/assets/{frozen-archive-writer-C0vwpeI6.js → frozen-archive-writer-qxZ9jGOV.js} +1 -1
  26. package/dist/ui/assets/fs-D6FCLu_F.js +1 -0
  27. package/dist/ui/assets/fs-Dkh-H6Cd.js +2 -0
  28. package/dist/ui/assets/{gelatiere-store-6PnudWGB.js → gelatiere-store-ChogqkEu.js} +1 -1
  29. package/dist/ui/assets/{gelatiere-unit-BguezRYn.js → gelatiere-unit-DxFUh33e.js} +1 -1
  30. package/dist/ui/assets/{github-CG-b1Yz_.js → github-CrHzeKQ8.js} +1 -1
  31. package/dist/ui/assets/{github-D7kyOyzh.js → github-D31l6kcK.js} +2 -2
  32. package/dist/ui/assets/{github-auth-BraqNx1i.js → github-auth-VTbKhlbJ.js} +1 -1
  33. package/dist/ui/assets/github-copilot-CVwHDKPD.js +2 -0
  34. package/dist/ui/assets/github-copilot-eUb4Djg_.js +1 -0
  35. package/dist/ui/assets/{github-install-BpIzczOh.js → github-install-Dkt1u6HU.js} +1 -1
  36. package/dist/ui/assets/{github-zip-CpV4XMuv.js → github-zip-B6gHXxqd.js} +1 -1
  37. package/dist/ui/assets/{guest-tool-gate-yzMDXmb7.js → guest-tool-gate-YxkVsl15.js} +1 -1
  38. package/dist/ui/assets/{hear-D1xfqCRf.js → hear-BKQjhhNP.js} +1 -1
  39. package/dist/ui/assets/{help-DNjYeiru.js → help-C7WHd3Ia.js} +1 -1
  40. package/dist/ui/assets/{installer-pNvmgsp2.js → installer-D35TzRKw.js} +1 -1
  41. package/dist/ui/assets/{interrupted-work-recovery-dk4HMys6.js → interrupted-work-recovery-BK9ZDM7F.js} +1 -1
  42. package/dist/ui/assets/js-realm-worker-BIVxi3Fa.js +50 -0
  43. package/dist/ui/assets/{jsh-executor-BuREMqJc.js → jsh-executor-DhdH2_yG.js} +2 -2
  44. package/dist/ui/assets/{kernel-worker-CMZdB97j.js → kernel-worker-UUfeG-Eg.js} +68 -68
  45. package/dist/ui/assets/{lick-ws-bridge-CVcgQWV0.js → lick-ws-bridge-DdgwrW91.js} +1 -1
  46. package/dist/ui/assets/{lick-ws-bridge-nPLmwzQd.js → lick-ws-bridge-DoyPgrSr.js} +1 -1
  47. package/dist/ui/assets/live-session-curation-6O9TA5qM.js +1 -0
  48. package/dist/ui/assets/{live-session-snapshot-BSndLrLB.js → live-session-snapshot-D_7T7FHe.js} +1 -1
  49. package/dist/ui/assets/{local-llm-o-MjgDNe.js → local-llm-BYaSa2xI.js} +1 -1
  50. package/dist/ui/assets/{local-llm-C4hKvsjN.js → local-llm-TK4oGrWD.js} +1 -1
  51. package/dist/ui/assets/main-Bgkf5d3Z.js +22 -0
  52. package/dist/ui/assets/{main-cherry-NHI23XOX.js → main-cherry-BUdIAeG5.js} +1 -1
  53. package/dist/ui/assets/{memory-curation-seam-CmUEG05f.js → memory-curation-seam-CNOuxuz4.js} +1 -1
  54. package/dist/ui/assets/{memory-health-DVwJNc8y.js → memory-health-BSo0HKQx.js} +1 -1
  55. package/dist/ui/assets/memory-v2-flag-CX_dAcAR.js +1 -0
  56. package/dist/ui/assets/{memory-write-execute-E9mWyIAl.js → memory-write-execute-mQfg-aG4.js} +1 -1
  57. package/dist/ui/assets/{mount-zxJpqjfc.js → mount-BpcQX-Sq.js} +1 -1
  58. package/dist/ui/assets/{mount-CkCLiqtz.js → mount-h-dwh5GL.js} +3 -3
  59. package/dist/ui/assets/new-session-CTx7YRbr.js +2 -0
  60. package/dist/ui/assets/oauth-bootstrap-B18nfDG4.js +2 -0
  61. package/dist/ui/assets/{onboarding-orchestrator-NspTxzE-.js → onboarding-orchestrator-Df3UDgbD.js} +1 -1
  62. package/dist/ui/assets/{openai-codex-CtV9F4YZ.js → openai-codex-Cu1dT_JE.js} +1 -1
  63. package/dist/ui/assets/{openai-codex-CcVYEGxA.js → openai-codex-DBUtEEk3.js} +1 -1
  64. package/dist/ui/assets/{openrouter-BNWklYTU.js → openrouter-BwrZKpwu.js} +1 -1
  65. package/dist/ui/assets/{openrouter-B_ZafRVO.js → openrouter-CrB0BbnV.js} +1 -1
  66. package/dist/ui/assets/{openrouter-free-BGkRgNKy.js → openrouter-free-B_LRYNX8.js} +1 -1
  67. package/dist/ui/assets/{openrouter-free-B9EMo-e7.js → openrouter-free-CXqUunRn.js} +1 -1
  68. package/dist/ui/assets/{openrouter-oauth-CIOPqcnL.js → openrouter-oauth-Bnohq7Ac.js} +1 -1
  69. package/dist/ui/assets/{openrouter-oauth-DqZoGOX4.js → openrouter-oauth-Bpzo9cvY.js} +1 -1
  70. package/dist/ui/assets/{opfs-mount-DVnNHDGI.js → opfs-mount-CmDtZOGy.js} +1 -1
  71. package/dist/ui/assets/panel-rpc-handlers-BFG-ZvfW.js +2 -0
  72. package/dist/ui/assets/{panelize-shell-6EgwajIj.js → panelize-shell-CLHSr5bz.js} +1 -1
  73. package/dist/ui/assets/{pi-edit-execution-C2vx7I8W.js → pi-edit-execution-wHbJ4R48.js} +1 -1
  74. package/dist/ui/assets/{provider-BM8Fl5eb.js → provider-BXK9OD8Z.js} +2 -2
  75. package/dist/ui/assets/{provider-Do8GE35W.js → provider-DyqdvQeZ.js} +1 -1
  76. package/dist/ui/assets/{provider-settings-C5-R4CAK.js → provider-settings-BO6Fedc5.js} +1 -1
  77. package/dist/ui/assets/provider-store-access-BFeKOGcv.js +1 -0
  78. package/dist/ui/assets/provider-store-access-C2X0AryS.js +1 -0
  79. package/dist/ui/assets/providers-BvApGkM9.js +2 -0
  80. package/dist/ui/assets/{providers-1XGnlkRB.js → providers-CAcycJZb.js} +1 -1
  81. package/dist/ui/assets/{quick-llm-C0JjR1ll.js → quick-llm-BENSRBxD.js} +1 -1
  82. package/dist/ui/assets/realm-inprocess-BBw2Fa8u.js +30 -0
  83. package/dist/ui/assets/{recovery-screen-DTnntvly.js → recovery-screen-Tq3wGnmV.js} +1 -1
  84. package/dist/ui/assets/{remote-terminal-view-Cd-B2Hl9.js → remote-terminal-view-C8LiE7Sl.js} +1 -1
  85. package/dist/ui/assets/{restore-B5L76uAO.js → restore-DVP0SPlY.js} +1 -1
  86. package/dist/ui/assets/{run-29F7vZr6.js → run-BGZP3j5p.js} +2 -2
  87. package/dist/ui/assets/{run-CQO2CvCb.js → run-BV_OY-0v.js} +1 -1
  88. package/dist/ui/assets/{run-BJ1lweaR.js → run-CPT6_R-_.js} +2 -2
  89. package/dist/ui/assets/{run-twzOjiSl.js → run-CiUSMP3Y.js} +2 -2
  90. package/dist/ui/assets/{run-BAVclQ_q.js → run-FyOp8GaC.js} +2 -2
  91. package/dist/ui/assets/{run-CG0v2Pw6.js → run-zLr2k5ZP.js} +1 -1
  92. package/dist/ui/assets/{session-command-memory-BBSebn07.js → session-command-memory-HovmIuMP.js} +2 -2
  93. package/dist/ui/assets/{session-jsonl-Dx1wwk9X.js → session-jsonl-DK-0Hm8U.js} +1 -1
  94. package/dist/ui/assets/{session-jsonl-__tig_P-.js → session-jsonl-PCOch0_B.js} +1 -1
  95. package/dist/ui/assets/{session-search-index-DCrprmyT.js → session-search-index-BNvhiRLv.js} +1 -1
  96. package/dist/ui/assets/setup-feature-flags-remote-2RQqEGaT.js +1 -0
  97. package/dist/ui/assets/setup-model-catalog-B911rONc.js +1 -0
  98. package/dist/ui/assets/{signed-fetch-D8kpqzQr.js → signed-fetch-gB25Bw53.js} +1 -1
  99. package/dist/ui/assets/{silent-renew-backoff-Zis9tJLB.js → silent-renew-backoff-Brcr76an.js} +1 -1
  100. package/dist/ui/assets/slicc-version-CAje2bW-.js +1 -0
  101. package/dist/ui/assets/{snapshot-D6x5FQ65.js → snapshot-Ci8jnY_A.js} +1 -1
  102. package/dist/ui/assets/{snapshot-features-B0z9yqF8.js → snapshot-features-BYEGCVfZ.js} +1 -1
  103. package/dist/ui/assets/{soundscape-BNuowQ7c.js → soundscape-CdQvLeB0.js} +1 -1
  104. package/dist/ui/assets/{speak-CM0G-jv2.js → speak-BT4Xdlvj.js} +1 -1
  105. package/dist/ui/assets/sprinkle-manager-8T1XJmL3.js +1 -0
  106. package/dist/ui/assets/{sprinkle-renderer-BZ70q8U0.js → sprinkle-renderer-_vOdPt8H.js} +1 -1
  107. package/dist/ui/assets/{state-CMaAjNLX.js → state-nnDajRje.js} +1 -1
  108. package/dist/ui/assets/{store-BkgqEymP.js → store-BxxMrsS7.js} +1 -1
  109. package/dist/ui/assets/{store-DClHiTYa.js → store-D9XL9aIQ.js} +1 -1
  110. package/dist/ui/assets/{sudo-PCV39MiN.js → sudo-CnXURhFV.js} +1 -1
  111. package/dist/ui/assets/{supervisor-DtbPDqlw.js → supervisor-fOZGoD0G.js} +1 -1
  112. package/dist/ui/assets/{sync-dialog-ulF7EhDB.js → sync-dialog-oh_O9Mv5.js} +1 -1
  113. package/dist/ui/assets/{transformers-env-DA6yIZOQ.js → transformers-env-zmBF2In6.js} +1 -1
  114. package/dist/ui/assets/{tray-leader-CaNUXMyA.js → tray-leader-Co-1rs4b.js} +1 -1
  115. package/dist/ui/assets/{tray-leave-runtime-B6H2og7r.js → tray-leave-runtime-PpRt0K76.js} +1 -1
  116. package/dist/ui/assets/{tray-sidecar-dMsrQrjt.js → tray-sidecar-DYuM8Ifi.js} +1 -1
  117. package/dist/ui/assets/{turn-journal-DGbDeEVx.js → turn-journal-_Hrn3Aoy.js} +1 -1
  118. package/dist/ui/assets/{upgrade-detection-B0UzxzJj.js → upgrade-detection-jhAzOLSL.js} +1 -1
  119. package/dist/ui/assets/{upskill-lick-skip-Dwqx8mXn.js → upskill-lick-skip-D1vFOKgN.js} +1 -1
  120. package/dist/ui/assets/{voice-reply-DZehR7u8.js → voice-reply--Z1dXvPT.js} +1 -1
  121. package/dist/ui/assets/wc-attach-BadBFuc7.js +13 -0
  122. package/dist/ui/assets/{wc-browser-Bn2kzFBz.js → wc-browser-DqUJaWcH.js} +1 -1
  123. package/dist/ui/assets/{wc-computers-BGpGK_lD.js → wc-computers-CTPf-95b.js} +1 -1
  124. package/dist/ui/assets/{wc-detached-C2Uoiq-A.js → wc-detached-UIVnUZp5.js} +1 -1
  125. package/dist/ui/assets/wc-extension-Bxc7adS3.js +2 -0
  126. package/dist/ui/assets/wc-follower-CcQiy0Ep.js +17 -0
  127. package/dist/ui/assets/{wc-follower-oauth-d5z3eyJQ.js → wc-follower-oauth-DEBzlhDR.js} +1 -1
  128. package/dist/ui/assets/wc-gelatiere-B3T_MsYw.js +1 -0
  129. package/dist/ui/assets/{wc-live-D_nDQ7fc.js → wc-live-B4gJYGS5.js} +8 -8
  130. package/dist/ui/assets/wc-nav-Cc31eRBb.js +2 -0
  131. package/dist/ui/assets/{wc-onboarding-zTyXdDGG.js → wc-onboarding-A_43Ieo4.js} +2 -2
  132. package/dist/ui/assets/{wc-permissions-DE03I9yf.js → wc-permissions-C9woviuI.js} +2 -2
  133. package/dist/ui/assets/wc-placeholder-t7YMeS_j.js +4 -0
  134. package/dist/ui/assets/{wc-secret-request-G0Qd5fKh.js → wc-secret-request-Dfm9QvyE.js} +1 -1
  135. package/dist/ui/assets/{wc-settings-D6ynnLLu.js → wc-settings-BD6JONjg.js} +3 -3
  136. package/dist/ui/assets/{wc-shell-CRmcNm3q.js → wc-shell-Ba5uNdmF.js} +152 -152
  137. package/dist/ui/assets/{wc-shortcut-config-BgzkZguq.js → wc-shortcut-config-DeU2Q2BU.js} +1 -1
  138. package/dist/ui/assets/wc-sprinkles-D4sQVRG5.js +2 -0
  139. package/dist/ui/assets/wc-transcript-export-CsUhlwMo.js +2 -0
  140. package/dist/ui/assets/{wc-tray-Dddp-0o-.js → wc-tray-CwvVidS8.js} +4 -4
  141. package/dist/ui/assets/welcome-detection-CIDbn0ev.js +1 -0
  142. package/dist/ui/assets/whisper-session-MB0YiZ0q.js +2 -0
  143. package/dist/ui/assets/xai-grok-0BxCS34q.js +1 -0
  144. package/dist/ui/assets/xai-grok-rwJAZiuv.js +1 -0
  145. package/dist/ui/index.html +5 -4
  146. package/dist/ui/packages/webapp/index.html +5 -4
  147. package/package.json +1 -1
  148. package/dist/ui/assets/account-store-C-p1lMw5.js +0 -2
  149. package/dist/ui/assets/account-store-CQ9VWuvY.js +0 -1
  150. package/dist/ui/assets/adobe-BUhDM15K.js +0 -2
  151. package/dist/ui/assets/adobe-CBr4ZN4n.js +0 -1
  152. package/dist/ui/assets/core-DeN3S2m9.js +0 -62
  153. package/dist/ui/assets/core-QNbq3R8b.js +0 -36
  154. package/dist/ui/assets/fs-BtFAX2_M.js +0 -2
  155. package/dist/ui/assets/fs-DvluRaqj.js +0 -1
  156. package/dist/ui/assets/github-copilot-CiSp3eBW.js +0 -1
  157. package/dist/ui/assets/github-copilot-DuD7Lgmt.js +0 -2
  158. package/dist/ui/assets/js-realm-worker-CkAMvsrT.js +0 -50
  159. package/dist/ui/assets/live-session-curation-eLY2VPhg.js +0 -1
  160. package/dist/ui/assets/main-CbW_Za2k.js +0 -22
  161. package/dist/ui/assets/memory-v2-flag-CnOOdxrM.js +0 -1
  162. package/dist/ui/assets/new-session-BtrbxZ1f.js +0 -2
  163. package/dist/ui/assets/oauth-bootstrap-CUEpFgrr.js +0 -2
  164. package/dist/ui/assets/panel-rpc-handlers-BSCm4kOU.js +0 -2
  165. package/dist/ui/assets/provider-store-access-CXCNqTez.js +0 -1
  166. package/dist/ui/assets/provider-store-access-HnHz6M14.js +0 -1
  167. package/dist/ui/assets/providers-vlrJYxJ5.js +0 -2
  168. package/dist/ui/assets/realm-inprocess-C6O9qOMR.js +0 -30
  169. package/dist/ui/assets/setup-feature-flags-remote-05sIbIjy.js +0 -1
  170. package/dist/ui/assets/slicc-version-yq-tq2SV.js +0 -1
  171. package/dist/ui/assets/sprinkle-manager-BEv6kGLS.js +0 -1
  172. package/dist/ui/assets/wc-attach-CM9VDfpp.js +0 -13
  173. package/dist/ui/assets/wc-extension-Dkkjge5w.js +0 -2
  174. package/dist/ui/assets/wc-follower-CszcNst7.js +0 -17
  175. package/dist/ui/assets/wc-gelatiere-CvD4RPku.js +0 -1
  176. package/dist/ui/assets/wc-nav-DYqaPxPj.js +0 -2
  177. package/dist/ui/assets/wc-placeholder-CFl99JIA.js +0 -4
  178. package/dist/ui/assets/wc-sprinkles-BEdhIep-.js +0 -2
  179. package/dist/ui/assets/wc-transcript-export-CRdtzxLx.js +0 -2
  180. package/dist/ui/assets/welcome-detection-D-EYPpBI.js +0 -1
  181. package/dist/ui/assets/whisper-session-BQeRsdCz.js +0 -2
  182. package/dist/ui/assets/xai-grok-CtZfuLLm.js +0 -1
  183. package/dist/ui/assets/xai-grok-D2lF8Cx-.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-FNia8qKH.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-CQ9VWuvY.js";import{n as ye}from"./proxied-fetch-CNe6icTW.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-ODKvqvjN.js";import{o as Ee}from"./snapshot-D6x5FQ65.js";import{n as De,r as Oe}from"./panel-rpc-DW7W4w6_.js";import{a as ke,t as Ae}from"./providers-1XGnlkRB.js";import{c as je,d as Me,o as Ne,s as Pe,t as Fe,u as Ie}from"./api-endpoint-D8lUKmPu.js";import{$ as Le,A as Re,At as ze,B as Be,C as Ve,Ct as He,D as Ue,Dt as v,E as We,Et as Ge,F as Ke,H as qe,I as Je,J as Ye,K as Xe,L as Ze,M as Qe,Mt as y,N as $e,Nt as et,O as tt,Ot as nt,P as rt,Q as it,R as at,St as ot,T as st,Tt as b,U as ct,V as lt,W as ut,X as dt,Y as ft,Z as pt,_ as mt,_t as ht,a as gt,at as x,b as _t,bt as vt,c as yt,ct as S,d as bt,dt as xt,et as St,f as Ct,ft as wt,g as Tt,gt as Et,h as Dt,ht as Ot,i as kt,it as At,j as jt,jt as Mt,k as Nt,kt as C,l as Pt,lt as Ft,m as It,mt as Lt,n as Rt,nt as zt,o as Bt,ot as w,p as Vt,pt as T,q as Ht,r as Ut,rt as E,s as Wt,st as D,t as Gt,tt as Kt,u as qt,ut as Jt,v as Yt,vt as Xt,w as Zt,wt as O,x as Qt,xt as $t,y as en,yt as tn,z as nn}from"./build-BRNa03GH.js";import{a as rn}from"./models-4WTk3EBD.js";import{o as an,t as on}from"./compat-uEPf6-XW.js";import{a as sn,r as cn,t as ln}from"./core-QNbq3R8b.js";import{i as un,n as dn,r as fn,t as pn}from"./context-compaction-Dpr7xgBZ.js";import{t as mn}from"./secrets-bridge-client-kWWipUuL.js";import{n as hn,t as gn}from"./image-markers-CwM1dvoI.js";import{i as _n}from"./tool-ui-DRnUkp2g.js";import{c as vn,t as yn}from"./claude-model-version-ceOteQ2f.js";import{a as bn,n as xn,t as Sn}from"./path-utils-DNJG-zQf.js";import{t as Cn}from"./merge-file-core-VJlzucJY.js";import{i as wn,n as Tn,r as En,t as Dn}from"./workspace-mode-D0kUKBVS.js";import{C as On,D as kn,E as k,S as An,T as jn,_ as Mn,a as Nn,c as Pn,d as Fn,f as In,g as Ln,h as Rn,l as zn,m as Bn,n as Vn,o as Hn,p as Un,r as Wn,s as Gn,t as Kn,u as qn,v as Jn,w as Yn,y as Xn}from"./record-ChU1ND2B.js";import{a as Zn,c as Qn,d as $n,i as er,l as tr,n as nr,o as rr,r as ir,s as ar,u as or}from"./descriptor-S4Jug1iP.js";import{n as sr,t as cr}from"./thinking-level-5x0UAu9N.js";import{t as A}from"./types-D8gIX-W-.js";import{i as lr,n as ur}from"./mount-index-CQfmUPuZ.js";import{a as dr,i as fr,n as pr,r as mr,s as hr,t as gr}from"./signed-fetch-D8kpqzQr.js";import{n as _r}from"./mount-table-store-DrF_Ifaz.js";import{t as vr}from"./remote-cache-BE5T1-53.js";import"./mount-zxJpqjfc.js";import{i as yr,n as br,r as xr}from"./fs-DvluRaqj.js";import{i as Sr,n as Cr,t as wr}from"./key-6HWbWSGF.js";import{n as Tr,r as Er,t as Dr}from"./tray-leader-status-CpkFr6n7.js";import"./tray-runtime-config-DBapPARd.js";import{r as Or}from"./slicc-version-yq-tq2SV.js";import{r as kr}from"./virtual-device-paths-CS5o4QVz.js";import{a as Ar,i as jr,r as Mr}from"./cost-command-DZQVtgRS.js";import{_ as Nr,a as Pr,c as Fr,d as Ir,f as Lr,g as Rr,h as zr,l as Br,m as Vr,n as Hr,p as Ur,r as Wr,s as Gr,t as Kr,u as qr,v as Jr}from"./sudoers-BdBYQPUn.js";import{n as Yr,r as Xr,t as Zr}from"./sudo-fs-C6r_MIIY.js";import{t as Qr}from"./llm-session-id-BZyXP_j2.js";import{t as $r}from"./buffer-polyfill-BccMjOKj.js";import{a as ei,i as ti,n as ni,o as ri}from"./memory-budget-Bcf7Eolo.js";import{i as ii}from"./browser-DuyhpHbR.js";import{t as ai}from"./jsh-discovery-CnvNKojr.js";import{t as oi}from"./process-manager-BkhAohXT.js";import{i as si,o as ci,r as li,t as ui}from"./jsh-executor-BuREMqJc.js";import{S as di,b as fi,c as pi,d as mi,g as hi,i as gi,m as _i,r as vi,y as yi}from"./sync-exec-dispatch-CEbwf9Az.js";import{n as bi}from"./just-bash-compat-B-SPHuh_.js";import{t as xi}from"./lick-target-env-8JxfVcIV.js";const Si=[`/workspace`,`/shared`,`/scoops`,`/home`];var Ci=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 wi(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 Ti=_(`cdp`);function Ei(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 Di=class{ws=null;nextId=1;_superseded=!1;pending=new Ci;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,Ti.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Ti.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(),Ti.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),Ti.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 wi(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;Ti.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Ti.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;Ti.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,Ti.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Ti.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Ti.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Ei(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 Oi(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function ki(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Ai=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function ji(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Ai.map(e=>Mi(i,e,t,r)))).filter(e=>e!==null)}async function Mi(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||!Ni(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Ni(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 Pi=3e4;var Fi=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`}},Ii=class extends Error{constructor(){super(`CDP reconnect is backing off`),this.name=`CdpReconnectBackoffError`}};function Li(e,t=Math.random){let n=Math.min(Pi,250*2**Math.min(Math.max(0,e),16)),r=Math.round(n*.2*t());return Math.min(Pi,n+r)}var Ri=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 zi(e,t){if(e?.aborted)throw new Ri(t)}function Bi(e,t){return e?{signal:e,error:()=>new Ri(t)}:void 0}function Vi(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new Ri(n));return}let a=()=>{clearTimeout(o),i(new Ri(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Hi(e,t,n){return t?t.aborted?Promise.reject(new Ri(n)):new Promise((r,i)=>{let a=()=>i(new Ri(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}const Ui=_(`har-recorder`);var Wi=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)}`;zi(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),zi(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),zi(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}`),Ui.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=>{Ui.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=>{Ui.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 Gi(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Ui.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 Ui.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)),Ui.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 Ui.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 Gi(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){Ui.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Ui.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Ki=`(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-BR1Hr6tM.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-0RMtbmqz.js";import{n as ye}from"./proxied-fetch-CNe6icTW.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-ODKvqvjN.js";import{o as Ee}from"./snapshot-Ci8jnY_A.js";import{n as De,r as Oe}from"./panel-rpc-DW7W4w6_.js";import{n as ke,r as Ae,t as je}from"./feature-flags-ysThCqxC.js";import{a as Me,t as Ne}from"./providers-CAcycJZb.js";import{c as Pe,d as Fe,o as Ie,s as Le,t as Re,u as ze}from"./api-endpoint-D8lUKmPu.js";import{$ as Be,A as Ve,At as He,B as Ue,C as We,Ct as Ge,D as Ke,Dt as v,E as qe,Et as Je,F as Ye,H as Xe,I as Ze,J as Qe,K as $e,L as et,M as tt,Mt as y,N as nt,Nt as rt,O as it,Ot as at,P as ot,Q as st,R as ct,St as lt,T as ut,Tt as b,U as dt,V as ft,W as pt,X as mt,Y as ht,Z as gt,_ as _t,_t as vt,a as yt,at as x,b as bt,bt as xt,c as St,ct as S,d as Ct,dt as wt,et as Tt,f as Et,ft as Dt,g as Ot,gt as kt,h as At,ht as jt,i as Mt,it as Nt,j as Pt,jt as Ft,k as It,kt as C,l as Lt,lt as Rt,m as zt,mt as Bt,n as Vt,nt as Ht,o as Ut,ot as w,p as Wt,pt as T,q as Gt,r as Kt,rt as E,s as qt,st as D,t as Jt,tt as Yt,u as Xt,ut as Zt,v as Qt,vt as $t,w as en,wt as O,x as tn,xt as nn,y as rn,yt as an,z as on}from"./build-BRNa03GH.js";import{a as sn}from"./models-4WTk3EBD.js";import{o as cn,t as ln}from"./compat-uEPf6-XW.js";import{a as un,r as dn,t as fn}from"./core-aQUekdF7.js";import{i as pn,n as mn,r as hn,t as gn}from"./context-compaction-Dpr7xgBZ.js";import{t as _n}from"./secrets-bridge-client-kWWipUuL.js";import{n as vn,t as yn}from"./image-markers-CwM1dvoI.js";import{i as bn}from"./tool-ui-DRnUkp2g.js";import{c as xn,t as Sn}from"./claude-model-version-ceOteQ2f.js";import{a as Cn,n as wn,t as Tn}from"./path-utils-DNJG-zQf.js";import{t as En}from"./merge-file-core-VJlzucJY.js";import{i as Dn,n as On,r as kn,t as An}from"./workspace-mode-D0kUKBVS.js";import{C as jn,D as Mn,E as k,S as Nn,T as Pn,_ as Fn,a as In,c as Ln,d as Rn,f as zn,g as Bn,h as Vn,l as Hn,m as Un,n as Wn,o as Gn,p as Kn,r as qn,s as Jn,t as Yn,u as Xn,v as Zn,w as Qn,y as $n}from"./record-ChU1ND2B.js";import{a as er,c as tr,d as nr,i as rr,l as ir,n as ar,o as or,r as sr,s as cr,u as lr}from"./descriptor-S4Jug1iP.js";import{n as ur,t as dr}from"./thinking-level-5x0UAu9N.js";import{t as A}from"./types-D8gIX-W-.js";import{i as fr,n as pr}from"./mount-index-CQfmUPuZ.js";import{a as mr,i as hr,n as gr,r as _r,s as vr,t as yr}from"./signed-fetch-gB25Bw53.js";import{n as br}from"./mount-table-store-DrF_Ifaz.js";import{t as xr}from"./remote-cache-BE5T1-53.js";import"./mount-BpcQX-Sq.js";import{i as Sr,n as Cr,r as wr}from"./fs-D6FCLu_F.js";import{i as Tr,n as Er,t as Dr}from"./key-6HWbWSGF.js";import{n as Or,r as kr,t as Ar}from"./tray-leader-status-CpkFr6n7.js";import"./tray-runtime-config-DBapPARd.js";import{r as jr}from"./slicc-version-CAje2bW-.js";import{r as Mr}from"./virtual-device-paths-CS5o4QVz.js";import{a as Nr,i as Pr,r as Fr}from"./cost-command-DZQVtgRS.js";import{_ as Ir,a as Lr,c as Rr,d as zr,f as Br,g as Vr,h as Hr,l as Ur,m as Wr,n as Gr,p as Kr,r as qr,s as Jr,t as Yr,u as Xr,v as Zr}from"./sudoers-BdBYQPUn.js";import{n as Qr,r as $r,t as ei}from"./sudo-fs-C6r_MIIY.js";import{t as ti}from"./llm-session-id-BZyXP_j2.js";import{t as ni}from"./buffer-polyfill-BccMjOKj.js";import{a as ri,i as ii,n as ai,o as oi}from"./memory-budget-Bcf7Eolo.js";import{i as si}from"./browser-DuyhpHbR.js";import{t as ci}from"./jsh-discovery-CnvNKojr.js";import{t as li}from"./process-manager-BkhAohXT.js";import{i as ui,o as di,r as fi,t as pi}from"./jsh-executor-DhdH2_yG.js";import{S as mi,b as hi,c as gi,d as _i,g as vi,i as yi,m as bi,r as xi,y as Si}from"./sync-exec-dispatch-CEbwf9Az.js";import{n as Ci}from"./just-bash-compat-B-SPHuh_.js";import{t as wi}from"./lick-target-env-8JxfVcIV.js";const Ti=[`/workspace`,`/shared`,`/scoops`,`/home`];var Ei=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 Di(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 Oi=_(`cdp`);function ki(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 Ai=class{ws=null;nextId=1;_superseded=!1;pending=new Ei;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,Oi.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Oi.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(),Oi.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),Oi.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 Di(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;Oi.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Oi.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;Oi.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,Oi.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Oi.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Oi.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(ki(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 ji(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Mi(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Ni=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Pi(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Ni.map(e=>Fi(i,e,t,r)))).filter(e=>e!==null)}async function Fi(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||!Ii(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Ii(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 Li=3e4;var Ri=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`}},zi=class extends Error{constructor(){super(`CDP reconnect is backing off`),this.name=`CdpReconnectBackoffError`}};function Bi(e,t=Math.random){let n=Math.min(Li,250*2**Math.min(Math.max(0,e),16)),r=Math.round(n*.2*t());return Math.min(Li,n+r)}var Vi=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 Hi(e,t){if(e?.aborted)throw new Vi(t)}function Ui(e,t){return e?{signal:e,error:()=>new Vi(t)}:void 0}function Wi(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new Vi(n));return}let a=()=>{clearTimeout(o),i(new Vi(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Gi(e,t,n){return t?t.aborted?Promise.reject(new Vi(n)):new Promise((r,i)=>{let a=()=>i(new Vi(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}const Ki=_(`har-recorder`);var qi=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)}`;Hi(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Hi(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Hi(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),Ki.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{Ki.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{Ki.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;!n||!r||i==null||e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return Ji(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Ki.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return Ki.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),Ki.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return Ki.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function Ji(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){Ki.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Ki.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Yi=`(function() {
2
2
  'use strict';
3
3
 
4
4
  // ===== DOM Utilities =====
@@ -868,34 +868,34 @@ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{C as t,S as n,_ as r,a
868
868
  } catch(e) {
869
869
  return { role: 'RootWebArea', name: '', description: 'Error: ' + (e.message || String(e)) };
870
870
  }
871
- })()`,qi=_(`tab-handle`);function Ji(e){try{let t=atob(e.slice(0,48));return t.startsWith(`‰PNG\r
871
+ })()`,Xi=_(`tab-handle`);function Zi(e){try{let t=atob(e.slice(0,48));return t.startsWith(`‰PNG\r
872
872
  
873
- `)?(t.charCodeAt(16)<<24|t.charCodeAt(17)<<16|t.charCodeAt(18)<<8|t.charCodeAt(19))>>>0:0}catch{return 0}}function Yi(e,t,n,r,i){return wi(r=>{let i=e=>{let t=e.sessionId;(typeof t!=`string`||t===n)&&r(e)};return e.on(t,i),()=>e.off(t,i)},r,`Timed out waiting for event: ${t}`,i)}var Xi=class{host;targetId;sessionId;transport;signal;constructor(e,t,n,r,i){this.host=e,this.targetId=t,this.sessionId=n,this.transport=r,this.signal=i}send(e,t={}){return zi(this.signal,`about to send ${e}`),this.transport.send(e,t,this.sessionId)}async navigate(e){await this.send(`Page.enable`);let t=Yi(this.transport,`Page.loadEventFired`,this.sessionId,3e4,Bi(this.signal,`waiting for ${e} to fire its load event`));t.catch(()=>void 0),await this.send(`Page.navigate`,{url:e}),await t}async bringToFront(){await this.host.runGlobal(this.targetId,async()=>{await this.send(`Page.bringToFront`)})}async screenshot(e){let t={format:e?.format??`png`,captureBeyondViewport:!!(e?.clip||e?.fullPage)};e?.quality!==void 0&&(t.quality=e.quality),(e?.clip||e?.fullPage)&&(t.clip=await this.captureClip(e));let n;try{n=await this.send(`Page.captureScreenshot`,t)}catch(r){if(e?.foregroundFallback===!1)throw r;n=await this.host.wakeCapture(this,t)}let r=n.data;return e?.maxWidth?await this.applyMaxWidth(r,e.maxWidth,t):r}async captureClip(e){if(e.clip)return{...e.clip,scale:e.clip.scale??1};let t=0,n=0;try{await this.send(`Runtime.enable`);let e=await this.send(`Runtime.evaluate`,{expression:`JSON.stringify({ w: window.innerWidth, h: document.documentElement.scrollHeight })`,returnByValue:!0}),r=JSON.parse(e.result?.value??`{}`);t=r.w??0,n=r.h??0}catch(e){qi.warn(`fullPage: failed to evaluate scroll dimensions, falling back to viewport`,e)}return{x:0,y:0,width:t||1280,height:n||800,scale:1}}async applyMaxWidth(e,t,n){let r=Ji(e);if(!r||r<=t)return e;let i=await this.maxWidthClip(n);n.captureBeyondViewport=!0;let a=(i.scale??1)*(t/r),o=null,s=0;for(let e=0;e<3;e++){i.scale=a;let e;try{e=(await this.send(`Page.captureScreenshot`,n)).data}catch(e){qi.warn(`maxWidth re-capture failed`,e);break}let r=Ji(e);if(!r)return e;if(r<=t&&r>s&&(o=e,s=r),r<=t&&r>=t*.98)break;let c=a*t/r;if(!Number.isFinite(c)||c<=0)break;a=c}return o??e}async maxWidthClip(e){let t=e.clip;if(t)return t;let n=1280,r=800,i=0,a=0;try{await this.send(`Runtime.enable`);let e=await this.send(`Runtime.evaluate`,{expression:`JSON.stringify({w:window.innerWidth,h:window.innerHeight,x:window.scrollX,y:window.scrollY})`,returnByValue:!0}),t=JSON.parse(e.result?.value??`{}`);n=t.w||1280,r=t.h||800,typeof t.x==`number`&&(i=t.x),typeof t.y==`number`&&(a=t.y)}catch{}let o={x:i,y:a,width:n,height:r};return e.clip=o,o}async setViewportOverride(e,t,n){let r=this.host.viewportOverride(this.targetId),i={width:e,height:t,deviceScaleFactor:n?.deviceScaleFactor??r?.deviceScaleFactor??1,mobile:n?.mobile??r?.mobile??!1,...(n?.userAgent??r?.userAgent)!==void 0&&{userAgent:n?.userAgent??r?.userAgent}};await this.applyViewportOverride(i),this.host.recordViewportOverride(this.targetId,i)}async applyViewportOverride(e){await this.send(`Emulation.setDeviceMetricsOverride`,{width:e.width,height:e.height,deviceScaleFactor:e.deviceScaleFactor,mobile:e.mobile}),e.mobile&&await this.send(`Emulation.setTouchEmulationEnabled`,{enabled:!0,maxTouchPoints:5}),e.userAgent!==void 0&&await this.send(`Emulation.setUserAgentOverride`,{userAgent:e.userAgent})}async evaluate(e,t){return await this.send(`Runtime.enable`),$i(await this.send(`Runtime.evaluate`,{expression:e,awaitPromise:t?.awaitPromise??!0,returnByValue:t?.returnByValue??!0}),`Evaluation failed`)}async evaluateInFrame(e,t,n){let r=n?.world===`main`?`main`:`isolated`,i;try{i=await this.resolveFrameContext(e,r)}catch(t){throw Error(`Failed to resolve ${r===`main`?`main world`:`isolated world`} for frame ${e}: ${t instanceof Error?t.message:String(t)}`)}r===`isolated`&&await this.send(`Runtime.enable`);let a={expression:t,contextId:i,awaitPromise:n?.awaitPromise??!0,returnByValue:n?.returnByValue??!0},o;try{o=await this.send(`Runtime.evaluate`,a)}catch(t){if(!ea(t))throw t;this.host.frameContexts(this.sessionId,r).delete(e),i=await this.resolveFrameContext(e,r),o=await this.send(`Runtime.evaluate`,{...a,contextId:i})}let s=Qi(o);if(s===null)return o.result?.value;if(this.host.frameContexts(this.sessionId,r).delete(e),!ea(Error(s)))throw Error(`Evaluation in frame ${e} failed: ${s}`);i=await this.resolveFrameContext(e,r);let c=await this.send(`Runtime.evaluate`,{...a,contextId:i}),l=Qi(c);if(l!==null)throw Error(`Evaluation in frame ${e} failed: ${l}`);return c.result?.value}async resolveFrameContext(e,t){let n=this.host.frameContexts(this.sessionId,t),r=n.get(e);if(r!==void 0)return r;if(t===`isolated`){let t=(await this.send(`Page.createIsolatedWorld`,{frameId:e,worldName:`__slicc_iframe`})).executionContextId;return n.set(e,t),t}await this.send(`Runtime.enable`);let i=n.get(e);if(i===void 0&&(await this.send(`Runtime.disable`),await this.send(`Runtime.enable`),i=n.get(e)),i===void 0)throw Error(`Failed to find main world execution context for frame ${e}`);return i}async click(e,t=0){let n=await this.boundingBox(e);if(!n)throw Error(`Element not found: ${e}`);await this.clickAt(n.x+n.width/2,n.y+n.height/2,t)}async type(e){for(let t of e)await this.send(`Input.dispatchKeyEvent`,{type:`keyDown`,text:t}),await this.send(`Input.dispatchKeyEvent`,{type:`keyUp`,text:t})}async insertText(e){await this.send(`Input.insertText`,{text:e})}async waitForSelector(e,t){let n=t?.timeout??3e4,r=t?.interval??100,i=Date.now(),a=`polling for selector ${e}`;for(;Date.now()-i<n;){if(zi(this.signal,a),await this.evaluate(`!!document.querySelector(${JSON.stringify(e)})`))return;await Vi(r,this.signal,a)}throw Error(`waitForSelector timed out after ${n}ms: ${e}`)}async clickByBackendNodeId(e,t=0){let n=await this.resolveNodeObjectId(e),r=await this.nodeBox(n);if(!r||r.width===0||r.height===0){await this.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function() { this.click(); }`});return}await this.clickAt(r.x+r.width/2,r.y+r.height/2,t)}async dblclickByBackendNodeId(e,t=`left`,n=0){let{x:r,y:i}=await this.resolveNodeCenter(e);for(let e of[1,2])await this.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:e,modifiers:n}),await this.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:e,modifiers:n})}async hoverByBackendNodeId(e){let{x:t,y:n}=await this.resolveNodeCenter(e);await this.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:t,y:n})}async selectByBackendNodeId(e,t){let n=await this.resolveNodeObjectId(e);await this.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function(val) { this.value = val; this.dispatchEvent(new Event('change', { bubbles: true })); }`,arguments:[{value:t}],returnByValue:!0})}async setCheckedByBackendNodeId(e,t){let n=await this.resolveNodeObjectId(e);return(await this.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function() { return this.checked; }`,returnByValue:!0})).result?.value===t?`already`:(await this.clickByBackendNodeId(e),`toggled`)}async dragByBackendNodeIds(e,t){let n=await this.resolveNodeCenter(e),r=await this.resolveNodeCenter(t);await this.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:n.x,y:n.y,button:`left`,clickCount:1}),await this.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:r.x,y:r.y}),await this.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r.x,y:r.y,button:`left`,clickCount:1})}async getFrameTree(){await this.send(`Page.enable`);let e=await this.send(`Page.getFrameTree`),t=[];return Zi(e.frameTree,t),t}async getAccessibilityTree(){let e=await this.evaluate(Ki,{awaitPromise:!1,returnByValue:!0});if(!e||typeof e!=`object`)return{role:`RootWebArea`,name:``};let t=ia(e);try{let e=(await this.send(`Accessibility.getFullAXTree`)).nodes;Array.isArray(e)&&ra(t,ta(e))}catch{}return t}async getAccessibilityTreeForFrame(e){if(!e)return this.getAccessibilityTree();let t=await this.evaluateInFrame(e,Ki,{awaitPromise:!1,returnByValue:!0});return!t||typeof t!=`object`?{role:`RootWebArea`,name:``}:ia(t)}async clickAt(e,t,n){await this.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:e,y:t,button:`left`,clickCount:1,modifiers:n}),await this.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:e,y:t,button:`left`,clickCount:1,modifiers:n})}async resolveNodeObjectId(e){await this.send(`DOM.enable`),await this.send(`Runtime.enable`);let t=(await this.send(`DOM.resolveNode`,{backendNodeId:e})).object;if(!t?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);return t.objectId}async nodeBox(e){return(await this.send(`Runtime.callFunctionOn`,{objectId:e,functionDeclaration:`function() {
873
+ `)?(t.charCodeAt(16)<<24|t.charCodeAt(17)<<16|t.charCodeAt(18)<<8|t.charCodeAt(19))>>>0:0}catch{return 0}}function Qi(e,t,n,r,i){return Di(r=>{let i=e=>{let t=e.sessionId;(typeof t!=`string`||t===n)&&r(e)};return e.on(t,i),()=>e.off(t,i)},r,`Timed out waiting for event: ${t}`,i)}var $i=class{host;targetId;sessionId;transport;signal;constructor(e,t,n,r,i){this.host=e,this.targetId=t,this.sessionId=n,this.transport=r,this.signal=i}send(e,t={}){return Hi(this.signal,`about to send ${e}`),this.transport.send(e,t,this.sessionId)}async navigate(e){await this.send(`Page.enable`);let t=Qi(this.transport,`Page.loadEventFired`,this.sessionId,3e4,Ui(this.signal,`waiting for ${e} to fire its load event`));t.catch(()=>void 0),await this.send(`Page.navigate`,{url:e}),await t}async bringToFront(){await this.host.runGlobal(this.targetId,async()=>{await this.send(`Page.bringToFront`)})}async screenshot(e){let t={format:e?.format??`png`,captureBeyondViewport:!!(e?.clip||e?.fullPage)};e?.quality!==void 0&&(t.quality=e.quality),(e?.clip||e?.fullPage)&&(t.clip=await this.captureClip(e));let n;try{n=await this.send(`Page.captureScreenshot`,t)}catch(r){if(e?.foregroundFallback===!1)throw r;n=await this.host.wakeCapture(this,t)}let r=n.data;return e?.maxWidth?await this.applyMaxWidth(r,e.maxWidth,t):r}async captureClip(e){if(e.clip)return{...e.clip,scale:e.clip.scale??1};let t=0,n=0;try{await this.send(`Runtime.enable`);let e=await this.send(`Runtime.evaluate`,{expression:`JSON.stringify({ w: window.innerWidth, h: document.documentElement.scrollHeight })`,returnByValue:!0}),r=JSON.parse(e.result?.value??`{}`);t=r.w??0,n=r.h??0}catch(e){Xi.warn(`fullPage: failed to evaluate scroll dimensions, falling back to viewport`,e)}return{x:0,y:0,width:t||1280,height:n||800,scale:1}}async applyMaxWidth(e,t,n){let r=Zi(e);if(!r||r<=t)return e;let i=await this.maxWidthClip(n);n.captureBeyondViewport=!0;let a=(i.scale??1)*(t/r),o=null,s=0;for(let e=0;e<3;e++){i.scale=a;let e;try{e=(await this.send(`Page.captureScreenshot`,n)).data}catch(e){Xi.warn(`maxWidth re-capture failed`,e);break}let r=Zi(e);if(!r)return e;if(r<=t&&r>s&&(o=e,s=r),r<=t&&r>=t*.98)break;let c=a*t/r;if(!Number.isFinite(c)||c<=0)break;a=c}return o??e}async maxWidthClip(e){let t=e.clip;if(t)return t;let n=1280,r=800,i=0,a=0;try{await this.send(`Runtime.enable`);let e=await this.send(`Runtime.evaluate`,{expression:`JSON.stringify({w:window.innerWidth,h:window.innerHeight,x:window.scrollX,y:window.scrollY})`,returnByValue:!0}),t=JSON.parse(e.result?.value??`{}`);n=t.w||1280,r=t.h||800,typeof t.x==`number`&&(i=t.x),typeof t.y==`number`&&(a=t.y)}catch{}let o={x:i,y:a,width:n,height:r};return e.clip=o,o}async setViewportOverride(e,t,n){let r=this.host.viewportOverride(this.targetId),i={width:e,height:t,deviceScaleFactor:n?.deviceScaleFactor??r?.deviceScaleFactor??1,mobile:n?.mobile??r?.mobile??!1,...(n?.userAgent??r?.userAgent)!==void 0&&{userAgent:n?.userAgent??r?.userAgent}};await this.applyViewportOverride(i),this.host.recordViewportOverride(this.targetId,i)}async applyViewportOverride(e){await this.send(`Emulation.setDeviceMetricsOverride`,{width:e.width,height:e.height,deviceScaleFactor:e.deviceScaleFactor,mobile:e.mobile}),e.mobile&&await this.send(`Emulation.setTouchEmulationEnabled`,{enabled:!0,maxTouchPoints:5}),e.userAgent!==void 0&&await this.send(`Emulation.setUserAgentOverride`,{userAgent:e.userAgent})}async evaluate(e,t){return await this.send(`Runtime.enable`),na(await this.send(`Runtime.evaluate`,{expression:e,awaitPromise:t?.awaitPromise??!0,returnByValue:t?.returnByValue??!0}),`Evaluation failed`)}async evaluateInFrame(e,t,n){let r=n?.world===`main`?`main`:`isolated`,i;try{i=await this.resolveFrameContext(e,r)}catch(t){throw Error(`Failed to resolve ${r===`main`?`main world`:`isolated world`} for frame ${e}: ${t instanceof Error?t.message:String(t)}`)}r===`isolated`&&await this.send(`Runtime.enable`);let a={expression:t,contextId:i,awaitPromise:n?.awaitPromise??!0,returnByValue:n?.returnByValue??!0},o;try{o=await this.send(`Runtime.evaluate`,a)}catch(t){if(!ra(t))throw t;this.host.frameContexts(this.sessionId,r).delete(e),i=await this.resolveFrameContext(e,r),o=await this.send(`Runtime.evaluate`,{...a,contextId:i})}let s=ta(o);if(s===null)return o.result?.value;if(this.host.frameContexts(this.sessionId,r).delete(e),!ra(Error(s)))throw Error(`Evaluation in frame ${e} failed: ${s}`);i=await this.resolveFrameContext(e,r);let c=await this.send(`Runtime.evaluate`,{...a,contextId:i}),l=ta(c);if(l!==null)throw Error(`Evaluation in frame ${e} failed: ${l}`);return c.result?.value}async resolveFrameContext(e,t){let n=this.host.frameContexts(this.sessionId,t),r=n.get(e);if(r!==void 0)return r;if(t===`isolated`){let t=(await this.send(`Page.createIsolatedWorld`,{frameId:e,worldName:`__slicc_iframe`})).executionContextId;return n.set(e,t),t}await this.send(`Runtime.enable`);let i=n.get(e);if(i===void 0&&(await this.send(`Runtime.disable`),await this.send(`Runtime.enable`),i=n.get(e)),i===void 0)throw Error(`Failed to find main world execution context for frame ${e}`);return i}async click(e,t=0){let n=await this.boundingBox(e);if(!n)throw Error(`Element not found: ${e}`);await this.clickAt(n.x+n.width/2,n.y+n.height/2,t)}async type(e){for(let t of e)await this.send(`Input.dispatchKeyEvent`,{type:`keyDown`,text:t}),await this.send(`Input.dispatchKeyEvent`,{type:`keyUp`,text:t})}async insertText(e){await this.send(`Input.insertText`,{text:e})}async waitForSelector(e,t){let n=t?.timeout??3e4,r=t?.interval??100,i=Date.now(),a=`polling for selector ${e}`;for(;Date.now()-i<n;){if(Hi(this.signal,a),await this.evaluate(`!!document.querySelector(${JSON.stringify(e)})`))return;await Wi(r,this.signal,a)}throw Error(`waitForSelector timed out after ${n}ms: ${e}`)}async clickByBackendNodeId(e,t=0){let n=await this.resolveNodeObjectId(e),r=await this.nodeBox(n);if(!r||r.width===0||r.height===0){await this.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function() { this.click(); }`});return}await this.clickAt(r.x+r.width/2,r.y+r.height/2,t)}async dblclickByBackendNodeId(e,t=`left`,n=0){let{x:r,y:i}=await this.resolveNodeCenter(e);for(let e of[1,2])await this.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:e,modifiers:n}),await this.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:e,modifiers:n})}async hoverByBackendNodeId(e){let{x:t,y:n}=await this.resolveNodeCenter(e);await this.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:t,y:n})}async selectByBackendNodeId(e,t){let n=await this.resolveNodeObjectId(e);await this.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function(val) { this.value = val; this.dispatchEvent(new Event('change', { bubbles: true })); }`,arguments:[{value:t}],returnByValue:!0})}async setCheckedByBackendNodeId(e,t){let n=await this.resolveNodeObjectId(e);return(await this.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function() { return this.checked; }`,returnByValue:!0})).result?.value===t?`already`:(await this.clickByBackendNodeId(e),`toggled`)}async dragByBackendNodeIds(e,t){let n=await this.resolveNodeCenter(e),r=await this.resolveNodeCenter(t);await this.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:n.x,y:n.y,button:`left`,clickCount:1}),await this.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:r.x,y:r.y}),await this.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r.x,y:r.y,button:`left`,clickCount:1})}async getFrameTree(){await this.send(`Page.enable`);let e=await this.send(`Page.getFrameTree`),t=[];return ea(e.frameTree,t),t}async getAccessibilityTree(){let e=await this.evaluate(Yi,{awaitPromise:!1,returnByValue:!0});if(!e||typeof e!=`object`)return{role:`RootWebArea`,name:``};let t=sa(e);try{let e=(await this.send(`Accessibility.getFullAXTree`)).nodes;Array.isArray(e)&&oa(t,ia(e))}catch{}return t}async getAccessibilityTreeForFrame(e){if(!e)return this.getAccessibilityTree();let t=await this.evaluateInFrame(e,Yi,{awaitPromise:!1,returnByValue:!0});return!t||typeof t!=`object`?{role:`RootWebArea`,name:``}:sa(t)}async clickAt(e,t,n){await this.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:e,y:t,button:`left`,clickCount:1,modifiers:n}),await this.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:e,y:t,button:`left`,clickCount:1,modifiers:n})}async resolveNodeObjectId(e){await this.send(`DOM.enable`),await this.send(`Runtime.enable`);let t=(await this.send(`DOM.resolveNode`,{backendNodeId:e})).object;if(!t?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);return t.objectId}async nodeBox(e){return(await this.send(`Runtime.callFunctionOn`,{objectId:e,functionDeclaration:`function() {
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 Zi(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)Zi(n,t)}function Qi(e){let t=e.exceptionDetails;return t?t.exception?.description??t.text:null}function $i(e,t){let n=Qi(e);if(n!==null)throw Error(`${t}: ${n}`);return e.result?.value}function ea(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 ta(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=na(a,o);t.has(s)||t.set(s,e)}return t}function na(e,t){return`${e.toLowerCase()}|${t.replace(/\s+/g,` `).trim()}`}function ra(e,t){let n=na(e.role,e.name),r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)ra(n,t)}function ia(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=>ia(e)).filter(e=>e.role!==`unknown`)),t}const aa=_(`browser-api`),oa=[`Session with given id not found`,`Target closed`,`No session with given id`,`No tab attached for sessionId`];var sa=class extends Error{};function ca(e){let t=e instanceof Error?e.message:String(e);return oa.some(e=>t.includes(e))}function la(e){let t=e??{queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0};return{queueDepth:t.queueDepth,totalWaitMs:t.tabWaitMs+t.bridgeWaitMs,tabWaitMs:t.tabWaitMs,bridgeWaitMs:t.bridgeWaitMs,acquisitions:t.acquisitions}}function ua(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var da=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)}},fa=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContexts=new Map;_sessions=new Map;_listenedTransports=new Set;_sessionReplacedSubs=new Map;_appliedSends=new Map;_pinnedTargets=new Map;_tabLocks=new Map;_bridgeLock=Promise.resolve();_bridgeHold=null;_bridgeWaiters=0;_viewportOverrides=new Map;_tabLockStats=new Map;_onSessionChange;_lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;_reconnectAttempt=0;_reconnectNotBefore=0;_bridgeRejection=null;bridgeRejectedHandler=null;bridgeRejectedNotified=!1;classifyConnectFailure=async()=>`transient`;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),aa.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){aa.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}handleExecutionContextCreated=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this.frameContexts(t,`main`).set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.executionContextId;if(typeof n!=`number`)return;let r=this._frameContexts.get(`main:${t}`);if(r)for(let[e,t]of r)t===n&&r.delete(e)};handleExecutionContextsCleared=e=>{let t=this.eventSessionId(e);t&&this._frameContexts.get(`main:${t}`)?.clear()};eventSessionId(e){let t=e.sessionId;return typeof t==`string`?t:this.sessionId}handleDetachedFromTarget=e=>{let t=e.sessionId;if(typeof t==`string`){for(let[e,n]of this._sessions)if(n.sessionId===t){this.forgetSession(e,n);return}}};handleTargetDestroyed=e=>{let t=e.targetId;if(typeof t==`string`){for(let[e,n]of this._sessions)if(e===t||n.remote?.localTargetId===t){this.forgetSession(e,n);return}}};constructor(e){this.client=e??new Di,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 da)return e;let t=this._accountedTransports.get(e);return t||(t=new da(e,e=>this.noteApplied(e)),this._accountedTransports.set(e,t)),t}noteApplied(e){this._appliedSends.set(e,(this._appliedSends.get(e)??0)+1)}createHarRecorder(e,t){return new Wi(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;zi(r,`starting a command on tab ${e}`);let i=this.tabCounters(e);i.queueDepth+=1;let a;try{a=await this.acquireTabLock(e,i,r)}catch(e){throw--i.queueDepth,e}let o=this.pinTarget(e);try{return i.acquisitions+=1,await this.runOnTab(e,t,r)}finally{o(),--i.queueDepth,a()}}async runOnTab(e,t,n){try{return await this.attemptOnTab(e,t,n)}catch(r){if(r instanceof sa||!ca(r))throw r;return aa.warn(`Stale CDP session — re-attaching and retrying once`,{targetId:e,error:r instanceof Error?r.message:String(r)}),this.invalidateSession(e),await this.attemptOnTab(e,t,n)}}async attemptOnTab(e,t,n){let r=await this.attachHandle(e,this.reentrantOwner(e),n);zi(n,`about to run a command on tab ${e}`);let i=r.sessionId,a=this._appliedSends.get(i)??0;try{return await t(r)}catch(t){if(!ca(t))throw t;let n=(this._appliedSends.get(i)??0)-a;if(n===0)throw t;this.invalidateSession(e);let r=t instanceof Error?t.message:String(t);throw aa.warn(`CDP session reset mid-command — not replaying`,{targetId:e,applied:n,reason:r}),new sa(`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 Xi(this,e,r,this.accountedTransportFor(i?.transport??this.client),n)}handleFor(e,t){return new Xi(this,e,t.sessionId,this.accountedTransportFor(t.transport))}getTabLockStats(e){if(e!==void 0)return la(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 la(t)}tabCounters(e){let t=this._tabLockStats.get(e);return t||(t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0},this._tabLockStats.set(e,t)),t}async acquireTabLock(e,t,n){let r,i=new Promise(e=>{r=e}),a=this._tabLocks.get(e);this._tabLocks.set(e,i);let o=()=>{this._tabLocks.get(e)===i&&this._tabLocks.delete(e),r()};if(a){let r=Date.now();try{await Hi(a,n,`queued for the lock on tab ${e}`)}catch(e){throw t.tabWaitMs+=Date.now()-r,a.then(o,o),e}t.tabWaitMs+=Date.now()-r}return o}async acquireBridgeLock(e){if(e?.owner!==void 0&&this._bridgeHold?.owner===e.owner)return()=>void 0;let t,n=new Promise(e=>{t=e}),r=this._bridgeLock,i=this._bridgeHold!==null||this._bridgeWaiters>0;if(this._bridgeLock=n,i){this._bridgeWaiters+=1;let t=Date.now();try{await r}finally{--this._bridgeWaiters}e?.counters&&(e.counters.bridgeWaitMs+=Date.now()-t)}let a={release:t,owner:Symbol(`bridge-hold`),targetId:e?.targetId??null};this._bridgeHold=a;let o=!1;return()=>{o||(o=!0,this._bridgeHold===a&&(this._bridgeHold=null),t())}}reentrantOwner(e){let t=this._bridgeHold;if(!(!t||e===null||t.targetId!==e))return t.owner}async runGlobal(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e),targetId:e});try{return await t()}finally{n()}}viewportOverride(e){return this._viewportOverrides.get(e)}recordViewportOverride(e,t){this._viewportOverrides.set(e,t)}frameContexts(e,t){let n=`${t}:${e}`,r=this._frameContexts.get(n);return r||(r=new Map,this._frameContexts.set(n,r)),r}dropFrameContexts(e){this._frameContexts.delete(`main:${e}`),this._frameContexts.delete(`isolated:${e}`)}async reapplyViewportOverride(e,t){let n=this._viewportOverrides.get(e);if(n)try{await this.handleFor(e,t).applyViewportOverride(n)}catch(t){aa.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){if(this._bridgeRejection)throw this.notifyBridgeRejected(),new Fi(this._bridgeRejection);this._lastConnectOptions=e?{...e}:{};try{await this.client.connect({url:e?.url??ua(),timeout:e?.timeout,...e?.protocols===void 0?{}:{protocols:e.protocols}})}catch(t){throw await this.noteReconnectFailure(e),this._bridgeRejection?new Fi(this._bridgeRejection):t}this.noteReconnectSuccess()}async reconnectIfNeeded(){await this.ensureConnected(),this.client!==this.localClient&&await this.ensureLocalConnected()}primeConnectOptions(e){this._lastConnectOptions=e?{...e}:{}}setCdpSupersededHandler(e){this.supersededHandler=e}setCdpBridgeRejectedHandler(e){this.bridgeRejectedHandler=e}setCdpConnectFailureClassifier(e){this.classifyConnectFailure=e}throwIfReconnectPaused(){if(this._bridgeRejection)throw this.notifyBridgeRejected(),new Fi(this._bridgeRejection);if(Date.now()<this._reconnectNotBefore)throw new Ii}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 Fi().message,this.notifyBridgeRejected();return}let t=Li(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{}}}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(),ha(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=_a((await(await this.transportForWindowOps(e)).send(`Browser.getWindowForTarget`,{targetId:ma(e)})).bounds),n=await this.readDevicePixelRatio(e);return{...t,dpr:n}}async setWindowBounds(e,t){await this.ensureConnected(),ha(t);let n=await this.transportForWindowOps(e),r=ma(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=_a(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=_a((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._viewportOverrides.delete(e),await this.dropSession(e),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let e=this.trayTargetProvider.createRemoteTransport(n,r);try{await e.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}return}}await this.localClient.send(`Target.closeTarget`,{targetId:e})}disconnect(){this.clearSessions(),this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){return this.attachToPageOwned(e,this.reentrantOwner(e))}async attachToPageOwned(e,t,n){let r=await this.acquireBridgeLock({owner:t,targetId:e,counters:this.tabCounters(e)});try{await this.ensureConnected();let t=this._sessions.get(e);return t?(this.activateSession(e,t),t.sessionId):await(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)?this.attachRemoteTarget(e,n):this.attachLocalTarget(e,n))}finally{r()}}async selectTab(e){await this.withTab(e,async()=>void 0)}async bringTabToFront(e){await this.withTab(e,e=>e.bringToFront())}async attachRemoteTarget(e,t){let n=e.indexOf(`:`),r=e.substring(0,n),i=e.substring(n+1),a=this.trayTargetProvider?.createRemoteTransport?.(r,i);if(!a)throw Error(`No remote transport for target ${e}`);zi(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),zi(t,`about to enable Page on tray tab ${e}`),await a.send(`Page.enable`,{},o.sessionId),zi(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(),zi(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),zi(t,`about to enable Page on tab ${e}`),await this.localClient.send(`Page.enable`,{},n.sessionId),zi(t,`about to restore the viewport of tab ${e}`),await this.reapplyViewportOverride(e,n),this.notifySessionChange(e,n),n.sessionId}async detach(){let e=this.attachedTargetId;e&&(await this.dropSession(e),this.useLocalTransport())}async wakeCapture(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e.targetId),targetId:e.targetId});try{return await this.wakeCaptureLocked(e,t,this._bridgeHold?.owner)}finally{n()}}async wakeCaptureLocked(e,t,n){let r=e.targetId,i=await this.findFocusedLocalPage(r,n).catch(()=>null),a=await this.attachHandle(r,n);try{return await a.send(`Page.bringToFront`),await a.send(`Page.captureScreenshot`,t)}finally{if(i)try{await(await this.attachHandle(i,n)).send(`Page.bringToFront`),await this.attachToPageOwned(r,n)}catch{}}}async findFocusedLocalPage(e,t){let n=await this.listPages();for(let r of n)if(!(!r.targetId||r.targetId===e)&&!r.targetId.includes(`:`))try{if(await(await this.attachHandle(r.targetId,t)).evaluate(`document.hasFocus()`)===!0)return r.targetId}catch{}return null}async ensureLocalConnected(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){this.throwIfReconnectPaused();let e=this._lastConnectOptions;try{await this.localClient.connect({url:e?.url??ua(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}catch(t){throw await this.noteReconnectFailure(e??void 0),this._bridgeRejection?new Fi(this._bridgeRejection):t}this.noteReconnectSuccess()}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}if(this.client.state===`disconnected`){this.throwIfReconnectPaused();let e=this.client;this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.clearSessionsForTransport(e),this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0)}}transportForSession(e){for(let t of this._sessions.values())if(t.sessionId===e)return t.transport;return this.client}addTransportListeners(e){this._listenedTransports.has(e)||(this._listenedTransports.add(e),e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.on(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.on(`Target.targetDestroyed`,this.handleTargetDestroyed))}releaseLifecycleTransport(e){if(e!==this.localClient&&this._listenedTransports.has(e)){for(let t of this._sessions.values())if(t.transport===e)return;this._listenedTransports.delete(e),e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.off(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.off(`Target.targetDestroyed`,this.handleTargetDestroyed)}}setClient(e){this.addTransportListeners(e),this.client=e}useLocalTransport(){let e=this.remoteTargetInfo;this.remoteTargetInfo=null,this.setClient(this.localClient),e&&([...this._sessions.values()].some(t=>t.remote?.runtimeId===e.runtimeId&&t.remote.localTargetId===e.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.runtimeId,e.localTargetId))}pruneAppliedSends(){if(this._appliedSends.size<=128)return;let e=new Set([...this._sessions.values()].map(e=>e.sessionId));for(let t of[...this._appliedSends.keys()])e.has(t)||this._appliedSends.delete(t)}rememberSession(e,t){this.addTransportListeners(t.transport),this.pruneAppliedSends(),this._sessions.set(e,t),this.enforceSessionCap(e)}enforceSessionCap(e){for(;this._sessions.size>32;){let t;for(let n of this._sessions.keys())if(!(n===e||this._pinnedTargets.has(n))){t=n;break}if(t===void 0)return;let n=this._sessions.get(t);this._sessions.delete(t),n&&(aa.debug(`Evicting least-recently-used CDP session`,{targetId:t}),this.detachSession(t,n))}}pinTarget(e){this._pinnedTargets.set(e,(this._pinnedTargets.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(this._pinnedTargets.get(e)??1)-1;n>0?this._pinnedTargets.set(e,n):this._pinnedTargets.delete(e),this.enforceSessionCap()}}activateSession(e,t){t.remote?(this.setClient(t.transport),this.remoteTargetInfo={...t.remote}):this.client!==t.transport&&this.useLocalTransport(),this.sessionId=t.sessionId,this.attachedTargetId=e,this._sessions.delete(e),this._sessions.set(e,t)}notifySessionChange(e,t){let n=this.accountedTransportFor(t.transport);this._onSessionChange?.(t.sessionId,n,e);let r=this._sessionReplacedSubs.get(e);if(r)for(let i of[...r])try{i(t.sessionId,n,e)}catch(t){aa.warn(`session-replaced subscriber threw`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}forgetSession(e,t){this.unregisterSession(e),this.disposeSessionTransport(t)}unregisterSession(e){let t=this._sessions.get(e);t&&this.dropFrameContexts(t.sessionId),this._sessions.delete(e),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disposeSessionTransport(e){this.releaseLifecycleTransport(e.transport),e.remote&&([...this._sessions.values()].some(t=>t.remote?.runtimeId===e.remote?.runtimeId&&t.remote?.localTargetId===e.remote?.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.remote.runtimeId,e.remote.localTargetId))}async detachSession(e,t){this.unregisterSession(e);try{await t.transport.send(`Target.detachFromTarget`,{sessionId:t.sessionId})}catch{}finally{this.disposeSessionTransport(t)}}async dropSession(e){let t=this._sessions.get(e);if(!t){this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null);return}await this.detachSession(e,t)}invalidateSession(e){let t=this._sessions.get(e);t&&this.forgetSession(e,t)}clearSessionsForTransport(e){for(let[t,n]of[...this._sessions])n.transport===e&&this.forgetSession(t,n)}clearSessions(){for(let[e,t]of[...this._sessions])this.forgetSession(e,t);this._sessions.clear(),this.sessionId=null,this.attachedTargetId=null}};const pa=new Set([`normal`,`minimized`,`maximized`,`fullscreen`]);function ma(e){let t=e.indexOf(`:`);return t>=0?e.substring(t+1):e}function ha(e){let t=e.state;if(!(!t||t===`normal`)){if(!pa.has(t))throw Error(`window state must be one of ${[...pa].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 ga(e){return typeof e==`object`&&!!e}function _a(e){let t=ga(e)?e:{},n=t.windowState??t.state,r=typeof n==`string`&&pa.has(n)?n:`normal`;return{left:va(t.left,0),top:va(t.top,0),width:va(t.width,0),height:va(t.height,0),state:r}}function va(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}const ya=_(`panel-rpc-cdp`);var ba=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=>{ya.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){ya.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=>{ya.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=>{ya.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function xa(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 ba(e,r,i),t.set(a,o)),o},removeRemoteTransport(e,r){let i=n(e,r),a=t.get(i);a&&(a.disconnect(),t.delete(i))},async openRemoteTab(t,n){let r=e();if(!r)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let{targetId:i}=await r.call(`remote-open-tab`,{runtimeId:t,url:n});return i}}}const Sa=Object.freeze([Object.freeze({id:`experimental-settings`,label:`Experimental settings`,description:`Show controls for experimental features.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1,since:`2026-07-31`}),Object.freeze({id:`panel-layouts`,label:`Panel layouts`,description:`Arrange the UI as movable, resizable panels instead of the fixed workbench.`,defaultValue:`off`,userToggleable:!0,since:`2026-08-03`}),Object.freeze({id:`agentic-memory`,label:`Agentic memory`,description:`Curate session memory with a background agent instead of a one-shot extraction call.`,defaultValue:`off`,userToggleable:!0,since:`2026-08-05`}),Object.freeze({id:`multiple-cones`,label:`Multiple cones`,description:`Add, switch between and remove cones from the freezer rail. Extra cones share the workspace.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1,since:`2026-08-21`}),Object.freeze({id:`compact-on-idle`,label:`Compact on idle`,description:`When a cone has been idle for a while with a large context, summarize its history in the background. The full transcript is kept in /sessions.`,defaultValue:`on`,userToggleable:!1,since:`2026-09-02`}),Object.freeze({id:`memory-v2`,label:`Memory v2`,description:`Searchable session history, scoop pre-compaction snapshots, and the gelatiere — a resident advisor that reviews your sessions and suggests skills and use cases.`,defaultValue:`off`,userToggleable:!0,since:`2026-09-10`})]);new Map(Sa.map(e=>[e.id,e]));const Ca=new Set([`1`,`on`,`true`]);let wa=`standalone`,Ta={},Ea={};function Da(e,t={},n=Oa()){let r={};for(let i of Sa){let a=n[i.id];if(typeof a==`string`&&Fa(i,e)){r[i.id]=a;continue}let o=Ea[i.id];if(typeof o==`string`&&Fa(i,e)){r[i.id]=o;continue}let s=t[i.id];r[i.id]=typeof s==`string`?s:Pa(i,e)}return r}function Oa(){try{let e=La()?.getItem(`slicc_feature_flags`);return e?Ia(JSON.parse(e)):{}}catch{return{}}}function ka(e,t={}){wa=e,Ta=Ia(t),Ea={}}function Aa(e,t){wa=e,Ta=Ia(t)}function ja(e){return Da(wa,Ta)[e]}function Ma(e){return typeof e==`string`&&Ca.has(e.trim().toLowerCase())}function Na(e){return Ma(ja(e))}function Pa(e,t){return e.floatDefaults?.[t]??e.defaultValue}function Fa(e,t){return e.userToggleable&&(e.overridableFloats===void 0||e.overridableFloats.includes(t))}function Ia(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t=e,n={};for(let e of Sa){let r=t[e.id];typeof r==`string`&&(n[e.id]=r)}return n}function La(){try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function Ra(e){return`slicc_feature_flags_remote:${e}`}let za=null;function Ba(e,t){let n=Ha(t);za=e,ka(e,Ua(n,e)??{})}function Va(e,t){if(!za||e!==void 0&&e!==Ra(za))return!1;let n=Ha(t);return Aa(za,Ua(n,za)??{}),!0}function Ha(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 Ua(e,t){try{let n=e?.getItem(Ra(t));return n?Wa(JSON.parse(n)):null}catch{return null}}function Wa(e){return!Ga(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function Ga(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ka=_(`stale-asset`),qa=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Ja(e){return qa.test(e)}let Ya=null;function Xa(e){if(!e){Ya=null;return}Ya=e}function Za(e=!1){if(!Ya||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Ya,replayTurn:e})}finally{t.close()}}function Qa(e){Ja(e instanceof Error?e.message:String(e))&&Za()}function $a(e,t){return!e||e===t?!1:(Ka.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),Za(),!0)}var eo=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new Ci;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 wi(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 to(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 no(e){let t=to(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var ro=class extends eo{constructor(e){let t=to(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 io(e,t){return e.find(e=>e.folder===t)??e.find(e=>e.folder===`${t}-scoop`)??e.find(e=>e.name===t)}const ao=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function oo(e){return ao.test(e)}function so(e,t){return`(${e} && ${t})`}function j(e,t){return`(${e} || ${t})`}function co(e){return`!(${e})`}function lo(e){return`Array.isArray(${e})`}function uo(e){return`typeof ${e} === "bigint"`}function fo(e){return`typeof ${e} === "boolean"`}function po(e){return`Number.isInteger(${e})`}function mo(e){return`${e} === null`}function ho(e){return`Number.isFinite(${e})`}function go(e){return so(_o(e),co(lo(e)))}function _o(e){return`typeof ${e} === "object" && ${e} !== null`}function vo(e){return`typeof ${e} === "string"`}function yo(e){return`typeof ${e} === "symbol"`}function bo(e){return`${e} === undefined`}function xo(e){return`typeof ${e} === "function"`}function So(e){return`Guard.IsConstructor(${e})`}function Co(e,t){return`${e} === ${t}`}function wo(e,t){return`${e} > ${t}`}function To(e,t){return`${e} < ${t}`}function Eo(e,t){return`${e} <= ${t}`}function Do(e,t){return`${e} >= ${t}`}function Oo(e,t){return`Guard.IsMinLength(${e}, ${t})`}function ko(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Ao(e,t,n,r){return T(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 jo(e){return`Object.entries(${e})`}function Mo(e){return`Object.getOwnPropertyNames(${e})`}function No(e,t){return T(t,`"__proto__"`)||T(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function Po(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function Fo(e){return`[${e.join(`, `)}]`}function Io(e,t){return`((${e.join(`, `)}) => ${t})`}function M(e,t){return`${e}(${t.join(`, `)})`}function Lo(e,t){return`new ${e}(${t.join(`, `)})`}function N(e,t){return`${e}${oo(t)?`.${t}`:`[${P(t)}]`}`}function P(e){return v(e)?JSON.stringify(e):`${e}`}function Ro(e,t,n){return`(${e} ? ${t} : ${n})`}function zo(e){return`{ ${e.join(`; `)}; }`}function Bo(e,t){return`const ${e} = ${t}`}function Vo(e,t){return`if(${e}) { ${t} }`}function Ho(e){return`return ${e}`}function F(e){return T(e.length,0)?`true`:e.reduce((e,t)=>so(e,t))}function Uo(e){return T(e.length,0)?`false`:e.reduce((e,t)=>j(e,t))}function Wo(e){return`++${e}`}function Go(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Ko=et;function qo(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let Jo;function Yo(){try{return Zo(`null`)(),!0}catch{return!1}}function Xo(){return C(Jo)&&(Jo=Yo()),Jo&&Kt().useAcceleration}function Zo(...e){return new globalThis.Function(...e)}function Qo(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 $o=Qo;function es(){return $o}const ts=[/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],ns=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function rs(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!ns.some(t=>t.test(e.errorMessage))&&ts.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 is(e){return D(e,`~refine`)&&S(e[`~refine`])&&x(e[`~refine`],0,e=>b(e)&&D(e,`check`)&&D(e,`error`)&&Lt(e.check)&&Lt(e.error))}function as(e){return b(e)&&!S(e)}function os(e){return Jt(e)}function I(e){return as(e)||os(e)}function ss(e){return D(e,`additionalItems`)&&I(e.additionalItems)}function cs(e){return D(e,`additionalProperties`)&&I(e.additionalProperties)}function ls(e){return D(e,`allOf`)&&S(e.allOf)&&e.allOf.every(e=>I(e))}function us(e){return D(e,`$anchor`)&&v(e.$anchor)}function ds(e){return D(e,`anyOf`)&&S(e.anyOf)&&e.anyOf.every(e=>I(e))}function fs(e){return D(e,`const`)}function ps(e){return D(e,`contains`)&&I(e.contains)}function ms(e){return D(e,`default`)}function hs(e){return D(e,`dependencies`)&&b(e.dependencies)&&Object.values(e.dependencies).every(e=>I(e)||S(e)&&e.every(e=>v(e)))}function gs(e){return D(e,`dependentRequired`)&&b(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>S(e)&&e.every(e=>v(e)))}function _s(e){return D(e,`dependentSchemas`)&&b(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>I(e))}function vs(e){return D(e,`$dynamicAnchor`)&&v(e.$dynamicAnchor)}function ys(e){return D(e,`$dynamicRef`)&&v(e.$dynamicRef)}function bs(e){return D(e,`else`)&&I(e.else)}function xs(e){return D(e,`enum`)&&S(e.enum)}function Ss(e){return D(e,`exclusiveMaximum`)&&(O(e.exclusiveMaximum)||Ft(e.exclusiveMaximum))}function Cs(e){return D(e,`exclusiveMinimum`)&&(O(e.exclusiveMinimum)||Ft(e.exclusiveMinimum))}function ws(e){return D(e,`format`)&&v(e.format)}function Ts(e){return D(e,`$id`)&&v(e.$id)}function Es(e){return D(e,`if`)&&I(e.if)}function Ds(e){return D(e,`items`)&&(I(e.items)||S(e.items)&&e.items.every(e=>I(e)))}function Os(e){return Ds(e)&&S(e.items)}function ks(e){return D(e,`maximum`)&&(O(e.maximum)||Ft(e.maximum))}function As(e){return D(e,`maxContains`)&&O(e.maxContains)}function js(e){return D(e,`maxItems`)&&O(e.maxItems)}function Ms(e){return D(e,`maxLength`)&&O(e.maxLength)}function Ns(e){return D(e,`maxProperties`)&&O(e.maxProperties)}function Ps(e){return D(e,`minimum`)&&(O(e.minimum)||Ft(e.minimum))}function Fs(e){return D(e,`minContains`)&&O(e.minContains)}function Is(e){return D(e,`minItems`)&&O(e.minItems)}function Ls(e){return D(e,`minLength`)&&O(e.minLength)}function Rs(e){return D(e,`minProperties`)&&O(e.minProperties)}function zs(e){return D(e,`multipleOf`)&&(O(e.multipleOf)||Ft(e.multipleOf))}function Bs(e){return D(e,`not`)&&I(e.not)}function Vs(e){return D(e,`oneOf`)&&S(e.oneOf)&&e.oneOf.every(e=>I(e))}function Hs(e){return D(e,`pattern`)&&(v(e.pattern)||e.pattern instanceof RegExp)}function Us(e){return D(e,`patternProperties`)&&b(e.patternProperties)&&Object.values(e.patternProperties).every(e=>I(e))}function Ws(e){return D(e,`prefixItems`)&&S(e.prefixItems)&&e.prefixItems.every(e=>I(e))}function Gs(e){return D(e,`properties`)&&b(e.properties)&&Object.values(e.properties).every(e=>I(e))}function Ks(e){return D(e,`propertyNames`)&&(b(e.propertyNames)||I(e.propertyNames))}function qs(e){return D(e,`$recursiveAnchor`)&&Jt(e.$recursiveAnchor)}function Js(e){return qs(e)&&T(e.$recursiveAnchor,!0)}function Ys(e){return D(e,`$recursiveRef`)&&v(e.$recursiveRef)}function Xs(e){return D(e,`$ref`)&&v(e.$ref)}function Zs(e){return D(e,`required`)&&S(e.required)&&e.required.every(e=>v(e))}function Qs(e){return D(e,`then`)&&I(e.then)}function $s(e){return D(e,`type`)&&(v(e.type)||S(e.type)&&e.type.every(e=>v(e)))}function ec(e){return D(e,`uniqueItems`)&&Jt(e.uniqueItems)}function tc(e){return D(e,`unevaluatedItems`)&&I(e.unevaluatedItems)}function nc(e){return D(e,`unevaluatedProperties`)&&I(e.unevaluatedProperties)}function rc(e){return tc(e)||nc(e)||y(e).some(t=>ac(e[t]))}function ic(e){return e.some(e=>ac(e))}function ac(e){return S(e)?ic(e):b(e)?rc(e):!1}function oc(e,t){return ac(t)||y(e).some(t=>ac(e[t]))}var sc=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return M(N(`context`,`Push`),[])}Pop(){return M(N(`context`,`Pop`),[])}AddIndex(e){return M(N(`context`,`AddIndex`),[e])}AddKey(e){return M(N(`context`,`AddKey`),[e])}Merge(e){return M(N(`context`,`Merge`),[e])}},cc=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}},lc=class extends cc{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},uc=class extends lc{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const dc={identifier:`External`,variables:[]};function fc(e){let t=`External[${dc.variables.length}]`;return dc.variables.push(e),t}function pc(){dc.variables=[]}function mc(){return{...dc}}function hc(e,t,n,r){return Ao(fc(n[`~refine`].map(e=>e)),P(0),[`refinement`,`_`],M(N(`refinement`,`check`),[r]))}function gc(e,t,n,r){return x(n[`~refine`],0,(e,t)=>e.check(r))}function _c(e,t,n,r,i,a){return w(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let vc=0;function L(){return`var_${vc++}`}function yc(e){return Ds(e)&&S(e.items)}function bc(e,t,n,r){if(!yc(n))return P(!0);let[i,a]=[L(),L()],o=Jf(e,t,n.additionalItems,i),s=To(a,P(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?j(s,so(o,c)):j(s,o);return M(N(r,`every`),[Io([i,a],l)])}function xc(e,t,n,r){return!yc(n)||r.every((r,i)=>tn(i,n.items.length)||Yf(e,t,n.additionalItems,r)&&t.AddIndex(i))}function Sc(e,t,n,r,i,a){return!yc(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return tn(o,i.items.length)||Xf(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function Cc(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function wc(e){let t=[];return Us(e)&&t.push(...y(e.patternProperties)),Gs(e)&&t.push(...y(e.properties).map(Cc)),T(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function Tc(e,t,n){return Zs(t)&&Gs(t)&&!Us(t)&&T(t.additionalProperties,!1)&&T(y(t.properties).length,t.required.length)}function Ec(e,t,n){return Co(N(M(N(`Object`,`getOwnPropertyNames`),[n]),`length`),P(t.required.length))}function Dc(e,t,n,r){let[i,a]=[L(),L()],o=fc(new RegExp(wc(n))),s=Jf(e,t,n.additionalProperties,`${r}[${i}]`),c=M(N(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?j(c,so(s,l)):j(c,s);return Ao(Mo(r),P(0),[i,a],u)}function Oc(e,t,n,r){return Tc(t,n,r)?Ec(t,n,r):Dc(e,t,n,r)}function kc(e,t,n,r){let i=new RegExp(wc(n));return x(y(r),0,(a,o)=>i.test(a)||Yf(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function Ac(e,t,n,r,i,a){let o=new RegExp(wc(i)),s=[];return w(y(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new uc,p=o.test(c)||Xf(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 jc(e,t,n,r,i){let a=Bo(`results`,`[]`),o=n.map((e,t)=>Bo(`context_${t}`,Lo(`CheckContext`,[]))),s=n.map((n,i)=>Bo(`condition_${i}`,M(Io([`context`],z(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>Vo(`condition_${t}`,M(N(`results`,`push`),[`context_${t}`]))),l=Ho(so(i,t.Merge(`results`)));return M(Io([],zo([a,...o,...s,...c,l])),[])}function Mc(e,t,n,r){return jc(e,t,n.allOf,r,Co(N(`results`,`length`),P(n.allOf.length)))}function Nc(e,t,n,r){return F(n.allOf.map(n=>z(e,t,n,r)))}function Pc(e,t,n,r){return t.UseUnevaluated()?Mc(e,t,n,r):Nc(e,t,n,r)}function Fc(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new cc;return B(e,i,n,r)?[...t,i]:t},[]);return T(i.length,n.allOf.length)&&t.Merge(i)}function Ic(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new uc,u=V(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=T(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function Lc(e,t,n,r){return jc(e,t,n.anyOf,r,wo(N(`results`,`length`),P(0)))}function Rc(e,t,n,r){return Uo(n.anyOf.map(n=>z(e,t,n,r)))}function zc(e,t,n,r){return t.UseUnevaluated()?Lc(e,t,n,r):Rc(e,t,n,r)}function Bc(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new cc;return B(e,i,n,r)?[...t,i]:t},[]);return Et(i.length,0)&&t.Merge(i)}function Vc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new uc,l=V(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=Et(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 Hc(e,t,n,r){return P(!!n)}function Uc(e,t,n,r){return n}function Wc(e,t,n,r,i,a){return Uc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function Gc(e,t,n,r){return Mt(n.const)?Co(r,P(n.const)):Po(r,fc(n.const))}function Kc(e,t,n,r){return Mt(n.const)?T(r,n.const):wt(r,n.const)}function qc(e,t,n,r,i,a){return Kc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Jc(e){return!(Fs(e)&&T(e.minContains,0))}function Yc(e,t,n,r){if(!Jc(n))return P(!0);let i=L();return so(co(Co(N(r,`length`),P(0))),M(N(r,`some`),[Io([i],z(e,t,n.contains,i))]))}function Xc(e,t,n,r){return!Jc(n)||!T(r.length,0)&&r.some(r=>B(e,t,n.contains,r))}function Zc(e,t,n,r,i,a){return Xc(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Qc(e,t,n,r){return j(Co(N(Mo(r),`length`),P(0)),F(E(n.dependencies).map(([n,i])=>{let a=co(No(r,P(n))),o=z(e,t,i,r);return j(a,S(i)?(e=>F(e.map(e=>No(r,P(e)))))(i):o)})))}function $c(e,t,n,r){let i=T(y(r).length,0),a=x(E(n.dependencies),0,([n,i])=>!D(r,n)||(S(i)?i.every(e=>D(r,e)):B(e,t,i,r)));return i||a}function el(e,t,n,r,i,a){let o=T(y(a).length,0),s=w(E(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!D(a,i)||(S(o)?o.every(e=>D(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):V(e,t,s,r,o,a))});return o||s}function tl(e,t,n,r){return j(Co(N(Mo(r),`length`),P(0)),F(E(n.dependentRequired).map(([e,t])=>j(co(No(r,P(e))),F(t.map(e=>No(r,P(e))))))))}function nl(e,t,n,r){let i=T(y(r).length,0),a=x(E(n.dependentRequired),0,([e,t])=>!D(r,e)||t.every(e=>D(r,e)));return i||a}function rl(e,t,n,r,i,a){let o=T(y(a).length,0),s=w(E(i.dependentRequired),0,([e,i])=>!D(a,e)||w(i,0,o=>D(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function il(e,t,n,r){return j(Co(N(Mo(r),`length`),P(0)),F(E(n.dependentSchemas).map(([n,i])=>j(co(No(r,P(n))),z(e,t,i,r)))))}function al(e,t,n,r){let i=T(y(r).length,0),a=x(E(n.dependentSchemas),0,([n,i])=>!D(r,n)||B(e,t,i,r));return i||a}function ol(e,t,n,r,i,a){let o=T(y(a).length,0),s=w(E(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!D(a,i)||V(e,t,s,r,o,a)});return o||s}function sl(e,t,n,r){return op(e,t,e.DynamicRef(n)??!1,r)}function cl(e,t,n,r){let i=e.DynamicRef(n)??!1;return I(i)&&B(e,t,i,r)}function ll(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return I(o)&&V(e,t,`#`,r,o,a)}function ul(e,t,n,r){return Uo(n.enum.map(e=>Mt(e)?Co(r,P(e)):Po(r,fc(e))))}function dl(e,t,n,r){return n.enum.some(e=>Mt(e)?T(r,e):wt(r,e))}function fl(e,t,n,r,i,a){return dl(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function pl(e,t,n,r){return To(r,P(n.exclusiveMaximum))}function ml(e,t,n,r){return tn(r,n.exclusiveMaximum)}function hl(e,t,n,r,i,a){return ml(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function gl(e,t,n,r){return wo(r,P(n.exclusiveMinimum))}function _l(e,t,n,r){return Et(r,n.exclusiveMinimum)}function vl(e,t,n,r,i,a){return _l(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const yl=[0,31,28,31,30,31,30,31,31,30,31,30,31],bl=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function xl(e){return e%4==0&&(e%100!=0||e%400==0)}function Sl(e){let t=bl.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&&xl(n)?29:yl[r])}const Cl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function wl(e,t=!0){let n=Cl.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 Tl(e,t=!0){let n=e.split(/T/i);return n.length===2&&Sl(n[0])&&wl(n[1],t)}const El=/^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 Dl(e){return El.test(e)}const Ol=/^(?!.*\.\.)[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 kl(e){return Ol.test(e)}function Al(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 jl(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)Je();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=Al(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function Ml(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function Nl(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function Pl(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function Fl(e){return Ml(e)||Nl(e)||Pl(e)}const Il=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),Ll=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 Rl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function zl(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function Bl(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function Vl(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function Hl(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function Ul(e){return e>=1632&&e<=1641}function Wl(e){return e>=1776&&e<=1785}function Gl(e){return Ll.has(e)}function Kl(e){if(e.length===0)return Je();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||Fl(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(Il.has(n))return!1;(Bl(n)||Vl(n)||Hl(n))&&(r=!0),Ul(n)&&(i=!0),Wl(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||!Rl(s))return!1;break;case 1523:case 1524:if(o===void 0||!zl(o))return!1;break;case 8204:if(o===void 0||o<128&&!Gl(o))return!1;break;case 8205:if(o===void 0||!Gl(o))return!1}}return!(e.includes(`・`)&&!r||i&&a)}function ql(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 Jl(e){return e.toLowerCase().startsWith(`xn--`)}function Yl(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=jl(t);return n?Kl(n):!1}catch{return!1}}function Xl(e){return e.length===0||e.length>63?!1:Jl(e)?Yl(e):Kl(e)}function Zl(e){return e.length===0||e.length>63?!1:Jl(e)?Yl(e):ql(e)}function Ql(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!Zl(t))return!1;return!0}const $l=/^(?!.*\.\.)[\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 eu(e){return $l.test(e)}function tu(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(!Xl(e))return!1;return!0}function nu(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 ru(e){return nu(e,0,e.length)}function iu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function au(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&&iu(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!nu(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 ou(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function su(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))?ou(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:ou(e)}function cu(e){try{return new URL(e),!0}catch{return!1}}const lu=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function uu(e){return lu.test(e)}const du=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function fu(e){return du.test(e)}function pu(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const mu=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function hu(e){return mu.test(e)}const gu=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function _u(e){return gu.test(e)}const vu=/^(?:(?:[^\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 yu(e){return vu.test(e)}function bu(e){return e>=97&&e<=122||e>=65&&e<=90}function xu(e){return bu(e)||e>=48&&e<=57}function Su(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Cu(e){return xu(e)||e===43||e===45||e===46}function wu(e){return xu(e)||e===45||e===46||e===95||e===126}function Tu(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 Eu(e){return wu(e)||Tu(e)||e===58||e===64}function Du(e){let t=e.length;if(t===0||!bu(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!Cu(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||!Su(e.charCodeAt(t+1))||!Su(e.charCodeAt(t+2)))return!1;t+=2}else if(!wu(n)&&!Tu(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&&!wu(t)&&!Tu(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||!Su(e.charCodeAt(n+1))||!Su(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(Eu(r)||r===47||r===63||r===35))return!1;n++}return!0}const Ou=/^(?: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 ku(e){return Ou.test(e)}const Au=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function ju(e){return Au.test(e)}const R=new Map;function Mu(){R.clear()}function Nu(){return[...R.entries()]}function Pu(e,t){R.set(e,t)}function Fu(e){return R.has(e)}function Iu(e){return R.get(e)}function Lu(e,t){return R.get(e)?.(t)??!0}function Ru(){Mu(),R.set(`date-time`,Tl),R.set(`date`,Sl),R.set(`duration`,Dl),R.set(`email`,kl),R.set(`hostname`,Ql),R.set(`idn-email`,eu),R.set(`idn-hostname`,tu),R.set(`ipv4`,ru),R.set(`ipv6`,au),R.set(`iri-reference`,su),R.set(`iri`,cu),R.set(`json-pointer-uri-fragment`,uu),R.set(`json-pointer`,fu),R.set(`regex`,pu),R.set(`relative-json-pointer`,hu),R.set(`time`,wl),R.set(`uri-reference`,_u),R.set(`uri-template`,yu),R.set(`uri`,Du),R.set(`url`,ku),R.set(`uuid`,ju)}Ru();var zu=e({Clear:()=>Mu,Entries:()=>Nu,Get:()=>Iu,Has:()=>Fu,IsDate:()=>Sl,IsDateTime:()=>Tl,IsDuration:()=>Dl,IsEmail:()=>kl,IsHostname:()=>Ql,IsIPv4:()=>ru,IsIPv6:()=>au,IsIdnEmail:()=>eu,IsIdnHostname:()=>tu,IsIri:()=>cu,IsIriReference:()=>su,IsJsonPointer:()=>fu,IsJsonPointerUriFragment:()=>uu,IsRegex:()=>pu,IsRelativeJsonPointer:()=>hu,IsTime:()=>wl,IsUri:()=>Du,IsUriReference:()=>_u,IsUriTemplate:()=>yu,IsUrl:()=>ku,IsUuid:()=>ju,Reset:()=>Ru,Set:()=>Pu,Test:()=>Lu});function Bu(e,t,n,r){return M(N(`Format`,`Test`),[P(n.format),r])}function Vu(e,t,n,r){return Lu(n.format,r)}function Hu(e,t,n,r,i,a){return Vu(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function Uu(e,t,n,r){let i=!Qs(n)||n.then,a=!bs(n)||n.else;return Ro(z(e,t,n.if,r),z(e,t,i,r),z(e,t,a,r))}function Wu(e,t,n,r){let i=!Qs(n)||n.then,a=!bs(n)||n.else;return B(e,t,n.if,r)?B(e,t,i,r):B(e,t,a,r)}function Gu(e,t,n,r,i,a){let o=!Qs(i)||i.then,s=!bs(i)||i.else,c=new uc,l=V(e,c,`${n}/if`,r,i.if,a)?V(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):V(e,t,`${n}/else`,r,s,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`else`}});return l&&t.Merge([c]),l}function Ku(e,t,n,r){return F(n.items.map((n,i)=>{let a=Eo(N(r,`length`),P(i)),o=Jf(e,t,n,`${r}[${i}]`),s=t.AddIndex(P(i));return j(a,t.UseUnevaluated()?so(o,s):o)}))}function qu(e,t,n,r){return x(n.items,0,(n,i)=>Xt(r.length,i)||Yf(e,t,n,r[i])&&t.AddIndex(i))}function Ju(e,t,n,r,i,a){return w(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return Xt(a.length,o)||Xf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Yu(e,t,n,r){let i=Ws(n)?n.prefixItems.length:0,a=Jf(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?so(a,o):a;return Ao(r,P(i),[`element`,`index`],s)}function Xu(e,t,n,r){let i=Ws(n)?n.prefixItems.length:0;return x(r,i,(r,i)=>Yf(e,t,n.items,r)&&t.AddIndex(i))}function Zu(e,t,n,r,i,a){let o=Ws(i)?i.prefixItems.length:0;return w(a,o,(a,o)=>Xf(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function Qu(e,t,n,r){return Os(n)?Ku(e,t,n,r):Yu(e,t,n,r)}function $u(e,t,n,r){return Os(n)?qu(e,t,n,r):Xu(e,t,n,r)}function ed(e,t,n,r,i,a){return Os(i)?Ju(e,t,n,r,i,a):Zu(e,t,n,r,i,a)}function td(e){return ps(e)}function nd(e,t,n,r){if(!td(n))return P(!0);let[i,a]=[L(),L()];return Eo(M(N(r,`reduce`),[Io([i,a],Ro(z(e,t,n.contains,a),Wo(i),i)),P(0)]),P(n.maxContains))}function rd(e,t,n,r){if(!td(n))return!0;let i=r.reduce((r,i)=>B(e,t,n.contains,i)?++r:r,0);return Xt(i,n.maxContains)}function id(e,t,n,r,i,a){let o=Fs(i)?i.minContains:1;return rd(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function ad(e,t,n,r){return Eo(r,P(n.maximum))}function od(e,t,n,r){return Xt(r,n.maximum)}function sd(e,t,n,r,i,a){return od(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function cd(e,t,n,r){return Eo(N(r,`length`),P(n.maxItems))}function ld(e,t,n,r){return Xt(r.length,n.maxItems)}function ud(e,t,n,r,i,a){return ld(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function dd(e,t,n,r){return ko(r,P(n.maxLength))}function fd(e,t,n,r){return vt(r,n.maxLength)}function pd(e,t,n,r,i,a){return fd(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function md(e,t,n,r){return Eo(N(Mo(r),`length`),P(n.maxProperties))}function hd(e,t,n,r){return Xt(y(r).length,n.maxProperties)}function gd(e,t,n,r,i,a){return hd(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function _d(e){return ps(e)}function vd(e,t,n,r){if(!_d(n))return P(!0);let[i,a]=[L(),L()];return Do(M(N(r,`reduce`),[Io([i,a],Ro(z(e,t,n.contains,a),Wo(i),i)),P(0)]),P(n.minContains))}function yd(e,t,n,r){if(!_d(n))return!0;let i=r.reduce((r,i)=>B(e,t,n.contains,i)?++r:r,0);return Ot(i,n.minContains)}function bd(e,t,n,r,i,a){return yd(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function xd(e,t,n,r){return Do(r,P(n.minimum))}function Sd(e,t,n,r){return Ot(r,n.minimum)}function Cd(e,t,n,r,i,a){return Sd(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function wd(e,t,n,r){return Do(N(r,`length`),P(n.minItems))}function Td(e,t,n,r){return Ot(r.length,n.minItems)}function Ed(e,t,n,r,i,a){return Td(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function Dd(e,t,n,r){return Oo(r,P(n.minLength))}function Od(e,t,n,r){return $t(r,n.minLength)}function kd(e,t,n,r,i,a){return Od(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function Ad(e,t,n,r){return Do(N(Mo(r),`length`),P(n.minProperties))}function jd(e,t,n,r){return Ot(y(r).length,n.minProperties)}function Md(e,t,n,r,i,a){return jd(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function Nd(e,t,n,r){return Go(r,P(n.multipleOf))}function Pd(e,t,n,r){return ot(r,n.multipleOf)}function Fd(e,t,n,r,i,a){return Pd(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function Id(e,t,n,r){return jc(e,t,[n.not],r,co(Co(N(`results`,`length`),P(1))))}function Ld(e,t,n,r){return co(z(e,t,n.not,r))}function Rd(e,t,n,r){return t.UseUnevaluated()?Id(e,t,n,r):Ld(e,t,n,r)}function zd(e,t,n,r){let i=new cc;return!B(e,i,n.not,r)&&t.Merge([i])}function Bd(e,t,n,r,i,a){return zd(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function Vd(e,t,n,r){return jc(e,t,n.oneOf,r,Co(N(`results`,`length`),P(1)))}function Hd(e,t,n,r){return Co(M(N(Fo(n.oneOf.map(n=>z(e,t,n,r))),`reduce`),[Io([`count`,`result`],Ro(Co(`result`,P(!0)),Wo(`count`),`count`)),P(0)]),P(1))}function Ud(e,t,n,r){return t.UseUnevaluated()?Vd(e,t,n,r):Hd(e,t,n,r)}function Wd(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new cc;return B(e,i,n,r)?[...t,i]:t},[]);return T(i.length,1)&&t.Merge(i)}function Gd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new uc,u=V(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=T(c.length,1)&&t.Merge(c);return!l&&T(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 Kd(e,t,n,r){return M(N(fc(v(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function qd(e,t,n,r){return(v(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function Jd(e,t,n,r,i,a){return qd(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function Yd(e,t,n,r){return F(E(n.patternProperties).map(([n,i])=>{let[a,o]=[L(),L()],s=co(M(N(fc(new RegExp(n,`u`)),`test`),[a])),c=Jf(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?j(s,so(c,l)):j(s,c);return Ao(jo(r),P(0),[`[${a}, ${o}]`,`_`],u)}))}function Xd(e,t,n,r){return x(E(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return x(E(r),0,([n,r])=>!a.test(n)||Yf(e,t,i,r)&&t.AddKey(n))})}function Zd(e,t,n,r,i,a){return w(E(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return w(E(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||Xf(e,t,s,a,o,i)&&t.AddKey(n)})})}function Qd(e,t,n,r){return F(n.prefixItems.map((n,i)=>{let a=Eo(N(r,`length`),P(i)),o=Jf(e,t,n,`${r}[${i}]`),s=t.AddIndex(P(i));return j(a,t.UseUnevaluated()?so(o,s):o)}))}function $d(e,t,n,r){return T(r.length,0)||x(n.prefixItems,0,(n,i)=>Xt(r.length,i)||Yf(e,t,n,r[i])&&t.AddIndex(i))}function ef(e,t,n,r,i,a){return T(a.length,0)||w(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return Xt(a.length,o)||Xf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function tf(e,t){return e.includes(t)||Kt().exactOptionalPropertyTypes}function nf(e,t){return bo(N(e,t))}function rf(e,t){return C(e[t])}function af(e,t,n,r){let i=Zs(n)?n.required:[];return F(E(n.properties).map(([n,a])=>{let o=co(No(r,P(n))),s=Jf(e,t,a,N(r,n)),c=t.AddKey(P(n)),l=t.UseUnevaluated()?so(s,c):s,u=i.includes(n)?l:j(o,l);return tf(i,n)?u:j(nf(r,n),u)}))}function of(e,t,n,r){let i=Zs(n)?n.required:[];return x(E(n.properties),0,([n,a])=>{let o=!D(r,n)||Yf(e,t,a,r[n])&&t.AddKey(n);return tf(i,n)?o:rf(r,n)||o})}function sf(e,t,n,r,i,a){let o=Zs(i)?i.required:[];return w(E(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!D(a,i)||Xf(e,t,c,l,s,a[i])&&t.AddKey(i);return tf(o,i)?u():rf(a,i)||u()})}function cf(e,t,n,r){let[i,a]=[L(),L()];return Ao(Mo(r),P(0),[i,a],z(e,t,n.propertyNames,i))}function lf(e,t,n,r){return x(y(r),0,(r,i)=>B(e,t,n.propertyNames,r))}function uf(e,t,n,r,i,a){let o=[];return w(y(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=V(e,new uc,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function df(e,t,n,r){return op(e,t,e.RecursiveRef(n)??!1,r)}function ff(e,t,n,r){let i=e.RecursiveRef(n)??!1;return I(i)&&B(e,t,i,r)}function pf(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return I(o)&&V(e,t,`#`,r,o,a)}function mf(e,t,n,r){let i=Io([`context`,`value`],op(e,t,n,`value`));return M(Io([`context`,`value`],zo([Bo(`nextContext`,Lo(`CheckContext`,[])),Bo(`result`,M(i,[`nextContext`,`value`])),Vo(`result`,t.Merge(`[nextContext]`)),Ho(`result`)])),[`context`,r])}function hf(e,t,n,r){return op(e,t,n,r)}function gf(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?mf(e,t,i,r):hf(e,t,i,r)}function _f(e,t,n,r){let i=e.Ref(n)??!1,a=new cc,o=I(i)&&B(e,a,i,r);return o&&t.Merge([a]),o}function vf(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new uc,c=I(o)&&V(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function yf(e,t,n,r){return F(n.required.map(e=>No(r,P(e))))}function bf(e,t,n,r){return x(n.required,0,e=>D(r,e))}function xf(e,t,n,r,i,a){let o=[];return w(i.required,0,e=>{let t=D(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function Sf(e,t,n,r){return T(n,`object`)?go(r):T(n,`array`)?lo(r):T(n,`boolean`)?fo(r):T(n,`integer`)?po(r):T(n,`number`)?ho(r):T(n,`null`)?mo(r):T(n,`string`)?vo(r):T(n,`bigint`)?uo(r):T(n,`constructor`)?So(r):T(n,`function`)?xo(r):T(n,`symbol`)?yo(r):T(n,`undefined`)||T(n,`void`)?bo(r):P(!0)}function Cf(e,t,n,r,i){return T(n,`object`)?Ge(i):T(n,`array`)?S(i):T(n,`boolean`)?Jt(i):T(n,`integer`)?ht(i):T(n,`number`)?O(i):T(n,`null`)?He(i):T(n,`string`)?v(i):T(n,`bigint`)?Ft(i):T(n,`constructor`)?xt(i):T(n,`function`)?Lt(i):T(n,`symbol`)?nt(i):T(n,`undefined`)?C(i):!T(n,`void`)||C(i)}function wf(e,t,n,r){return Uo(n.map(n=>Sf(e,t,n,r)))}function Tf(e,t,n,r,i){return n.some(n=>Cf(e,t,n,r,i))}function Ef(e,t,n,r){return S(n.type)?wf(e,t,n.type,r):Sf(e,t,n.type,r)}function Df(e,t,n,r){return S(n.type)?Tf(e,t,n.type,n,r):Cf(e,t,n.type,n,r)}function Of(e,t,n,r,i,a){return(S(i.type)?Tf(e,t,i.type,i,a):Cf(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function kf(e,t,n,r){let[i,a]=[L(),L()],o=M(N(`context`,`GetIndices`),[]),s=M(N(`indices`,`has`),[i]),c=z(e,t,n.unevaluatedItems,a),l=M(N(`context`,`AddIndex`),[i]),u=Ao(r,P(0),[a,i],so(j(s,c),l));return M(Io([`context`],zo([Bo(`indices`,o),Ho(u)])),[`context`])}function Af(e,t,n,r){let i=t.GetIndices();return x(r,0,(r,a)=>(i.has(a)||B(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function jf(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return w(a,0,(a,c)=>{let l=new uc,u=(o.has(c)||V(e,l,n,r,i.unevaluatedItems,a))&&t.AddIndex(c);return u||s.push(c),u})||t.AddError({keyword:`unevaluatedItems`,schemaPath:n,instancePath:r,params:{unevaluatedItems:s}})}function Mf(e,t,n,r){let[i,a]=[L(),L()],o=M(N(`context`,`GetKeys`),[]),s=M(N(`keys`,`has`),[i]),c=M(N(`context`,`AddKey`),[i]),l=z(e,t,n.unevaluatedProperties,a),u=Ao(jo(r),P(0),[`[${i}, ${a}]`,`_`],j(s,so(l,c)));return M(Io([`context`],zo([Bo(`keys`,o),Ho(u)])),[`context`])}function Nf(e,t,n,r){let i=t.GetKeys();return x(E(r),0,([r,a])=>i.has(r)||B(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function Pf(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return w(E(a),0,([a,c])=>{let l=new uc,u=o.has(a)||V(e,l,n,r,i.unevaluatedProperties,c)&&t.AddKey(a);return u||s.push(a),u})||t.AddError({keyword:`unevaluatedProperties`,schemaPath:n,instancePath:r,params:{unevaluatedProperties:s}})}function Ff(e){return!T(e.uniqueItems,!1)}function If(e,t,n,r){return Ff(n)?Co(N(Lo(`Set`,[M(N(r,`map`),[N(`Hashing`,`Hash`)])]),`size`),N(r,`length`)):P(!0)}function Lf(e,t,n,r){if(!Ff(n))return!0;let i=new Set(r.map(rt)).size,a=r.length;return T(i,a)}function Rf(e,t,n,r,i,a){if(!Ff(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=rt(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return T(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function zf(e,t){return $s(e)&&(S(e.type)&&Et(e.type.length,0)&&x(e.type,0,e=>T(e,t))||T(e.type,t))}function Bf(e){return zf(e,`object`)}function Vf(e){return as(e)&&(cs(e)||hs(e)||gs(e)||_s(e)||Gs(e)||Us(e)||Ks(e)||Rs(e)||Ns(e)||Zs(e)||nc(e))}function Hf(e){return zf(e,`array`)}function Uf(e){return as(e)&&(ss(e)||Ds(e)||ps(e)||As(e)||js(e)||Fs(e)||Is(e)||Ws(e)||tc(e)||ec(e))}function Wf(e){return zf(e,`string`)}function Gf(e){return as(e)&&(Ls(e)||Ms(e)||ws(e)||Hs(e))}function Kf(e){return zf(e,`number`)||zf(e,`bigint`)}function qf(e){return as(e)&&(Ps(e)||ks(e)||Ss(e)||Cs(e)||zs(e))}function Jf(e,t,n,r){return t.UseUnevaluated()?so(so(t.Push(),z(e,t,n,r)),t.Pop()):z(e,t,n,r)}function z(e,t,n,r){e.Push(n);let i=[];if(os(n))return Hc(e,t,n,r);if($s(n)&&i.push(Ef(e,t,n,r)),Vf(n)){let a=[];Zs(n)&&a.push(yf(e,t,n,r)),cs(n)&&a.push(Oc(e,t,n,r)),hs(n)&&a.push(Qc(e,t,n,r)),gs(n)&&a.push(tl(e,t,n,r)),_s(n)&&a.push(il(e,t,n,r)),Us(n)&&a.push(Yd(e,t,n,r)),Gs(n)&&a.push(af(e,t,n,r)),Ks(n)&&a.push(cf(e,t,n,r)),Rs(n)&&a.push(Ad(e,t,n,r)),Ns(n)&&a.push(md(e,t,n,r));let o=F(a),s=j(co(go(r)),o);i.push(Bf(n)?o:s)}if(Uf(n)){let a=[];ss(n)&&a.push(bc(e,t,n,r)),ps(n)&&a.push(Yc(e,t,n,r)),Ds(n)&&a.push(Qu(e,t,n,r)),As(n)&&a.push(nd(e,t,n,r)),js(n)&&a.push(cd(e,t,n,r)),Fs(n)&&a.push(vd(e,t,n,r)),Is(n)&&a.push(wd(e,t,n,r)),Ws(n)&&a.push(Qd(e,t,n,r)),ec(n)&&a.push(If(e,t,n,r));let o=F(a),s=j(co(lo(r)),o);i.push(Hf(n)?o:s)}if(Gf(n)){let a=[];Ms(n)&&a.push(dd(e,t,n,r)),Ls(n)&&a.push(Dd(e,t,n,r)),ws(n)&&a.push(Bu(e,t,n,r)),Hs(n)&&a.push(Kd(e,t,n,r));let o=F(a),s=j(co(vo(r)),o);i.push(Wf(n)?o:s)}if(qf(n)){let a=[];Ss(n)&&a.push(pl(e,t,n,r)),Cs(n)&&a.push(gl(e,t,n,r)),ks(n)&&a.push(ad(e,t,n,r)),Ps(n)&&a.push(xd(e,t,n,r)),zs(n)&&a.push(Nd(e,t,n,r));let o=F(a),s=j(co(j(ho(r),uo(r))),o);i.push(Kf(n)?o:s)}Xs(n)&&i.push(gf(e,t,n,r)),Ys(n)&&i.push(df(e,t,n,r)),ys(n)&&i.push(sl(e,t,n,r)),fs(n)&&i.push(Gc(e,t,n,r)),xs(n)&&i.push(ul(e,t,n,r)),Es(n)&&i.push(Uu(e,t,n,r)),Bs(n)&&i.push(Rd(e,t,n,r)),ls(n)&&i.push(Pc(e,t,n,r)),ds(n)&&i.push(zc(e,t,n,r)),Vs(n)&&i.push(Ud(e,t,n,r)),tc(n)&&i.push(j(co(lo(r)),kf(e,t,n,r))),nc(n)&&i.push(j(co(_o(r)),Mf(e,t,n,r))),is(n)&&i.push(hc(e,t,n,r));let a=F(i);return e.Pop(n),a}function Yf(e,t,n,r){return t.Push()&&B(e,t,n,r)&&t.Pop()}function B(e,t,n,r){e.Push(n);let i=os(n)?Uc(e,t,n,r):(!$s(n)||Df(e,t,n,r))&&(!(b(r)&&!S(r))||(!Zs(n)||bf(e,t,n,r))&&(!cs(n)||kc(e,t,n,r))&&(!hs(n)||$c(e,t,n,r))&&(!gs(n)||nl(e,t,n,r))&&(!_s(n)||al(e,t,n,r))&&(!Us(n)||Xd(e,t,n,r))&&(!Gs(n)||of(e,t,n,r))&&(!Ks(n)||lf(e,t,n,r))&&(!Rs(n)||jd(e,t,n,r))&&(!Ns(n)||hd(e,t,n,r)))&&(!S(r)||(!ss(n)||xc(e,t,n,r))&&(!ps(n)||Xc(e,t,n,r))&&(!Ds(n)||$u(e,t,n,r))&&(!As(n)||rd(e,t,n,r))&&(!js(n)||ld(e,t,n,r))&&(!Fs(n)||yd(e,t,n,r))&&(!Is(n)||Td(e,t,n,r))&&(!Ws(n)||$d(e,t,n,r))&&(!ec(n)||Lf(e,t,n,r)))&&(!v(r)||(!Ms(n)||fd(e,t,n,r))&&(!Ls(n)||Od(e,t,n,r))&&(!ws(n)||Vu(e,t,n,r))&&(!Hs(n)||qd(e,t,n,r)))&&(!(O(r)||Ft(r))||(!Ss(n)||ml(e,t,n,r))&&(!Cs(n)||_l(e,t,n,r))&&(!ks(n)||od(e,t,n,r))&&(!Ps(n)||Sd(e,t,n,r))&&(!zs(n)||Pd(e,t,n,r)))&&(!Xs(n)||_f(e,t,n,r))&&(!Ys(n)||ff(e,t,n,r))&&(!ys(n)||cl(e,t,n,r))&&(!fs(n)||Kc(e,t,n,r))&&(!xs(n)||dl(e,t,n,r))&&(!Es(n)||Wu(e,t,n,r))&&(!Bs(n)||zd(e,t,n,r))&&(!ls(n)||Fc(e,t,n,r))&&(!ds(n)||Bc(e,t,n,r))&&(!Vs(n)||Wd(e,t,n,r))&&(!tc(n)||!S(r)||Af(e,t,n,r))&&(!nc(n)||!b(r)||Nf(e,t,n,r))&&(!is(n)||gc(e,t,n,r));return e.Pop(n),i}function Xf(e,t,n,r,i,a){return t.Push()&&V(e,t,n,r,i,a)&&t.Pop()}function V(e,t,n,r,i,a){e.Push(i);let o=os(i)?Wc(e,t,n,r,i,a):!!((!$s(i)||Of(e,t,n,r,i,a))&+(!(b(a)&&!S(a))||!!((!Zs(i)||xf(e,t,n,r,i,a))&+(!cs(i)||Ac(e,t,n,r,i,a))&(!hs(i)||el(e,t,n,r,i,a))&(!gs(i)||rl(e,t,n,r,i,a))&(!_s(i)||ol(e,t,n,r,i,a))&(!Us(i)||Zd(e,t,n,r,i,a))&(!Gs(i)||sf(e,t,n,r,i,a))&(!Ks(i)||uf(e,t,n,r,i,a))&(!Rs(i)||Md(e,t,n,r,i,a))&(!Ns(i)||gd(e,t,n,r,i,a))))&(!S(a)||!!((!ss(i)||Sc(e,t,n,r,i,a))&+(!ps(i)||Zc(e,t,n,r,i,a))&(!Ds(i)||ed(e,t,n,r,i,a))&(!As(i)||id(e,t,n,r,i,a))&(!js(i)||ud(e,t,n,r,i,a))&(!Fs(i)||bd(e,t,n,r,i,a))&(!Is(i)||Ed(e,t,n,r,i,a))&(!Ws(i)||ef(e,t,n,r,i,a))&(!ec(i)||Rf(e,t,n,r,i,a))))&(!v(a)||!!((!Ms(i)||pd(e,t,n,r,i,a))&+(!Ls(i)||kd(e,t,n,r,i,a))&(!ws(i)||Hu(e,t,n,r,i,a))&(!Hs(i)||Jd(e,t,n,r,i,a))))&(!(O(a)||Ft(a))||!!((!Ss(i)||hl(e,t,n,r,i,a))&+(!Cs(i)||vl(e,t,n,r,i,a))&(!ks(i)||sd(e,t,n,r,i,a))&(!Ps(i)||Cd(e,t,n,r,i,a))&(!zs(i)||Fd(e,t,n,r,i,a))))&(!Xs(i)||vf(e,t,n,r,i,a))&(!Ys(i)||pf(e,t,n,r,i,a))&(!ys(i)||ll(e,t,n,r,i,a))&(!fs(i)||qc(e,t,n,r,i,a))&(!xs(i)||fl(e,t,n,r,i,a))&(!Es(i)||Gu(e,t,n,r,i,a))&(!Bs(i)||Bd(e,t,n,r,i,a))&(!ls(i)||Ic(e,t,n,r,i,a))&(!ds(i)||Vc(e,t,n,r,i,a))&(!Vs(i)||Gd(e,t,n,r,i,a))&(!tc(i)||!S(a)||jf(e,t,n,r,i,a))&(!nc(i)||!b(a)||Pf(e,t,n,r,i,a)))&&(!is(i)||_c(e,t,n,r,i,a));return e.Pop(i),o}const Zf=[0],Qf=new Map,$f=new Map;function ep(){return rt(Zf[0]++)}function tp(e,t){Qf.has(e)||Qf.set(e,new Map);let n=Qf.get(e);if(n.has(t))return n.get(t);let r=ep();return n.set(t,r),r}function np(e,t,n,r){return e.UseUnevaluated()?M(`check_${n}`,[`context`,r]):M(`check_${n}`,[r])}function rp(e,t,n,r){let i=z(e,t,n,`value`);return t.UseUnevaluated()?Bo(`check_${r}`,Io([`context`,`value`],i)):Bo(`check_${r}`,Io([`value`],i))}function ip(){Zf[0]=0,Qf.clear(),$f.clear()}function ap(){return[...$f.values()]}function op(e,t,n,r){let i=tp(n,e.BaseURL().href),a=np(t,n,i,r);return $f.has(i)?a:($f.set(i,``),$f.set(i,rp(e,t,n,i)),a)}function sp(e,t){return b(t)&&!ze(e)?t[e]:void 0}function cp(e,t){return e.reduce((e,t)=>sp(t,e),t)}function lp(e){if(T(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 up(e,t){return cp(lp(t),e)}function dp(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(T(r.pathname,i.pathname))return n.hash.startsWith(`#`)?mp(e,t,n):e}function fp(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return T(r.href,i.href)?e:void 0}function pp(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return T(r.href,i.href)?e:void 0}function mp(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 up(e,r)}function hp(e,t,n){if(Ts(e)){let r=dp(e,t,n);if(!C(r))return r}if(us(e)){let r=fp(e,t,n);if(!C(r))return r}if(vs(e)){let r=pp(e,t,n);if(!C(r))return r}return mp(e,t,n)}function gp(e,t,n){return e.reduce((e,r)=>{let i=vp(r,t,n);return C(i)?e:i},void 0)}function _p(e,t,n){return y(e).reduce((r,i)=>{let a=vp(e[i],t,n);return C(a)?r:a},void 0)}function vp(e,t,n){let r=as(e)&&Ts(e)?new URL(e.$id,t.href):t;if(as(e)){let t=hp(e,r,n);if(!C(t))return t}if(S(e))return gp(e,r,n);if(b(e))return _p(e,r,n)}function yp(e,t){let n=new URL(`http://unknown/`),r=Ts(e)?new URL(e.$id,n.href):n;return vp(e,r,new URL(t,r.href))}function bp(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?yp(t,n.$dynamicRef):yp(e,n.$dynamicRef);if(!C(i))return!as(i)||!vs(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var xp=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)},Sp,Cp,wp,Tp,Ep,Dp=class{constructor(e,t){Sp.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){as(e)&&(Ts(e)&&(this.ids.push(e),xp(this,Sp,`m`,Cp).call(this,e)),us(e)&&this.anchors.push(e),Js(e)&&this.recursiveAnchors.push(e),vs(e)&&this.dynamicAnchors.push(e))}Pop(e){as(e)&&(Ts(e)&&(this.ids.pop(),xp(this,Sp,`m`,wp).call(this,e)),us(e)&&this.anchors.pop(),Js(e)&&this.recursiveAnchors.pop(),vs(e)&&this.dynamicAnchors.pop())}Ref(e){return xp(this,Sp,`m`,Tp).call(this,e)??xp(this,Sp,`m`,Ep).call(this,e)}RecursiveRef(e){return Js(this.Base())?yp(this.recursiveAnchors[0],e.$recursiveRef):yp(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return bp(t,this.Base(),e,this.dynamicAnchors)}};Sp=new WeakSet,Cp=function e(t,n=!0){if(!as(t))return;let r=t;if(!(!n&&Ts(r))){!n&&vs(r)&&this.dynamicAnchors.push(r);for(let t of y(r))xp(this,Sp,`m`,e).call(this,r[t],!1)}},wp=function e(t,n=!0){if(!as(t))return;let r=t;if(!(!n&&Ts(r))){!n&&vs(r)&&this.dynamicAnchors.pop();for(let t of y(r))xp(this,Sp,`m`,e).call(this,r[t],!1)}},Tp=function(e){return D(this.context,e.$ref)?this.context[e.$ref]:void 0},Ep=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?yp(this.Base(),e.$ref):yp(t,e.$ref)};function Op(e){return`${e.Functions().join(`;
878
- `)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function kp(e,t){return Zo(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(cc,et,zu,Ke,e.External().variables)}function Ap(e){let t=new Dp(e.Context(),e.Schema()),n=new cc;return r=>B(t,n,e.Schema(),r)}function jp(e,t){return Xo()?kp(e,t):Ap(e)}var Mp=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)}},Np=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=Op(this),t=jp(this,e);return new Mp(Xo(),e,t)}};function Pp(...e){let[t,n]=qo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});pc(),ip();let r=new Dp(t,n),i=new sc(oc(t,n)),a=op(r,i,n,`value`),o=ap();return new Np(t,n,mc(),o,a,i.UseUnevaluated())}function Fp(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=Kt(),a=es(),o=[];return[V(new Dp(t,n),new lc(e=>{if(!Ot(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function Ip(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return B(new Dp(t,n),new cc,n,r)}function Lp(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Ip(t,n,r)}function Rp(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=Fp(t,n,r);return a}var zp=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 Bp(e,t,n){return S(n)?n.map(n=>Zp(e,t.items,n)):n}function Vp(e,t,n){return Zp({...e,...t.$defs},Ye(t.$ref),n)}function Hp(e,t){let n=D(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=Ut(e,t),i=Rt(r);return qe(i)?kt(i,n):i}function Up(e,t,n){return Zp(e,Hp(e,t),n)}function Wp(e){return D(e,`additionalProperties`)?e.additionalProperties:void 0}function Gp(e,t,n){if(!b(n)||S(n))return n;let r=Wp(t);for(let i of y(n)){if(D(t.properties,i)){n[i]=Zp(e,t.properties[i],n[i]);continue}if(Jt(r)&&T(r,!0)||St(r)&&Lp(e,r,n[i])){n[i]=Zp(e,r,n[i]);continue}delete n[i]}return n}function Kp(e,t,n){if(!b(n))return n;let r=Wp(t),[i,a]=[new RegExp(bt(t)),Ct(t)];for(let t of y(n)){if(i.test(t)){n[t]=Zp(e,a,n[t]);continue}if(Jt(r)&&T(r,!0)||St(r)&&Lp(e,r,n[t])){n[t]=Zp(e,r,n[t]);continue}delete n[t]}return n}function qp(e,t,n){return D(e,t.$ref)?Zp(e,e[t.$ref],n):n}function Jp(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]=Zp(e,t.items[i],n[i]);return Et(n.length,r)?n.slice(0,r):n}function Yp(e){return zt(e)}function Xp(e,t,n){for(let r of t.anyOf){let t=Zp(e,r,Yp(n));if(Lp(e,r,t))return t}return n}function Zp(e,t,n){return it(t)?Bp(e,t,n):Be(t)?Vp(e,t,n):at(t)?Up(e,t,n):qe(t)?Gp(e,t,n):yt(t)?Kp(e,t,n):Ht(t)?qp(e,t,n):Vt(t)?Jp(e,t,n):Tt(t)?Xp(e,t,n):n}function Qp(e,t){for(let n of Ko.Keys(e))Ko.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function $p(e){let t={};for(let n of Ko.Keys(e))t[n]=nm(e[n]);return t}function em(e){return tm(Gt(e))}function tm(e){return e.map(e=>nm(e))}function nm(e){return Qp(e,it(e)?Le(nm(e.items),pt(e)):at(e)?Ze(tm(e.allOf)):Tt(e)?mt(em(e.anyOf)):qe(e)?ct($p(e.properties)):yt(e)?Pt(qt(e),nm(Ct(e))):Vt(e)?It(tm(e.items)):e)}function rm(e){return nm(e)}function im(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Zp(t,Kt().unionPrioritySort?rm(n):n,r)}function am(e){return b(e)&&D(e,`value`)}function H(e){return{value:e}}function om(e){return S(e)?H(e):H([e])}function sm(e){return T(e,!0)?H(BigInt(1)):H(BigInt(0))}const cm=/^-?(0|[1-9]\d*)n$/,lm=/^-?(0|[1-9]\d*)\.\d+$/,um=/^-?(0|[1-9]\d*)$/;function dm(e){return cm.test(e)}function fm(e){return lm.test(e)}function pm(e){return um.test(e)}function mm(e){let t=e.toLowerCase();return dm(e)?H(BigInt(e.slice(0,e.length-1))):fm(e)?H(BigInt(e.split(`.`)[0])):pm(e)?H(BigInt(e)):T(t,`false`)?H(BigInt(0)):T(t,`true`)?H(BigInt(1)):void 0}function hm(e){return Ft(e)?H(e):Jt(e)?sm(e):O(e)?H(BigInt(Math.trunc(e))):He(e)?H(BigInt(0)):v(e)?mm(e):C(e)?H(BigInt(0)):void 0}function gm(e){return T(e,BigInt(0))?H(!1):T(e,BigInt(1))?H(!0):void 0}function _m(e){return T(e,0)?H(!1):T(e,1)?H(!0):void 0}function vm(e){return T(e.toLowerCase(),`false`)?H(!1):T(e.toLowerCase(),`true`)?H(!0):T(e,`0`)?H(!1):T(e,`1`)?H(!0):void 0}function ym(e){return Ft(e)?gm(e):Jt(e)?H(e):O(e)?_m(e):He(e)?H(!1):v(e)?vm(e):C(e)?H(!1):void 0}function bm(e){return T(e,BigInt(0))?H(null):void 0}function xm(e){return T(e,!1)?H(null):void 0}function Sm(e){return T(e,0)?H(null):void 0}function Cm(e){let t=e.toLowerCase();return T(t,`undefined`)||T(t,`null`)||T(e,``)||T(e,`0`)?H(null):void 0}function wm(e){return Ft(e)?bm(e):Jt(e)?xm(e):O(e)?Sm(e):He(e)?H(null):v(e)?Cm(e):C(e)?H(null):void 0}const Tm=BigInt(2**53-1),Em=BigInt(-(2**53-1));function Dm(e){return e<=Tm&&e>=Em?H(Number(e)):void 0}function Om(e){return H(+!!e)}function km(e){let t=+e;if(O(t))return H(t);let n=e.toLowerCase();if(T(n,`false`))return H(0);if(T(n,`true`))return H(1);let r=hm(e);if(am(r))return r.value<=Tm&&r.value>=Em?H(Number(r.value)):void 0}function Am(e){return Ft(e)?Dm(e):Jt(e)?Om(e):O(e)?H(e):He(e)?H(0):v(e)?km(e):C(e)?H(0):void 0}function jm(e){return Ft(e)||Jt(e)||O(e)?H(e.toString()):He(e)?H(`null`):v(e)?H(e):C(e)?H(``):void 0}function Mm(e){return T(e,BigInt(0))?H(void 0):void 0}function Nm(e){return T(e,!1)?H(void 0):void 0}function Pm(e){return T(e,0)?H(void 0):void 0}function Fm(e){let t=e.toLowerCase();return T(t,`undefined`)||T(t,`null`)||T(e,``)||T(e,`0`)?H(void 0):void 0}function Im(e){return Ft(e)?Mm(e):Jt(e)?Nm(e):O(e)?Pm(e):He(e)?H(void 0):v(e)?Fm(e):C(e)?H(e):void 0}function Lm(e,t,n){return om(n).value.map(n=>uh(e,t.items,n))}function Rm(e,t,n){let r=hm(n);return am(r)?r.value:n}function zm(e,t,n){let r=ym(n);return am(r)?r.value:n}function Bm(e,t,n){return uh({...e,...t.$defs},Ye(t.$ref),n)}function Vm(e,t,n){return uh(e,Rt(t),n)}function Hm(e,t,n){let r=Am(n);return am(r)?Math.trunc(r.value):n}function Um(e,t,n){let r=Ut(e,t);return uh(e,Rt(r),n)}function Wm(e,t,n){let r=hm(n);return am(r)&&T(t.const,r.value)?r.value:n}function Gm(e,t,n){let r=ym(n);return am(r)&&T(t.const,r.value)?r.value:n}function Km(e,t,n){let r=Am(n);return am(r)&&T(t.const,r.value)?r.value:n}function qm(e,t,n){let r=jm(n);return am(r)&&T(t.const,r.value)?r.value:n}function Jm(e,t,n){return T(t.const,n)?n:st(t)?Wm(e,t,n):We(t)?Gm(e,t,n):Ue(t)?Km(e,t,n):tt(t)?qm(e,t,n):Je()}function Ym(e,t,n){let r=wm(n);return am(r)?r.value:n}function Xm(e,t,n){let r=Am(n);return am(r)?r.value:n}function Zm(e,t,n,r){let i=y(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=uh(e,n,r[t]));return r}function Qm(e,t,n){return ut(e)&&C(n[t])}function $m(e,t,n){let r=At(t.properties),i=y(n);for(let[t,a]of r)for(let r of i)!t.test(r)||Qm(a,r,n)||(n[r]=uh(e,a,n[r]));return D(t,`additionalProperties`)&&b(t.additionalProperties)?Zm(e,r,t.additionalProperties,n):n}function eh(e,t,n){return Ge(n)?$m(e,t,n):n}function th(e,t,n){let r=At(t.patternProperties),i=y(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=uh(e,a,n[r]));return D(t,`additionalProperties`)&&b(t.additionalProperties)?Zm(e,r,t.additionalProperties,n):n}function nh(e,t,n){return Ge(n)?th(e,t,n):n}function rh(e,t,n){return D(e,t.$ref)?uh(e,e[t.$ref],n):n}function ih(e,t,n){let r=jm(n);return am(r)?r.value:n}function ah(e,t,n){return uh(e,Rt(t),n)}function oh(e,t,n){if(!S(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=uh(e,t.items[r],n[r]);return n}function sh(e,t,n){let r=Im(n);return am(r)?r.value:n}function ch(e,t,n){if(t.anyOf.some(t=>Lp(e,t,n)))return n;let r=t.anyOf.map(t=>uh(e,t,Yp(n))).find(n=>Lp(e,t,n));return C(r)?n:r}function lh(e,t,n){return am(Im(n))?void 0:n}function uh(e,t,n){return it(t)?Lm(e,t,n):Qe(t)?Rm(e,t,n):jt(t)?zm(e,t,n):Be(t)?Bm(e,t,n):nn(t)?Vm(e,t,n):Re(t)?Hm(e,t,n):at(t)?Um(e,t,n):Zt(t)?Jm(e,t,n):Ve(t)?Ym(e,t,n):Qt(t)?Xm(e,t,n):qe(t)?eh(e,t,n):yt(t)?nh(e,t,n):Ht(t)?rh(e,t,n):Yt(t)?ih(e,t,n):gt(t)?ah(e,t,n):Vt(t)?oh(e,t,n):Wt(t)?sh(e,t,n):Tt(t)?ch(e,t,n):Bt(t)?lh(e,t,n):n}function dh(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return uh(t,n,r)}function fh(e,t,n){if(!S(n))return n;for(let r=0;r<n.length;r++)n[r]=xh(e,t.items,n[r]);return n}function ph(e,t,n){return xh({...e,...t.$defs},Ye(t.$ref),n)}function mh(e,t){return C(t)?Lt(e.default)?e.default():Yp(e.default):t}function hh(e,t,n){let r=Ut(e,t);return xh(e,Rt(r),n)}function gh(e,t,n){if(!b(n))return n;let r=y(t.properties);for(let i of r){let r=xh(e,t.properties[i],n[i]);C(r)&&(ut(t.properties[i])||!D(t.properties[i],`default`))||(n[i]=r)}if(!cs(t)||Jt(t.additionalProperties))return n;for(let i of y(n))r.includes(i)||(n[i]=xh(e,t.additionalProperties,n[i]));return n}function _h(e,t,n){if(!b(n))return n;let[r,i]=[new RegExp(bt(t)),Ct(t)];for(let t of y(n))r.test(t)&&ms(i)&&(n[t]=xh(e,i,n[t]));if(!cs(t))return n;for(let i of y(n))r.test(i)||(n[i]=xh(e,t.additionalProperties,n[i]));return n}function vh(e,t,n){return D(e,t.$ref)?xh(e,e[t.$ref],n):n}function yh(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]=xh(e,r[t],n[t]));return n}function bh(e,t,n){for(let r of t.anyOf){let t=xh(e,r,Yp(n));if(Lp(e,r,t))return t}return n}function xh(e,t,n){let r=ms(t)?mh(t,n):n;return it(t)?fh(e,t,r):Be(t)?ph(e,t,r):at(t)?hh(e,t,r):qe(t)?gh(e,t,r):yt(t)?_h(e,t,r):Ht(t)?vh(e,t,r):Vt(t)?yh(e,t,r):Tt(t)?bh(e,t,r):r}function Sh(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return xh(t,n,r)}function Ch(e){return(...t)=>{let[n,r,i]=qo(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function wh(e,t,n){return t[`~codec`].decode(n)}function Th(e,t,n){return t[`~codec`].encode(n)}function U(e,t,n,r){return $e(n)?T(e,`Decode`)?wh(t,n,r):Th(t,n,r):r}function Eh(e,t,n,r){if(!S(r))return r;for(let i=0;i<r.length;i++)r[i]=W(e,t,n.items,r[i]);return U(e,t,n,r)}function Dh(e,t,n,r){let i=U(e,t,n,r);if(!S(i))return i;for(let r=0;r<i.length;r++)i[r]=W(e,t,n.items,i[r]);return i}function Oh(e,t,n,r){return T(e,`Decode`)?Eh(e,t,n,r):Dh(e,t,n,r)}function kh(e,t,n,r){return r=W(e,{...t,...n.$defs},Ye(n.$ref),r),U(e,t,n,r)}function Ah(e){return e.reduce((e,t)=>({...e,...t}),{})}function jh(e,t){for(let n of t)if(!wt(e,n))return n;return e}function Mh(e,t,n,r){if(T(n.allOf.length,0))return U(e,t,n,r);let i=n.allOf.map(n=>W(e,t,n,im(n,Yp(r))));return U(e,t,n,i.every(e=>b(e))?Ah(i):jh(r,i))}function Nh(e,t,n,r){if(T(n.allOf.length,0))return U(e,t,n,r);let i=U(e,t,n,r),a=n.allOf.map(n=>W(e,t,n,im(n,Yp(i))));return a.every(e=>b(e))?Ah(a):jh(i,a)}function Ph(e,t,n,r){return T(e,`Decode`)?Mh(e,t,n,r):Nh(e,t,n,r)}function Fh(e,t,n,r){if(!Ge(r))return r;for(let i of y(n.properties))!D(r,i)||Qm(n.properties[i],i,r)||(r[i]=W(e,t,n.properties[i],r[i]));return U(e,t,n,r)}function Ih(e,t,n,r){let i=U(e,t,n,r);if(!Ge(i))return i;for(let r of y(n.properties))!D(i,r)||Qm(n.properties[r],r,i)||(i[r]=W(e,t,n.properties[r],i[r]));return i}function Lh(e,t,n,r){return T(e,`Decode`)?Fh(e,t,n,r):Ih(e,t,n,r)}function Rh(e,t,n,r){if(!Ge(r))return r;let i=new RegExp(bt(n));for(let a of y(r))i.test(a)&&(r[a]=W(e,t,Ct(n),r[a]));return U(e,t,n,r)}function zh(e,t,n,r){let i=U(e,t,n,r);if(!Ge(i))return i;let a=new RegExp(bt(n));for(let r of y(i))a.test(r)&&(i[r]=W(e,t,Ct(n),i[r]));return i}function Bh(e,t,n,r){return T(e,`Decode`)?Rh(e,t,n,r):zh(e,t,n,r)}function Vh(e,t,n,r){return D(t,n.$ref)?W(e,t,t[n.$ref],r):r}function Hh(e,t,n,r){return T(e,`Decode`)?U(e,t,n,Vh(e,t,n,r)):Vh(e,t,n,U(e,t,n,r))}function Uh(e,t,n,r){if(!S(r))return r;for(let i=0;i<Math.min(n.items.length,r.length);i++)r[i]=W(e,t,n.items[i],r[i]);return U(e,t,n,r)}function Wh(e,t,n,r){let i=U(e,t,n,r);if(!S(i))return r;for(let r=0;r<Math.min(n.items.length,i.length);r++)i[r]=W(e,t,n.items[r],i[r]);return i}function Gh(e,t,n,r){return T(e,`Decode`)?Uh(e,t,n,r):Wh(e,t,n,r)}function Kh(e,t,n,r){for(let i of n.anyOf)if(Lp(t,i,r))return U(e,t,n,W(e,t,i,r));return r}function qh(e,t,n,r){let i=U(e,t,n,r);for(let r of n.anyOf){let n=W(e,t,r,Yp(i));if(Lp(t,r,n))return n}return i}function Jh(e,t,n,r){return T(e,`Decode`)?Kh(e,t,n,r):qh(e,t,n,r)}function W(e,t,n,r){return it(n)?Oh(e,t,n,r):Be(n)?kh(e,t,n,r):at(n)?Ph(e,t,n,r):qe(n)?Lh(e,t,n,r):yt(n)?Bh(e,t,n,r):Ht(n)?Hh(e,t,n,r):Vt(n)?Gh(e,t,n,r):Tt(n)?Jh(e,t,n,r):U(e,t,n,r)}var Yh=class extends zp{constructor(e,t){super(`Decode`,e,t)}};function Xh(e,t,n){if(!Lp(e,t,n))throw new Yh(n,Rp(e,t,n));return n}function Zh(e,t,n){return W(`Decode`,e,Kt().unionPrioritySort?rm(t):t,n)}const Qh=Ch([(e,t,n)=>Yp(n),(e,t,n)=>Sh(e,t,n),(e,t,n)=>dh(e,t,n),(e,t,n)=>im(e,t,n),(e,t,n)=>Xh(e,t,n),(e,t,n)=>Zh(e,t,n)]);function $h(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Qh(t,n,r)}var eg=class extends zp{constructor(e,t){super(`Encode`,e,t)}};function tg(e,t,n){if(!Lp(e,t,n))throw new eg(n,Rp(e,t,n));return n}function ng(e,t,n){return W(`Encode`,e,Kt().unionPrioritySort?rm(t):t,n)}const rg=Ch([(e,t,n)=>Yp(n),(e,t,n)=>ng(e,t,n),(e,t,n)=>Sh(e,t,n),(e,t,n)=>dh(e,t,n),(e,t,n)=>im(e,t,n),(e,t,n)=>tg(e,t,n)]);function ig(...e){let[t,n,r]=qo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return rg(t,n,r)}function ag(e,t){return $e(t)||pg(e,t.items)}function og(e,t){return $e(t)||ug({...e,...t.$defs},Ye(t.$ref))}function sg(e,t){return $e(t)||t.allOf.some(t=>pg(e,t))}function cg(e,t){return $e(t)||y(t.properties).some(n=>pg(e,t.properties[n]))}function lg(e,t){return $e(t)||pg(e,Ct(t))}function ug(e,t){return!mg.has(t.$ref)&&(mg.add(t.$ref),$e(t)||D(e,t.$ref)&&pg(e,e[t.$ref]))}function dg(e,t){return $e(t)||t.items.some(t=>pg(e,t))}function fg(e,t){return $e(t)||t.anyOf.some(t=>pg(e,t))}function pg(e,t){return it(t)?ag(e,t):Be(t)?og(e,t):at(t)?sg(e,t):qe(t)?cg(e,t):yt(t)?lg(e,t):Ht(t)?ug(e,t):Vt(t)?dg(e,t):Tt(t)?fg(e,t):$e(t)}const mg=new Set;function hg(...e){let[t,n]=qo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return mg.clear(),pg(t,n)}var gg=class extends Error{constructor(e,t){super(t),this.type=e}};function _g(e,t){return Lt(t.default)?t.default(t):b(t.default)?Yp(t.default):t.default}function vg(e,t){if(ec(t)&&!ms(t))throw new gg(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=Is(t)?t.minItems:0;return Array.from({length:n},()=>zg(e,t.items))}function yg(e,t){return Cs(t)?BigInt(t.exclusiveMinimum)+BigInt(1):Ps(t)?BigInt(t.minimum):BigInt(0)}function bg(e,t){return!1}function xg(e,t){let n=zg(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function Sg(e,t){return zg({...e,...t.$defs},Ye(t.$ref))}function Cg(e,t){return zg(e,Rt(t))}function wg(e,t){let n=zg(e,t.returnType);return()=>n}function Tg(e,t){return Cs(t)&&O(t.exclusiveMinimum)?t.exclusiveMinimum+1:Ps(t)?t.minimum:0}function Eg(e,t){let n=Ut(e,t);return zg(e,Rt(n))}function Dg(e,t){return t.const}function Og(e,t){throw new gg(t,`Cannot create TNever types`)}function kg(e,t){return null}function Ag(e,t){return Cs(t)&&O(t.exclusiveMinimum)?t.exclusiveMinimum+1:Ps(t)?t.minimum:0}function jg(e,t){return(C(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:zg(e,t.properties[r])}),{})}function Mg(e,t){if(Rs(t)&&!ms(t))throw new gg(t,`Record with the minProperties constraint must have a default annotation`);return{}}function Ng(e,t){return D(e,t.$ref)?zg(e,e[t.$ref]):(()=>{throw new gg(t,`Unable to deref Ref`)})()}function Pg(e,t){if((Hs(t)||ws(t))&&!ms(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=Ls(t)?t.minLength:0;return``.padEnd(n)}function Fg(e,t){return Symbol()}function Ig(e,t){let n=Dt(t.pattern);if(Yt(n))throw new gg(t,`Unable to create TemplateLiteral due to infinite type expansion`);return zg(e,n)}function Lg(e,t){return Array.from({length:t.minItems},(n,r)=>zg(e,t.items[r]))}function Rg(e,t){if(T(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return zg(e,t.anyOf[0])}function zg(e,t){return ms(t)?_g(e,t):it(t)?vg(e,t):Qe(t)?yg(e,t):jt(t)?bg(e,t):dt(t)?xg(e,t):Be(t)?Sg(e,t):nn(t)?Cg(e,t):ft(t)?wg(e,t):Re(t)?Tg(e,t):at(t)?Eg(e,t):Zt(t)?Dg(e,t):Xe(t)?Og(e,t):Ve(t)?kg(e,t):Qt(t)?Ag(e,t):qe(t)?jg(e,t):yt(t)?Mg(e,t):Ht(t)?Ng(e,t):Yt(t)?Pg(e,t):_t(t)?Fg(e,t):gt(t)?Ig(e,t):Vt(t)?Lg(e,t):Wt(t)?void 0:Tt(t)?Rg(e,t):(Bt(t),void 0)}function Bg(...e){let[t,n]=qo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return zg(t,n)}var Vg=class extends zp{constructor(e,t){super(`Parse`,e,t)}};function Hg(e,t,n){if(!Lp(e,t,n))throw new Vg(n,Rp(e,t,n));return n}const Ug=Ch([(e,t,n)=>Yp(n),(e,t,n)=>Sh(e,t,n),(e,t,n)=>dh(e,t,n),(e,t,n)=>im(e,t,n),(e,t,n)=>Hg(e,t,n)]),Wg=ct({type:Nt(`insert`),path:en(),value:lt()}),Gg=Object({type:Nt(`update`),path:en(),value:lt()}),Kg=ct({type:Nt(`delete`),path:en()});mt([Wg,Gg,Kg]);var qg=class{constructor(e,t){this.hasCodec=hg(e,t),this.buildResult=Pp(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(Kt().correctiveParse)return Ug(this.Context(),this.Type(),e);throw new Vg(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:Rp(this.Context(),this.Type(),e)}Clean(e){return im(this.Context(),this.Type(),e)}Convert(e){return dh(this.Context(),this.Type(),e)}Create(){return Bg(this.Context(),this.Type())}Default(e){return Sh(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?$h(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?ig(this.Context(),this.Type(),e):this.Parse(e)}};function Jg(...e){let[t,n]=qo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new qg(t,n)}const Yg=new WeakMap,Xg=Symbol.for(`TypeBox.Kind`);function Zg(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function Qg(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 $g(e){try{return o_(e)}catch{return}}function e_(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 t_(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]=i_(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=i_(i,t.additionalProperties))}function n_(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=i_(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=i_(e[n],t.items)}function r_(e,t){for(let n of t)if($g(n)?.Check(e))return e;for(let n of t){let t=i_(structuredClone(e),n);if($g(n)?.Check(t))return t}return e}function i_(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=i_(n,e);Array.isArray(t.anyOf)&&(n=r_(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=r_(n,t.oneOf));let r=Zg(t),i=r.length>1&&r.some(e=>Qg(n,e));if(r.length>0&&!i)for(let e of r){let t=e_(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&t_(n,t),r.includes(`array`)&&Array.isArray(n)&&n_(n,t),n}function a_(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&&a_(e[n],r)}else if(t.items)for(let n of e)a_(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`&&$g(i)?.Check(null)===!1?delete n[e]:a_(n[e],i))}function o_(e){let t=e,n=Yg.get(t);if(n)return n;let r=Jg(e);return Yg.set(t,r),r}function s_(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 c_(e,t){let n=structuredClone(t.arguments);a_(n,e.parameters),dh(e.parameters,n);let r=o_(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Xg)){let t=i_(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=>` - ${s_(e)}: ${e.message}`).join(`
879
- `)||`Unknown validation error`,a=`Validation failed for tool "${t.name}":\n${i}\n\nReceived arguments:\n${JSON.stringify(t.arguments,null,2)}`;throw Error(a)}function l_(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function u_(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 f_(s,o,n,i,r,a??l_()),o}async function d_(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 f_(o,a,t,r,n,i??l_()),a}async function f_(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 p_(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 m_(u,i):await h_(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 p_(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 m_(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:C_(`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 w_(e,t);let i=T_(e);await E_(i,t),n.push(i)}return{messages:n,terminate:!1}}async function h_(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?g_(e,t,a,n,r,i):__(e,t,a,n,r,i)}async function g_(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 b_(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await S_(e,t,n,await x_(n,i,a),r,i),await w_(l,a);let u=T_(l);if(await E_(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:v_(o)}}async function __(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 b_(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await w_(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{let o=await x_(n,i,a),s=await S_(e,t,n,o,r,i);return await w_(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=T_(e);await E_(t,a),c.push(t)}return{messages:c,terminate:v_(s)}}function v_(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function y_(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function b_(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:C_(`Tool ${n.name} not found`),isError:!0};try{let o=c_(a,y_(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:C_(`Operation aborted`),isError:!0};if(a?.block){let e=C_(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:C_(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:C_(e instanceof Error?e.message:String(e)),isError:!0}}}async function x_(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:C_(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function S_(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=C_(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function C_(e){return{content:[{type:`text`,text:e}],details:{}}}async function w_(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function T_(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 E_(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function D_(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const O_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},k_={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 A_(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??k_,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 j_=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=[]}},M_=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=A_(t.initialState),this.convertToLlm=t.convertToLlm??D_,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??l_(),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 j_(t.steeringMode??`one-at-a-time`),this.followUpQueue=new j_(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 u_(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await d_(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:O_,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 N_(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 P_(e){let t=e.mimeType||`application/octet-stream`;return`${e.name} (${t}, ${N_(e.size)})`}function F_(e){let t=P_(e);return e.kind===`image`&&e.data?e.path?`[Attached image: ${t} — full-resolution copy saved to ${e.path}]`:`[Attached image: ${t}]`:e.kind===`text`&&e.text!==void 0?[`----- BEGIN ATTACHMENT ${t} -----`,e.text,`----- END ATTACHMENT ${e.name} -----`].join(`
880
- `):e.path?`[Attached ${e.kind===`image`?`image`:e.kind===`text`?`text file`:`file`} saved to ${e.path} — ${t}. Read it from the virtual filesystem when you need its contents.]`:e.error?`[Attachment not included: ${t}. ${e.error}]`:`[Attachment not included: ${t}. Unsupported binary attachment.]`}function I_(e,t){if(!t?.length)return e;let n=t.map(F_),r=e.trim();return r?`${r}\n\n${n.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 ea(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)ea(n,t)}function ta(e){let t=e.exceptionDetails;return t?t.exception?.description??t.text:null}function na(e,t){let n=ta(e);if(n!==null)throw Error(`${t}: ${n}`);return e.result?.value}function ra(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 ia(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=aa(a,o);t.has(s)||t.set(s,e)}return t}function aa(e,t){return`${e.toLowerCase()}|${t.replace(/\s+/g,` `).trim()}`}function oa(e,t){let n=aa(e.role,e.name),r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)oa(n,t)}function sa(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=>sa(e)).filter(e=>e.role!==`unknown`)),t}const ca=_(`browser-api`),la=[`Session with given id not found`,`Target closed`,`No session with given id`,`No tab attached for sessionId`];var ua=class extends Error{};function da(e){let t=e instanceof Error?e.message:String(e);return la.some(e=>t.includes(e))}function fa(e){let t=e??{queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0};return{queueDepth:t.queueDepth,totalWaitMs:t.tabWaitMs+t.bridgeWaitMs,tabWaitMs:t.tabWaitMs,bridgeWaitMs:t.bridgeWaitMs,acquisitions:t.acquisitions}}function pa(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var ma=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)}},ha=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContexts=new Map;_sessions=new Map;_listenedTransports=new Set;_sessionReplacedSubs=new Map;_appliedSends=new Map;_pinnedTargets=new Map;_tabLocks=new Map;_bridgeLock=Promise.resolve();_bridgeHold=null;_bridgeWaiters=0;_viewportOverrides=new Map;_tabLockStats=new Map;_onSessionChange;_lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;_reconnectAttempt=0;_reconnectNotBefore=0;_bridgeRejection=null;bridgeRejectedHandler=null;bridgeRejectedNotified=!1;classifyConnectFailure=async()=>`transient`;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),ca.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){ca.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}handleExecutionContextCreated=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this.frameContexts(t,`main`).set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=this.eventSessionId(e);if(!t)return;let n=e.executionContextId;if(typeof n!=`number`)return;let r=this._frameContexts.get(`main:${t}`);if(r)for(let[e,t]of r)t===n&&r.delete(e)};handleExecutionContextsCleared=e=>{let t=this.eventSessionId(e);t&&this._frameContexts.get(`main:${t}`)?.clear()};eventSessionId(e){let t=e.sessionId;return typeof t==`string`?t:this.sessionId}handleDetachedFromTarget=e=>{let t=e.sessionId;if(typeof t==`string`){for(let[e,n]of this._sessions)if(n.sessionId===t){this.forgetSession(e,n);return}}};handleTargetDestroyed=e=>{let t=e.targetId;if(typeof t==`string`){for(let[e,n]of this._sessions)if(e===t||n.remote?.localTargetId===t){this.forgetSession(e,n);return}}};constructor(e){this.client=e??new Ai,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 ma)return e;let t=this._accountedTransports.get(e);return t||(t=new ma(e,e=>this.noteApplied(e)),this._accountedTransports.set(e,t)),t}noteApplied(e){this._appliedSends.set(e,(this._appliedSends.get(e)??0)+1)}createHarRecorder(e,t){return new qi(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;Hi(r,`starting a command on tab ${e}`);let i=this.tabCounters(e);i.queueDepth+=1;let a;try{a=await this.acquireTabLock(e,i,r)}catch(e){throw--i.queueDepth,e}let o=this.pinTarget(e);try{return i.acquisitions+=1,await this.runOnTab(e,t,r)}finally{o(),--i.queueDepth,a()}}async runOnTab(e,t,n){try{return await this.attemptOnTab(e,t,n)}catch(r){if(r instanceof ua||!da(r))throw r;return ca.warn(`Stale CDP session — re-attaching and retrying once`,{targetId:e,error:r instanceof Error?r.message:String(r)}),this.invalidateSession(e),await this.attemptOnTab(e,t,n)}}async attemptOnTab(e,t,n){let r=await this.attachHandle(e,this.reentrantOwner(e),n);Hi(n,`about to run a command on tab ${e}`);let i=r.sessionId,a=this._appliedSends.get(i)??0;try{return await t(r)}catch(t){if(!da(t))throw t;let n=(this._appliedSends.get(i)??0)-a;if(n===0)throw t;this.invalidateSession(e);let r=t instanceof Error?t.message:String(t);throw ca.warn(`CDP session reset mid-command — not replaying`,{targetId:e,applied:n,reason:r}),new ua(`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 $i(this,e,r,this.accountedTransportFor(i?.transport??this.client),n)}handleFor(e,t){return new $i(this,e,t.sessionId,this.accountedTransportFor(t.transport))}getTabLockStats(e){if(e!==void 0)return fa(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 fa(t)}tabCounters(e){let t=this._tabLockStats.get(e);return t||(t={queueDepth:0,tabWaitMs:0,bridgeWaitMs:0,acquisitions:0},this._tabLockStats.set(e,t)),t}async acquireTabLock(e,t,n){let r,i=new Promise(e=>{r=e}),a=this._tabLocks.get(e);this._tabLocks.set(e,i);let o=()=>{this._tabLocks.get(e)===i&&this._tabLocks.delete(e),r()};if(a){let r=Date.now();try{await Gi(a,n,`queued for the lock on tab ${e}`)}catch(e){throw t.tabWaitMs+=Date.now()-r,a.then(o,o),e}t.tabWaitMs+=Date.now()-r}return o}async acquireBridgeLock(e){if(e?.owner!==void 0&&this._bridgeHold?.owner===e.owner)return()=>void 0;let t,n=new Promise(e=>{t=e}),r=this._bridgeLock,i=this._bridgeHold!==null||this._bridgeWaiters>0;if(this._bridgeLock=n,i){this._bridgeWaiters+=1;let t=Date.now();try{await r}finally{--this._bridgeWaiters}e?.counters&&(e.counters.bridgeWaitMs+=Date.now()-t)}let a={release:t,owner:Symbol(`bridge-hold`),targetId:e?.targetId??null};this._bridgeHold=a;let o=!1;return()=>{o||(o=!0,this._bridgeHold===a&&(this._bridgeHold=null),t())}}reentrantOwner(e){let t=this._bridgeHold;if(!(!t||e===null||t.targetId!==e))return t.owner}async runGlobal(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e),targetId:e});try{return await t()}finally{n()}}viewportOverride(e){return this._viewportOverrides.get(e)}recordViewportOverride(e,t){this._viewportOverrides.set(e,t)}frameContexts(e,t){let n=`${t}:${e}`,r=this._frameContexts.get(n);return r||(r=new Map,this._frameContexts.set(n,r)),r}dropFrameContexts(e){this._frameContexts.delete(`main:${e}`),this._frameContexts.delete(`isolated:${e}`)}async reapplyViewportOverride(e,t){let n=this._viewportOverrides.get(e);if(n)try{await this.handleFor(e,t).applyViewportOverride(n)}catch(t){ca.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){if(this._bridgeRejection)throw this.notifyBridgeRejected(),new Ri(this._bridgeRejection);this._lastConnectOptions=e?{...e}:{};try{await this.client.connect({url:e?.url??pa(),timeout:e?.timeout,...e?.protocols===void 0?{}:{protocols:e.protocols}})}catch(t){throw await this.noteReconnectFailure(e),this._bridgeRejection?new Ri(this._bridgeRejection):t}this.noteReconnectSuccess()}async reconnectIfNeeded(){await this.ensureConnected(),this.client!==this.localClient&&await this.ensureLocalConnected()}primeConnectOptions(e){this._lastConnectOptions=e?{...e}:{}}setCdpSupersededHandler(e){this.supersededHandler=e}setCdpBridgeRejectedHandler(e){this.bridgeRejectedHandler=e}setCdpConnectFailureClassifier(e){this.classifyConnectFailure=e}throwIfReconnectPaused(){if(this._bridgeRejection)throw this.notifyBridgeRejected(),new Ri(this._bridgeRejection);if(Date.now()<this._reconnectNotBefore)throw new zi}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 Ri().message,this.notifyBridgeRejected();return}let t=Bi(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{}}}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(),va(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=ba((await(await this.transportForWindowOps(e)).send(`Browser.getWindowForTarget`,{targetId:_a(e)})).bounds),n=await this.readDevicePixelRatio(e);return{...t,dpr:n}}async setWindowBounds(e,t){await this.ensureConnected(),va(t);let n=await this.transportForWindowOps(e),r=_a(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=ba(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=ba((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._viewportOverrides.delete(e),await this.dropSession(e),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let e=this.trayTargetProvider.createRemoteTransport(n,r);try{await e.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}return}}await this.localClient.send(`Target.closeTarget`,{targetId:e})}disconnect(){this.clearSessions(),this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){return this.attachToPageOwned(e,this.reentrantOwner(e))}async attachToPageOwned(e,t,n){let r=await this.acquireBridgeLock({owner:t,targetId:e,counters:this.tabCounters(e)});try{await this.ensureConnected();let t=this._sessions.get(e);return t?(this.activateSession(e,t),t.sessionId):await(this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)?this.attachRemoteTarget(e,n):this.attachLocalTarget(e,n))}finally{r()}}async selectTab(e){await this.withTab(e,async()=>void 0)}async bringTabToFront(e){await this.withTab(e,e=>e.bringToFront())}async attachRemoteTarget(e,t){let n=e.indexOf(`:`),r=e.substring(0,n),i=e.substring(n+1),a=this.trayTargetProvider?.createRemoteTransport?.(r,i);if(!a)throw Error(`No remote transport for target ${e}`);Hi(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),Hi(t,`about to enable Page on tray tab ${e}`),await a.send(`Page.enable`,{},o.sessionId),Hi(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(),Hi(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),Hi(t,`about to enable Page on tab ${e}`),await this.localClient.send(`Page.enable`,{},n.sessionId),Hi(t,`about to restore the viewport of tab ${e}`),await this.reapplyViewportOverride(e,n),this.notifySessionChange(e,n),n.sessionId}async detach(){let e=this.attachedTargetId;e&&(await this.dropSession(e),this.useLocalTransport())}async wakeCapture(e,t){let n=await this.acquireBridgeLock({owner:this.reentrantOwner(e.targetId),targetId:e.targetId});try{return await this.wakeCaptureLocked(e,t,this._bridgeHold?.owner)}finally{n()}}async wakeCaptureLocked(e,t,n){let r=e.targetId,i=await this.findFocusedLocalPage(r,n).catch(()=>null),a=await this.attachHandle(r,n);try{return await a.send(`Page.bringToFront`),await a.send(`Page.captureScreenshot`,t)}finally{if(i)try{await(await this.attachHandle(i,n)).send(`Page.bringToFront`),await this.attachToPageOwned(r,n)}catch{}}}async findFocusedLocalPage(e,t){let n=await this.listPages();for(let r of n)if(!(!r.targetId||r.targetId===e)&&!r.targetId.includes(`:`))try{if(await(await this.attachHandle(r.targetId,t)).evaluate(`document.hasFocus()`)===!0)return r.targetId}catch{}return null}async ensureLocalConnected(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){this.throwIfReconnectPaused();let e=this._lastConnectOptions;try{await this.localClient.connect({url:e?.url??pa(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}catch(t){throw await this.noteReconnectFailure(e??void 0),this._bridgeRejection?new Ri(this._bridgeRejection):t}this.noteReconnectSuccess()}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}if(this.client.state===`disconnected`){this.throwIfReconnectPaused();let e=this.client;this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.clearSessionsForTransport(e),this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0)}}transportForSession(e){for(let t of this._sessions.values())if(t.sessionId===e)return t.transport;return this.client}addTransportListeners(e){this._listenedTransports.has(e)||(this._listenedTransports.add(e),e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.on(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.on(`Target.targetDestroyed`,this.handleTargetDestroyed))}releaseLifecycleTransport(e){if(e!==this.localClient&&this._listenedTransports.has(e)){for(let t of this._sessions.values())if(t.transport===e)return;this._listenedTransports.delete(e),e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening),e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared),e.off(`Target.detachedFromTarget`,this.handleDetachedFromTarget),e.off(`Target.targetDestroyed`,this.handleTargetDestroyed)}}setClient(e){this.addTransportListeners(e),this.client=e}useLocalTransport(){let e=this.remoteTargetInfo;this.remoteTargetInfo=null,this.setClient(this.localClient),e&&([...this._sessions.values()].some(t=>t.remote?.runtimeId===e.runtimeId&&t.remote.localTargetId===e.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.runtimeId,e.localTargetId))}pruneAppliedSends(){if(this._appliedSends.size<=128)return;let e=new Set([...this._sessions.values()].map(e=>e.sessionId));for(let t of[...this._appliedSends.keys()])e.has(t)||this._appliedSends.delete(t)}rememberSession(e,t){this.addTransportListeners(t.transport),this.pruneAppliedSends(),this._sessions.set(e,t),this.enforceSessionCap(e)}enforceSessionCap(e){for(;this._sessions.size>32;){let t;for(let n of this._sessions.keys())if(!(n===e||this._pinnedTargets.has(n))){t=n;break}if(t===void 0)return;let n=this._sessions.get(t);this._sessions.delete(t),n&&(ca.debug(`Evicting least-recently-used CDP session`,{targetId:t}),this.detachSession(t,n))}}pinTarget(e){this._pinnedTargets.set(e,(this._pinnedTargets.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(this._pinnedTargets.get(e)??1)-1;n>0?this._pinnedTargets.set(e,n):this._pinnedTargets.delete(e),this.enforceSessionCap()}}activateSession(e,t){t.remote?(this.setClient(t.transport),this.remoteTargetInfo={...t.remote}):this.client!==t.transport&&this.useLocalTransport(),this.sessionId=t.sessionId,this.attachedTargetId=e,this._sessions.delete(e),this._sessions.set(e,t)}notifySessionChange(e,t){let n=this.accountedTransportFor(t.transport);this._onSessionChange?.(t.sessionId,n,e);let r=this._sessionReplacedSubs.get(e);if(r)for(let i of[...r])try{i(t.sessionId,n,e)}catch(t){ca.warn(`session-replaced subscriber threw`,{targetId:e,error:t instanceof Error?t.message:String(t)})}}forgetSession(e,t){this.unregisterSession(e),this.disposeSessionTransport(t)}unregisterSession(e){let t=this._sessions.get(e);t&&this.dropFrameContexts(t.sessionId),this._sessions.delete(e),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disposeSessionTransport(e){this.releaseLifecycleTransport(e.transport),e.remote&&([...this._sessions.values()].some(t=>t.remote?.runtimeId===e.remote?.runtimeId&&t.remote?.localTargetId===e.remote?.localTargetId)||this.trayTargetProvider?.removeRemoteTransport?.(e.remote.runtimeId,e.remote.localTargetId))}async detachSession(e,t){this.unregisterSession(e);try{await t.transport.send(`Target.detachFromTarget`,{sessionId:t.sessionId})}catch{}finally{this.disposeSessionTransport(t)}}async dropSession(e){let t=this._sessions.get(e);if(!t){this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null);return}await this.detachSession(e,t)}invalidateSession(e){let t=this._sessions.get(e);t&&this.forgetSession(e,t)}clearSessionsForTransport(e){for(let[t,n]of[...this._sessions])n.transport===e&&this.forgetSession(t,n)}clearSessions(){for(let[e,t]of[...this._sessions])this.forgetSession(e,t);this._sessions.clear(),this.sessionId=null,this.attachedTargetId=null}};const ga=new Set([`normal`,`minimized`,`maximized`,`fullscreen`]);function _a(e){let t=e.indexOf(`:`);return t>=0?e.substring(t+1):e}function va(e){let t=e.state;if(!(!t||t===`normal`)){if(!ga.has(t))throw Error(`window state must be one of ${[...ga].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 ya(e){return typeof e==`object`&&!!e}function ba(e){let t=ya(e)?e:{},n=t.windowState??t.state,r=typeof n==`string`&&ga.has(n)?n:`normal`;return{left:xa(t.left,0),top:xa(t.top,0),width:xa(t.width,0),height:xa(t.height,0),state:r}}function xa(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}const Sa=_(`panel-rpc-cdp`);var Ca=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=>{Sa.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){Sa.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=>{Sa.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=>{Sa.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function wa(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 Ca(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 Ta(e){return`slicc_feature_flags_remote:${e}`}let Ea=null;function Da(e,t){let n=ka(t);Ea=e,je(e,Aa(n,e)??{})}function Oa(e,t){if(!Ea||e!==void 0&&e!==Ta(Ea))return!1;let n=ka(t);return Ae(Ea,Aa(n,Ea)??{}),!0}function ka(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 Aa(e,t){try{let n=e?.getItem(Ta(t));return n?ja(JSON.parse(n)):null}catch{return null}}function ja(e){return!Ma(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function Ma(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Na=_(`stale-asset`),Pa=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function Fa(e){return Pa.test(e)}let Ia=null;function La(e){if(!e){Ia=null;return}Ia=e}function Ra(e=!1){if(!Ia||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:Ia,replayTurn:e})}finally{t.close()}}function za(e){Fa(e instanceof Error?e.message:String(e))&&Ra()}function Ba(e,t){return!e||e===t?!1:(Na.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),Ra(),!0)}var Va=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new Ei;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 Di(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 Ha(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 Ua(e){let t=Ha(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var Wa=class extends Va{constructor(e){let t=Ha(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 Ga(e,t){return e.find(e=>e.folder===t)??e.find(e=>e.folder===`${t}-scoop`)??e.find(e=>e.name===t)}const Ka=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function qa(e){return Ka.test(e)}function Ja(e,t){return`(${e} && ${t})`}function j(e,t){return`(${e} || ${t})`}function Ya(e){return`!(${e})`}function Xa(e){return`Array.isArray(${e})`}function Za(e){return`typeof ${e} === "bigint"`}function Qa(e){return`typeof ${e} === "boolean"`}function $a(e){return`Number.isInteger(${e})`}function eo(e){return`${e} === null`}function to(e){return`Number.isFinite(${e})`}function no(e){return Ja(ro(e),Ya(Xa(e)))}function ro(e){return`typeof ${e} === "object" && ${e} !== null`}function io(e){return`typeof ${e} === "string"`}function ao(e){return`typeof ${e} === "symbol"`}function oo(e){return`${e} === undefined`}function so(e){return`typeof ${e} === "function"`}function co(e){return`Guard.IsConstructor(${e})`}function lo(e,t){return`${e} === ${t}`}function uo(e,t){return`${e} > ${t}`}function fo(e,t){return`${e} < ${t}`}function po(e,t){return`${e} <= ${t}`}function mo(e,t){return`${e} >= ${t}`}function ho(e,t){return`Guard.IsMinLength(${e}, ${t})`}function go(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function _o(e,t,n,r){return T(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 vo(e){return`Object.entries(${e})`}function yo(e){return`Object.getOwnPropertyNames(${e})`}function bo(e,t){return T(t,`"__proto__"`)||T(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function xo(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function So(e){return`[${e.join(`, `)}]`}function Co(e,t){return`((${e.join(`, `)}) => ${t})`}function M(e,t){return`${e}(${t.join(`, `)})`}function wo(e,t){return`new ${e}(${t.join(`, `)})`}function N(e,t){return`${e}${qa(t)?`.${t}`:`[${P(t)}]`}`}function P(e){return v(e)?JSON.stringify(e):`${e}`}function To(e,t,n){return`(${e} ? ${t} : ${n})`}function Eo(e){return`{ ${e.join(`; `)}; }`}function Do(e,t){return`const ${e} = ${t}`}function Oo(e,t){return`if(${e}) { ${t} }`}function ko(e){return`return ${e}`}function Ao(e){return T(e.length,0)?`true`:e.reduce((e,t)=>Ja(e,t))}function jo(e){return T(e.length,0)?`false`:e.reduce((e,t)=>j(e,t))}function Mo(e){return`++${e}`}function No(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Po=rt;function Fo(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let Io;function Lo(){try{return zo(`null`)(),!0}catch{return!1}}function Ro(){return C(Io)&&(Io=Lo()),Io&&Yt().useAcceleration}function zo(...e){return new globalThis.Function(...e)}function Bo(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 Vo=Bo;function Ho(){return Vo}const Uo=[/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],Wo=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Go(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!Wo.some(t=>t.test(e.errorMessage))&&Uo.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 Ko(e){return D(e,`~refine`)&&S(e[`~refine`])&&x(e[`~refine`],0,e=>b(e)&&D(e,`check`)&&D(e,`error`)&&Bt(e.check)&&Bt(e.error))}function qo(e){return b(e)&&!S(e)}function Jo(e){return Zt(e)}function F(e){return qo(e)||Jo(e)}function Yo(e){return D(e,`additionalItems`)&&F(e.additionalItems)}function Xo(e){return D(e,`additionalProperties`)&&F(e.additionalProperties)}function Zo(e){return D(e,`allOf`)&&S(e.allOf)&&e.allOf.every(e=>F(e))}function Qo(e){return D(e,`$anchor`)&&v(e.$anchor)}function $o(e){return D(e,`anyOf`)&&S(e.anyOf)&&e.anyOf.every(e=>F(e))}function es(e){return D(e,`const`)}function ts(e){return D(e,`contains`)&&F(e.contains)}function ns(e){return D(e,`default`)}function rs(e){return D(e,`dependencies`)&&b(e.dependencies)&&Object.values(e.dependencies).every(e=>F(e)||S(e)&&e.every(e=>v(e)))}function is(e){return D(e,`dependentRequired`)&&b(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>S(e)&&e.every(e=>v(e)))}function as(e){return D(e,`dependentSchemas`)&&b(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>F(e))}function os(e){return D(e,`$dynamicAnchor`)&&v(e.$dynamicAnchor)}function ss(e){return D(e,`$dynamicRef`)&&v(e.$dynamicRef)}function cs(e){return D(e,`else`)&&F(e.else)}function ls(e){return D(e,`enum`)&&S(e.enum)}function us(e){return D(e,`exclusiveMaximum`)&&(O(e.exclusiveMaximum)||Rt(e.exclusiveMaximum))}function ds(e){return D(e,`exclusiveMinimum`)&&(O(e.exclusiveMinimum)||Rt(e.exclusiveMinimum))}function fs(e){return D(e,`format`)&&v(e.format)}function ps(e){return D(e,`$id`)&&v(e.$id)}function ms(e){return D(e,`if`)&&F(e.if)}function hs(e){return D(e,`items`)&&(F(e.items)||S(e.items)&&e.items.every(e=>F(e)))}function gs(e){return hs(e)&&S(e.items)}function _s(e){return D(e,`maximum`)&&(O(e.maximum)||Rt(e.maximum))}function vs(e){return D(e,`maxContains`)&&O(e.maxContains)}function ys(e){return D(e,`maxItems`)&&O(e.maxItems)}function bs(e){return D(e,`maxLength`)&&O(e.maxLength)}function xs(e){return D(e,`maxProperties`)&&O(e.maxProperties)}function Ss(e){return D(e,`minimum`)&&(O(e.minimum)||Rt(e.minimum))}function Cs(e){return D(e,`minContains`)&&O(e.minContains)}function ws(e){return D(e,`minItems`)&&O(e.minItems)}function Ts(e){return D(e,`minLength`)&&O(e.minLength)}function Es(e){return D(e,`minProperties`)&&O(e.minProperties)}function Ds(e){return D(e,`multipleOf`)&&(O(e.multipleOf)||Rt(e.multipleOf))}function Os(e){return D(e,`not`)&&F(e.not)}function ks(e){return D(e,`oneOf`)&&S(e.oneOf)&&e.oneOf.every(e=>F(e))}function As(e){return D(e,`pattern`)&&(v(e.pattern)||e.pattern instanceof RegExp)}function js(e){return D(e,`patternProperties`)&&b(e.patternProperties)&&Object.values(e.patternProperties).every(e=>F(e))}function Ms(e){return D(e,`prefixItems`)&&S(e.prefixItems)&&e.prefixItems.every(e=>F(e))}function Ns(e){return D(e,`properties`)&&b(e.properties)&&Object.values(e.properties).every(e=>F(e))}function Ps(e){return D(e,`propertyNames`)&&(b(e.propertyNames)||F(e.propertyNames))}function Fs(e){return D(e,`$recursiveAnchor`)&&Zt(e.$recursiveAnchor)}function Is(e){return Fs(e)&&T(e.$recursiveAnchor,!0)}function Ls(e){return D(e,`$recursiveRef`)&&v(e.$recursiveRef)}function Rs(e){return D(e,`$ref`)&&v(e.$ref)}function zs(e){return D(e,`required`)&&S(e.required)&&e.required.every(e=>v(e))}function Bs(e){return D(e,`then`)&&F(e.then)}function Vs(e){return D(e,`type`)&&(v(e.type)||S(e.type)&&e.type.every(e=>v(e)))}function Hs(e){return D(e,`uniqueItems`)&&Zt(e.uniqueItems)}function Us(e){return D(e,`unevaluatedItems`)&&F(e.unevaluatedItems)}function Ws(e){return D(e,`unevaluatedProperties`)&&F(e.unevaluatedProperties)}function Gs(e){return Us(e)||Ws(e)||y(e).some(t=>qs(e[t]))}function Ks(e){return e.some(e=>qs(e))}function qs(e){return S(e)?Ks(e):b(e)?Gs(e):!1}function Js(e,t){return qs(t)||y(e).some(t=>qs(e[t]))}var Ys=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return M(N(`context`,`Push`),[])}Pop(){return M(N(`context`,`Pop`),[])}AddIndex(e){return M(N(`context`,`AddIndex`),[e])}AddKey(e){return M(N(`context`,`AddKey`),[e])}Merge(e){return M(N(`context`,`Merge`),[e])}},Xs=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}},Zs=class extends Xs{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Qs=class extends Zs{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const $s={identifier:`External`,variables:[]};function ec(e){let t=`External[${$s.variables.length}]`;return $s.variables.push(e),t}function tc(){$s.variables=[]}function nc(){return{...$s}}function rc(e,t,n,r){return _o(ec(n[`~refine`].map(e=>e)),P(0),[`refinement`,`_`],M(N(`refinement`,`check`),[r]))}function ic(e,t,n,r){return x(n[`~refine`],0,(e,t)=>e.check(r))}function ac(e,t,n,r,i,a){return w(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let oc=0;function I(){return`var_${oc++}`}function sc(e){return hs(e)&&S(e.items)}function cc(e,t,n,r){if(!sc(n))return P(!0);let[i,a]=[I(),I()],o=If(e,t,n.additionalItems,i),s=fo(a,P(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?j(s,Ja(o,c)):j(s,o);return M(N(r,`every`),[Co([i,a],l)])}function lc(e,t,n,r){return!sc(n)||r.every((r,i)=>an(i,n.items.length)||Lf(e,t,n.additionalItems,r)&&t.AddIndex(i))}function uc(e,t,n,r,i,a){return!sc(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return an(o,i.items.length)||Rf(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function dc(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function fc(e){let t=[];return js(e)&&t.push(...y(e.patternProperties)),Ns(e)&&t.push(...y(e.properties).map(dc)),T(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function pc(e,t,n){return zs(t)&&Ns(t)&&!js(t)&&T(t.additionalProperties,!1)&&T(y(t.properties).length,t.required.length)}function mc(e,t,n){return lo(N(M(N(`Object`,`getOwnPropertyNames`),[n]),`length`),P(t.required.length))}function hc(e,t,n,r){let[i,a]=[I(),I()],o=ec(new RegExp(fc(n))),s=If(e,t,n.additionalProperties,`${r}[${i}]`),c=M(N(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?j(c,Ja(s,l)):j(c,s);return _o(yo(r),P(0),[i,a],u)}function gc(e,t,n,r){return pc(t,n,r)?mc(t,n,r):hc(e,t,n,r)}function _c(e,t,n,r){let i=new RegExp(fc(n));return x(y(r),0,(a,o)=>i.test(a)||Lf(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function vc(e,t,n,r,i,a){let o=new RegExp(fc(i)),s=[];return w(y(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new Qs,p=o.test(c)||Rf(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 yc(e,t,n,r,i){let a=Do(`results`,`[]`),o=n.map((e,t)=>Do(`context_${t}`,wo(`CheckContext`,[]))),s=n.map((n,i)=>Do(`condition_${i}`,M(Co([`context`],R(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>Oo(`condition_${t}`,M(N(`results`,`push`),[`context_${t}`]))),l=ko(Ja(i,t.Merge(`results`)));return M(Co([],Eo([a,...o,...s,...c,l])),[])}function bc(e,t,n,r){return yc(e,t,n.allOf,r,lo(N(`results`,`length`),P(n.allOf.length)))}function xc(e,t,n,r){return Ao(n.allOf.map(n=>R(e,t,n,r)))}function Sc(e,t,n,r){return t.UseUnevaluated()?bc(e,t,n,r):xc(e,t,n,r)}function Cc(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new Xs;return z(e,i,n,r)?[...t,i]:t},[]);return T(i.length,n.allOf.length)&&t.Merge(i)}function wc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new Qs,u=B(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=T(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function Tc(e,t,n,r){return yc(e,t,n.anyOf,r,uo(N(`results`,`length`),P(0)))}function Ec(e,t,n,r){return jo(n.anyOf.map(n=>R(e,t,n,r)))}function Dc(e,t,n,r){return t.UseUnevaluated()?Tc(e,t,n,r):Ec(e,t,n,r)}function Oc(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new Xs;return z(e,i,n,r)?[...t,i]:t},[]);return kt(i.length,0)&&t.Merge(i)}function kc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new Qs,l=B(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=kt(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 Ac(e,t,n,r){return P(!!n)}function jc(e,t,n,r){return n}function Mc(e,t,n,r,i,a){return jc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function Nc(e,t,n,r){return Ft(n.const)?lo(r,P(n.const)):xo(r,ec(n.const))}function Pc(e,t,n,r){return Ft(n.const)?T(r,n.const):Dt(r,n.const)}function Fc(e,t,n,r,i,a){return Pc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Ic(e){return!(Cs(e)&&T(e.minContains,0))}function Lc(e,t,n,r){if(!Ic(n))return P(!0);let i=I();return Ja(Ya(lo(N(r,`length`),P(0))),M(N(r,`some`),[Co([i],R(e,t,n.contains,i))]))}function Rc(e,t,n,r){return!Ic(n)||!T(r.length,0)&&r.some(r=>z(e,t,n.contains,r))}function zc(e,t,n,r,i,a){return Rc(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Bc(e,t,n,r){return j(lo(N(yo(r),`length`),P(0)),Ao(E(n.dependencies).map(([n,i])=>{let a=Ya(bo(r,P(n))),o=R(e,t,i,r);return j(a,S(i)?(e=>Ao(e.map(e=>bo(r,P(e)))))(i):o)})))}function Vc(e,t,n,r){let i=T(y(r).length,0),a=x(E(n.dependencies),0,([n,i])=>!D(r,n)||(S(i)?i.every(e=>D(r,e)):z(e,t,i,r)));return i||a}function Hc(e,t,n,r,i,a){let o=T(y(a).length,0),s=w(E(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!D(a,i)||(S(o)?o.every(e=>D(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 Uc(e,t,n,r){return j(lo(N(yo(r),`length`),P(0)),Ao(E(n.dependentRequired).map(([e,t])=>j(Ya(bo(r,P(e))),Ao(t.map(e=>bo(r,P(e))))))))}function Wc(e,t,n,r){let i=T(y(r).length,0),a=x(E(n.dependentRequired),0,([e,t])=>!D(r,e)||t.every(e=>D(r,e)));return i||a}function Gc(e,t,n,r,i,a){let o=T(y(a).length,0),s=w(E(i.dependentRequired),0,([e,i])=>!D(a,e)||w(i,0,o=>D(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function Kc(e,t,n,r){return j(lo(N(yo(r),`length`),P(0)),Ao(E(n.dependentSchemas).map(([n,i])=>j(Ya(bo(r,P(n))),R(e,t,i,r)))))}function qc(e,t,n,r){let i=T(y(r).length,0),a=x(E(n.dependentSchemas),0,([n,i])=>!D(r,n)||z(e,t,i,r));return i||a}function Jc(e,t,n,r,i,a){let o=T(y(a).length,0),s=w(E(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!D(a,i)||B(e,t,s,r,o,a)});return o||s}function Yc(e,t,n,r){return Jf(e,t,e.DynamicRef(n)??!1,r)}function Xc(e,t,n,r){let i=e.DynamicRef(n)??!1;return F(i)&&z(e,t,i,r)}function Zc(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return F(o)&&B(e,t,`#`,r,o,a)}function Qc(e,t,n,r){return jo(n.enum.map(e=>Ft(e)?lo(r,P(e)):xo(r,ec(e))))}function $c(e,t,n,r){return n.enum.some(e=>Ft(e)?T(r,e):Dt(r,e))}function el(e,t,n,r,i,a){return $c(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function tl(e,t,n,r){return fo(r,P(n.exclusiveMaximum))}function nl(e,t,n,r){return an(r,n.exclusiveMaximum)}function rl(e,t,n,r,i,a){return nl(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function il(e,t,n,r){return uo(r,P(n.exclusiveMinimum))}function al(e,t,n,r){return kt(r,n.exclusiveMinimum)}function ol(e,t,n,r,i,a){return al(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const sl=[0,31,28,31,30,31,30,31,31,30,31,30,31],cl=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function ll(e){return e%4==0&&(e%100!=0||e%400==0)}function ul(e){let t=cl.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&&ll(n)?29:sl[r])}const dl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function fl(e,t=!0){let n=dl.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 pl(e,t=!0){let n=e.split(/T/i);return n.length===2&&ul(n[0])&&fl(n[1],t)}const ml=/^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 hl(e){return ml.test(e)}const gl=/^(?!.*\.\.)[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 _l(e){return gl.test(e)}function vl(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 yl(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)Ze();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=vl(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function bl(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function xl(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function Sl(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function Cl(e){return bl(e)||xl(e)||Sl(e)}const wl=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),Tl=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 El(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function Dl(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function Ol(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function kl(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function Al(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function jl(e){return e>=1632&&e<=1641}function Ml(e){return e>=1776&&e<=1785}function Nl(e){return Tl.has(e)}function Pl(e){if(e.length===0)return Ze();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||Cl(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(wl.has(n))return!1;(Ol(n)||kl(n)||Al(n))&&(r=!0),jl(n)&&(i=!0),Ml(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||!El(s))return!1;break;case 1523:case 1524:if(o===void 0||!Dl(o))return!1;break;case 8204:if(o===void 0||o<128&&!Nl(o))return!1;break;case 8205:if(o===void 0||!Nl(o))return!1}}return!(e.includes(`・`)&&!r||i&&a)}function Fl(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 Il(e){return e.toLowerCase().startsWith(`xn--`)}function Ll(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=yl(t);return n?Pl(n):!1}catch{return!1}}function Rl(e){return e.length===0||e.length>63?!1:Il(e)?Ll(e):Pl(e)}function zl(e){return e.length===0||e.length>63?!1:Il(e)?Ll(e):Fl(e)}function Bl(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!zl(t))return!1;return!0}const Vl=/^(?!.*\.\.)[\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 Hl(e){return Vl.test(e)}function Ul(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(!Rl(e))return!1;return!0}function Wl(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 Gl(e){return Wl(e,0,e.length)}function Kl(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ql(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&&Kl(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!Wl(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 Jl(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function Yl(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))?Jl(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:Jl(e)}function Xl(e){try{return new URL(e),!0}catch{return!1}}const Zl=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Ql(e){return Zl.test(e)}const $l=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function eu(e){return $l.test(e)}function tu(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const nu=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function ru(e){return nu.test(e)}const iu=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function au(e){return iu.test(e)}const ou=/^(?:(?:[^\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 su(e){return ou.test(e)}function cu(e){return e>=97&&e<=122||e>=65&&e<=90}function lu(e){return cu(e)||e>=48&&e<=57}function uu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function du(e){return lu(e)||e===43||e===45||e===46}function fu(e){return lu(e)||e===45||e===46||e===95||e===126}function pu(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 mu(e){return fu(e)||pu(e)||e===58||e===64}function hu(e){let t=e.length;if(t===0||!cu(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!du(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||!uu(e.charCodeAt(t+1))||!uu(e.charCodeAt(t+2)))return!1;t+=2}else if(!fu(n)&&!pu(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&&!fu(t)&&!pu(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||!uu(e.charCodeAt(n+1))||!uu(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(mu(r)||r===47||r===63||r===35))return!1;n++}return!0}const gu=/^(?: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 _u(e){return gu.test(e)}const vu=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function yu(e){return vu.test(e)}const L=new Map;function bu(){L.clear()}function xu(){return[...L.entries()]}function Su(e,t){L.set(e,t)}function Cu(e){return L.has(e)}function wu(e){return L.get(e)}function Tu(e,t){return L.get(e)?.(t)??!0}function Eu(){bu(),L.set(`date-time`,pl),L.set(`date`,ul),L.set(`duration`,hl),L.set(`email`,_l),L.set(`hostname`,Bl),L.set(`idn-email`,Hl),L.set(`idn-hostname`,Ul),L.set(`ipv4`,Gl),L.set(`ipv6`,ql),L.set(`iri-reference`,Yl),L.set(`iri`,Xl),L.set(`json-pointer-uri-fragment`,Ql),L.set(`json-pointer`,eu),L.set(`regex`,tu),L.set(`relative-json-pointer`,ru),L.set(`time`,fl),L.set(`uri-reference`,au),L.set(`uri-template`,su),L.set(`uri`,hu),L.set(`url`,_u),L.set(`uuid`,yu)}Eu();var Du=e({Clear:()=>bu,Entries:()=>xu,Get:()=>wu,Has:()=>Cu,IsDate:()=>ul,IsDateTime:()=>pl,IsDuration:()=>hl,IsEmail:()=>_l,IsHostname:()=>Bl,IsIPv4:()=>Gl,IsIPv6:()=>ql,IsIdnEmail:()=>Hl,IsIdnHostname:()=>Ul,IsIri:()=>Xl,IsIriReference:()=>Yl,IsJsonPointer:()=>eu,IsJsonPointerUriFragment:()=>Ql,IsRegex:()=>tu,IsRelativeJsonPointer:()=>ru,IsTime:()=>fl,IsUri:()=>hu,IsUriReference:()=>au,IsUriTemplate:()=>su,IsUrl:()=>_u,IsUuid:()=>yu,Reset:()=>Eu,Set:()=>Su,Test:()=>Tu});function Ou(e,t,n,r){return M(N(`Format`,`Test`),[P(n.format),r])}function ku(e,t,n,r){return Tu(n.format,r)}function Au(e,t,n,r,i,a){return ku(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function ju(e,t,n,r){let i=!Bs(n)||n.then,a=!cs(n)||n.else;return To(R(e,t,n.if,r),R(e,t,i,r),R(e,t,a,r))}function Mu(e,t,n,r){let i=!Bs(n)||n.then,a=!cs(n)||n.else;return z(e,t,n.if,r)?z(e,t,i,r):z(e,t,a,r)}function Nu(e,t,n,r,i,a){let o=!Bs(i)||i.then,s=!cs(i)||i.else,c=new Qs,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 Pu(e,t,n,r){return Ao(n.items.map((n,i)=>{let a=po(N(r,`length`),P(i)),o=If(e,t,n,`${r}[${i}]`),s=t.AddIndex(P(i));return j(a,t.UseUnevaluated()?Ja(o,s):o)}))}function Fu(e,t,n,r){return x(n.items,0,(n,i)=>$t(r.length,i)||Lf(e,t,n,r[i])&&t.AddIndex(i))}function Iu(e,t,n,r,i,a){return w(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return $t(a.length,o)||Rf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Lu(e,t,n,r){let i=Ms(n)?n.prefixItems.length:0,a=If(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?Ja(a,o):a;return _o(r,P(i),[`element`,`index`],s)}function Ru(e,t,n,r){let i=Ms(n)?n.prefixItems.length:0;return x(r,i,(r,i)=>Lf(e,t,n.items,r)&&t.AddIndex(i))}function zu(e,t,n,r,i,a){let o=Ms(i)?i.prefixItems.length:0;return w(a,o,(a,o)=>Rf(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function Bu(e,t,n,r){return gs(n)?Pu(e,t,n,r):Lu(e,t,n,r)}function Vu(e,t,n,r){return gs(n)?Fu(e,t,n,r):Ru(e,t,n,r)}function Hu(e,t,n,r,i,a){return gs(i)?Iu(e,t,n,r,i,a):zu(e,t,n,r,i,a)}function Uu(e){return ts(e)}function Wu(e,t,n,r){if(!Uu(n))return P(!0);let[i,a]=[I(),I()];return po(M(N(r,`reduce`),[Co([i,a],To(R(e,t,n.contains,a),Mo(i),i)),P(0)]),P(n.maxContains))}function Gu(e,t,n,r){if(!Uu(n))return!0;let i=r.reduce((r,i)=>z(e,t,n.contains,i)?++r:r,0);return $t(i,n.maxContains)}function Ku(e,t,n,r,i,a){let o=Cs(i)?i.minContains:1;return Gu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function qu(e,t,n,r){return po(r,P(n.maximum))}function Ju(e,t,n,r){return $t(r,n.maximum)}function Yu(e,t,n,r,i,a){return Ju(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function Xu(e,t,n,r){return po(N(r,`length`),P(n.maxItems))}function Zu(e,t,n,r){return $t(r.length,n.maxItems)}function Qu(e,t,n,r,i,a){return Zu(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function $u(e,t,n,r){return go(r,P(n.maxLength))}function ed(e,t,n,r){return xt(r,n.maxLength)}function td(e,t,n,r,i,a){return ed(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function nd(e,t,n,r){return po(N(yo(r),`length`),P(n.maxProperties))}function rd(e,t,n,r){return $t(y(r).length,n.maxProperties)}function id(e,t,n,r,i,a){return rd(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function ad(e){return ts(e)}function od(e,t,n,r){if(!ad(n))return P(!0);let[i,a]=[I(),I()];return mo(M(N(r,`reduce`),[Co([i,a],To(R(e,t,n.contains,a),Mo(i),i)),P(0)]),P(n.minContains))}function sd(e,t,n,r){if(!ad(n))return!0;let i=r.reduce((r,i)=>z(e,t,n.contains,i)?++r:r,0);return jt(i,n.minContains)}function cd(e,t,n,r,i,a){return sd(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function ld(e,t,n,r){return mo(r,P(n.minimum))}function ud(e,t,n,r){return jt(r,n.minimum)}function dd(e,t,n,r,i,a){return ud(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function fd(e,t,n,r){return mo(N(r,`length`),P(n.minItems))}function pd(e,t,n,r){return jt(r.length,n.minItems)}function md(e,t,n,r,i,a){return pd(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function hd(e,t,n,r){return ho(r,P(n.minLength))}function gd(e,t,n,r){return nn(r,n.minLength)}function _d(e,t,n,r,i,a){return gd(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function vd(e,t,n,r){return mo(N(yo(r),`length`),P(n.minProperties))}function yd(e,t,n,r){return jt(y(r).length,n.minProperties)}function bd(e,t,n,r,i,a){return yd(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function xd(e,t,n,r){return No(r,P(n.multipleOf))}function Sd(e,t,n,r){return lt(r,n.multipleOf)}function Cd(e,t,n,r,i,a){return Sd(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function wd(e,t,n,r){return yc(e,t,[n.not],r,Ya(lo(N(`results`,`length`),P(1))))}function Td(e,t,n,r){return Ya(R(e,t,n.not,r))}function Ed(e,t,n,r){return t.UseUnevaluated()?wd(e,t,n,r):Td(e,t,n,r)}function Dd(e,t,n,r){let i=new Xs;return!z(e,i,n.not,r)&&t.Merge([i])}function Od(e,t,n,r,i,a){return Dd(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function kd(e,t,n,r){return yc(e,t,n.oneOf,r,lo(N(`results`,`length`),P(1)))}function Ad(e,t,n,r){return lo(M(N(So(n.oneOf.map(n=>R(e,t,n,r))),`reduce`),[Co([`count`,`result`],To(lo(`result`,P(!0)),Mo(`count`),`count`)),P(0)]),P(1))}function jd(e,t,n,r){return t.UseUnevaluated()?kd(e,t,n,r):Ad(e,t,n,r)}function Md(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new Xs;return z(e,i,n,r)?[...t,i]:t},[]);return T(i.length,1)&&t.Merge(i)}function Nd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new Qs,u=B(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=T(c.length,1)&&t.Merge(c);return!l&&T(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 Pd(e,t,n,r){return M(N(ec(v(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function Fd(e,t,n,r){return(v(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function Id(e,t,n,r,i,a){return Fd(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function Ld(e,t,n,r){return Ao(E(n.patternProperties).map(([n,i])=>{let[a,o]=[I(),I()],s=Ya(M(N(ec(new RegExp(n,`u`)),`test`),[a])),c=If(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?j(s,Ja(c,l)):j(s,c);return _o(vo(r),P(0),[`[${a}, ${o}]`,`_`],u)}))}function Rd(e,t,n,r){return x(E(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return x(E(r),0,([n,r])=>!a.test(n)||Lf(e,t,i,r)&&t.AddKey(n))})}function zd(e,t,n,r,i,a){return w(E(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return w(E(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||Rf(e,t,s,a,o,i)&&t.AddKey(n)})})}function Bd(e,t,n,r){return Ao(n.prefixItems.map((n,i)=>{let a=po(N(r,`length`),P(i)),o=If(e,t,n,`${r}[${i}]`),s=t.AddIndex(P(i));return j(a,t.UseUnevaluated()?Ja(o,s):o)}))}function Vd(e,t,n,r){return T(r.length,0)||x(n.prefixItems,0,(n,i)=>$t(r.length,i)||Lf(e,t,n,r[i])&&t.AddIndex(i))}function Hd(e,t,n,r,i,a){return T(a.length,0)||w(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return $t(a.length,o)||Rf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Ud(e,t){return e.includes(t)||Yt().exactOptionalPropertyTypes}function Wd(e,t){return oo(N(e,t))}function Gd(e,t){return C(e[t])}function Kd(e,t,n,r){let i=zs(n)?n.required:[];return Ao(E(n.properties).map(([n,a])=>{let o=Ya(bo(r,P(n))),s=If(e,t,a,N(r,n)),c=t.AddKey(P(n)),l=t.UseUnevaluated()?Ja(s,c):s,u=i.includes(n)?l:j(o,l);return Ud(i,n)?u:j(Wd(r,n),u)}))}function qd(e,t,n,r){let i=zs(n)?n.required:[];return x(E(n.properties),0,([n,a])=>{let o=!D(r,n)||Lf(e,t,a,r[n])&&t.AddKey(n);return Ud(i,n)?o:Gd(r,n)||o})}function Jd(e,t,n,r,i,a){let o=zs(i)?i.required:[];return w(E(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!D(a,i)||Rf(e,t,c,l,s,a[i])&&t.AddKey(i);return Ud(o,i)?u():Gd(a,i)||u()})}function Yd(e,t,n,r){let[i,a]=[I(),I()];return _o(yo(r),P(0),[i,a],R(e,t,n.propertyNames,i))}function Xd(e,t,n,r){return x(y(r),0,(r,i)=>z(e,t,n.propertyNames,r))}function Zd(e,t,n,r,i,a){let o=[];return w(y(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=B(e,new Qs,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Qd(e,t,n,r){return Jf(e,t,e.RecursiveRef(n)??!1,r)}function $d(e,t,n,r){let i=e.RecursiveRef(n)??!1;return F(i)&&z(e,t,i,r)}function ef(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return F(o)&&B(e,t,`#`,r,o,a)}function tf(e,t,n,r){let i=Co([`context`,`value`],Jf(e,t,n,`value`));return M(Co([`context`,`value`],Eo([Do(`nextContext`,wo(`CheckContext`,[])),Do(`result`,M(i,[`nextContext`,`value`])),Oo(`result`,t.Merge(`[nextContext]`)),ko(`result`)])),[`context`,r])}function nf(e,t,n,r){return Jf(e,t,n,r)}function rf(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?tf(e,t,i,r):nf(e,t,i,r)}function af(e,t,n,r){let i=e.Ref(n)??!1,a=new Xs,o=F(i)&&z(e,a,i,r);return o&&t.Merge([a]),o}function of(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new Qs,c=F(o)&&B(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function sf(e,t,n,r){return Ao(n.required.map(e=>bo(r,P(e))))}function cf(e,t,n,r){return x(n.required,0,e=>D(r,e))}function lf(e,t,n,r,i,a){let o=[];return w(i.required,0,e=>{let t=D(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function uf(e,t,n,r){return T(n,`object`)?no(r):T(n,`array`)?Xa(r):T(n,`boolean`)?Qa(r):T(n,`integer`)?$a(r):T(n,`number`)?to(r):T(n,`null`)?eo(r):T(n,`string`)?io(r):T(n,`bigint`)?Za(r):T(n,`constructor`)?co(r):T(n,`function`)?so(r):T(n,`symbol`)?ao(r):T(n,`undefined`)||T(n,`void`)?oo(r):P(!0)}function df(e,t,n,r,i){return T(n,`object`)?Je(i):T(n,`array`)?S(i):T(n,`boolean`)?Zt(i):T(n,`integer`)?vt(i):T(n,`number`)?O(i):T(n,`null`)?Ge(i):T(n,`string`)?v(i):T(n,`bigint`)?Rt(i):T(n,`constructor`)?wt(i):T(n,`function`)?Bt(i):T(n,`symbol`)?at(i):T(n,`undefined`)?C(i):!T(n,`void`)||C(i)}function ff(e,t,n,r){return jo(n.map(n=>uf(e,t,n,r)))}function pf(e,t,n,r,i){return n.some(n=>df(e,t,n,r,i))}function mf(e,t,n,r){return S(n.type)?ff(e,t,n.type,r):uf(e,t,n.type,r)}function hf(e,t,n,r){return S(n.type)?pf(e,t,n.type,n,r):df(e,t,n.type,n,r)}function gf(e,t,n,r,i,a){return(S(i.type)?pf(e,t,i.type,i,a):df(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function _f(e,t,n,r){let[i,a]=[I(),I()],o=M(N(`context`,`GetIndices`),[]),s=M(N(`indices`,`has`),[i]),c=R(e,t,n.unevaluatedItems,a),l=M(N(`context`,`AddIndex`),[i]),u=_o(r,P(0),[a,i],Ja(j(s,c),l));return M(Co([`context`],Eo([Do(`indices`,o),ko(u)])),[`context`])}function vf(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 yf(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return w(a,0,(a,c)=>{let l=new Qs,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 bf(e,t,n,r){let[i,a]=[I(),I()],o=M(N(`context`,`GetKeys`),[]),s=M(N(`keys`,`has`),[i]),c=M(N(`context`,`AddKey`),[i]),l=R(e,t,n.unevaluatedProperties,a),u=_o(vo(r),P(0),[`[${i}, ${a}]`,`_`],j(s,Ja(l,c)));return M(Co([`context`],Eo([Do(`keys`,o),ko(u)])),[`context`])}function xf(e,t,n,r){let i=t.GetKeys();return x(E(r),0,([r,a])=>i.has(r)||z(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function Sf(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return w(E(a),0,([a,c])=>{let l=new Qs,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 Cf(e){return!T(e.uniqueItems,!1)}function wf(e,t,n,r){return Cf(n)?lo(N(wo(`Set`,[M(N(r,`map`),[N(`Hashing`,`Hash`)])]),`size`),N(r,`length`)):P(!0)}function Tf(e,t,n,r){if(!Cf(n))return!0;let i=new Set(r.map(ot)).size,a=r.length;return T(i,a)}function Ef(e,t,n,r,i,a){if(!Cf(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=ot(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return T(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function Df(e,t){return Vs(e)&&(S(e.type)&&kt(e.type.length,0)&&x(e.type,0,e=>T(e,t))||T(e.type,t))}function Of(e){return Df(e,`object`)}function kf(e){return qo(e)&&(Xo(e)||rs(e)||is(e)||as(e)||Ns(e)||js(e)||Ps(e)||Es(e)||xs(e)||zs(e)||Ws(e))}function Af(e){return Df(e,`array`)}function jf(e){return qo(e)&&(Yo(e)||hs(e)||ts(e)||vs(e)||ys(e)||Cs(e)||ws(e)||Ms(e)||Us(e)||Hs(e))}function Mf(e){return Df(e,`string`)}function Nf(e){return qo(e)&&(Ts(e)||bs(e)||fs(e)||As(e))}function Pf(e){return Df(e,`number`)||Df(e,`bigint`)}function Ff(e){return qo(e)&&(Ss(e)||_s(e)||us(e)||ds(e)||Ds(e))}function If(e,t,n,r){return t.UseUnevaluated()?Ja(Ja(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(Jo(n))return Ac(e,t,n,r);if(Vs(n)&&i.push(mf(e,t,n,r)),kf(n)){let a=[];zs(n)&&a.push(sf(e,t,n,r)),Xo(n)&&a.push(gc(e,t,n,r)),rs(n)&&a.push(Bc(e,t,n,r)),is(n)&&a.push(Uc(e,t,n,r)),as(n)&&a.push(Kc(e,t,n,r)),js(n)&&a.push(Ld(e,t,n,r)),Ns(n)&&a.push(Kd(e,t,n,r)),Ps(n)&&a.push(Yd(e,t,n,r)),Es(n)&&a.push(vd(e,t,n,r)),xs(n)&&a.push(nd(e,t,n,r));let o=Ao(a),s=j(Ya(no(r)),o);i.push(Of(n)?o:s)}if(jf(n)){let a=[];Yo(n)&&a.push(cc(e,t,n,r)),ts(n)&&a.push(Lc(e,t,n,r)),hs(n)&&a.push(Bu(e,t,n,r)),vs(n)&&a.push(Wu(e,t,n,r)),ys(n)&&a.push(Xu(e,t,n,r)),Cs(n)&&a.push(od(e,t,n,r)),ws(n)&&a.push(fd(e,t,n,r)),Ms(n)&&a.push(Bd(e,t,n,r)),Hs(n)&&a.push(wf(e,t,n,r));let o=Ao(a),s=j(Ya(Xa(r)),o);i.push(Af(n)?o:s)}if(Nf(n)){let a=[];bs(n)&&a.push($u(e,t,n,r)),Ts(n)&&a.push(hd(e,t,n,r)),fs(n)&&a.push(Ou(e,t,n,r)),As(n)&&a.push(Pd(e,t,n,r));let o=Ao(a),s=j(Ya(io(r)),o);i.push(Mf(n)?o:s)}if(Ff(n)){let a=[];us(n)&&a.push(tl(e,t,n,r)),ds(n)&&a.push(il(e,t,n,r)),_s(n)&&a.push(qu(e,t,n,r)),Ss(n)&&a.push(ld(e,t,n,r)),Ds(n)&&a.push(xd(e,t,n,r));let o=Ao(a),s=j(Ya(j(to(r),Za(r))),o);i.push(Pf(n)?o:s)}Rs(n)&&i.push(rf(e,t,n,r)),Ls(n)&&i.push(Qd(e,t,n,r)),ss(n)&&i.push(Yc(e,t,n,r)),es(n)&&i.push(Nc(e,t,n,r)),ls(n)&&i.push(Qc(e,t,n,r)),ms(n)&&i.push(ju(e,t,n,r)),Os(n)&&i.push(Ed(e,t,n,r)),Zo(n)&&i.push(Sc(e,t,n,r)),$o(n)&&i.push(Dc(e,t,n,r)),ks(n)&&i.push(jd(e,t,n,r)),Us(n)&&i.push(j(Ya(Xa(r)),_f(e,t,n,r))),Ws(n)&&i.push(j(Ya(ro(r)),bf(e,t,n,r))),Ko(n)&&i.push(rc(e,t,n,r));let a=Ao(i);return e.Pop(n),a}function Lf(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=Jo(n)?jc(e,t,n,r):(!Vs(n)||hf(e,t,n,r))&&(!(b(r)&&!S(r))||(!zs(n)||cf(e,t,n,r))&&(!Xo(n)||_c(e,t,n,r))&&(!rs(n)||Vc(e,t,n,r))&&(!is(n)||Wc(e,t,n,r))&&(!as(n)||qc(e,t,n,r))&&(!js(n)||Rd(e,t,n,r))&&(!Ns(n)||qd(e,t,n,r))&&(!Ps(n)||Xd(e,t,n,r))&&(!Es(n)||yd(e,t,n,r))&&(!xs(n)||rd(e,t,n,r)))&&(!S(r)||(!Yo(n)||lc(e,t,n,r))&&(!ts(n)||Rc(e,t,n,r))&&(!hs(n)||Vu(e,t,n,r))&&(!vs(n)||Gu(e,t,n,r))&&(!ys(n)||Zu(e,t,n,r))&&(!Cs(n)||sd(e,t,n,r))&&(!ws(n)||pd(e,t,n,r))&&(!Ms(n)||Vd(e,t,n,r))&&(!Hs(n)||Tf(e,t,n,r)))&&(!v(r)||(!bs(n)||ed(e,t,n,r))&&(!Ts(n)||gd(e,t,n,r))&&(!fs(n)||ku(e,t,n,r))&&(!As(n)||Fd(e,t,n,r)))&&(!(O(r)||Rt(r))||(!us(n)||nl(e,t,n,r))&&(!ds(n)||al(e,t,n,r))&&(!_s(n)||Ju(e,t,n,r))&&(!Ss(n)||ud(e,t,n,r))&&(!Ds(n)||Sd(e,t,n,r)))&&(!Rs(n)||af(e,t,n,r))&&(!Ls(n)||$d(e,t,n,r))&&(!ss(n)||Xc(e,t,n,r))&&(!es(n)||Pc(e,t,n,r))&&(!ls(n)||$c(e,t,n,r))&&(!ms(n)||Mu(e,t,n,r))&&(!Os(n)||Dd(e,t,n,r))&&(!Zo(n)||Cc(e,t,n,r))&&(!$o(n)||Oc(e,t,n,r))&&(!ks(n)||Md(e,t,n,r))&&(!Us(n)||!S(r)||vf(e,t,n,r))&&(!Ws(n)||!b(r)||xf(e,t,n,r))&&(!Ko(n)||ic(e,t,n,r));return e.Pop(n),i}function Rf(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=Jo(i)?Mc(e,t,n,r,i,a):!!((!Vs(i)||gf(e,t,n,r,i,a))&+(!(b(a)&&!S(a))||!!((!zs(i)||lf(e,t,n,r,i,a))&+(!Xo(i)||vc(e,t,n,r,i,a))&(!rs(i)||Hc(e,t,n,r,i,a))&(!is(i)||Gc(e,t,n,r,i,a))&(!as(i)||Jc(e,t,n,r,i,a))&(!js(i)||zd(e,t,n,r,i,a))&(!Ns(i)||Jd(e,t,n,r,i,a))&(!Ps(i)||Zd(e,t,n,r,i,a))&(!Es(i)||bd(e,t,n,r,i,a))&(!xs(i)||id(e,t,n,r,i,a))))&(!S(a)||!!((!Yo(i)||uc(e,t,n,r,i,a))&+(!ts(i)||zc(e,t,n,r,i,a))&(!hs(i)||Hu(e,t,n,r,i,a))&(!vs(i)||Ku(e,t,n,r,i,a))&(!ys(i)||Qu(e,t,n,r,i,a))&(!Cs(i)||cd(e,t,n,r,i,a))&(!ws(i)||md(e,t,n,r,i,a))&(!Ms(i)||Hd(e,t,n,r,i,a))&(!Hs(i)||Ef(e,t,n,r,i,a))))&(!v(a)||!!((!bs(i)||td(e,t,n,r,i,a))&+(!Ts(i)||_d(e,t,n,r,i,a))&(!fs(i)||Au(e,t,n,r,i,a))&(!As(i)||Id(e,t,n,r,i,a))))&(!(O(a)||Rt(a))||!!((!us(i)||rl(e,t,n,r,i,a))&+(!ds(i)||ol(e,t,n,r,i,a))&(!_s(i)||Yu(e,t,n,r,i,a))&(!Ss(i)||dd(e,t,n,r,i,a))&(!Ds(i)||Cd(e,t,n,r,i,a))))&(!Rs(i)||of(e,t,n,r,i,a))&(!Ls(i)||ef(e,t,n,r,i,a))&(!ss(i)||Zc(e,t,n,r,i,a))&(!es(i)||Fc(e,t,n,r,i,a))&(!ls(i)||el(e,t,n,r,i,a))&(!ms(i)||Nu(e,t,n,r,i,a))&(!Os(i)||Od(e,t,n,r,i,a))&(!Zo(i)||wc(e,t,n,r,i,a))&(!$o(i)||kc(e,t,n,r,i,a))&(!ks(i)||Nd(e,t,n,r,i,a))&(!Us(i)||!S(a)||yf(e,t,n,r,i,a))&(!Ws(i)||!b(a)||Sf(e,t,n,r,i,a)))&&(!Ko(i)||ac(e,t,n,r,i,a));return e.Pop(i),o}const zf=[0],Bf=new Map,Vf=new Map;function Hf(){return ot(zf[0]++)}function Uf(e,t){Bf.has(e)||Bf.set(e,new Map);let n=Bf.get(e);if(n.has(t))return n.get(t);let r=Hf();return n.set(t,r),r}function Wf(e,t,n,r){return e.UseUnevaluated()?M(`check_${n}`,[`context`,r]):M(`check_${n}`,[r])}function Gf(e,t,n,r){let i=R(e,t,n,`value`);return t.UseUnevaluated()?Do(`check_${r}`,Co([`context`,`value`],i)):Do(`check_${r}`,Co([`value`],i))}function Kf(){zf[0]=0,Bf.clear(),Vf.clear()}function qf(){return[...Vf.values()]}function Jf(e,t,n,r){let i=Uf(n,e.BaseURL().href),a=Wf(t,n,i,r);return Vf.has(i)?a:(Vf.set(i,``),Vf.set(i,Gf(e,t,n,i)),a)}function Yf(e,t){return b(t)&&!He(e)?t[e]:void 0}function Xf(e,t){return e.reduce((e,t)=>Yf(t,e),t)}function Zf(e){if(T(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 Qf(e,t){return Xf(Zf(t),e)}function $f(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(T(r.pathname,i.pathname))return n.hash.startsWith(`#`)?np(e,t,n):e}function ep(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return T(r.href,i.href)?e:void 0}function tp(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return T(r.href,i.href)?e:void 0}function np(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 Qf(e,r)}function rp(e,t,n){if(ps(e)){let r=$f(e,t,n);if(!C(r))return r}if(Qo(e)){let r=ep(e,t,n);if(!C(r))return r}if(os(e)){let r=tp(e,t,n);if(!C(r))return r}return np(e,t,n)}function ip(e,t,n){return e.reduce((e,r)=>{let i=op(r,t,n);return C(i)?e:i},void 0)}function ap(e,t,n){return y(e).reduce((r,i)=>{let a=op(e[i],t,n);return C(a)?r:a},void 0)}function op(e,t,n){let r=qo(e)&&ps(e)?new URL(e.$id,t.href):t;if(qo(e)){let t=rp(e,r,n);if(!C(t))return t}if(S(e))return ip(e,r,n);if(b(e))return ap(e,r,n)}function sp(e,t){let n=new URL(`http://unknown/`),r=ps(e)?new URL(e.$id,n.href):n;return op(e,r,new URL(t,r.href))}function cp(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?sp(t,n.$dynamicRef):sp(e,n.$dynamicRef);if(!C(i))return!qo(i)||!os(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var lp=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)},up,dp,fp,pp,mp,hp=class{constructor(e,t){up.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){qo(e)&&(ps(e)&&(this.ids.push(e),lp(this,up,`m`,dp).call(this,e)),Qo(e)&&this.anchors.push(e),Is(e)&&this.recursiveAnchors.push(e),os(e)&&this.dynamicAnchors.push(e))}Pop(e){qo(e)&&(ps(e)&&(this.ids.pop(),lp(this,up,`m`,fp).call(this,e)),Qo(e)&&this.anchors.pop(),Is(e)&&this.recursiveAnchors.pop(),os(e)&&this.dynamicAnchors.pop())}Ref(e){return lp(this,up,`m`,pp).call(this,e)??lp(this,up,`m`,mp).call(this,e)}RecursiveRef(e){return Is(this.Base())?sp(this.recursiveAnchors[0],e.$recursiveRef):sp(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return cp(t,this.Base(),e,this.dynamicAnchors)}};up=new WeakSet,dp=function e(t,n=!0){if(!qo(t))return;let r=t;if(!(!n&&ps(r))){!n&&os(r)&&this.dynamicAnchors.push(r);for(let t of y(r))lp(this,up,`m`,e).call(this,r[t],!1)}},fp=function e(t,n=!0){if(!qo(t))return;let r=t;if(!(!n&&ps(r))){!n&&os(r)&&this.dynamicAnchors.pop();for(let t of y(r))lp(this,up,`m`,e).call(this,r[t],!1)}},pp=function(e){return D(this.context,e.$ref)?this.context[e.$ref]:void 0},mp=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?sp(this.Base(),e.$ref):sp(t,e.$ref)};function gp(e){return`${e.Functions().join(`;
878
+ `)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function _p(e,t){return zo(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(Xs,rt,Du,Ye,e.External().variables)}function vp(e){let t=new hp(e.Context(),e.Schema()),n=new Xs;return r=>z(t,n,e.Schema(),r)}function yp(e,t){return Ro()?_p(e,t):vp(e)}var bp=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)}},xp=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=gp(this),t=yp(this,e);return new bp(Ro(),e,t)}};function Sp(...e){let[t,n]=Fo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});tc(),Kf();let r=new hp(t,n),i=new Ys(Js(t,n)),a=Jf(r,i,n,`value`),o=qf();return new xp(t,n,nc(),o,a,i.UseUnevaluated())}function Cp(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=Yt(),a=Ho(),o=[];return[B(new hp(t,n),new Zs(e=>{if(!jt(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function wp(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return z(new hp(t,n),new Xs,n,r)}function Tp(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return wp(t,n,r)}function Ep(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=Cp(t,n,r);return a}var Dp=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 Op(e,t,n){return S(n)?n.map(n=>zp(e,t.items,n)):n}function kp(e,t,n){return zp({...e,...t.$defs},Qe(t.$ref),n)}function Ap(e,t){let n=D(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=Kt(e,t),i=Vt(r);return Xe(i)?Mt(i,n):i}function jp(e,t,n){return zp(e,Ap(e,t),n)}function Mp(e){return D(e,`additionalProperties`)?e.additionalProperties:void 0}function Np(e,t,n){if(!b(n)||S(n))return n;let r=Mp(t);for(let i of y(n)){if(D(t.properties,i)){n[i]=zp(e,t.properties[i],n[i]);continue}if(Zt(r)&&T(r,!0)||Tt(r)&&Tp(e,r,n[i])){n[i]=zp(e,r,n[i]);continue}delete n[i]}return n}function Pp(e,t,n){if(!b(n))return n;let r=Mp(t),[i,a]=[new RegExp(Ct(t)),Et(t)];for(let t of y(n)){if(i.test(t)){n[t]=zp(e,a,n[t]);continue}if(Zt(r)&&T(r,!0)||Tt(r)&&Tp(e,r,n[t])){n[t]=zp(e,r,n[t]);continue}delete n[t]}return n}function Fp(e,t,n){return D(e,t.$ref)?zp(e,e[t.$ref],n):n}function Ip(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]=zp(e,t.items[i],n[i]);return kt(n.length,r)?n.slice(0,r):n}function Lp(e){return Ht(e)}function Rp(e,t,n){for(let r of t.anyOf){let t=zp(e,r,Lp(n));if(Tp(e,r,t))return t}return n}function zp(e,t,n){return st(t)?Op(e,t,n):Ue(t)?kp(e,t,n):ct(t)?jp(e,t,n):Xe(t)?Np(e,t,n):St(t)?Pp(e,t,n):Gt(t)?Fp(e,t,n):Wt(t)?Ip(e,t,n):Ot(t)?Rp(e,t,n):n}function Bp(e,t){for(let n of Po.Keys(e))Po.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function Vp(e){let t={};for(let n of Po.Keys(e))t[n]=Wp(e[n]);return t}function Hp(e){return Up(Jt(e))}function Up(e){return e.map(e=>Wp(e))}function Wp(e){return Bp(e,st(e)?Be(Wp(e.items),gt(e)):ct(e)?et(Up(e.allOf)):Ot(e)?_t(Hp(e.anyOf)):Xe(e)?dt(Vp(e.properties)):St(e)?Lt(Xt(e),Wp(Et(e))):Wt(e)?zt(Up(e.items)):e)}function Gp(e){return Wp(e)}function Kp(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return zp(t,Yt().unionPrioritySort?Gp(n):n,r)}function qp(e){return b(e)&&D(e,`value`)}function V(e){return{value:e}}function Jp(e){return S(e)?V(e):V([e])}function Yp(e){return T(e,!0)?V(BigInt(1)):V(BigInt(0))}const Xp=/^-?(0|[1-9]\d*)n$/,Zp=/^-?(0|[1-9]\d*)\.\d+$/,Qp=/^-?(0|[1-9]\d*)$/;function $p(e){return Xp.test(e)}function em(e){return Zp.test(e)}function tm(e){return Qp.test(e)}function nm(e){let t=e.toLowerCase();return $p(e)?V(BigInt(e.slice(0,e.length-1))):em(e)?V(BigInt(e.split(`.`)[0])):tm(e)?V(BigInt(e)):T(t,`false`)?V(BigInt(0)):T(t,`true`)?V(BigInt(1)):void 0}function rm(e){return Rt(e)?V(e):Zt(e)?Yp(e):O(e)?V(BigInt(Math.trunc(e))):Ge(e)?V(BigInt(0)):v(e)?nm(e):C(e)?V(BigInt(0)):void 0}function im(e){return T(e,BigInt(0))?V(!1):T(e,BigInt(1))?V(!0):void 0}function am(e){return T(e,0)?V(!1):T(e,1)?V(!0):void 0}function om(e){return T(e.toLowerCase(),`false`)?V(!1):T(e.toLowerCase(),`true`)?V(!0):T(e,`0`)?V(!1):T(e,`1`)?V(!0):void 0}function sm(e){return Rt(e)?im(e):Zt(e)?V(e):O(e)?am(e):Ge(e)?V(!1):v(e)?om(e):C(e)?V(!1):void 0}function cm(e){return T(e,BigInt(0))?V(null):void 0}function lm(e){return T(e,!1)?V(null):void 0}function um(e){return T(e,0)?V(null):void 0}function dm(e){let t=e.toLowerCase();return T(t,`undefined`)||T(t,`null`)||T(e,``)||T(e,`0`)?V(null):void 0}function fm(e){return Rt(e)?cm(e):Zt(e)?lm(e):O(e)?um(e):Ge(e)?V(null):v(e)?dm(e):C(e)?V(null):void 0}const pm=BigInt(2**53-1),mm=BigInt(-(2**53-1));function hm(e){return e<=pm&&e>=mm?V(Number(e)):void 0}function gm(e){return V(+!!e)}function _m(e){let t=+e;if(O(t))return V(t);let n=e.toLowerCase();if(T(n,`false`))return V(0);if(T(n,`true`))return V(1);let r=rm(e);if(qp(r))return r.value<=pm&&r.value>=mm?V(Number(r.value)):void 0}function vm(e){return Rt(e)?hm(e):Zt(e)?gm(e):O(e)?V(e):Ge(e)?V(0):v(e)?_m(e):C(e)?V(0):void 0}function ym(e){return Rt(e)||Zt(e)||O(e)?V(e.toString()):Ge(e)?V(`null`):v(e)?V(e):C(e)?V(``):void 0}function bm(e){return T(e,BigInt(0))?V(void 0):void 0}function xm(e){return T(e,!1)?V(void 0):void 0}function Sm(e){return T(e,0)?V(void 0):void 0}function Cm(e){let t=e.toLowerCase();return T(t,`undefined`)||T(t,`null`)||T(e,``)||T(e,`0`)?V(void 0):void 0}function wm(e){return Rt(e)?bm(e):Zt(e)?xm(e):O(e)?Sm(e):Ge(e)?V(void 0):v(e)?Cm(e):C(e)?V(e):void 0}function Tm(e,t,n){return Jp(n).value.map(n=>Qm(e,t.items,n))}function Em(e,t,n){let r=rm(n);return qp(r)?r.value:n}function Dm(e,t,n){let r=sm(n);return qp(r)?r.value:n}function Om(e,t,n){return Qm({...e,...t.$defs},Qe(t.$ref),n)}function km(e,t,n){return Qm(e,Vt(t),n)}function Am(e,t,n){let r=vm(n);return qp(r)?Math.trunc(r.value):n}function jm(e,t,n){let r=Kt(e,t);return Qm(e,Vt(r),n)}function Mm(e,t,n){let r=rm(n);return qp(r)&&T(t.const,r.value)?r.value:n}function Nm(e,t,n){let r=sm(n);return qp(r)&&T(t.const,r.value)?r.value:n}function Pm(e,t,n){let r=vm(n);return qp(r)&&T(t.const,r.value)?r.value:n}function Fm(e,t,n){let r=ym(n);return qp(r)&&T(t.const,r.value)?r.value:n}function Im(e,t,n){return T(t.const,n)?n:ut(t)?Mm(e,t,n):qe(t)?Nm(e,t,n):Ke(t)?Pm(e,t,n):it(t)?Fm(e,t,n):Ze()}function Lm(e,t,n){let r=fm(n);return qp(r)?r.value:n}function Rm(e,t,n){let r=vm(n);return qp(r)?r.value:n}function zm(e,t,n,r){let i=y(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=Qm(e,n,r[t]));return r}function Bm(e,t,n){return pt(e)&&C(n[t])}function Vm(e,t,n){let r=Nt(t.properties),i=y(n);for(let[t,a]of r)for(let r of i)!t.test(r)||Bm(a,r,n)||(n[r]=Qm(e,a,n[r]));return D(t,`additionalProperties`)&&b(t.additionalProperties)?zm(e,r,t.additionalProperties,n):n}function Hm(e,t,n){return Je(n)?Vm(e,t,n):n}function Um(e,t,n){let r=Nt(t.patternProperties),i=y(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=Qm(e,a,n[r]));return D(t,`additionalProperties`)&&b(t.additionalProperties)?zm(e,r,t.additionalProperties,n):n}function Wm(e,t,n){return Je(n)?Um(e,t,n):n}function Gm(e,t,n){return D(e,t.$ref)?Qm(e,e[t.$ref],n):n}function Km(e,t,n){let r=ym(n);return qp(r)?r.value:n}function qm(e,t,n){return Qm(e,Vt(t),n)}function Jm(e,t,n){if(!S(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=Qm(e,t.items[r],n[r]);return n}function Ym(e,t,n){let r=wm(n);return qp(r)?r.value:n}function Xm(e,t,n){if(t.anyOf.some(t=>Tp(e,t,n)))return n;let r=t.anyOf.map(t=>Qm(e,t,Lp(n))).find(n=>Tp(e,t,n));return C(r)?n:r}function Zm(e,t,n){return qp(wm(n))?void 0:n}function Qm(e,t,n){return st(t)?Tm(e,t,n):tt(t)?Em(e,t,n):Pt(t)?Dm(e,t,n):Ue(t)?Om(e,t,n):on(t)?km(e,t,n):Ve(t)?Am(e,t,n):ct(t)?jm(e,t,n):en(t)?Im(e,t,n):We(t)?Lm(e,t,n):tn(t)?Rm(e,t,n):Xe(t)?Hm(e,t,n):St(t)?Wm(e,t,n):Gt(t)?Gm(e,t,n):Qt(t)?Km(e,t,n):yt(t)?qm(e,t,n):Wt(t)?Jm(e,t,n):qt(t)?Ym(e,t,n):Ot(t)?Xm(e,t,n):Ut(t)?Zm(e,t,n):n}function $m(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Qm(t,n,r)}function eh(e,t,n){if(!S(n))return n;for(let r=0;r<n.length;r++)n[r]=lh(e,t.items,n[r]);return n}function th(e,t,n){return lh({...e,...t.$defs},Qe(t.$ref),n)}function nh(e,t){return C(t)?Bt(e.default)?e.default():Lp(e.default):t}function rh(e,t,n){let r=Kt(e,t);return lh(e,Vt(r),n)}function ih(e,t,n){if(!b(n))return n;let r=y(t.properties);for(let i of r){let r=lh(e,t.properties[i],n[i]);C(r)&&(pt(t.properties[i])||!D(t.properties[i],`default`))||(n[i]=r)}if(!Xo(t)||Zt(t.additionalProperties))return n;for(let i of y(n))r.includes(i)||(n[i]=lh(e,t.additionalProperties,n[i]));return n}function ah(e,t,n){if(!b(n))return n;let[r,i]=[new RegExp(Ct(t)),Et(t)];for(let t of y(n))r.test(t)&&ns(i)&&(n[t]=lh(e,i,n[t]));if(!Xo(t))return n;for(let i of y(n))r.test(i)||(n[i]=lh(e,t.additionalProperties,n[i]));return n}function oh(e,t,n){return D(e,t.$ref)?lh(e,e[t.$ref],n):n}function sh(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]=lh(e,r[t],n[t]));return n}function ch(e,t,n){for(let r of t.anyOf){let t=lh(e,r,Lp(n));if(Tp(e,r,t))return t}return n}function lh(e,t,n){let r=ns(t)?nh(t,n):n;return st(t)?eh(e,t,r):Ue(t)?th(e,t,r):ct(t)?rh(e,t,r):Xe(t)?ih(e,t,r):St(t)?ah(e,t,r):Gt(t)?oh(e,t,r):Wt(t)?sh(e,t,r):Ot(t)?ch(e,t,r):r}function uh(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return lh(t,n,r)}function dh(e){return(...t)=>{let[n,r,i]=Fo(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function fh(e,t,n){return t[`~codec`].decode(n)}function ph(e,t,n){return t[`~codec`].encode(n)}function H(e,t,n,r){return nt(n)?T(e,`Decode`)?fh(t,n,r):ph(t,n,r):r}function mh(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 hh(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 gh(e,t,n,r){return T(e,`Decode`)?mh(e,t,n,r):hh(e,t,n,r)}function _h(e,t,n,r){return r=U(e,{...t,...n.$defs},Qe(n.$ref),r),H(e,t,n,r)}function vh(e){return e.reduce((e,t)=>({...e,...t}),{})}function yh(e,t){for(let n of t)if(!Dt(e,n))return n;return e}function bh(e,t,n,r){if(T(n.allOf.length,0))return H(e,t,n,r);let i=n.allOf.map(n=>U(e,t,n,Kp(n,Lp(r))));return H(e,t,n,i.every(e=>b(e))?vh(i):yh(r,i))}function xh(e,t,n,r){if(T(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,Kp(n,Lp(i))));return a.every(e=>b(e))?vh(a):yh(i,a)}function Sh(e,t,n,r){return T(e,`Decode`)?bh(e,t,n,r):xh(e,t,n,r)}function Ch(e,t,n,r){if(!Je(r))return r;for(let i of y(n.properties))!D(r,i)||Bm(n.properties[i],i,r)||(r[i]=U(e,t,n.properties[i],r[i]));return H(e,t,n,r)}function wh(e,t,n,r){let i=H(e,t,n,r);if(!Je(i))return i;for(let r of y(n.properties))!D(i,r)||Bm(n.properties[r],r,i)||(i[r]=U(e,t,n.properties[r],i[r]));return i}function Th(e,t,n,r){return T(e,`Decode`)?Ch(e,t,n,r):wh(e,t,n,r)}function Eh(e,t,n,r){if(!Je(r))return r;let i=new RegExp(Ct(n));for(let a of y(r))i.test(a)&&(r[a]=U(e,t,Et(n),r[a]));return H(e,t,n,r)}function Dh(e,t,n,r){let i=H(e,t,n,r);if(!Je(i))return i;let a=new RegExp(Ct(n));for(let r of y(i))a.test(r)&&(i[r]=U(e,t,Et(n),i[r]));return i}function Oh(e,t,n,r){return T(e,`Decode`)?Eh(e,t,n,r):Dh(e,t,n,r)}function kh(e,t,n,r){return D(t,n.$ref)?U(e,t,t[n.$ref],r):r}function Ah(e,t,n,r){return T(e,`Decode`)?H(e,t,n,kh(e,t,n,r)):kh(e,t,n,H(e,t,n,r))}function jh(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 Mh(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 Nh(e,t,n,r){return T(e,`Decode`)?jh(e,t,n,r):Mh(e,t,n,r)}function Ph(e,t,n,r){for(let i of n.anyOf)if(Tp(t,i,r))return H(e,t,n,U(e,t,i,r));return r}function Fh(e,t,n,r){let i=H(e,t,n,r);for(let r of n.anyOf){let n=U(e,t,r,Lp(i));if(Tp(t,r,n))return n}return i}function Ih(e,t,n,r){return T(e,`Decode`)?Ph(e,t,n,r):Fh(e,t,n,r)}function U(e,t,n,r){return st(n)?gh(e,t,n,r):Ue(n)?_h(e,t,n,r):ct(n)?Sh(e,t,n,r):Xe(n)?Th(e,t,n,r):St(n)?Oh(e,t,n,r):Gt(n)?Ah(e,t,n,r):Wt(n)?Nh(e,t,n,r):Ot(n)?Ih(e,t,n,r):H(e,t,n,r)}var Lh=class extends Dp{constructor(e,t){super(`Decode`,e,t)}};function Rh(e,t,n){if(!Tp(e,t,n))throw new Lh(n,Ep(e,t,n));return n}function zh(e,t,n){return U(`Decode`,e,Yt().unionPrioritySort?Gp(t):t,n)}const Bh=dh([(e,t,n)=>Lp(n),(e,t,n)=>uh(e,t,n),(e,t,n)=>$m(e,t,n),(e,t,n)=>Kp(e,t,n),(e,t,n)=>Rh(e,t,n),(e,t,n)=>zh(e,t,n)]);function Vh(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Bh(t,n,r)}var Hh=class extends Dp{constructor(e,t){super(`Encode`,e,t)}};function Uh(e,t,n){if(!Tp(e,t,n))throw new Hh(n,Ep(e,t,n));return n}function Wh(e,t,n){return U(`Encode`,e,Yt().unionPrioritySort?Gp(t):t,n)}const Gh=dh([(e,t,n)=>Lp(n),(e,t,n)=>Wh(e,t,n),(e,t,n)=>uh(e,t,n),(e,t,n)=>$m(e,t,n),(e,t,n)=>Kp(e,t,n),(e,t,n)=>Uh(e,t,n)]);function Kh(...e){let[t,n,r]=Fo(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Gh(t,n,r)}function qh(e,t){return nt(t)||tg(e,t.items)}function Jh(e,t){return nt(t)||Qh({...e,...t.$defs},Qe(t.$ref))}function Yh(e,t){return nt(t)||t.allOf.some(t=>tg(e,t))}function Xh(e,t){return nt(t)||y(t.properties).some(n=>tg(e,t.properties[n]))}function Zh(e,t){return nt(t)||tg(e,Et(t))}function Qh(e,t){return!ng.has(t.$ref)&&(ng.add(t.$ref),nt(t)||D(e,t.$ref)&&tg(e,e[t.$ref]))}function $h(e,t){return nt(t)||t.items.some(t=>tg(e,t))}function eg(e,t){return nt(t)||t.anyOf.some(t=>tg(e,t))}function tg(e,t){return st(t)?qh(e,t):Ue(t)?Jh(e,t):ct(t)?Yh(e,t):Xe(t)?Xh(e,t):St(t)?Zh(e,t):Gt(t)?Qh(e,t):Wt(t)?$h(e,t):Ot(t)?eg(e,t):nt(t)}const ng=new Set;function rg(...e){let[t,n]=Fo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return ng.clear(),tg(t,n)}var ig=class extends Error{constructor(e,t){super(t),this.type=e}};function ag(e,t){return Bt(t.default)?t.default(t):b(t.default)?Lp(t.default):t.default}function og(e,t){if(Hs(t)&&!ns(t))throw new ig(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=ws(t)?t.minItems:0;return Array.from({length:n},()=>Dg(e,t.items))}function sg(e,t){return ds(t)?BigInt(t.exclusiveMinimum)+BigInt(1):Ss(t)?BigInt(t.minimum):BigInt(0)}function cg(e,t){return!1}function lg(e,t){let n=Dg(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function ug(e,t){return Dg({...e,...t.$defs},Qe(t.$ref))}function dg(e,t){return Dg(e,Vt(t))}function fg(e,t){let n=Dg(e,t.returnType);return()=>n}function pg(e,t){return ds(t)&&O(t.exclusiveMinimum)?t.exclusiveMinimum+1:Ss(t)?t.minimum:0}function mg(e,t){let n=Kt(e,t);return Dg(e,Vt(n))}function hg(e,t){return t.const}function gg(e,t){throw new ig(t,`Cannot create TNever types`)}function _g(e,t){return null}function vg(e,t){return ds(t)&&O(t.exclusiveMinimum)?t.exclusiveMinimum+1:Ss(t)?t.minimum:0}function yg(e,t){return(C(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:Dg(e,t.properties[r])}),{})}function bg(e,t){if(Es(t)&&!ns(t))throw new ig(t,`Record with the minProperties constraint must have a default annotation`);return{}}function xg(e,t){return D(e,t.$ref)?Dg(e,e[t.$ref]):(()=>{throw new ig(t,`Unable to deref Ref`)})()}function Sg(e,t){if((As(t)||fs(t))&&!ns(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=Ts(t)?t.minLength:0;return``.padEnd(n)}function Cg(e,t){return Symbol()}function wg(e,t){let n=At(t.pattern);if(Qt(n))throw new ig(t,`Unable to create TemplateLiteral due to infinite type expansion`);return Dg(e,n)}function Tg(e,t){return Array.from({length:t.minItems},(n,r)=>Dg(e,t.items[r]))}function Eg(e,t){if(T(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return Dg(e,t.anyOf[0])}function Dg(e,t){return ns(t)?ag(e,t):st(t)?og(e,t):tt(t)?sg(e,t):Pt(t)?cg(e,t):mt(t)?lg(e,t):Ue(t)?ug(e,t):on(t)?dg(e,t):ht(t)?fg(e,t):Ve(t)?pg(e,t):ct(t)?mg(e,t):en(t)?hg(e,t):$e(t)?gg(e,t):We(t)?_g(e,t):tn(t)?vg(e,t):Xe(t)?yg(e,t):St(t)?bg(e,t):Gt(t)?xg(e,t):Qt(t)?Sg(e,t):bt(t)?Cg(e,t):yt(t)?wg(e,t):Wt(t)?Tg(e,t):qt(t)?void 0:Ot(t)?Eg(e,t):(Ut(t),void 0)}function Og(...e){let[t,n]=Fo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Dg(t,n)}var kg=class extends Dp{constructor(e,t){super(`Parse`,e,t)}};function Ag(e,t,n){if(!Tp(e,t,n))throw new kg(n,Ep(e,t,n));return n}const jg=dh([(e,t,n)=>Lp(n),(e,t,n)=>uh(e,t,n),(e,t,n)=>$m(e,t,n),(e,t,n)=>Kp(e,t,n),(e,t,n)=>Ag(e,t,n)]),Mg=dt({type:It(`insert`),path:rn(),value:ft()}),Ng=Object({type:It(`update`),path:rn(),value:ft()}),Pg=dt({type:It(`delete`),path:rn()});_t([Mg,Ng,Pg]);var Fg=class{constructor(e,t){this.hasCodec=rg(e,t),this.buildResult=Sp(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(Yt().correctiveParse)return jg(this.Context(),this.Type(),e);throw new kg(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:Ep(this.Context(),this.Type(),e)}Clean(e){return Kp(this.Context(),this.Type(),e)}Convert(e){return $m(this.Context(),this.Type(),e)}Create(){return Og(this.Context(),this.Type())}Default(e){return uh(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Vh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Kh(this.Context(),this.Type(),e):this.Parse(e)}};function Ig(...e){let[t,n]=Fo(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new Fg(t,n)}const Lg=new WeakMap,Rg=Symbol.for(`TypeBox.Kind`);function zg(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function Bg(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 Vg(e){try{return Jg(e)}catch{return}}function Hg(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 Ug(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]=Kg(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=Kg(i,t.additionalProperties))}function Wg(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=Kg(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=Kg(e[n],t.items)}function Gg(e,t){for(let n of t)if(Vg(n)?.Check(e))return e;for(let n of t){let t=Kg(structuredClone(e),n);if(Vg(n)?.Check(t))return t}return e}function Kg(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=Kg(n,e);Array.isArray(t.anyOf)&&(n=Gg(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=Gg(n,t.oneOf));let r=zg(t),i=r.length>1&&r.some(e=>Bg(n,e));if(r.length>0&&!i)for(let e of r){let t=Hg(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&Ug(n,t),r.includes(`array`)&&Array.isArray(n)&&Wg(n,t),n}function qg(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&&qg(e[n],r)}else if(t.items)for(let n of e)qg(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`&&Vg(i)?.Check(null)===!1?delete n[e]:qg(n[e],i))}function Jg(e){let t=e,n=Lg.get(t);if(n)return n;let r=Ig(e);return Lg.set(t,r),r}function Yg(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 Xg(e,t){let n=structuredClone(t.arguments);qg(n,e.parameters),$m(e.parameters,n);let r=Jg(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Rg)){let t=Kg(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=>` - ${Yg(e)}: ${e.message}`).join(`
879
+ `)||`Unknown validation error`,a=`Validation failed for tool "${t.name}":\n${i}\n\nReceived arguments:\n${JSON.stringify(t.arguments,null,2)}`;throw Error(a)}function Zg(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function Qg(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 e_(s,o,n,i,r,a??Zg()),o}async function $g(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 e_(o,a,t,r,n,i??Zg()),a}async function e_(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 t_(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 n_(u,i):await r_(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 t_(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 n_(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:d_(`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 f_(e,t);let i=p_(e);await m_(i,t),n.push(i)}return{messages:n,terminate:!1}}async function r_(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?i_(e,t,a,n,r,i):a_(e,t,a,n,r,i)}async function i_(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 c_(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await u_(e,t,n,await l_(n,i,a),r,i),await f_(l,a);let u=p_(l);if(await m_(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:o_(o)}}async function a_(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 c_(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await f_(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{let o=await l_(n,i,a),s=await u_(e,t,n,o,r,i);return await f_(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=p_(e);await m_(t,a),c.push(t)}return{messages:c,terminate:o_(s)}}function o_(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function s_(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function c_(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:d_(`Tool ${n.name} not found`),isError:!0};try{let o=Xg(a,s_(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:d_(`Operation aborted`),isError:!0};if(a?.block){let e=d_(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:d_(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:d_(e instanceof Error?e.message:String(e)),isError:!0}}}async function l_(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:d_(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function u_(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=d_(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function d_(e){return{content:[{type:`text`,text:e}],details:{}}}async function f_(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function p_(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 m_(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function h_(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const g_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},__={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 v_(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??__,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 y_=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=[]}},b_=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=v_(t.initialState),this.convertToLlm=t.convertToLlm??h_,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??Zg(),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 y_(t.steeringMode??`one-at-a-time`),this.followUpQueue=new y_(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 Qg(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await $g(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:g_,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 x_(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 S_(e){let t=e.mimeType||`application/octet-stream`;return`${e.name} (${t}, ${x_(e.size)})`}function C_(e){let t=S_(e);return e.kind===`image`&&e.data?e.path?`[Attached image: ${t} — full-resolution copy saved to ${e.path}]`:`[Attached image: ${t}]`:e.kind===`text`&&e.text!==void 0?[`----- BEGIN ATTACHMENT ${t} -----`,e.text,`----- END ATTACHMENT ${e.name} -----`].join(`
880
+ `):e.path?`[Attached ${e.kind===`image`?`image`:e.kind===`text`?`text file`:`file`} saved to ${e.path} — ${t}. Read it from the virtual filesystem when you need its contents.]`:e.error?`[Attachment not included: ${t}. ${e.error}]`:`[Attachment not included: ${t}. Unsupported binary attachment.]`}function w_(e,t){if(!t?.length)return e;let n=t.map(C_),r=e.trim();return r?`${r}\n\n${n.join(`
881
881
 
882
882
  `)}`:n.join(`
883
883
 
884
- `)}function L_(e){return e?.length?e.filter(e=>e.kind===`image`&&e.data).map(e=>({type:`image`,data:e.data,mimeType:e.mimeType})):[]}const R_=`sessions`;function z_(){return new Promise((e,t)=>{let n=indexedDB.open(`agent-sessions`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(R_)||e.createObjectStore(R_,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var B_=class{dbPromise=null;getDB(){return this.dbPromise||=z_().then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise}async save(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(R_,`readwrite`).objectStore(R_).put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(R_,`readonly`).objectStore(R_).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async delete(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(R_,`readwrite`).objectStore(R_).delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async loadAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(R_,`readonly`).objectStore(R_).getAll();r.onsuccess=()=>t(r.result??[]),r.onerror=()=>n(r.error)})}async list(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(R_,`readonly`).objectStore(R_).getAll();r.onsuccess=()=>{t((r.result??[]).map(e=>({id:e.id,updatedAt:e.updatedAt})))},r.onerror=()=>n(r.error)})}async clearAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(R_,`readwrite`).objectStore(R_).clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}static newId(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}static createSession(e,t){let n=Date.now();return{id:e,messages:[],config:t,createdAt:n,updatedAt:n}}static updateMessages(e,t){return{...e,messages:t,updatedAt:Date.now()}}},V_=class{resolve;providerId;now;#e=null;#t=null;#n=null;#r=null;constructor(e,t,n=Date.now){this.resolve=e,this.providerId=t,this.now=n}#i(e){return e===`ok`?6e4:e===`unsupported`?18e5:3e5}isStale(){let e=this.#e;return!e||this.#t!==this.providerId()||this.now()-e.at>=this.#i(e.outcome)}snapshot(){return this.#t===this.providerId()?this.#e?.window??null:null}async refresh(e={}){if(!e.force&&!this.isStale())return this.snapshot();let t=this.providerId();return this.#n!==null&&this.#r===t?this.#n:(this.#n=this.resolve().then(e=>{let n=e?{...e,at:this.now()}:null;return this.#a(t,n?`ok`:`unsupported`,n),n}).catch(()=>{let e=this.snapshot();return this.#a(t,`failed`,e),e}).finally(()=>{this.#r===t&&(this.#n=null,this.#r=null)}),this.#r=t,this.#n)}#a(e,t,n){e===this.providerId()&&(this.#t=e,this.#e={outcome:t,window:n,at:this.now()})}clear(){this.#e=null,this.#t=null}},H_=e({clearBudgetWindowCache:()=>J_,getBudgetWindowSnapshot:()=>K_,refreshBudgetWindow:()=>q_});async function U_(){let e=ue();if(!e)return null;let t=Ae(e);if(!t?.getBudgetUsage)return null;let n=await t.getBudgetUsage();return n?{...n,providerId:e}:null}function W_(){try{return ue()}catch{return``}}const G_=new V_(U_,W_);function K_(){return G_.snapshot()}function q_(e){return G_.refresh(e)}function J_(){G_.clear()}const Y_=`abject.abortive.abrasive.absolute.abstruse.abundant.abyssal.accessible.acerbic.acrid.adamant.adept.adlerian.adornian.adroit.adventurous.aeolian.aerated.aesthetic.affable.aged.ageless.agile.airborne.airlocked.airy.akkadian.alabaster.alacritous.alert.alien.alloyed.allusive.aloof.alpha.alpine.alternate.altruistic.amaranthine.amber.ambidextrous.ambivalent.ambrosial.amiable.amorphous.ample.analog.analytical.ancestral.ancient.angelic.animated.animist.anomalous.antediluvian.antic.antlered.apollinairian.apollonian.apt.aquatic.arbitrary.arcadian.arcane.archaic.archimedean.ardent.arduous.arendtian.argent.argentine.argive.aristotelian.armstrongian.aromatic.arresting.artful.arthurian.articulate.artificial.artisanal.artless.ascetic.ashen.ashy.asimovian.aspiring.assiduous.assyrian.asteroidal.astral.astute.asynchronous.athenian.atlantean.atomic.attentive.attic.audacious.audenesque.augmented.august.augustan.aureate.auric.auroral.austenian.austere.austral.authentic.autonomous.autumnal.avalonian.avid.avuncular.aztec.azure.babbagean.babylonian.bacchic.bachian.bactrian.ballardian.ballistic.balmy.banksian.barefoot.barreled.barthesian.bartokian.bashy.baudelairean.bayesian.beatific.beckettesque.beckettian.beethovenian.beguiling.bellicose.bemused.benevolent.benign.benjaminian.bergmanesque.beta.bewitched.binary.bionic.bismarckian.bitter.bitwise.blackened.blakean.blameless.bland.blazar.blazing.blended.blessed.blissful.blistered.blithe.blooming.blunt.blustery.boeotian.boggy.bohrian.boingy.boisterous.bold.bolted.bombastic.bonny.boolean.boreal.borgesian.borgian.bosky.botticellian.bottled.bouncy.boundless.bountiful.bourbon.bradburyan.brahmsian.braised.brambly.brash.brave.brazen.bready.breathless.brechtian.breezy.briared.briery.bright.brilliant.brined.briny.brisk.bristling.briton.brittenesque.broadband.brontean.bronzed.brooding.browned.browningesque.brucknerian.brumal.brusque.bubbling.bubbly.bucolic.budding.bunuelian.buoyant.burnished.burnt.buttered.buttery.bygone.byronic.bytewise.byzantine.cacophonous.caesarean.callow.calm.candescent.candid.candied.canny.cantorian.capable.capricious.caramelized.caravaggesque.carbon.carefree.carolingian.cartesian.carved.casked.cast.cavafian.cavalier.celebrated.celestial.celtic.ceramic.cerebral.ceremonious.cerulean.cervantine.cezannesque.chagallian.chalky.chaplinesque.charcoal.charismatic.charmed.charming.charred.chaucerian.cheeky.cheerful.chekhovian.cherished.cherubic.chewy.chilled.chilly.chimerical.chipper.chirpy.chivalrous.chopinesque.chromospheric.chronal.chthonic.chubby.chunky.churchillian.cimmerian.cindered.circumspect.circumstellar.citrusy.civil.clandestine.clangy.clarified.clarkean.classic.clement.clever.cloaked.clockwork.clompy.cloned.cloudlike.cloudy.clunky.clustered.coastal.cobalt.cognitive.coherent.coleridgean.colossal.coltranesque.comely.cometary.compiled.complacent.composite.concurrent.conradian.constablean.convivial.copernican.copious.coplandesque.cordial.corinthian.corked.cornelian.coronal.cortical.cosmic.coy.cozy.cracked.crackling.crafty.cranky.crashy.creamy.credible.crepuscular.cretan.crimson.crisp.crispy.crowned.crumbly.crunchy.crushed.cryo.cryofrozen.cryogenic.cryonic.cryptic.crystalline.cuddly.cumulative.cunning.cupric.cured.curious.cursed.cursory.cushy.cybernetic.cyberpunk.cynical.cyprian.daliesque.dancy.dandy.dantean.dantesque.dapper.dappled.daring.dark.darwinian.dashing.dashy.dauntless.davisian.dawning.dazzling.deathless.debonair.deboned.debussyan.decanted.decompiled.decorous.decrypted.deep.deferential.deft.degasian.delectable.deleuzian.delian.deliberate.delicate.delirious.delphic.delta.demure.depressurized.derridean.destined.devout.dewy.dexterous.diaphanous.diced.dickensian.dickian.dickinsonian.didactic.dieselpunk.diffident.digital.dignified.diligent.dimensional.dinky.dionysian.discerning.discreet.disheveled.disparate.distant.distinct.distributed.diurnal.divine.dizzy.docile.docked.dogged.doomed.dorian.dormant.dostoevskian.dotty.doughty.doughy.downy.dozy.draconic.dreamful.dreamy.drifting.dripping.drizzly.droll.drowsy.druidic.dulcet.dun.dunky.durkheimian.dusky.dwarven.dynamic.dystopian.eager.earnest.earthy.eastward.easygoing.ebony.ebullient.eclectic.eclipsed.ecstatic.edenic.edwardian.effervescent.effulgent.effusive.einsteinian.elamite.elastic.elated.eldritch.electric.electronic.elegant.elegiac.elgarian.eliotian.eliotic.elizabethan.ellingtonian.eloquent.elusive.elven.elvish.elysian.embered.emergent.eminent.emphatic.emulsified.enchanted.encoded.encrypted.endearing.endless.endogenous.energetic.enhanced.enigmatic.enthralling.ephemeral.epic.epicurean.equanimous.errant.erudite.escherian.esoteric.esteemed.eternal.ethereal.ethiopian.etruscan.euclidean.eulerian.euphonious.euphoric.evanescent.evening.eventide.everlasting.evocative.exacting.exalted.exemplary.exo.exogenous.expansive.expressive.exquisite.extraterrestrial.extruded.exuberant.fabled.fabulous.facetious.faithful.fallow.fanciful.fantastic.faradayic.faraway.farmhouse.fastidious.fated.fateful.fathomless.faulknerian.faunal.fearless.feathered.feathery.fecund.federated.feisty.felicitous.felliniesque.fenny.fermented.ferny.ferrous.fervent.fervid.festive.fetching.fey.fickle.fierce.fiery.filleted.filtered.fitzgeraldian.fizzy.flaky.flamboyant.flamed.flashy.flawless.fleecy.fleet.fleeting.flexible.flickering.flinty.floral.florid.flouncy.flourishing.flowering.fluent.fluffy.fluid.fluvial.foamy.folded.fond.foraged.forged.formidable.forthright.fortuitous.forward.foucauldian.fourier.fractal.fragrant.frank.frankish.freckled.free.fresh.freudian.friedmanite.frisky.frizzy.frolicsome.frosted.frosty.frothy.frozen.frugal.fruiting.fruity.funky.furred.furtive.futuristic.fuzzy.gaelic.galactic.galbraithian.galilean.gallant.gallic.galvanic.gamesome.gamma.gandhian.garlanded.garrulous.gauguinesque.gaussian.gauzy.generous.genetic.genial.genomic.genteel.gentle.geomagnetic.georgian.gershwinesque.ghostly.giant.gibsonian.giddy.gifted.giga.giggly.gilded.giottesque.glacial.glad.glazed.gleaming.gleeful.glimmering.glistening.glorious.glossy.glowing.gnomish.godardian.godelian.goethean.goethesque.gogolian.golden.gooey.goofy.gorgeous.gorsy.gossamer.gothic.gowned.goyaesque.graceful.gracious.grainy.grand.grassy.grated.gravitic.gregarious.grilled.groovy.ground.grounded.guileless.gushy.gusty.habermasian.habsburg.hadrianic.halcyon.hale.hallowed.haloed.halved.hamiltonian.han.handelian.handmade.handsome.hanoverian.hapless.happy.hardy.hardyesque.harmonious.hashed.haunted.haydnesque.hayekian.hazy.heady.heaneyesque.hearthside.hearty.heathen.heathered.heavenly.hegelian.heideggerian.heinesque.heinleinian.heirloom.heisenbergian.heliacal.hellenic.hellish.hemingwayesque.herbal.herbertian.herculean.hermetic.heroic.hexed.hibernal.hilbertian.histrionic.hitchcockian.hittite.hoar.hoary.hobbesian.hobbitish.hogarthian.holderlinian.holo.holographic.holy.homerian.homeric.homeward.honest.honeyed.honky.hooded.hooved.hopeful.hopkinsian.hopperesque.hoppy.horatian.horned.hospitable.hot.housemade.huggy.humble.humean.humming.humorous.hunky.hunnish.hurrian.hushed.hydraulic.hyper.hyperborean.hypersonic.hyperspatial.hypnotic.iberian.ibsenite.iced.icy.ideal.idyllic.igneous.illustrious.imaginative.immaculate.immense.immortal.impassioned.impeccable.impetuous.impish.impressive.incan.incandescent.incisive.incorrigible.indefatigable.indelible.indigo.indolent.indomitable.industrious.ineffable.inexorable.infernal.infinite.infra.infrared.infused.ingenious.ingenuous.inimitable.innocuous.inquisitive.insatiable.inspired.intense.intergalactic.interstellar.intragalactic.intrepid.intricate.intrinsic.intuitive.inventive.inveterate.invincible.inward.ionian.ionic.ionospheric.irenic.iridescent.irrepressible.ithacan.itinerant.ivory.jacobean.jammy.jangly.jaunty.jazzy.jeffersonian.jiggly.jingly.jocular.jocund.johnsonian.jolly.jouncy.jovial.jovian.joycean.joyful.joyous.jubilant.judicious.juiced.juicy.jumped.jumpy.jungian.junky.justinianic.jute.kafkaesque.kandinskian.kantian.keatonesque.keatsian.keen.keplerian.keynesian.kierkegaardian.kindly.kindred.kinetic.kiplingesque.klimtian.knowing.kooky.kubrickian.kurosawan.lacanian.laconic.lacquered.lacustrine.lacy.lamarckian.lambda.lambent.laminated.landed.languid.lanky.laplacian.larkinesque.laser.latent.lathed.latin.lattice.laudable.launched.laureled.lavish.layered.leaden.leafy.lean.learned.legendary.leguinian.leibnizian.lemian.lemurian.lenient.leonardesque.liberal.libyan.lidar.light.lighthearted.likable.lilac.lilting.liminal.limpid.lincolnesque.lingering.linnaean.lissome.lisztian.literate.lithe.littoral.lively.loamy.local.lockean.lofty.logical.loopy.loose.loquacious.lorcaesque.lorcan.lossless.lossy.lovecraftian.lovelacean.loyal.lucent.lucid.lucky.ludic.lukewarm.luminal.luminous.lunar.luscious.lush.lushy.lusitanian.lustrous.lydian.lynchian.lyotardian.lyric.lyrical.macerated.machiavellian.macro.magical.magnanimous.magnetar.magnetic.magnetospheric.magnificent.magrittean.mahlerian.majestic.mallarmean.malleable.malthusian.malty.mandelan.manetesque.manifold.marbled.marshy.martial.martian.marvelous.marxian.maser.masked.masterful.matchless.matin.matissean.mature.matutinal.mauve.maverick.mawkish.maxwellian.mayan.meandering.mechanical.median.medicean.mega.mellifluous.mellow.melodic.mendelian.merciful.mercurial.merovingian.merry.meshed.meta.metamorphic.meteoric.meticulous.metternichian.mettlesome.michelangelesque.micro.microwave.midnight.mighty.mild.milled.miltonian.miltonic.minced.mindful.mineral.ming.mingusian.minoan.minty.miraculous.mired.miroesque.mirthful.mischievous.misty.mobile.modest.modular.molecular.molieresque.momentous.mondrianesque.monetian.monkish.mono.montane.moonless.moonlit.mordant.morning.mossy.motley.mottled.mouthwatering.mozartian.mughal.multiversal.munificent.murmuring.mushy.musical.mutable.mutant.mycenaean.mysterious.mystical.mythic.nabokovian.nameless.nano.nanoscale.napoleonic.narrowband.nascent.natty.neat.nebular.nebulous.nefarious.neptunian.nerudian.networked.neural.neutron.neutronic.newtonian.nietzschean.nifty.nimble.noble.nocturnal.nonchalant.nonpareil.noontide.norse.northward.nostalgic.notable.novel.nozickian.nuanced.nubian.nuclear.numinous.nutty.oaky.obdurate.oblique.observant.obstinate.obtuse.oceanic.ochre.odyssean.olden.olympian.omega.omni.onward.opaline.opportune.optical.optimistic.opulent.oracular.orbital.orbiting.orderly.original.ornate.orphic.orwellian.osirian.ostentatious.otherworldly.otiose.ottoman.outgoing.outspoken.outward.overcast.overclocked.ovidian.pacific.pagan.painstaking.palatial.pale.pallid.palpable.paradisal.paradoxical.parallel.paramount.parkerish.parsonian.parthian.passionate.pastoral.patched.pathless.patient.pavlovian.peaceable.peaceful.peachy.pearly.peaty.pebbly.peeled.peered.peerless.pelagic.pellucid.penetrating.pensive.peppered.peppery.peppy.perceptive.perennial.perfect.perfumed.perky.persian.persistent.perspicacious.persuasive.pert.pervasive.pessoan.petaled.petrarchan.phantom.pharaonic.phased.philosophical.phlegmatic.phoenician.photonic.photospheric.phrygian.picassoesque.pickled.pictish.picturesque.pillowy.pindaric.pinteresque.piping.piquant.pirandellian.pithy.pivotal.pixelated.placid.planckian.planetary.planetoid.plangent.plasmic.plathian.platinum.platonic.playful.pleasant.plentiful.pliant.plinky.plonky.plucky.plumed.plummy.plush.plushy.plutonian.plutonic.pneumatic.poached.poesque.poetic.poignant.poised.polished.polite.pollockian.poly.polygonal.polymer.polynesian.popean.popped.popular.portly.posh.positronic.posthuman.potent.pouncy.powdery.powerful.pragmatic.prancy.precise.precocious.precognitive.preeminent.premier.prescient.pressed.pressurized.prestigious.pretty.primeval.primordial.princely.printed.pristine.private.prized.prodigious.profane.proficient.profound.profuse.prokofievian.prolific.promethean.prompt.proper.prophetic.prosaic.prosperous.protean.proto.protostellar.proud.proustian.providential.prudent.psionic.puccinian.puckish.pudgy.puffed.pulled.pulsar.punctilious.punctual.pungent.punic.pure.purposeful.pushkinian.pynchonesque.pythagorean.quaint.quantum.quartered.quasar.questing.quick.quiescent.quiet.quintessential.quirky.quixotic.rabelaisian.racinian.radar.radiant.radio.rainwashed.rainy.rakish.rambunctious.raphaelesque.rapid.rapturous.rare.rational.ravelian.rawlsian.raytraced.ready.reasonable.rebooted.receptive.recondite.recursive.redolent.reduced.reedy.refined.reflective.refulgent.regal.relativistic.relaxed.reliable.remarkable.rembrandtesque.remote.rendered.renoiresque.renowned.replete.replicated.resilient.resinous.resolute.resourceful.respectful.resplendent.responsive.restful.restive.restless.reticent.retro.reverent.rhapsodic.rhodian.rhythmic.ricardian.rich.richelieuvian.riemannian.rigorous.rilkean.rimbaudian.rimed.ringed.ripe.ripening.rippling.risible.riverine.riveted.roaming.roaring.roasted.robed.robotic.robust.rolled.roly.roman.romanov.romantic.rompy.rooseveltian.roseate.rosy.rothkoesque.rousing.rousseauian.rowdy.royal.rubenesque.ruddy.runic.rushy.russet.rustic.sabine.sable.sacred.sagacious.sage.saintly.salient.saline.salingeresque.salted.salty.salubrious.samian.sandaled.sandy.sanguine.sapid.sapient.sapphic.sardonic.sarmatian.sartrean.sassy.satiny.saturnian.saturnine.saucy.savory.savvy.saxon.scalding.scarlet.schielesque.schillerian.schoenbergian.scholarly.schubertian.schumannesque.schumpeterian.scintillating.scorched.scorsesean.scrappy.scruffy.scrupulous.scythian.seaborne.seamless.seared.seasonal.seaward.secure.sedate.sedgy.sedimentary.sedulous.seemly.seismic.selenic.selfless.sensible.sensitive.sentient.sentimental.seraphic.sere.serene.seuratian.shaded.shadowed.shadowy.shaggy.shaken.shakespearean.shamanic.shannonian.sharded.sharp.shaved.shavian.shelleyan.shielded.shimmering.shiny.shoreless.shostakovian.shrewd.shucked.sibelian.sibilant.sibylline.sicilian.sidereal.sienna.sifted.sigma.silicon.silken.silky.silly.silty.silver.silvered.simmering.simulated.sincere.singed.singing.singular.sinuous.sisyphean.sizzling.skeptical.skillful.skinnerian.skittish.skyward.sleek.sleepless.sleepy.slender.sliced.slick.slipstreamed.slow.sly.smart.smashy.smithian.smoked.smoky.smoldering.smooth.snappy.snazzy.snoozy.snowy.snug.snuggly.soaring.sociable.socratic.sodden.soft.sogdian.solar.solarpunk.solemn.solid.somnolent.sonar.song.sonic.sonorous.sooty.soporific.soulful.sound.soundless.sour.southward.sovereign.spaceborne.spacefaring.spacious.sparkling.sparkly.spartan.special.speckled.spectacular.spectral.speedy.spellbound.spiced.spicy.spielbergian.spiffy.spinozan.spirited.splashy.splendid.split.sploshy.spontaneous.spooky.sporty.spotless.spotted.sprightly.sproingy.spry.spun.spunky.squally.squashy.squelchy.squiggly.squishy.staid.stainless.stalwart.starborn.starfaring.starless.starlit.stasisbound.stately.steadfast.steady.steaming.steampunk.steely.steeped.steinbeckian.stellar.stellarborn.sticky.stirred.stirring.stoic.stoical.stolid.stompy.stoppardian.storied.stormy.stout.strained.stratospheric.straussian.stravinskian.streaky.stretched.striking.strindbergian.striped.strong.stuart.stubby.studious.stunning.sturdy.stygian.suave.subatomic.sublime.suborbital.subsonic.substantial.subtle.succinct.succulent.sudsy.sugared.sugary.sumerian.summery.sunless.sunlit.sunny.sunward.superb.supergalactic.superlative.superluminal.supersonic.supple.supreme.sure.surreptitious.svelte.swanky.sweeping.sweet.swift.swiftian.swirled.swooshy.sylvan.sympathetic.synaptic.synchronous.synthetic.syrupy.tableside.tachyonic.taciturn.talented.talleyrandian.tame.tang.tangy.tarantinoesque.tarkovskian.tart.tasteful.tattered.taut.tawny.tectonic.telekinetic.telepathic.temperate.tempered.temporal.tenacious.tender.tennysonian.tenuous.tepid.tera.terran.terrific.terse.textured.thackerayan.thankful.thawed.theban.thessalian.theta.thorny.thorough.thoughtful.thracian.threadbare.thriving.thundery.tidal.tidy.timeless.timely.timeworn.tinkly.tiny.tipsy.tireless.titanesque.titanian.titanic.titanium.titianesque.toasted.toasty.tocharian.tokenized.tolerant.tolkienesque.tolstoyan.tonic.tonky.toothsome.torched.totemic.tough.towering.trackless.tranquil.transcendent.transhuman.treacly.treasured.tremendous.tremulous.trenchant.tricky.trim.triumphant.trojan.trollopian.truculent.true.truffautian.truffled.trusty.truthful.tudor.turbo.turingian.turneresque.twangy.twilight.twilit.twinkling.twinkly.ubiquitous.ultra.ultrasonic.ultraviolet.umami.umber.unassuming.unbounded.uncanny.uncorked.unctuous.undaunted.underworldly.undocked.undying.unearthly.unerring.unflappable.unique.unknown.unruffled.upbeat.upgraded.upright.upstanding.upward.uranian.urbane.utopian.vacuous.valeryan.valiant.valorous.vandal.vangoghian.vast.veblenian.vectorized.vedic.vehement.veiled.velazquezian.velvet.velvety.venerable.venturous.venusian.veracious.verbose.verdant.verdian.verdurous.verlainian.vermeerian.vermilion.vernal.verneian.versatile.vesper.vespertine.vibrant.victorian.vigilant.vigorous.vintage.violet.virgilian.virtual.virtuous.visceral.vital.vivacious.vivid.vocal.voidborn.voidward.volcanic.voltairean.voluble.vonnegutian.voracious.voxel.vroomy.wacky.wagnerian.wakeful.waking.wan.wandering.warholian.warm.warped.wary.washingtonian.wayward.wealthy.weathered.weberian.welcome.welded.wellesian.wellsian.westward.whacky.whimsical.whimsy.whipped.whisked.whispering.whistlerian.whitmanesque.whole.wholesome.whooshy.wide.wiggly.wild.wildean.willowy.wilsonian.wily.windswept.windy.winged.winning.winsome.wintry.wired.wireframe.wireless.wise.wishful.wispy.wistful.wittgensteinian.witty.wobbly.wodehousian.wondrous.wonky.wooded.woody.woolly.woozy.wordless.wordsworthian.wormholed.worthy.wraithlike.wreathed.wriggly.wry.xenial.xeno.yanky.yearning.yeasty.yeatsian.young.youthful.yuletide.yummy.zany.zappy.zealous.zested.zestful.zesty.zeta.zingy.zippy.zodiacal.zonked.zonky.zoomy.zoroastrian`.split(`.`),X_=`abalone.absinthe.absyrtus.accelerator.achilles.acorn.acquerello.actuator.adobo.adonis.aeetes.aegis.aello.aeneas.aengus.aether.affogato.afterburner.agartha.agate.agni.agnolotti.aioli.airlock.ajax.aji.albatross.alder.ale.alecto.aleppo.alfheim.allegory.alliteration.almond.amaranth.amaretto.amaterasu.ambrosia.americano.amphiaraus.anago.anapest.ancho.anchovy.android.andromeda.anise.annal.annwn.ansible.antaeus.antenna.anthem.antigone.antimony.antistrophe.anubis.aoidos.aperol.aphelion.aphrodite.apogee.apollo.apple.apricot.aquamarine.aquavit.aqueduct.arabica.arachne.arawn.arbor.arborio.arc.arcadia.arch.archipelago.ares.argo.argon.argonaut.aria.ariadne.ark.arke.armagnac.array.arrow.artemis.arthur.artichoke.artifact.arugula.asgard.asgardia.ash.asparagus.aspen.assam.assonance.asteroid.astronaut.atalanta.athena.atlantis.atlas.atoll.atom.atropos.aubergine.augean.aura.aurora.avalon.avalonia.avocado.awning.axion.axle.azurite.bacchus.bagna.baharat.balder.ballad.balladeer.banana.banshee.baozi.bard.barge.barium.barley.barn.basalt.basil.basilisk.basmati.bastet.bastion.bay.bayleaf.beacon.beam.bean.bearing.beech.beetroot.behemoth.bellini.beowulf.bergamot.berth.beryl.beryllium.bifrost.biodome.birch.biscotti.bismuth.bisque.bit.bittern.blackberry.blast.blaster.blini.block.blodeuwedd.bloodstone.blossom.bluebell.blueberry.bolt.bomba.bonito.boom.borage.boson.botargo.bottarga.bouillon.boundary.bow.bower.bragi.bramble.bran.branch.brandy.branwen.breeze.brew.bridge.brigid.brioche.broccoli.brook.brulee.brunhild.brush.bucatini.buckler.buckwheat.buffer.bulkhead.bunting.burrata.burst.bus.busiris.butte.butter.buttercup.butterscotch.byte.cabbage.cabin.cacao.cachaca.cache.cacus.cadence.caesura.calamarata.calamari.calcite.caldera.calliope.calvados.calypso.cam.camellia.camelot.camembert.campari.canal.cannelloni.cannoli.canopy.cantaloupe.cantata.canticle.canvas.canyon.canzone.capacitor.capellini.caper.capon.cappelletti.cappuccino.capsule.caramel.cardamom.cardoon.carillon.carnaroli.carnation.carol.carrier.carrot.cascade.cashew.cassandra.cassis.castle.castor.cavatelli.caviar.cayenne.cedar.celaeno.celeriac.cell.centaur.cerberi.cerberus.cernunnos.ceryneian.cesium.ceto.ceylon.chaff.chaffinch.chai.chain.chalk.chamomile.champagne.chandra.channel.chanson.chanterelle.chard.charon.chartreuse.cheddar.cherry.chert.chervil.chestnut.chickweed.chicory.chili.chime.chimera.chimichurri.chimney.chip.chipotle.chirashi.chiron.chive.chocolate.chorale.chorizo.chorus.chronicle.chrysanthemum.chrysaor.chrysomallus.chutney.ciabatta.cibola.cider.cilantro.cinder.cinnamon.cipher.circe.circlet.circuit.cirque.cistern.citadel.citrine.citron.clementine.cliff.clio.clipper.cloak.clotho.cloud.clove.clover.cluster.coal.cobbler.cockaigne.cockpit.cocoa.coconut.codex.coffee.cog.cognac.coif.coil.col.colchis.collider.colony.combe.comet.compote.concerto.conchiglie.conduit.confit.console.consomme.consonance.continuum.contour.cookies.coordinate.core.coriander.cormorant.corona.coronet.cortado.corvette.cosmos.cottage.couplet.course.couscous.cove.cowl.cowslip.crab.craft.crag.cranberry.crane.crayon.cream.creme.crepe.cress.crocus.croissant.crosne.crown.cruiser.crumble.cryopod.cryosleep.crystal.cuchulainn.cuckoo.cucumber.cuirass.cumin.cupid.curlew.currant.current.curry.custard.cyborg.cycle.cyclops.cyclotron.cylinder.dactyl.daedalus.daemon.daffodil.dagda.dahlia.daiquiri.dais.daisy.dale.dam.dandelion.danu.daphne.darjeeling.dart.dashi.date.dawn.daydream.deck.deirdre.demeter.destroyer.dew.diadem.diary.dill.dimension.diode.diomedean.dionysus.ditalini.ditch.djinn.dock.doenjang.domain.donburi.donjon.door.doppio.dove.downlink.dreadnought.dream.drift.droid.dryad.dukkah.dulce.dumpling.dune.durga.dusk.dust.dyke.eagle.earlgrey.easel.echidna.echo.eclair.eclipse.ecliptic.edamame.eddy.edelweiss.edge.egret.einsteinium.elderflower.eldorado.electra.elegy.elm.elysium.ember.endive.enigma.enjambment.enkidu.envoi.eos.epigram.epistle.epode.erato.erinyes.eros.erymanthian.escargot.espresso.estuary.eumenides.euryale.eurybia.eurydice.eurytion.excalibur.exoplanet.fable.fafnir.falcon.fancy.farfalle.fate.feather.feldspar.fell.fence.fennel.fenrir.fenugreek.fermion.fern.fettuccine.fiddlehead.field.fig.finch.finn.fionn.firebird.firefly.fission.fizz.fjord.flake.flame.flare.flash.flicker.flint.flue.fluorite.flux.flywheel.focaccia.fog.folio.fondant.forge.fortress.foxglove.fragment.fraise.frame.frangipane.frappe.freesia.fregola.freighter.freya.frigate.frigg.frost.fudge.fugue.fumarole.furies.fusilli.fusion.gaia.galahad.galangal.galatea.galaxy.galette.galleon.gallium.ganache.ganesh.gannet.gantry.ganymede.garam.gardenia.garlic.garuda.gateway.gauntlet.gawain.gazebo.gear.gelato.gemelli.genmaicha.genoise.geranium.germ.germanium.geryon.geyser.ghazal.ghee.ghost.gilgamesh.ginger.gingko.ginnungagap.girder.glacier.glade.glaze.gleam.gleeman.glen.glimmer.glint.glitter.gloss.glow.gluon.gnocchi.gochujang.goldfinch.golem.goose.gooseberry.gorgon.gouda.governor.gradient.graeae.granary.granite.grapefruit.grappa.gratin.graviton.greave.grebe.gremolata.grenadine.grendel.grid.griffin.gruyere.guajillo.guava.gudrun.guinevere.gunkan.gwydion.gyoza.gyroscope.habanero.habitat.hades.hadron.haiku.hall.halloumi.halo.halva.hamachi.hangar.hanuman.harissa.harpies.harpy.harvest.hatch.hauberk.hawthorn.haze.hazel.hazelnut.heading.headland.heap.heart.hearth.heather.hecate.hedge.heimdall.hel.helheim.helios.helium.helix.helle.hellebore.helm.hemistich.hephaestus.hera.hermes.heron.hesperides.hestia.hibiscus.hippogriff.hirame.hive.hoisin.hojicha.hollandaise.hollow.holly.hologram.honey.honeycomb.honeysuckle.hood.hoopoe.horizon.horseradish.horus.hrothgar.hub.huckleberry.hue.huginn.hull.husk.hut.hyacinth.hydra.hydras.hylas.hymn.hyperborea.hypercube.hyperdrive.hyperion.hyperspace.hyssop.iamb.ibis.icarus.idas.idunn.idyll.igniter.igraine.ikura.indium.indra.inductor.infusion.injector.ink.inlet.inspiration.ion.iridium.iris.ishtar.isis.isolde.isotope.ivy.iwashi.izanagi.jackdaw.jackfruit.jalapeno.janus.jasmine.jason.jasper.javelin.jay.jet.jiaozi.jongleur.jonquil.jormungandr.jotunheim.journal.julep.jumpgate.juniper.juno.jupiter.kaffir.kale.kali.kampachi.karaage.karasumi.katsu.keel.keep.kefir.kelpie.kenning.kernel.kestrel.khinkali.kiln.kimchi.kingfisher.kinmedai.kirsch.kite.kitsune.kiwi.koan.kohlrabi.kombucha.koshihikari.kraken.krypton.kumquat.kvass.lachesis.lacquer.ladon.ladons.laertes.lager.lagoon.lake.lakshmi.lambic.lament.lance.lancelot.lander.lane.langoustine.lantern.lapis.lark.larkspur.lasagna.latte.laureate.laurel.lava.lavender.leaf.leda.leek.legend.lemon.lemonbalm.lemongrass.lemuria.lens.lentil.lepton.lernaean.lethe.letter.levee.lever.leviathan.lightyear.lily.lime.limerick.limoncello.linden.linguine.link.linnet.lir.lithium.lityerses.lobster.loch.lock.lodge.loki.loop.loquat.lotus.lovage.lugh.lullaby.lungo.luster.lychee.lynceus.lyonesse.lyricist.macadamia.macaron.macchiato.madai.madeleine.madrigal.magma.magnolia.magpie.mail.mainframe.maki.makrut.malachite.manannan.mango.manicotti.manor.manti.manticore.mantle.mantou.manuscript.maple.marble.marduk.margarita.marigold.marjoram.marquee.marrow.martini.marvel.marzipan.masago.masala.mascarpone.mast.matcha.matrix.mead.meadow.mech.medea.medusa.megaera.meleager.memoir.mentaiko.mercury.meringue.merlin.merlot.mesa.mesh.metaphor.meteor.meter.mezcal.mezzaluna.mica.midas.midgard.mill.mimir.mimosa.minerva.minotaur.minstrel.mint.minuet.miracle.mirin.mirror.miso.missive.mist.mjolnir.mocha.module.moira.mojito.molasses.mole.momo.monolith.moonbase.moonbeam.moonstone.moor.mopsus.mordred.morel.morgana.morpheus.morrigan.moss.mote.motet.mousse.mu.mulberry.muninn.muon.muse.muspelheim.mustard.myrtle.mystery.myth.nadir.naga.naiad.nanite.nanobot.narcissus.neapolitan.nebula.nectarine.needle.negroni.nemean.nemesis.neon.neptune.neptunium.nereid.nereus.nessus.nest.nestor.net.nettle.neutrino.nexus.niamh.nib.nibble.nibiru.niflheim.nightingale.nigiri.nike.niobe.njord.nocturne.node.nog.nori.norn.note.nougat.nova.nozzle.nuada.nutmeg.nyx.oak.oasis.oat.obelisk.oberon.obsidian.oceanid.oceanus.octave.octavo.ocypete.ode.odin.odysseus.oisin.okonomiyaki.olive.olympus.oni.onigiri.oolong.oracle.orange.orb.orbit.orbiter.orchard.orchid.oreads.orecchiette.oregano.orion.orpheus.orthros.orthrus.orzo.oscillator.osiris.osmium.osprey.ouroboros.outline.outpost.ouzo.oven.overture.owl.oyster.paccheri.packet.padron.page.palace.palette.palladium.palm.pan.pandan.pandora.panettone.pansotti.pansy.pantoum.papaya.pappardelle.paprika.papyrus.parable.paradox.parcae.parchment.parfait.parmesan.parsec.parsley.parsnip.particle.partridge.parvati.pasilla.passionfruit.pastel.pastis.patina.pavilion.pavlova.peach.peak.pear.pebble.pecan.pegasi.pegasus.pekoe.peleus.pelican.pelmeni.pen.pencil.penelope.penne.peony.pepper.peppermint.percival.peregrine.pergola.peridot.perigee.perihelion.perry.persephone.perseus.persillade.persimmon.pesto.petal.petrel.phase.pheasant.phoenix.pholus.phorcys.photon.phrixus.pickle.pierogi.pigment.pimento.pine.pineapple.ping.pinot.pipe.pipit.piquillo.pisco.pistachio.piston.pith.plane.plasma.plate.plover.plum.plume.pluto.plutonium.poblano.pod.podarge.poet.polenta.pollux.polyphemus.pomegranate.pomelo.pond.pontus.ponzu.pooka.pool.poplar.poppy.porcini.port.portal.porter.porthole.poseidon.positron.prairie.praline.prelude.primrose.prism.probe.profile.prometheus.prosciutto.prosecco.proteus.protocol.psalm.psyche.pudding.puffin.pulse.pumice.pumpkin.purslane.pwyll.pylon.pyrrhic.quadrant.quail.quark.quarto.quartz.quatrain.qubit.quetzalcoatl.queue.quill.quince.quinoa.quiver.radish.radium.radon.ragnarok.rain.rama.ramen.ramp.rampart.ramson.raspberry.ratatoskr.raven.ravioli.ray.reactor.realm.reaper.reed.reef.refrain.region.register.relay.relic.remnant.requiem.reservoir.residue.resistor.resonator.reverie.rhapsode.rhapsody.rhea.rhiannon.rhodium.rhododendron.rhubarb.rhyme.ricotta.riddle.ridge.riesling.rigatoni.rim.ring.risotto.ristretto.river.roast.robin.robusta.roc.rocket.rod.romesco.rondeau.rooibos.rook.root.rose.rosemary.rosewater.roundel.rover.rowan.rubidium.rum.rune.saba.saffron.saga.saison.sake.salmoriglio.salsa.salsify.sambal.sambuca.samphire.sancerre.sandpiper.sangria.sanma.sansho.saraswati.sashimi.sasquatch.satellite.satyr.sauternes.savanna.sawara.sazerac.scaffold.scalar.scallop.scansion.scepter.schnapps.schooner.scop.scorzonera.scotchbonnet.scroll.sector.seed.sekhmet.selene.selenite.selenium.selkie.sencha.sensor.sequoia.serenade.serrano.servo.sesame.sestina.sextet.shack.shade.shadow.shaft.shale.shallot.shambhala.shard.shed.sheen.sherbet.sherry.shield.shimmer.ship.shishito.shiso.shiva.shoyu.shrub.shumai.shuttle.sibyl.sif.signal.sigurd.silhouette.silo.simile.simurgh.singularity.siren.sita.skadi.skald.skiff.skuld.skylark.slant.slate.sleipnir.sling.slipstream.sliver.sloop.sluice.smithy.smoke.snowdrop.socket.sofrito.sonata.sonnet.soot.sorbet.sorrel.souffle.soul.soy.spaceport.spaghetti.spark.sparkle.sparrow.spear.speck.specter.speculoos.spelt.sphere.sphinx.sphinxes.spindle.spinel.spiral.spire.spirit.splinter.spoke.spondee.spore.spring.spritz.spruce.sriracha.ssamjang.stack.stanza.starbase.starlight.starling.starport.starship.stasis.station.steam.stellarator.steppe.stheno.stork.stracciatella.strawberry.stream.strontium.strophe.strozzapreti.strut.stylus.stymphalian.styx.subspace.sumac.summit.sunbeam.sunstone.supernova.surge.surya.susanoo.sushi.svartalfheim.swallow.swan.swarm.sycamore.syleus.synchrotron.tabard.tachyon.tagliatelle.tahini.takoyaki.taliesin.tamari.tamarind.tangerine.tanka.tanker.tapenade.tapioca.tarako.taranis.tare.tarn.tarragon.tartarus.telamon.telemetry.teleporter.tellurium.temaki.tempura.tengu.tensor.tent.tequila.tercet.teriyaki.terminal.tern.terraform.tesseract.tethys.thalassa.thalia.thallium.thaumas.themis.theseus.thistle.thor.thorium.thoth.threshold.throne.throttle.thrush.thruster.thule.thunderbird.thyme.tiamat.tiara.tide.tint.tintagel.tiphys.tiramisu.tirnanog.tisane.tisiphone.titan.tobiko.toccata.toddy.toffee.tofu.tokamak.tomatillo.tomato.tome.tone.tonka.tonkatsu.tor.tortellini.torus.tourmaline.tower.trace.track.transducer.transistor.treacle.trellis.triolet.tristan.triton.trochee.trofie.trope.troubadour.trouvere.truffle.trunk.truss.tug.tulip.tundra.tungsten.turbine.turmeric.turquoise.turret.twinkle.typhon.tyr.udon.ulysses.unagi.uni.unicorn.uplink.uramaki.urania.uranium.urd.urfa.uther.vale.valhalla.valkyrie.valve.vanadium.vanaheim.vanilla.vapor.vareniki.varnish.varuna.vector.veil.vellum.vent.venus.verbena.verdandi.verge.verjus.vermouth.verse.vessel.vesta.vestige.vialone.viewport.villanelle.vishnu.vodka.volcano.volta.volume.vortex.vulcan.wall.walnut.waltz.warbler.warpgate.wasabi.wash.watercress.watermelon.wave.waypoint.web.weir.well.wendigo.wheat.whisky.whisper.wiglaf.willow.wimple.window.wisteria.wonder.wonton.woodcock.woodpecker.word.wormhole.wraith.wren.wyrm.wyvern.xenon.yacht.yakitori.yama.yarrow.yeti.yew.yggdrasil.yokai.yuzu.zaatar.zabaglione.zenith.zephyr.zeus.zinnia.zircon.zirconium.ziti.zone.zucchini`.split(`.`);Y_.length*X_.length;const Z_=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`discovery`,`upgrade`,`workflow`,`bash`,`jshd`,`preview`,`scoop-notify`,`scoop-idle`,`scoop-wait`,`sudo-request`]);function Q_(e){return e!=null&&Z_.has(e)}const $_=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]),ev=65536;function tv(e,t=ev){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${av(t)} of ${av(e.length)} — the agent received the full output]`}function nv(e,t=ev,n=4){if(typeof e==`string`)return tv(e,t);if(typeof e!=`object`||!e||n<=0)return e;if(Array.isArray(e)){let r=null;for(let i=0;i<e.length;i++){let a=nv(e[i],t,n-1);a!==e[i]&&(r??=[...e],r[i]=a)}return r??e}let r=null;for(let[i,a]of Object.entries(e)){let o=nv(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}function rv(e,t=ev){if(!e)return e;if(!hn().test(e))return tv(e,t);let n=tv(e.replace(hn(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function iv(e,t=ev){if(e.length<=t)return e;if(!hn().test(e))return tv(e,t);let n=[],r=0;for(let i of e.matchAll(hn()))n.push(tv(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(tv(e.slice(r),t)),n.join(``)}function av(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}var ov=e({agentMessagesToChatMessages:()=>sv,lickChannelFromBody:()=>Sv,lickChannelFromSenderName:()=>xv,lickIdFromBody:()=>Cv,splitEnvelopes:()=>bv,unwrapMessageEnvelope:()=>yv});function sv(e,t={}){let{source:n=`cone`,idSeed:r=vv,hiddenToolNames:i=$_,uncapped:a=!1}=t,o=[],s=null,c=new Set;for(let t of e)dv(t)?(o.push(...cv(t,r)),s=null):fv(t)?(s=lv(t,n,r,i,c,a),o.push(s)):pv(t)&&uv(t,s,c,a);return o}function cv(e,t){let n=mv(e.content);if(n.length===0)return[];let r=[];for(let i of bv(n)){if(i.body.length===0&&i.sender==null)continue;let n=(i.sender?xv(i.sender):null)??Sv(i.body),a=n?Cv(i.body):void 0,o={id:n===`sudo-request`&&a?`sudo-request-${a}`:t(),role:`user`,content:i.body,timestamp:e.timestamp};n&&(o.source=`lick`,o.channel=n,a&&(o.lickId=a)),r.push(o)}return r}function lv(e,t,n,r,i,a=!1){let o=[];for(let t of _v(e,a))r.has(t.name)?i.add(t.id):o.push(t);let s={id:n(),role:`assistant`,content:mv(e.content),timestamp:e.timestamp,source:t,model:e.model},{usage:c}=e;return c&&(s.usage={input:c.input,output:c.output,cacheRead:c.cacheRead,cacheWrite:c.cacheWrite,cost:{input:c.cost.input,output:c.cost.output,cacheRead:c.cost.cacheRead,cacheWrite:c.cost.cacheWrite,total:c.cost.total}}),o.length>0&&(s.toolCalls=o),s}function uv(e,t,n,r=!1){if(n.has(e.toolCallId))return;let i=t?.toolCalls?.find(t=>t.id===e.toolCallId);if(!i)return;let a=mv(e.content);i.result=r?a:tv(a),i.isError=e.isError}function dv(e){return e.role===`user`}function fv(e){return e.role===`assistant`}function pv(e){return e.role===`toolResult`}function mv(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)hv(n)&&t.push(n.text);return t.join(``)}function hv(e){return e.type===`text`}function gv(e){return e.type===`toolCall`}function _v(e,t=!1){if(!Array.isArray(e.content))return[];let n=[];for(let r of e.content)gv(r)&&n.push({id:r.id,name:r.name,input:t?r.arguments:nv(r.arguments)});return n}function vv(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function yv(e){if(!e.startsWith(`[`))return null;let t=e.indexOf(`] `);if(t<=0||e.lastIndexOf(`
885
- `,t)!==-1)return null;let n=e.slice(t+2);if(n.startsWith(`User: `))return{sender:`User`,body:n.slice(6)};for(let e of Z_){let t=`${e}:`;if(!n.startsWith(t))continue;let r=n.indexOf(`
884
+ `)}function T_(e){return e?.length?e.filter(e=>e.kind===`image`&&e.data).map(e=>({type:`image`,data:e.data,mimeType:e.mimeType})):[]}const E_=`sessions`;function D_(){return new Promise((e,t)=>{let n=indexedDB.open(`agent-sessions`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(E_)||e.createObjectStore(E_,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var O_=class{dbPromise=null;getDB(){return this.dbPromise||=D_().then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise}async save(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(E_,`readwrite`).objectStore(E_).put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(E_,`readonly`).objectStore(E_).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async delete(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(E_,`readwrite`).objectStore(E_).delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async loadAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(E_,`readonly`).objectStore(E_).getAll();r.onsuccess=()=>t(r.result??[]),r.onerror=()=>n(r.error)})}async list(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(E_,`readonly`).objectStore(E_).getAll();r.onsuccess=()=>{t((r.result??[]).map(e=>({id:e.id,updatedAt:e.updatedAt})))},r.onerror=()=>n(r.error)})}async clearAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(E_,`readwrite`).objectStore(E_).clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}static newId(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}static createSession(e,t){let n=Date.now();return{id:e,messages:[],config:t,createdAt:n,updatedAt:n}}static updateMessages(e,t){return{...e,messages:t,updatedAt:Date.now()}}},k_=class{resolve;providerId;now;#e=null;#t=null;#n=null;#r=null;constructor(e,t,n=Date.now){this.resolve=e,this.providerId=t,this.now=n}#i(e){return e===`ok`?6e4:e===`unsupported`?18e5:3e5}isStale(){let e=this.#e;return!e||this.#t!==this.providerId()||this.now()-e.at>=this.#i(e.outcome)}snapshot(){return this.#t===this.providerId()?this.#e?.window??null:null}async refresh(e={}){if(!e.force&&!this.isStale())return this.snapshot();let t=this.providerId();return this.#n!==null&&this.#r===t?this.#n:(this.#n=this.resolve().then(e=>{let n=e?{...e,at:this.now()}:null;return this.#a(t,n?`ok`:`unsupported`,n),n}).catch(()=>{let e=this.snapshot();return this.#a(t,`failed`,e),e}).finally(()=>{this.#r===t&&(this.#n=null,this.#r=null)}),this.#r=t,this.#n)}#a(e,t,n){e===this.providerId()&&(this.#t=e,this.#e={outcome:t,window:n,at:this.now()})}clear(){this.#e=null,this.#t=null}},A_=e({clearBudgetWindowCache:()=>I_,getBudgetWindowSnapshot:()=>P_,refreshBudgetWindow:()=>F_});async function j_(){let e=ue();if(!e)return null;let t=Ne(e);if(!t?.getBudgetUsage)return null;let n=await t.getBudgetUsage();return n?{...n,providerId:e}:null}function M_(){try{return ue()}catch{return``}}const N_=new k_(j_,M_);function P_(){return N_.snapshot()}function F_(e){return N_.refresh(e)}function I_(){N_.clear()}const L_=`abject.abortive.abrasive.absolute.abstruse.abundant.abyssal.accessible.acerbic.acrid.adamant.adept.adlerian.adornian.adroit.adventurous.aeolian.aerated.aesthetic.affable.aged.ageless.agile.airborne.airlocked.airy.akkadian.alabaster.alacritous.alert.alien.alloyed.allusive.aloof.alpha.alpine.alternate.altruistic.amaranthine.amber.ambidextrous.ambivalent.ambrosial.amiable.amorphous.ample.analog.analytical.ancestral.ancient.angelic.animated.animist.anomalous.antediluvian.antic.antlered.apollinairian.apollonian.apt.aquatic.arbitrary.arcadian.arcane.archaic.archimedean.ardent.arduous.arendtian.argent.argentine.argive.aristotelian.armstrongian.aromatic.arresting.artful.arthurian.articulate.artificial.artisanal.artless.ascetic.ashen.ashy.asimovian.aspiring.assiduous.assyrian.asteroidal.astral.astute.asynchronous.athenian.atlantean.atomic.attentive.attic.audacious.audenesque.augmented.august.augustan.aureate.auric.auroral.austenian.austere.austral.authentic.autonomous.autumnal.avalonian.avid.avuncular.aztec.azure.babbagean.babylonian.bacchic.bachian.bactrian.ballardian.ballistic.balmy.banksian.barefoot.barreled.barthesian.bartokian.bashy.baudelairean.bayesian.beatific.beckettesque.beckettian.beethovenian.beguiling.bellicose.bemused.benevolent.benign.benjaminian.bergmanesque.beta.bewitched.binary.bionic.bismarckian.bitter.bitwise.blackened.blakean.blameless.bland.blazar.blazing.blended.blessed.blissful.blistered.blithe.blooming.blunt.blustery.boeotian.boggy.bohrian.boingy.boisterous.bold.bolted.bombastic.bonny.boolean.boreal.borgesian.borgian.bosky.botticellian.bottled.bouncy.boundless.bountiful.bourbon.bradburyan.brahmsian.braised.brambly.brash.brave.brazen.bready.breathless.brechtian.breezy.briared.briery.bright.brilliant.brined.briny.brisk.bristling.briton.brittenesque.broadband.brontean.bronzed.brooding.browned.browningesque.brucknerian.brumal.brusque.bubbling.bubbly.bucolic.budding.bunuelian.buoyant.burnished.burnt.buttered.buttery.bygone.byronic.bytewise.byzantine.cacophonous.caesarean.callow.calm.candescent.candid.candied.canny.cantorian.capable.capricious.caramelized.caravaggesque.carbon.carefree.carolingian.cartesian.carved.casked.cast.cavafian.cavalier.celebrated.celestial.celtic.ceramic.cerebral.ceremonious.cerulean.cervantine.cezannesque.chagallian.chalky.chaplinesque.charcoal.charismatic.charmed.charming.charred.chaucerian.cheeky.cheerful.chekhovian.cherished.cherubic.chewy.chilled.chilly.chimerical.chipper.chirpy.chivalrous.chopinesque.chromospheric.chronal.chthonic.chubby.chunky.churchillian.cimmerian.cindered.circumspect.circumstellar.citrusy.civil.clandestine.clangy.clarified.clarkean.classic.clement.clever.cloaked.clockwork.clompy.cloned.cloudlike.cloudy.clunky.clustered.coastal.cobalt.cognitive.coherent.coleridgean.colossal.coltranesque.comely.cometary.compiled.complacent.composite.concurrent.conradian.constablean.convivial.copernican.copious.coplandesque.cordial.corinthian.corked.cornelian.coronal.cortical.cosmic.coy.cozy.cracked.crackling.crafty.cranky.crashy.creamy.credible.crepuscular.cretan.crimson.crisp.crispy.crowned.crumbly.crunchy.crushed.cryo.cryofrozen.cryogenic.cryonic.cryptic.crystalline.cuddly.cumulative.cunning.cupric.cured.curious.cursed.cursory.cushy.cybernetic.cyberpunk.cynical.cyprian.daliesque.dancy.dandy.dantean.dantesque.dapper.dappled.daring.dark.darwinian.dashing.dashy.dauntless.davisian.dawning.dazzling.deathless.debonair.deboned.debussyan.decanted.decompiled.decorous.decrypted.deep.deferential.deft.degasian.delectable.deleuzian.delian.deliberate.delicate.delirious.delphic.delta.demure.depressurized.derridean.destined.devout.dewy.dexterous.diaphanous.diced.dickensian.dickian.dickinsonian.didactic.dieselpunk.diffident.digital.dignified.diligent.dimensional.dinky.dionysian.discerning.discreet.disheveled.disparate.distant.distinct.distributed.diurnal.divine.dizzy.docile.docked.dogged.doomed.dorian.dormant.dostoevskian.dotty.doughty.doughy.downy.dozy.draconic.dreamful.dreamy.drifting.dripping.drizzly.droll.drowsy.druidic.dulcet.dun.dunky.durkheimian.dusky.dwarven.dynamic.dystopian.eager.earnest.earthy.eastward.easygoing.ebony.ebullient.eclectic.eclipsed.ecstatic.edenic.edwardian.effervescent.effulgent.effusive.einsteinian.elamite.elastic.elated.eldritch.electric.electronic.elegant.elegiac.elgarian.eliotian.eliotic.elizabethan.ellingtonian.eloquent.elusive.elven.elvish.elysian.embered.emergent.eminent.emphatic.emulsified.enchanted.encoded.encrypted.endearing.endless.endogenous.energetic.enhanced.enigmatic.enthralling.ephemeral.epic.epicurean.equanimous.errant.erudite.escherian.esoteric.esteemed.eternal.ethereal.ethiopian.etruscan.euclidean.eulerian.euphonious.euphoric.evanescent.evening.eventide.everlasting.evocative.exacting.exalted.exemplary.exo.exogenous.expansive.expressive.exquisite.extraterrestrial.extruded.exuberant.fabled.fabulous.facetious.faithful.fallow.fanciful.fantastic.faradayic.faraway.farmhouse.fastidious.fated.fateful.fathomless.faulknerian.faunal.fearless.feathered.feathery.fecund.federated.feisty.felicitous.felliniesque.fenny.fermented.ferny.ferrous.fervent.fervid.festive.fetching.fey.fickle.fierce.fiery.filleted.filtered.fitzgeraldian.fizzy.flaky.flamboyant.flamed.flashy.flawless.fleecy.fleet.fleeting.flexible.flickering.flinty.floral.florid.flouncy.flourishing.flowering.fluent.fluffy.fluid.fluvial.foamy.folded.fond.foraged.forged.formidable.forthright.fortuitous.forward.foucauldian.fourier.fractal.fragrant.frank.frankish.freckled.free.fresh.freudian.friedmanite.frisky.frizzy.frolicsome.frosted.frosty.frothy.frozen.frugal.fruiting.fruity.funky.furred.furtive.futuristic.fuzzy.gaelic.galactic.galbraithian.galilean.gallant.gallic.galvanic.gamesome.gamma.gandhian.garlanded.garrulous.gauguinesque.gaussian.gauzy.generous.genetic.genial.genomic.genteel.gentle.geomagnetic.georgian.gershwinesque.ghostly.giant.gibsonian.giddy.gifted.giga.giggly.gilded.giottesque.glacial.glad.glazed.gleaming.gleeful.glimmering.glistening.glorious.glossy.glowing.gnomish.godardian.godelian.goethean.goethesque.gogolian.golden.gooey.goofy.gorgeous.gorsy.gossamer.gothic.gowned.goyaesque.graceful.gracious.grainy.grand.grassy.grated.gravitic.gregarious.grilled.groovy.ground.grounded.guileless.gushy.gusty.habermasian.habsburg.hadrianic.halcyon.hale.hallowed.haloed.halved.hamiltonian.han.handelian.handmade.handsome.hanoverian.hapless.happy.hardy.hardyesque.harmonious.hashed.haunted.haydnesque.hayekian.hazy.heady.heaneyesque.hearthside.hearty.heathen.heathered.heavenly.hegelian.heideggerian.heinesque.heinleinian.heirloom.heisenbergian.heliacal.hellenic.hellish.hemingwayesque.herbal.herbertian.herculean.hermetic.heroic.hexed.hibernal.hilbertian.histrionic.hitchcockian.hittite.hoar.hoary.hobbesian.hobbitish.hogarthian.holderlinian.holo.holographic.holy.homerian.homeric.homeward.honest.honeyed.honky.hooded.hooved.hopeful.hopkinsian.hopperesque.hoppy.horatian.horned.hospitable.hot.housemade.huggy.humble.humean.humming.humorous.hunky.hunnish.hurrian.hushed.hydraulic.hyper.hyperborean.hypersonic.hyperspatial.hypnotic.iberian.ibsenite.iced.icy.ideal.idyllic.igneous.illustrious.imaginative.immaculate.immense.immortal.impassioned.impeccable.impetuous.impish.impressive.incan.incandescent.incisive.incorrigible.indefatigable.indelible.indigo.indolent.indomitable.industrious.ineffable.inexorable.infernal.infinite.infra.infrared.infused.ingenious.ingenuous.inimitable.innocuous.inquisitive.insatiable.inspired.intense.intergalactic.interstellar.intragalactic.intrepid.intricate.intrinsic.intuitive.inventive.inveterate.invincible.inward.ionian.ionic.ionospheric.irenic.iridescent.irrepressible.ithacan.itinerant.ivory.jacobean.jammy.jangly.jaunty.jazzy.jeffersonian.jiggly.jingly.jocular.jocund.johnsonian.jolly.jouncy.jovial.jovian.joycean.joyful.joyous.jubilant.judicious.juiced.juicy.jumped.jumpy.jungian.junky.justinianic.jute.kafkaesque.kandinskian.kantian.keatonesque.keatsian.keen.keplerian.keynesian.kierkegaardian.kindly.kindred.kinetic.kiplingesque.klimtian.knowing.kooky.kubrickian.kurosawan.lacanian.laconic.lacquered.lacustrine.lacy.lamarckian.lambda.lambent.laminated.landed.languid.lanky.laplacian.larkinesque.laser.latent.lathed.latin.lattice.laudable.launched.laureled.lavish.layered.leaden.leafy.lean.learned.legendary.leguinian.leibnizian.lemian.lemurian.lenient.leonardesque.liberal.libyan.lidar.light.lighthearted.likable.lilac.lilting.liminal.limpid.lincolnesque.lingering.linnaean.lissome.lisztian.literate.lithe.littoral.lively.loamy.local.lockean.lofty.logical.loopy.loose.loquacious.lorcaesque.lorcan.lossless.lossy.lovecraftian.lovelacean.loyal.lucent.lucid.lucky.ludic.lukewarm.luminal.luminous.lunar.luscious.lush.lushy.lusitanian.lustrous.lydian.lynchian.lyotardian.lyric.lyrical.macerated.machiavellian.macro.magical.magnanimous.magnetar.magnetic.magnetospheric.magnificent.magrittean.mahlerian.majestic.mallarmean.malleable.malthusian.malty.mandelan.manetesque.manifold.marbled.marshy.martial.martian.marvelous.marxian.maser.masked.masterful.matchless.matin.matissean.mature.matutinal.mauve.maverick.mawkish.maxwellian.mayan.meandering.mechanical.median.medicean.mega.mellifluous.mellow.melodic.mendelian.merciful.mercurial.merovingian.merry.meshed.meta.metamorphic.meteoric.meticulous.metternichian.mettlesome.michelangelesque.micro.microwave.midnight.mighty.mild.milled.miltonian.miltonic.minced.mindful.mineral.ming.mingusian.minoan.minty.miraculous.mired.miroesque.mirthful.mischievous.misty.mobile.modest.modular.molecular.molieresque.momentous.mondrianesque.monetian.monkish.mono.montane.moonless.moonlit.mordant.morning.mossy.motley.mottled.mouthwatering.mozartian.mughal.multiversal.munificent.murmuring.mushy.musical.mutable.mutant.mycenaean.mysterious.mystical.mythic.nabokovian.nameless.nano.nanoscale.napoleonic.narrowband.nascent.natty.neat.nebular.nebulous.nefarious.neptunian.nerudian.networked.neural.neutron.neutronic.newtonian.nietzschean.nifty.nimble.noble.nocturnal.nonchalant.nonpareil.noontide.norse.northward.nostalgic.notable.novel.nozickian.nuanced.nubian.nuclear.numinous.nutty.oaky.obdurate.oblique.observant.obstinate.obtuse.oceanic.ochre.odyssean.olden.olympian.omega.omni.onward.opaline.opportune.optical.optimistic.opulent.oracular.orbital.orbiting.orderly.original.ornate.orphic.orwellian.osirian.ostentatious.otherworldly.otiose.ottoman.outgoing.outspoken.outward.overcast.overclocked.ovidian.pacific.pagan.painstaking.palatial.pale.pallid.palpable.paradisal.paradoxical.parallel.paramount.parkerish.parsonian.parthian.passionate.pastoral.patched.pathless.patient.pavlovian.peaceable.peaceful.peachy.pearly.peaty.pebbly.peeled.peered.peerless.pelagic.pellucid.penetrating.pensive.peppered.peppery.peppy.perceptive.perennial.perfect.perfumed.perky.persian.persistent.perspicacious.persuasive.pert.pervasive.pessoan.petaled.petrarchan.phantom.pharaonic.phased.philosophical.phlegmatic.phoenician.photonic.photospheric.phrygian.picassoesque.pickled.pictish.picturesque.pillowy.pindaric.pinteresque.piping.piquant.pirandellian.pithy.pivotal.pixelated.placid.planckian.planetary.planetoid.plangent.plasmic.plathian.platinum.platonic.playful.pleasant.plentiful.pliant.plinky.plonky.plucky.plumed.plummy.plush.plushy.plutonian.plutonic.pneumatic.poached.poesque.poetic.poignant.poised.polished.polite.pollockian.poly.polygonal.polymer.polynesian.popean.popped.popular.portly.posh.positronic.posthuman.potent.pouncy.powdery.powerful.pragmatic.prancy.precise.precocious.precognitive.preeminent.premier.prescient.pressed.pressurized.prestigious.pretty.primeval.primordial.princely.printed.pristine.private.prized.prodigious.profane.proficient.profound.profuse.prokofievian.prolific.promethean.prompt.proper.prophetic.prosaic.prosperous.protean.proto.protostellar.proud.proustian.providential.prudent.psionic.puccinian.puckish.pudgy.puffed.pulled.pulsar.punctilious.punctual.pungent.punic.pure.purposeful.pushkinian.pynchonesque.pythagorean.quaint.quantum.quartered.quasar.questing.quick.quiescent.quiet.quintessential.quirky.quixotic.rabelaisian.racinian.radar.radiant.radio.rainwashed.rainy.rakish.rambunctious.raphaelesque.rapid.rapturous.rare.rational.ravelian.rawlsian.raytraced.ready.reasonable.rebooted.receptive.recondite.recursive.redolent.reduced.reedy.refined.reflective.refulgent.regal.relativistic.relaxed.reliable.remarkable.rembrandtesque.remote.rendered.renoiresque.renowned.replete.replicated.resilient.resinous.resolute.resourceful.respectful.resplendent.responsive.restful.restive.restless.reticent.retro.reverent.rhapsodic.rhodian.rhythmic.ricardian.rich.richelieuvian.riemannian.rigorous.rilkean.rimbaudian.rimed.ringed.ripe.ripening.rippling.risible.riverine.riveted.roaming.roaring.roasted.robed.robotic.robust.rolled.roly.roman.romanov.romantic.rompy.rooseveltian.roseate.rosy.rothkoesque.rousing.rousseauian.rowdy.royal.rubenesque.ruddy.runic.rushy.russet.rustic.sabine.sable.sacred.sagacious.sage.saintly.salient.saline.salingeresque.salted.salty.salubrious.samian.sandaled.sandy.sanguine.sapid.sapient.sapphic.sardonic.sarmatian.sartrean.sassy.satiny.saturnian.saturnine.saucy.savory.savvy.saxon.scalding.scarlet.schielesque.schillerian.schoenbergian.scholarly.schubertian.schumannesque.schumpeterian.scintillating.scorched.scorsesean.scrappy.scruffy.scrupulous.scythian.seaborne.seamless.seared.seasonal.seaward.secure.sedate.sedgy.sedimentary.sedulous.seemly.seismic.selenic.selfless.sensible.sensitive.sentient.sentimental.seraphic.sere.serene.seuratian.shaded.shadowed.shadowy.shaggy.shaken.shakespearean.shamanic.shannonian.sharded.sharp.shaved.shavian.shelleyan.shielded.shimmering.shiny.shoreless.shostakovian.shrewd.shucked.sibelian.sibilant.sibylline.sicilian.sidereal.sienna.sifted.sigma.silicon.silken.silky.silly.silty.silver.silvered.simmering.simulated.sincere.singed.singing.singular.sinuous.sisyphean.sizzling.skeptical.skillful.skinnerian.skittish.skyward.sleek.sleepless.sleepy.slender.sliced.slick.slipstreamed.slow.sly.smart.smashy.smithian.smoked.smoky.smoldering.smooth.snappy.snazzy.snoozy.snowy.snug.snuggly.soaring.sociable.socratic.sodden.soft.sogdian.solar.solarpunk.solemn.solid.somnolent.sonar.song.sonic.sonorous.sooty.soporific.soulful.sound.soundless.sour.southward.sovereign.spaceborne.spacefaring.spacious.sparkling.sparkly.spartan.special.speckled.spectacular.spectral.speedy.spellbound.spiced.spicy.spielbergian.spiffy.spinozan.spirited.splashy.splendid.split.sploshy.spontaneous.spooky.sporty.spotless.spotted.sprightly.sproingy.spry.spun.spunky.squally.squashy.squelchy.squiggly.squishy.staid.stainless.stalwart.starborn.starfaring.starless.starlit.stasisbound.stately.steadfast.steady.steaming.steampunk.steely.steeped.steinbeckian.stellar.stellarborn.sticky.stirred.stirring.stoic.stoical.stolid.stompy.stoppardian.storied.stormy.stout.strained.stratospheric.straussian.stravinskian.streaky.stretched.striking.strindbergian.striped.strong.stuart.stubby.studious.stunning.sturdy.stygian.suave.subatomic.sublime.suborbital.subsonic.substantial.subtle.succinct.succulent.sudsy.sugared.sugary.sumerian.summery.sunless.sunlit.sunny.sunward.superb.supergalactic.superlative.superluminal.supersonic.supple.supreme.sure.surreptitious.svelte.swanky.sweeping.sweet.swift.swiftian.swirled.swooshy.sylvan.sympathetic.synaptic.synchronous.synthetic.syrupy.tableside.tachyonic.taciturn.talented.talleyrandian.tame.tang.tangy.tarantinoesque.tarkovskian.tart.tasteful.tattered.taut.tawny.tectonic.telekinetic.telepathic.temperate.tempered.temporal.tenacious.tender.tennysonian.tenuous.tepid.tera.terran.terrific.terse.textured.thackerayan.thankful.thawed.theban.thessalian.theta.thorny.thorough.thoughtful.thracian.threadbare.thriving.thundery.tidal.tidy.timeless.timely.timeworn.tinkly.tiny.tipsy.tireless.titanesque.titanian.titanic.titanium.titianesque.toasted.toasty.tocharian.tokenized.tolerant.tolkienesque.tolstoyan.tonic.tonky.toothsome.torched.totemic.tough.towering.trackless.tranquil.transcendent.transhuman.treacly.treasured.tremendous.tremulous.trenchant.tricky.trim.triumphant.trojan.trollopian.truculent.true.truffautian.truffled.trusty.truthful.tudor.turbo.turingian.turneresque.twangy.twilight.twilit.twinkling.twinkly.ubiquitous.ultra.ultrasonic.ultraviolet.umami.umber.unassuming.unbounded.uncanny.uncorked.unctuous.undaunted.underworldly.undocked.undying.unearthly.unerring.unflappable.unique.unknown.unruffled.upbeat.upgraded.upright.upstanding.upward.uranian.urbane.utopian.vacuous.valeryan.valiant.valorous.vandal.vangoghian.vast.veblenian.vectorized.vedic.vehement.veiled.velazquezian.velvet.velvety.venerable.venturous.venusian.veracious.verbose.verdant.verdian.verdurous.verlainian.vermeerian.vermilion.vernal.verneian.versatile.vesper.vespertine.vibrant.victorian.vigilant.vigorous.vintage.violet.virgilian.virtual.virtuous.visceral.vital.vivacious.vivid.vocal.voidborn.voidward.volcanic.voltairean.voluble.vonnegutian.voracious.voxel.vroomy.wacky.wagnerian.wakeful.waking.wan.wandering.warholian.warm.warped.wary.washingtonian.wayward.wealthy.weathered.weberian.welcome.welded.wellesian.wellsian.westward.whacky.whimsical.whimsy.whipped.whisked.whispering.whistlerian.whitmanesque.whole.wholesome.whooshy.wide.wiggly.wild.wildean.willowy.wilsonian.wily.windswept.windy.winged.winning.winsome.wintry.wired.wireframe.wireless.wise.wishful.wispy.wistful.wittgensteinian.witty.wobbly.wodehousian.wondrous.wonky.wooded.woody.woolly.woozy.wordless.wordsworthian.wormholed.worthy.wraithlike.wreathed.wriggly.wry.xenial.xeno.yanky.yearning.yeasty.yeatsian.young.youthful.yuletide.yummy.zany.zappy.zealous.zested.zestful.zesty.zeta.zingy.zippy.zodiacal.zonked.zonky.zoomy.zoroastrian`.split(`.`),R_=`abalone.absinthe.absyrtus.accelerator.achilles.acorn.acquerello.actuator.adobo.adonis.aeetes.aegis.aello.aeneas.aengus.aether.affogato.afterburner.agartha.agate.agni.agnolotti.aioli.airlock.ajax.aji.albatross.alder.ale.alecto.aleppo.alfheim.allegory.alliteration.almond.amaranth.amaretto.amaterasu.ambrosia.americano.amphiaraus.anago.anapest.ancho.anchovy.android.andromeda.anise.annal.annwn.ansible.antaeus.antenna.anthem.antigone.antimony.antistrophe.anubis.aoidos.aperol.aphelion.aphrodite.apogee.apollo.apple.apricot.aquamarine.aquavit.aqueduct.arabica.arachne.arawn.arbor.arborio.arc.arcadia.arch.archipelago.ares.argo.argon.argonaut.aria.ariadne.ark.arke.armagnac.array.arrow.artemis.arthur.artichoke.artifact.arugula.asgard.asgardia.ash.asparagus.aspen.assam.assonance.asteroid.astronaut.atalanta.athena.atlantis.atlas.atoll.atom.atropos.aubergine.augean.aura.aurora.avalon.avalonia.avocado.awning.axion.axle.azurite.bacchus.bagna.baharat.balder.ballad.balladeer.banana.banshee.baozi.bard.barge.barium.barley.barn.basalt.basil.basilisk.basmati.bastet.bastion.bay.bayleaf.beacon.beam.bean.bearing.beech.beetroot.behemoth.bellini.beowulf.bergamot.berth.beryl.beryllium.bifrost.biodome.birch.biscotti.bismuth.bisque.bit.bittern.blackberry.blast.blaster.blini.block.blodeuwedd.bloodstone.blossom.bluebell.blueberry.bolt.bomba.bonito.boom.borage.boson.botargo.bottarga.bouillon.boundary.bow.bower.bragi.bramble.bran.branch.brandy.branwen.breeze.brew.bridge.brigid.brioche.broccoli.brook.brulee.brunhild.brush.bucatini.buckler.buckwheat.buffer.bulkhead.bunting.burrata.burst.bus.busiris.butte.butter.buttercup.butterscotch.byte.cabbage.cabin.cacao.cachaca.cache.cacus.cadence.caesura.calamarata.calamari.calcite.caldera.calliope.calvados.calypso.cam.camellia.camelot.camembert.campari.canal.cannelloni.cannoli.canopy.cantaloupe.cantata.canticle.canvas.canyon.canzone.capacitor.capellini.caper.capon.cappelletti.cappuccino.capsule.caramel.cardamom.cardoon.carillon.carnaroli.carnation.carol.carrier.carrot.cascade.cashew.cassandra.cassis.castle.castor.cavatelli.caviar.cayenne.cedar.celaeno.celeriac.cell.centaur.cerberi.cerberus.cernunnos.ceryneian.cesium.ceto.ceylon.chaff.chaffinch.chai.chain.chalk.chamomile.champagne.chandra.channel.chanson.chanterelle.chard.charon.chartreuse.cheddar.cherry.chert.chervil.chestnut.chickweed.chicory.chili.chime.chimera.chimichurri.chimney.chip.chipotle.chirashi.chiron.chive.chocolate.chorale.chorizo.chorus.chronicle.chrysanthemum.chrysaor.chrysomallus.chutney.ciabatta.cibola.cider.cilantro.cinder.cinnamon.cipher.circe.circlet.circuit.cirque.cistern.citadel.citrine.citron.clementine.cliff.clio.clipper.cloak.clotho.cloud.clove.clover.cluster.coal.cobbler.cockaigne.cockpit.cocoa.coconut.codex.coffee.cog.cognac.coif.coil.col.colchis.collider.colony.combe.comet.compote.concerto.conchiglie.conduit.confit.console.consomme.consonance.continuum.contour.cookies.coordinate.core.coriander.cormorant.corona.coronet.cortado.corvette.cosmos.cottage.couplet.course.couscous.cove.cowl.cowslip.crab.craft.crag.cranberry.crane.crayon.cream.creme.crepe.cress.crocus.croissant.crosne.crown.cruiser.crumble.cryopod.cryosleep.crystal.cuchulainn.cuckoo.cucumber.cuirass.cumin.cupid.curlew.currant.current.curry.custard.cyborg.cycle.cyclops.cyclotron.cylinder.dactyl.daedalus.daemon.daffodil.dagda.dahlia.daiquiri.dais.daisy.dale.dam.dandelion.danu.daphne.darjeeling.dart.dashi.date.dawn.daydream.deck.deirdre.demeter.destroyer.dew.diadem.diary.dill.dimension.diode.diomedean.dionysus.ditalini.ditch.djinn.dock.doenjang.domain.donburi.donjon.door.doppio.dove.downlink.dreadnought.dream.drift.droid.dryad.dukkah.dulce.dumpling.dune.durga.dusk.dust.dyke.eagle.earlgrey.easel.echidna.echo.eclair.eclipse.ecliptic.edamame.eddy.edelweiss.edge.egret.einsteinium.elderflower.eldorado.electra.elegy.elm.elysium.ember.endive.enigma.enjambment.enkidu.envoi.eos.epigram.epistle.epode.erato.erinyes.eros.erymanthian.escargot.espresso.estuary.eumenides.euryale.eurybia.eurydice.eurytion.excalibur.exoplanet.fable.fafnir.falcon.fancy.farfalle.fate.feather.feldspar.fell.fence.fennel.fenrir.fenugreek.fermion.fern.fettuccine.fiddlehead.field.fig.finch.finn.fionn.firebird.firefly.fission.fizz.fjord.flake.flame.flare.flash.flicker.flint.flue.fluorite.flux.flywheel.focaccia.fog.folio.fondant.forge.fortress.foxglove.fragment.fraise.frame.frangipane.frappe.freesia.fregola.freighter.freya.frigate.frigg.frost.fudge.fugue.fumarole.furies.fusilli.fusion.gaia.galahad.galangal.galatea.galaxy.galette.galleon.gallium.ganache.ganesh.gannet.gantry.ganymede.garam.gardenia.garlic.garuda.gateway.gauntlet.gawain.gazebo.gear.gelato.gemelli.genmaicha.genoise.geranium.germ.germanium.geryon.geyser.ghazal.ghee.ghost.gilgamesh.ginger.gingko.ginnungagap.girder.glacier.glade.glaze.gleam.gleeman.glen.glimmer.glint.glitter.gloss.glow.gluon.gnocchi.gochujang.goldfinch.golem.goose.gooseberry.gorgon.gouda.governor.gradient.graeae.granary.granite.grapefruit.grappa.gratin.graviton.greave.grebe.gremolata.grenadine.grendel.grid.griffin.gruyere.guajillo.guava.gudrun.guinevere.gunkan.gwydion.gyoza.gyroscope.habanero.habitat.hades.hadron.haiku.hall.halloumi.halo.halva.hamachi.hangar.hanuman.harissa.harpies.harpy.harvest.hatch.hauberk.hawthorn.haze.hazel.hazelnut.heading.headland.heap.heart.hearth.heather.hecate.hedge.heimdall.hel.helheim.helios.helium.helix.helle.hellebore.helm.hemistich.hephaestus.hera.hermes.heron.hesperides.hestia.hibiscus.hippogriff.hirame.hive.hoisin.hojicha.hollandaise.hollow.holly.hologram.honey.honeycomb.honeysuckle.hood.hoopoe.horizon.horseradish.horus.hrothgar.hub.huckleberry.hue.huginn.hull.husk.hut.hyacinth.hydra.hydras.hylas.hymn.hyperborea.hypercube.hyperdrive.hyperion.hyperspace.hyssop.iamb.ibis.icarus.idas.idunn.idyll.igniter.igraine.ikura.indium.indra.inductor.infusion.injector.ink.inlet.inspiration.ion.iridium.iris.ishtar.isis.isolde.isotope.ivy.iwashi.izanagi.jackdaw.jackfruit.jalapeno.janus.jasmine.jason.jasper.javelin.jay.jet.jiaozi.jongleur.jonquil.jormungandr.jotunheim.journal.julep.jumpgate.juniper.juno.jupiter.kaffir.kale.kali.kampachi.karaage.karasumi.katsu.keel.keep.kefir.kelpie.kenning.kernel.kestrel.khinkali.kiln.kimchi.kingfisher.kinmedai.kirsch.kite.kitsune.kiwi.koan.kohlrabi.kombucha.koshihikari.kraken.krypton.kumquat.kvass.lachesis.lacquer.ladon.ladons.laertes.lager.lagoon.lake.lakshmi.lambic.lament.lance.lancelot.lander.lane.langoustine.lantern.lapis.lark.larkspur.lasagna.latte.laureate.laurel.lava.lavender.leaf.leda.leek.legend.lemon.lemonbalm.lemongrass.lemuria.lens.lentil.lepton.lernaean.lethe.letter.levee.lever.leviathan.lightyear.lily.lime.limerick.limoncello.linden.linguine.link.linnet.lir.lithium.lityerses.lobster.loch.lock.lodge.loki.loop.loquat.lotus.lovage.lugh.lullaby.lungo.luster.lychee.lynceus.lyonesse.lyricist.macadamia.macaron.macchiato.madai.madeleine.madrigal.magma.magnolia.magpie.mail.mainframe.maki.makrut.malachite.manannan.mango.manicotti.manor.manti.manticore.mantle.mantou.manuscript.maple.marble.marduk.margarita.marigold.marjoram.marquee.marrow.martini.marvel.marzipan.masago.masala.mascarpone.mast.matcha.matrix.mead.meadow.mech.medea.medusa.megaera.meleager.memoir.mentaiko.mercury.meringue.merlin.merlot.mesa.mesh.metaphor.meteor.meter.mezcal.mezzaluna.mica.midas.midgard.mill.mimir.mimosa.minerva.minotaur.minstrel.mint.minuet.miracle.mirin.mirror.miso.missive.mist.mjolnir.mocha.module.moira.mojito.molasses.mole.momo.monolith.moonbase.moonbeam.moonstone.moor.mopsus.mordred.morel.morgana.morpheus.morrigan.moss.mote.motet.mousse.mu.mulberry.muninn.muon.muse.muspelheim.mustard.myrtle.mystery.myth.nadir.naga.naiad.nanite.nanobot.narcissus.neapolitan.nebula.nectarine.needle.negroni.nemean.nemesis.neon.neptune.neptunium.nereid.nereus.nessus.nest.nestor.net.nettle.neutrino.nexus.niamh.nib.nibble.nibiru.niflheim.nightingale.nigiri.nike.niobe.njord.nocturne.node.nog.nori.norn.note.nougat.nova.nozzle.nuada.nutmeg.nyx.oak.oasis.oat.obelisk.oberon.obsidian.oceanid.oceanus.octave.octavo.ocypete.ode.odin.odysseus.oisin.okonomiyaki.olive.olympus.oni.onigiri.oolong.oracle.orange.orb.orbit.orbiter.orchard.orchid.oreads.orecchiette.oregano.orion.orpheus.orthros.orthrus.orzo.oscillator.osiris.osmium.osprey.ouroboros.outline.outpost.ouzo.oven.overture.owl.oyster.paccheri.packet.padron.page.palace.palette.palladium.palm.pan.pandan.pandora.panettone.pansotti.pansy.pantoum.papaya.pappardelle.paprika.papyrus.parable.paradox.parcae.parchment.parfait.parmesan.parsec.parsley.parsnip.particle.partridge.parvati.pasilla.passionfruit.pastel.pastis.patina.pavilion.pavlova.peach.peak.pear.pebble.pecan.pegasi.pegasus.pekoe.peleus.pelican.pelmeni.pen.pencil.penelope.penne.peony.pepper.peppermint.percival.peregrine.pergola.peridot.perigee.perihelion.perry.persephone.perseus.persillade.persimmon.pesto.petal.petrel.phase.pheasant.phoenix.pholus.phorcys.photon.phrixus.pickle.pierogi.pigment.pimento.pine.pineapple.ping.pinot.pipe.pipit.piquillo.pisco.pistachio.piston.pith.plane.plasma.plate.plover.plum.plume.pluto.plutonium.poblano.pod.podarge.poet.polenta.pollux.polyphemus.pomegranate.pomelo.pond.pontus.ponzu.pooka.pool.poplar.poppy.porcini.port.portal.porter.porthole.poseidon.positron.prairie.praline.prelude.primrose.prism.probe.profile.prometheus.prosciutto.prosecco.proteus.protocol.psalm.psyche.pudding.puffin.pulse.pumice.pumpkin.purslane.pwyll.pylon.pyrrhic.quadrant.quail.quark.quarto.quartz.quatrain.qubit.quetzalcoatl.queue.quill.quince.quinoa.quiver.radish.radium.radon.ragnarok.rain.rama.ramen.ramp.rampart.ramson.raspberry.ratatoskr.raven.ravioli.ray.reactor.realm.reaper.reed.reef.refrain.region.register.relay.relic.remnant.requiem.reservoir.residue.resistor.resonator.reverie.rhapsode.rhapsody.rhea.rhiannon.rhodium.rhododendron.rhubarb.rhyme.ricotta.riddle.ridge.riesling.rigatoni.rim.ring.risotto.ristretto.river.roast.robin.robusta.roc.rocket.rod.romesco.rondeau.rooibos.rook.root.rose.rosemary.rosewater.roundel.rover.rowan.rubidium.rum.rune.saba.saffron.saga.saison.sake.salmoriglio.salsa.salsify.sambal.sambuca.samphire.sancerre.sandpiper.sangria.sanma.sansho.saraswati.sashimi.sasquatch.satellite.satyr.sauternes.savanna.sawara.sazerac.scaffold.scalar.scallop.scansion.scepter.schnapps.schooner.scop.scorzonera.scotchbonnet.scroll.sector.seed.sekhmet.selene.selenite.selenium.selkie.sencha.sensor.sequoia.serenade.serrano.servo.sesame.sestina.sextet.shack.shade.shadow.shaft.shale.shallot.shambhala.shard.shed.sheen.sherbet.sherry.shield.shimmer.ship.shishito.shiso.shiva.shoyu.shrub.shumai.shuttle.sibyl.sif.signal.sigurd.silhouette.silo.simile.simurgh.singularity.siren.sita.skadi.skald.skiff.skuld.skylark.slant.slate.sleipnir.sling.slipstream.sliver.sloop.sluice.smithy.smoke.snowdrop.socket.sofrito.sonata.sonnet.soot.sorbet.sorrel.souffle.soul.soy.spaceport.spaghetti.spark.sparkle.sparrow.spear.speck.specter.speculoos.spelt.sphere.sphinx.sphinxes.spindle.spinel.spiral.spire.spirit.splinter.spoke.spondee.spore.spring.spritz.spruce.sriracha.ssamjang.stack.stanza.starbase.starlight.starling.starport.starship.stasis.station.steam.stellarator.steppe.stheno.stork.stracciatella.strawberry.stream.strontium.strophe.strozzapreti.strut.stylus.stymphalian.styx.subspace.sumac.summit.sunbeam.sunstone.supernova.surge.surya.susanoo.sushi.svartalfheim.swallow.swan.swarm.sycamore.syleus.synchrotron.tabard.tachyon.tagliatelle.tahini.takoyaki.taliesin.tamari.tamarind.tangerine.tanka.tanker.tapenade.tapioca.tarako.taranis.tare.tarn.tarragon.tartarus.telamon.telemetry.teleporter.tellurium.temaki.tempura.tengu.tensor.tent.tequila.tercet.teriyaki.terminal.tern.terraform.tesseract.tethys.thalassa.thalia.thallium.thaumas.themis.theseus.thistle.thor.thorium.thoth.threshold.throne.throttle.thrush.thruster.thule.thunderbird.thyme.tiamat.tiara.tide.tint.tintagel.tiphys.tiramisu.tirnanog.tisane.tisiphone.titan.tobiko.toccata.toddy.toffee.tofu.tokamak.tomatillo.tomato.tome.tone.tonka.tonkatsu.tor.tortellini.torus.tourmaline.tower.trace.track.transducer.transistor.treacle.trellis.triolet.tristan.triton.trochee.trofie.trope.troubadour.trouvere.truffle.trunk.truss.tug.tulip.tundra.tungsten.turbine.turmeric.turquoise.turret.twinkle.typhon.tyr.udon.ulysses.unagi.uni.unicorn.uplink.uramaki.urania.uranium.urd.urfa.uther.vale.valhalla.valkyrie.valve.vanadium.vanaheim.vanilla.vapor.vareniki.varnish.varuna.vector.veil.vellum.vent.venus.verbena.verdandi.verge.verjus.vermouth.verse.vessel.vesta.vestige.vialone.viewport.villanelle.vishnu.vodka.volcano.volta.volume.vortex.vulcan.wall.walnut.waltz.warbler.warpgate.wasabi.wash.watercress.watermelon.wave.waypoint.web.weir.well.wendigo.wheat.whisky.whisper.wiglaf.willow.wimple.window.wisteria.wonder.wonton.woodcock.woodpecker.word.wormhole.wraith.wren.wyrm.wyvern.xenon.yacht.yakitori.yama.yarrow.yeti.yew.yggdrasil.yokai.yuzu.zaatar.zabaglione.zenith.zephyr.zeus.zinnia.zircon.zirconium.ziti.zone.zucchini`.split(`.`);L_.length*R_.length;const z_=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`discovery`,`upgrade`,`workflow`,`bash`,`jshd`,`preview`,`scoop-notify`,`scoop-idle`,`scoop-wait`,`sudo-request`]);function B_(e){return e!=null&&z_.has(e)}const V_=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]),H_=65536;function U_(e,t=H_){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${q_(t)} of ${q_(e.length)} — the agent received the full output]`}function W_(e,t=H_,n=4){if(typeof e==`string`)return U_(e,t);if(typeof e!=`object`||!e||n<=0)return e;if(Array.isArray(e)){let r=null;for(let i=0;i<e.length;i++){let a=W_(e[i],t,n-1);a!==e[i]&&(r??=[...e],r[i]=a)}return r??e}let r=null;for(let[i,a]of Object.entries(e)){let o=W_(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}function G_(e,t=H_){if(!e)return e;if(!vn().test(e))return U_(e,t);let n=U_(e.replace(vn(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function K_(e,t=H_){if(e.length<=t)return e;if(!vn().test(e))return U_(e,t);let n=[],r=0;for(let i of e.matchAll(vn()))n.push(U_(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(U_(e.slice(r),t)),n.join(``)}function q_(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}var J_=e({agentMessagesToChatMessages:()=>Y_,lickChannelFromBody:()=>uv,lickChannelFromSenderName:()=>lv,lickIdFromBody:()=>dv,splitEnvelopes:()=>cv,unwrapMessageEnvelope:()=>sv});function Y_(e,t={}){let{source:n=`cone`,idSeed:r=ov,hiddenToolNames:i=V_,uncapped:a=!1}=t,o=[],s=null,c=new Set;for(let t of e)$_(t)?(o.push(...X_(t,r)),s=null):ev(t)?(s=Z_(t,n,r,i,c,a),o.push(s)):tv(t)&&Q_(t,s,c,a);return o}function X_(e,t){let n=nv(e.content);if(n.length===0)return[];let r=[];for(let i of cv(n)){if(i.body.length===0&&i.sender==null)continue;let n=(i.sender?lv(i.sender):null)??uv(i.body),a=n?dv(i.body):void 0,o={id:n===`sudo-request`&&a?`sudo-request-${a}`:t(),role:`user`,content:i.body,timestamp:e.timestamp};n&&(o.source=`lick`,o.channel=n,a&&(o.lickId=a)),r.push(o)}return r}function Z_(e,t,n,r,i,a=!1){let o=[];for(let t of av(e,a))r.has(t.name)?i.add(t.id):o.push(t);let s={id:n(),role:`assistant`,content:nv(e.content),timestamp:e.timestamp,source:t,model:e.model},{usage:c}=e;return c&&(s.usage={input:c.input,output:c.output,cacheRead:c.cacheRead,cacheWrite:c.cacheWrite,cost:{input:c.cost.input,output:c.cost.output,cacheRead:c.cost.cacheRead,cacheWrite:c.cost.cacheWrite,total:c.cost.total}}),o.length>0&&(s.toolCalls=o),s}function Q_(e,t,n,r=!1){if(n.has(e.toolCallId))return;let i=t?.toolCalls?.find(t=>t.id===e.toolCallId);if(!i)return;let a=nv(e.content);i.result=r?a:U_(a),i.isError=e.isError}function $_(e){return e.role===`user`}function ev(e){return e.role===`assistant`}function tv(e){return e.role===`toolResult`}function nv(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)rv(n)&&t.push(n.text);return t.join(``)}function rv(e){return e.type===`text`}function iv(e){return e.type===`toolCall`}function av(e,t=!1){if(!Array.isArray(e.content))return[];let n=[];for(let r of e.content)iv(r)&&n.push({id:r.id,name:r.name,input:t?r.arguments:W_(r.arguments)});return n}function ov(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function sv(e){if(!e.startsWith(`[`))return null;let t=e.indexOf(`] `);if(t<=0||e.lastIndexOf(`
885
+ `,t)!==-1)return null;let n=e.slice(t+2);if(n.startsWith(`User: `))return{sender:`User`,body:n.slice(6)};for(let e of z_){let t=`${e}:`;if(!n.startsWith(t))continue;let r=n.indexOf(`
886
886
  `),i=r===-1?n.length:r,a=n.slice(0,i),o=-1,s=a.indexOf(`[`,t.length);if(s>t.length&&(o=a.lastIndexOf(`: `,s)),o<t.length&&(o=n.indexOf(`: `,t.length)),!(o<0||o>=i))return{sender:n.slice(0,o),body:n.slice(o+2)}}let r=n.indexOf(`
887
887
  `),i=r===-1?n.length:r,a=n.indexOf(`: `);if(a<=0||a>=i)return null;let o=n.slice(0,a);return o.includes(`
888
- `)?null:{sender:o,body:n.slice(a+2)}}function bv(e){if(e.length===0)return[];let t=e.split(`
888
+ `)?null:{sender:o,body:n.slice(a+2)}}function cv(e){if(e.length===0)return[];let t=e.split(`
889
889
  `);if(!t[0].startsWith(`[`))return[{sender:null,body:e}];let n=[],r=null,i=()=>{if(!r)return;let e=r.rest.length>0?`${r.firstLine}\n${r.rest.join(`
890
- `)}`:r.firstLine,t=yv(e);t?n.push({sender:t.sender,body:t.body}):n.push({sender:null,body:e}),r=null};for(let e of t){if(e.startsWith(`[`)&&/^\[[^\]\n]+\] /.test(e)&&e.includes(`: `)&&yv(e)){i(),r={firstLine:e,rest:[]};continue}r?r.rest.push(e):r={firstLine:e,rest:[]}}return i(),n.length===0?[{sender:null,body:e}]:n}function xv(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t);return Q_(n)?n:null}function Sv(e){let t=/^\[@[^\]\s]+ (completed|idle)\]/.exec(e);return t?t[1]===`idle`?`scoop-idle`:`scoop-notify`:/^\[@[^\]\s]+ sudo-request\]/.test(e)?`sudo-request`:/^\[scoop_wait [^\]]+\]/.test(e)?`scoop-wait`:e.startsWith(`[Session Reload]`)?`session-reload`:null}function Cv(e){return/^(?:Lick ID|Request ID): (\S+)/m.exec(e)?.[1]}function wv(e){let t=sv(e.messages,{source:e.name}),n=t.filter(e=>e.role===`assistant`).length,r=[`# Agent session: ${e.name}`,``,`- jid: ${e.jid}`,`- exit code: ${e.exitCode}`,`- turns: ${n}`,`- messages: ${e.messages.length}`,`- timestamp: ${e.timestamp}`,``,`## Prompt`,``,e.prompt.length>0?e.prompt:`_(empty prompt)_`,``,`---`,``];if(t.length===0)r.push(`_(no messages captured)_`,``);else for(let e of t)Tv(r,e);return Se(r.join(`
891
- `),Ce())}function Tv(e,t){e.push(`## ${t.role}`,``);let n=t.content.trim();n.length>0&&e.push(n,``);for(let n of t.toolCalls??[])Ev(e,n)}function Ev(e,t){e.push(`### tool: ${t.name}`,``,`Input:`,``,"```json",Dv(t.input),"```",``),t.result!==void 0&&e.push(t.isError?`Result (error):`:`Result:`,``,"```",t.result,"```",``)}function Dv(e){try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}const Ov=_(`agent-bridge`),kv=`__slicc_agent`;function Av(e){for(let t=0;t<8;t++){let t=e.generateName(),n=`agent_${ey(t)}`;if(!e.orchestrator.getScoops().some(e=>e.jid===n))return t}return e.generateUid()}function jv(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=Pn(n);if(!r||r.length===0)return null;let i=zn(n);return i?{modelId:r,providerId:i}:{modelId:r}}function Mv(e,t){let n=e.getWorkUnits(),r=(t===null?null:n.rootOf(t))??n.resolveDefaultRoot();return rr(r?.descriptor.workspace??nr)}function Nv(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=Rn(n).level;return r&&sr(r)?r:null}function Pv(e,t){let n=e.modelId,r,i;if(n!==void 0){let a=e.modelProviderId!==void 0&&n!==``?`${e.modelProviderId}:${n}`:n,o=a===``?{ok:!1,error:`unknown model: ${n}`}:t(a);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};r=o.selection.modelId,i=o.selection.providerId}let a=e.thinkingLevel;if(a!==void 0&&!sr(a))return{error:{finalText:`agent: invalid thinking level: ${String(a)} (one of: ${cr.join(`, `)})`,exitCode:1}};let o=En(e.workspaceMode);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};let s=e.backgroundAfterSeconds;if(s!==void 0&&(typeof s!=`number`||!Number.isFinite(s)||s<0))return{error:{finalText:`agent: invalid backgroundAfterSeconds: ${String(s)} (seconds >= 0)`,exitCode:1}};let c=Fv(e);if(c)return c;let l=e.name;if(l!==void 0&&!Vv(l))return{error:{finalText:`agent: invalid name: ${l} (lowercase tokens joined by single dashes)`,exitCode:1}};for(let[t,n]of[[`maxTurns`,e.maxTurns],[`maxWallClockMs`,e.maxWallClockMs]])if(n!==void 0&&(!Number.isInteger(n)||n<=0))return{error:{finalText:`agent: ${t} must be a positive integer: ${String(n)}`,exitCode:1}};return{resolvedModelId:r,resolvedProviderId:i}}function Fv(e){let t=e.mergeOnSuccess,n=[[`successReceiptPath`,e.successReceiptPath],[`outcomeReceiptPath`,e.outcomeReceiptPath],[`mergeOnSuccess.targetPath`,t?.targetPath],[`mergeOnSuccess.basePath`,t?.basePath],[`mergeOnSuccess.draftPath`,t?.draftPath]],r=t===void 0?void 0:``;for(let[e,t]of n){let n=t??(e.startsWith(`mergeOnSuccess`)?r:void 0);if(n!==void 0&&!n.startsWith(`/`))return{error:{finalText:`agent: ${e} must be absolute: ${String(t)}`,exitCode:1}}}return null}function Iv(e){return/^agent run terminated: .*\bbound\b.*\bexceeded\b/.test(e)}async function Lv(e,t){let n=async t=>{try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){if(cy(e,`ENOENT`))return``;throw e}},r=async()=>{for(let n of[t.basePath,t.draftPath])try{await e.rm(n)}catch{}},i=async t=>{try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){if(cy(e,`ENOENT`))return null;throw e}};try{let a=await i(t.draftPath);if(a===null)return await r(),{applied:!1,conflicts:0};let o=await n(t.targetPath);if(a===o)return await r(),{applied:!1,conflicts:0};let s=await i(t.basePath);if(s===null)return{applied:!1,conflicts:0,error:`base snapshot missing; target left as-is`};if(a===s)return await r(),{applied:!1,conflicts:0};if(o===s)return await e.writeFile(t.targetPath,a),await r(),{applied:!0,conflicts:0};let c=Cn(o,s,a,{favor:`theirs`});return await e.writeFile(t.targetPath,c.content),await r(),{applied:!0,conflicts:c.conflicts}}catch(e){let n=sy(e);return Ov.warn(`mergeOnSuccess failed; target left as-is, staging kept`,{target:t.targetPath,error:n}),{applied:!1,conflicts:0,error:n}}}async function Rv(e,t,n,r){try{let i=t.slice(0,t.lastIndexOf(`/`));i&&await e.mkdir(i,{recursive:!0}),await e.writeFile(t,JSON.stringify({status:n.exitCode===0?`ok`:`failed`,exitCode:n.exitCode,finishedAt:new Date().toISOString(),...n.exitCode===0&&!r?.promotedOnTrip?{}:{reason:n.finalText.slice(0,500)},...r?{merge:r}:{}},null,2))}catch(e){Ov.warn(`outcome receipt write failed`,{path:t,error:sy(e)})}}async function zv(e,t){try{let n=t.slice(0,t.lastIndexOf(`/`));n&&await e.mkdir(n,{recursive:!0}),await e.writeFile(t,new Date().toISOString())}catch(e){Ov.warn(`success receipt write failed`,{path:t,error:sy(e)})}}const Bv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function Vv(e){return Bv.test(e)}const Hv=`agent: name already in use`;async function Uv(e,t,n,r,i){if(t.persistSession===!1)return;let a=t.persistSession===!0?`/sessions`:`/tmp`,o=new Date().toISOString().replace(/[:.]/g,`-`),s=`${a}/agent-${r}-${o}.md`;try{let c=e.orchestrator.getScoopContext(n),l=typeof c?.getAgentMessages==`function`?c.getAgentMessages():[],u=wv({name:r,jid:n,prompt:t.prompt,exitCode:i.exitCode,messages:l,timestamp:o});await e.sharedFs.mkdir(a,{recursive:!0}),await e.sharedFs.writeFile(s,u)}catch(e){Ov.warn(`agent session archive write failed`,{path:s,error:sy(e)})}}function Wv(e,t,n,r,i,a){let o=ny(e.cwd),s=ry(e.workspaceMode),c={visiblePaths:ay(e,a,s),writablePaths:oy([...iy(e.writablePaths,o,s),`${i}/`,`/tmp/`]),workspaceMode:s,allowedCommands:e.allowedCommands};return e.maxTurns!==void 0&&(c.maxTurns=e.maxTurns),e.maxWallClockMs!==void 0&&(c.maxWallClockMs=e.maxWallClockMs),e.backgroundAfterSeconds!==void 0&&(c.backgroundAfterSeconds=e.backgroundAfterSeconds),t&&(c.modelId=t,n!==void 0&&(c.modelProviderId=n)),r!==void 0&&(c.thinkingLevel=r),e.structuredOutputSchema!==void 0&&(c.structuredOutputSchema=e.structuredOutputSchema),c}function Gv(e,t){let n={sendMessages:[],responseBuffer:``,scoopError:null,unsubscribe:null};return n.unsubscribe=e.observeScoop(t,{onSendMessage:e=>{n.sendMessages.push(e)},onResponse:(e,t)=>{t?n.responseBuffer+=e:n.responseBuffer=e},onError:e=>{n.scoopError===null&&(n.scoopError=e)}}),n}async function Kv(e,t,n,r,i){if(await e.sendPrompt(t,n,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};if(r){let n=e.getScoopContext(t),r=n?.getStructuredOutput?.();for(let a=0;a<2&&!r?.captured;a++){if(await e.sendPrompt(t,`You did not call StructuredOutput. Call it now with your result, matching the schema.`,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};r=n?.getStructuredOutput?.()}return r?.captured?{finalText:JSON.stringify(r.value),exitCode:0}:{finalText:`agent: scoop did not produce StructuredOutput`,exitCode:1}}return{finalText:i.sendMessages.length>0?i.sendMessages[i.sendMessages.length-1]:i.responseBuffer,exitCode:0}}async function qv(e,t,n,r){try{await e.orchestrator.unregisterScoop(t)}catch(e){Ov.warn(`unregisterScoop failed`,{jid:t,error:sy(e)})}try{await e.sharedFs.rm(r,{recursive:!0})}catch(e){cy(e,`ENOENT`)||Ov.warn(`scratch folder cleanup failed`,{folder:n,error:sy(e)})}if(e.sessionStore)try{await e.sessionStore.delete(t)}catch(e){Ov.warn(`sessionStore.delete failed`,{jid:t,error:sy(e)})}}async function Jv(e,t,n,r,i){let a=await Yv(e,t,n,r,i),o;return a.exitCode===0&&t.mergeOnSuccess?(o=await Lv(e.sharedFs,t.mergeOnSuccess),o.error!==void 0&&(a={finalText:`agent: mergeOnSuccess failed: ${o.error}`,exitCode:1})):t.mergeOnSuccess&&Iv(a.finalText)&&(o=await Lv(e.sharedFs,t.mergeOnSuccess),o.applied?(o.promotedOnTrip=!0,Ov.info(`run tripped its bound; staged rewrite promoted`,{target:t.mergeOnSuccess.targetPath,conflicts:o.conflicts}),a={finalText:`${a.finalText} — staged rewrite promoted`,exitCode:0}):o.error===void 0&&(o=void 0)),a.exitCode===0&&t.successReceiptPath&&await zv(e.sharedFs,t.successReceiptPath),t.outcomeReceiptPath&&await Rv(e.sharedFs,t.outcomeReceiptPath,a,o),a}async function Yv(e,t,n,r,i){try{await e.orchestrator.registerScoop(n)}catch(e){return{finalText:i.scoopError??sy(e),exitCode:1}}try{let n=await Kv(e.orchestrator,r,t.prompt,t.structuredOutputSchema,i);return t.signal?.aborted?{finalText:`agent: aborted`,exitCode:1}:n||{finalText:i.scoopError??``,exitCode:1}}catch(e){return{finalText:i.scoopError??sy(e),exitCode:1}}}function Xv(e,t,n=null,r={}){let i={orchestrator:e,sharedFs:t,sessionStore:n,generateName:r.generateName??$v,generateUid:r.generateUid??Qv,resolveModel:r.resolveModel??ty};async function a(e){let t=Pv(e,i.resolveModel);if(`error`in t)return t.error;let n=jv(i.orchestrator,e.parentJid),r=t.resolvedModelId??n?.modelId??``,a=t.resolvedModelId===void 0?n?.providerId:t.resolvedProviderId,o=e.thinkingLevel??Nv(i.orchestrator,e.parentJid)??void 0,s=e.name===void 0?Av(i):e.name,c=`agent-${s}`,l=`agent_${ey(s)}`,u=new Set(i.orchestrator.getScoops().map(e=>e.jid));if(e.name!==void 0&&u.has(l))return{finalText:`${Hv}: ${s}`,exitCode:1};let d=(e.exclusiveWith??[]).find(e=>u.has(`agent_${ey(e)}`));if(d!==void 0)return{finalText:`${Hv}: ${d}`,exitCode:1};let f=`/scoops/${c}`,p=e.parentJid??k(i.orchestrator.getScoops())[0]?.jid??null,m=Wv(e,r,a,o,f,Mv(i.orchestrator,p)),h={jid:l,name:c,folder:c,requiresTrigger:!1,assistantLabel:c,addedAt:new Date().toISOString(),config:m,configSchemaVersion:3,notifyOnComplete:e.notifyOnComplete===!0,parentJid:p},ee=Gv(i.orchestrator,l),g=()=>{try{i.orchestrator.stopScoop(l)}catch(e){Ov.warn(`stopScoop on abort failed`,{jid:l,error:sy(e)})}};if(e.signal?.addEventListener(`abort`,g,{once:!0}),e.signal?.aborted)return e.signal.removeEventListener(`abort`,g),ee.unsubscribe?.(),{finalText:`agent: aborted before start`,exitCode:1};let te={finalText:``,exitCode:1};try{return te=await Jv(i,e,h,l,ee),te}finally{e.signal?.removeEventListener(`abort`,g),ee.unsubscribe?.(),await Uv(i,e,l,s,te),await qv(i,l,c,f)}}return{spawn:a}}function Zv(e,t,n=null,r={}){let i=Xv(e,t,n,r);return globalThis[kv]=i,Ov.info(`agent bridge published on globalThis.__slicc_agent`),i}function Qv(){let e=globalThis;return typeof e.crypto?.randomUUID==`function`?e.crypto.randomUUID().replace(/-/g,``).slice(0,12):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function $v(){return`${Y_[Math.floor(Math.random()*Y_.length)]}-${X_[Math.floor(Math.random()*X_.length)]}`}function ey(e){return e.replace(/-/g,`_`)}function ty(e){try{return de(e)}catch(t){return Ov.warn(`defaultResolveModel: provider/account lookup threw; treating model as unknown`,{modelId:e,error:t instanceof Error?t.message:String(t)}),{ok:!1,error:`unknown model: ${e}`}}}function ny(e){let t=xn(e);return t.endsWith(`/`)?t:`${t}/`}function ry(e){let t=En(e);return t.ok?t.mode:Dn}function iy(e,t,n=Dn){let r=n===`private`?[t]:[t,`/shared/`];return e===void 0||e.some(e=>typeof e!=`string`||!e.startsWith(`/`)||e.includes(`\0`))?r:e.map(ny)}function ay(e,t,n=Dn){if(e.visiblePaths!==void 0)return e.visiblePaths.map(ny);if(n===`private`)return[];let r=[...t];return e.invokingCwd&&e.invokingCwd.length>0&&r.push(ny(e.invokingCwd)),oy(r)}function oy(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function sy(e){return e instanceof Error?e.message:String(e)}function cy(e,t){if(typeof e!=`object`||!e)return!1;let n=e.code;return typeof n==`string`&&n===t}const ly=`sessions`;function uy(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(ly)||e.createObjectStore(ly,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var dy=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await uy();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(ly,`readwrite`);i.objectStore(ly).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(ly,`readonly`).objectStore(ly).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(ly,`readonly`).objectStore(ly).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(ly,`readwrite`);i.objectStore(ly).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};const fy={summarizing:`summarizing`,fallback:`fallback`,cancelled:`discarded`,idle:`summarized`};var py=class{mintId;open=new Map;settled=new Map;constructor(e){this.mintId=e}apply(e,t,n,r){if(t===`extracting-memory`)return null;let i=this.open.get(e)??this.lateRetraction(e,t,n)??r;if(t!==`summarizing`&&!i)return null;t!==`summarizing`&&(this.open.delete(e),this.settled.delete(e));let a=i??this.mintId(e);if(t===`summarizing`&&this.open.set(e,a),(t===`idle`||t===`fallback`)&&n.roundId&&this.settled.set(e,{messageId:a,roundId:n.roundId}),t===`cancelled`)return{kind:`retract`,messageId:a};let o={trigger:n.trigger,state:fy[t],...n.transcriptPath?{transcriptPath:n.transcriptPath}:{}};return t===`summarizing`?{kind:`open`,messageId:a,marker:o}:{kind:`settle`,messageId:a,marker:o}}forget(e){this.open.delete(e),this.settled.delete(e)}lateRetraction(e,t,n){if(t!==`cancelled`||!n.roundId)return;let r=this.settled.get(e);return r?.roundId===n.roundId?r.messageId:void 0}},my=e({formatMountRecoveryPrompt:()=>xy,mdInlineCode:()=>by,recoverMounts:()=>vy,shellQuote:()=>yy});function hy(e){return e instanceof Error?e.message:String(e)}async function gy(e,t,n,r){let i=await _r(t.idbHandleKey),a=typeof i?.name==`string`?i.name:``,o={kind:`local`,path:e,dirName:a};if(!i||!(`queryPermission`in i))return{entry:o,ok:!1};let s;try{s=await i.queryPermission({mode:`readwrite`})}catch(t){return r?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:hy(t)}),{entry:o,ok:!1}}if(s!==`granted`)return{entry:o,ok:!1};try{let s=lr.fromHandle(i,{mountId:t.mountId});return await n.mount(e,s,{limits:ur}),r?.info?.(`Restored mount from previous session`,{path:e,name:a}),{entry:o,ok:!0}}catch(t){return r?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:hy(t)}),{entry:o,ok:!1}}}async function _y(e,t,n,r){let{kind:i,source:a,profile:o,mountId:s}=t,c=i===`s3`?`S3`:i===`aem`?`AEM`:`DA`;try{let t={source:a,profile:o,cache:new vr({mountId:s,ttlMs:3e4}),mountId:s},l=i===`s3`?new fr({...t,signedFetch:pr(o)}):i===`aem`?new hr({...t,signedFetch:gr()}):new dr({...t,signedFetch:gr()});return await n.mount(e,l),r?.info?.(`Restored ${c} mount from previous session`,{path:e,source:a}),{entry:{kind:i,path:e,source:a,profile:o,reason:``},ok:!0}}catch(t){let n=hy(t);return r?.warn?.(`Failed to restore ${c} mount`,{path:e,error:n}),{entry:{kind:i,path:e,source:a,profile:o,reason:n},ok:!1}}}async function vy(e,t,n){let r=[],i=[];for(let{targetPath:a,descriptor:o}of e){if(o.kind===`hostfs`)continue;let e=o.kind===`local`?await gy(a,o,t,n):await _y(a,o,t,n);(e.ok?r:i).push(e.entry)}return{restored:r,needsRecovery:i}}function yy(e){return`'${e.replace(/'/g,`'\\''`)}'`}function by(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function xy(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`||e.kind===`aem`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${by(t)})`:``;return`- ${by(e)}${n}`}),i=r.map(({path:e})=>` mount ${yy(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${yy(n)}`,a=`mount --source ${yy(t)}${i} ${yy(e)}`;return`- ${by(e)} (${by(t)}, profile ${by(n)}) — ${r}\n Retry: ${by(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
892
- `)}const Sy=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`bash`,`jshd`,`sudo-request`,`preview`,`discovery`]);function Cy(e){return e!=null&&Sy.has(e)}const wy={webhook:`Webhook Event`,sprinkle:`Sprinkle Event`,fswatch:`File Watch Event`,"session-reload":`Session Reload`,navigate:`Navigate Event`,upgrade:`Upgrade Event`,cherry:`Cherry Event`,workflow:`Workflow Event`,bash:`Background Command`,jshd:`jshd Unit`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`,preview:`Preview`,discovery:`Discovery Event`};function Ty(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`session-reload`:return Ey(e);case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`cherry`:return e.cherryName;case`workflow`:return e.workflowName;case`bash`:return e.bashJobId;case`jshd`:return e.jshdName;case`sudo-request`:return e.sudoScoopName;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Ey(e){let t=e.body?.reason;return typeof t==`string`&&t?t:`mount-recovery`}function Dy(e){let t=e.body,n=Array.isArray(t?.tools)?t.tools:[],r=n.map(e=>{let t=e.args?` ${e.args}`:``;return`- \`${e.toolName??`unknown`}\`${t}`});return`[Session Reload: tool-call-interrupted]\nThe page reloaded while your last turn was running. ${n.length===1?`A tool call was`:`${n.length} tool calls were`} still in flight, so ${n.length===1?`its result was`:`their results were`} lost:\n${r.join(`
893
- `)}\n\nThey were NOT re-run automatically, because tool calls can have side effects — each may or may not have completed. Check the current state (files, tabs, processes) before deciding whether to run any of them again, then continue the task.`}function Oy(e,t){let n=e.body,r=e.lickId;if(n?.reason===`tool-call-interrupted`){let n=r?`\n\nLick ID: ${r}\nCall \`lick_dismiss\` with this lick id once you have dealt with it.`:``;return{label:t,content:`${Dy(e)}${n}`}}if(n?.reason===`mount-recovery`){let e=xy(n.mounts??[]);return e===null?null:{label:t,content:`${e}${r?`\n\nLick ID: ${r}\nThis card is actionable: call \`lick_confirm\` with this lick id to re-run the listed \`mount …\` command(s) so the user can re-authorize, or \`lick_dismiss\` to leave them unmounted. The card flips to ✓ on confirm / muted ✗ on dismiss.`:``}`}}let i=Ly(e,t);if(!r)return i;let a=`\n\nLick ID: ${r}\nThis card is informational — there is NO confirm action. Call \`lick_dismiss\` with this lick id to acknowledge and clear it. The card flips to muted ✗ on dismiss.`;return{label:i.label,content:`${i.content}${a}`}}function ky(e,t){let n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`,i=e.body?.releasedAt??null,a=i?`\nReleased: ${i}`:``,o=e.lickId;return{label:t,content:`[${t}: ${n}→${r}]\n\nSLICC was upgraded from \`${n}\` to \`${r}\`.${a}${o?`\n\nLick ID: ${o}\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`). The card is a binary action: call \`lick_confirm\` with this lick id to **Update workspace files** (it runs the three-way merge of bundled vfs-root content into the user's VFS), or \`lick_dismiss\` to clear it. The card flips to ✓ on confirm / muted ✗ on dismiss. Reviewing the changelog is a separate step you can run first — it is NOT a card action.`:`
894
-
895
- Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function Ay(e,t){let n=e.cherryOrigin??`unknown origin`,r=e.cherryRuntimeId??`unknown`;return{label:t,content:`[${t}: ${e.cherryName??`unnamed`}] from ${n} (runtime ${r})\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function jy(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function My(e,t){let n=e.workflowName??`workflow`,r=e.resultPath??`(no result file)`,i=e.preview??``;return{label:t,content:`[${t}: ${n}] ${e.body?.status??`complete`} — ${i}\nFull result: ${r} (read it only if you need the whole thing).`}}function Ny(e,t){let n=e.jshdName??`unknown`,r=e.jshdRestarts??0,i=e.resultPath;return{label:t,content:`[${t}: ${n}] marked errored after ${r} restarts.\nThe restart policy stopped trying so the unit does not crash-loop.\n${i?`Logs: ${i} (page with \`jshd logs ${n}\`).`:`No log file was written.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nInspect with \`jshd status ${n}\`; start it again with \`jshd start -n ${n}\` after fixing the script.`}}function Py(e,t){let n=e.bashJobId??`unknown job`,r=e.bashJobPid===void 0?``:` (pid ${e.bashJobPid})`,i=e.bashCommand??`(unknown command)`,a=e.bashExitCode,o=a===0?`succeeded`:a===130||a===137||a===143?`was terminated (exit code ${a}) — killed by a signal, not by its own failure`:`failed (exit code ${a??`unknown`})`,s=e.resultPath;return{label:t,content:`[${t}: ${n}${r}] \`${i}\` ${o}.\n${s?`Full output: ${s} (page it with \`sed -n\`/\`tail\`/\`grep\` if the preview below is cut).`:`Its output could NOT be written to a file — the preview below is all that survived.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nThis is the delayed result of a command that was detached earlier in this session — do not re-run it. Act on it if it still matters, otherwise acknowledge and move on.`}}function Fy(e,t){let n=e.sudoScoopName??`a scoop`,r=e.lickId??`(unknown)`,i=e.sudoKind??`unknown`,a=e.sudoDetail??``,o=[`[${t}: ${n}]`,`Lick ID: ${r}`,`Kind: ${i}`,`Detail: ${a}`];return e.sudoReason&&o.push(`Reason given: ${e.sudoReason}`),e.sudoSuggestedPattern&&o.push(`Suggested pattern: ${e.sudoSuggestedPattern}`),o.push(``,`Use the lick_confirm tool with lick_id="${r}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${r}" and a reason to deny.`),{label:t,content:o.join(`
896
- `)}}function Iy(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.${e.discoveryKind===`llms-txt`&&e.lickId?`\n\nLick ID: ${e.lickId}\nThis card is dismiss-only: call \`lick_dismiss\` to add the advertising host to \`/etc/llmstxtignore\` and silence future discoveries without a prompt. There is NO confirm action.`:`
897
- This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function Ly(e,t){let n=Ty(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Ry(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Ly(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function zy(e,t){let n=Ly(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill … --all\` with any branch/path scope from the body, so it installs EVERY skill under that scope — a broad path can be many); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function By(e){let t=wy[e.type];return e.type===`session-reload`?Oy(e,t):e.type===`upgrade`?ky(e,t):e.type===`cherry`?Ay(e,t):e.type===`preview`?jy(e,t):e.type===`workflow`?My(e,t):e.type===`bash`?Py(e,t):e.type===`jshd`?Ny(e,t):e.type===`sudo-request`?Fy(e,t):e.type===`navigate`?zy(e,t):e.type===`webhook`?Ry(e,t):e.type===`discovery`?Iy(e,t):Ly(e,t)}function Vy(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i=n?e.config:Hy(e,r),a={jid:e.id??(n?`cone_${t()}`:`scoop_${r}_${t()}`),name:e.name,folder:r,requiresTrigger:!n,assistantLabel:n?`sliccy`:r,addedAt:new Date(t()).toISOString(),parentJid:e.parentId,...i?{config:i,configSchemaVersion:3}:{},...e.notifyOnComplete===!1?{notifyOnComplete:!1}:{},...!n&&e.onParentClose===`detach`?{onParentClose:`detach`}:{}};return n||(a.trigger=`@${r}`),a}function Hy(e,t){let n=wn(e.workspace?.mode??e.config?.workspaceMode),r=e.workspace?.from??`/workspace`,i=Zn(n,t,{root:r},e.workspace?.from),a=e.config;return{...a,workspaceMode:n,visiblePaths:a?.visiblePaths===void 0?i.visiblePaths:a.visiblePaths,writablePaths:a?.writablePaths===void 0?i.writablePaths:a.writablePaths}}function Uy(e,t){if(e.parentId===null||e.workspace?.from!==void 0)return e;let n=t.getScoop(e.parentId);return n?{...e,workspace:{mode:e.workspace?.mode??e.config?.workspaceMode??`shared-readonly`,from:or(n).root}}:e}var Wy=class{host;constructor(e){this.host=e}async create(e){e.parentId===null&&e.workspace?.mode!==void 0&&wn(e.workspace.mode);let t=Vy(Uy(e,this.host));if(Yy(t.jid,e=>this.host.getScoop(e)),e.parentId!==null){let n=this.host.getScoop(e.parentId);if(!n)throw Error(`Parent work unit not found: ${e.parentId}`);Mn(t,n)}return await this.host.registerScoop(t),this.get(t.jid).descriptor}async createMany(e){if(e.length===0)return[];Xy(e,e=>this.host.getScoop(e),()=>this.host.getScoops());let t=Jy(e);for(let e of t)e.id&&Yy(e.id,e=>this.host.getScoop(e));let n=Qy(t),r=[],i=new Map;try{for(let e of n){let t=await this.create(e);r.push(t.id),i.set(e,t)}}catch(e){for(let e=r.length-1;e>=0;e--)await this.close(r[e]).catch(()=>void 0);throw e}return t.map(e=>i.get(e))}async join(e,t){return(await this.host.waitForScoops(e,t?.timeoutMs)).map(e=>({id:e.jid,summary:e.summary,timedOut:e.timedOut}))}list(){return this.host.getScoops().map(e=>this.get(e.jid).descriptor)}get(e){return this.host.getScoop(e)?this.host.ensureLiveUnit(e):null}getParent(e){let t=this.host.getScoop(e)?.parentJid;return t?this.get(t):null}getChildren(e){return Xn(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return k(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=new Set,n=this.host.getScoop(e);for(;n&&n.parentJid!==null;){if(t.has(n.jid))return null;t.add(n.jid),n=this.host.getScoop(n.parentJid)}return n?this.get(n.jid):null}abort(e,t){let n=this.get(e);return n?n.abort(t):Promise.resolve()}async promote(e){let t=this.host.getScoop(e);if(!t)throw Error(`Work unit not found: ${e}`);if(t.parentJid===null)return this.get(e).descriptor;let n=Cr(t),r=Ky(t,t.parentJid);t.parentJid=null,qn(t);try{await this.host.persistScoop(t)}catch(e){throw qy(t,r),e}return await this.host.rekeyConversation?.(n,{key:Cr(t),workUnitId:t.jid,workspaceId:Sr(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:Vn(t)}}),await this.host.reinitLiveUnit(e),this.get(e).descriptor}detach(e){return this.promote(e)}async close(e,t){let n=this.get(e);if(!n)return;let r=this.getChildren(e);for(let e of r)Gy(e,t)===`detach`?await this.promote(e.descriptor.id):await this.close(e.descriptor.id,t);await n.close()}};function Gy(e,t){return t?.descendants??e.descriptor.onParentClose}function Ky(e,t){return{parentJid:t,trigger:e.trigger,requiresTrigger:e.requiresTrigger,approvesGuestRequests:e.approvesGuestRequests,onParentClose:e.onParentClose}}function qy(e,t){e.parentJid=t.parentJid,e.trigger=t.trigger,e.requiresTrigger=t.requiresTrigger,e.approvesGuestRequests=t.approvesGuestRequests,e.onParentClose=t.onParentClose}function Jy(e){let t=Date.now();return e.map(e=>{if(e.id)return e;let n=e.folder??e.name,r=e.parentId===null?`cone_${t++}`:`scoop_${n}_${t++}`;return{...e,id:r}})}function Yy(e,t){if(t(e))throw Error(`Work unit already exists: ${e}`)}function Xy(e,t,n){let r=new Set;for(let n of e)if(n.id){if(r.has(n.id))throw Error(`Duplicate work unit id in createMany: ${n.id}`);Yy(n.id,t),r.add(n.id)}Zy(e,n);let i=[],a=new Set;for(let n of e)n.parentId!==null&&(t(n.parentId)||r.has(n.parentId)||a.has(n.parentId)||(a.add(n.parentId),i.push(n.parentId)));if(i.length>0)throw Error(`Parent work unit not found: ${i.join(`, `)}`)}function Zy(e,t){let n=new Set(t().map(e=>e.folder)),r=new Set;for(let t of e){let e=t.folder??t.name;if(r.has(e)||n.has(e))throw Error(`Duplicate work unit folder in createMany: ${e}`);r.add(e)}}function Qy(e){let t=e.length;if(t<=1)return e.slice();let n=new Map;for(let r=0;r<t;r++){let t=e[r].id;t&&n.set(t,r)}let r=Array(t).fill(0),i=Array.from({length:t},()=>[]);for(let a=0;a<t;a++){let t=e[a].parentId;if(t===null)continue;let o=n.get(t);o!==void 0&&(i[o].push(a),r[a]+=1)}let a=[];for(let e=0;e<t;e++)r[e]===0&&a.push(e);let o=[];for(let t=0;t<a.length;t++){let n=a[t];o.push(e[n]);for(let e of i[n])--r[e],r[e]===0&&a.push(e)}if(o.length!==t)throw Error(`createMany cycle: parentId edges in this batch form a cycle`);return o}const $y=_(`kernel-agent-event-stream`);var eb=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){$y.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${tb()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=e.displayScoopJid?`tool-ui-${e.requestId??``}`:i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=e.displayScoopJid?`tool-ui-${e.requestId??``}`:this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function tb(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var nb=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=rb(e);return{jid:e.jid,name:e.name,folder:e.folder,parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=k(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function rb(e){let t=Pn(e),n=zn(e),{level:r,effortOverride:i}=Rn(e);if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{modelProviderId:n},...r===void 0?{}:{thinkingLevel:r},...i===void 0?{}:{effortOverride:i}}}const G={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let ib=null;function ab(e){if(!e.objectStoreNames.contains(G.MESSAGES)){let t=e.createObjectStore(G.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(G.SESSIONS)||e.createObjectStore(G.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(G.TASKS)||e.createObjectStore(G.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(G.STATE)||e.createObjectStore(G.STATE,{keyPath:`key`})}function ob(e,t){let n=e.isMain??!1;return{jid:e.jid,name:e.name,folder:e.folder,trigger:n?void 0:e.trigger||`@${e.folder}`,requiresTrigger:!n&&(e.requiresTrigger??!0),parentJid:n?null:t??null,assistantLabel:n?`sliccy`:e.config?.assistantName||e.folder,addedAt:e.addedAt,config:e.config?{systemPromptAppend:e.config.systemPromptAppend,timeout:e.config.timeout,assistantName:e.config.assistantName}:void 0}}function sb(e,t){if(t.objectStoreNames.contains(`groups`)){let n=e.target.transaction.objectStore(`groups`).getAll();n.onsuccess=()=>{let e=n.result;t.deleteObjectStore(`groups`);let r=t.createObjectStore(G.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);let i=e.find(e=>e.isMain)?.jid;for(let t of e)r.put(ob(t,i))};return}t.objectStoreNames.contains(G.SCOOPS)||t.createObjectStore(G.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function cb(e){e.objectStoreNames.contains(G.WEBHOOKS)||e.createObjectStore(G.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(G.CRONTASKS)||e.createObjectStore(G.CRONTASKS,{keyPath:`id`})}function lb(e){let t=e.target.result,n=e.oldVersion;n<1&&ab(t),n<2&&sb(e,t),n<3&&cb(t)}function ub(){if(!ib)return null;let e=Object.values(G).every(e=>ib.objectStoreNames.contains(e));return ib.version===3&&e?ib:(ib.close(),ib=null,null)}function db(e){e.onversionchange=()=>{e.close(),ib===e&&(ib=null)},e.onclose=()=>{ib===e&&(ib=null)}}async function fb(){return ub()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=lb,n.onsuccess=()=>{let t=n.result;db(t),ib=t,e(t)},n.onerror=()=>t(n.error)})}async function K(e,t=`readonly`){return(await fb()).transaction(e,t).objectStore(e)}async function pb(e){let t=await K(G.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function mb(){let e=await K(G.SCOOPS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>{let e={};for(let t of r.result)e[t.jid]=t;t(e)},r.onerror=()=>n(r.error)})}async function hb(e){let t=await K(G.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function gb(){let e=await K(G.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function _b(e){let t=(await K(G.MESSAGES,`readwrite`)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,`￿`],!1,!1);return new Promise((e,r)=>{let i=t.openCursor(n);i.onsuccess=()=>{let t=i.result;if(!t){e();return}t.delete(),t.continue()},i.onerror=()=>r(i.error)})}async function vb(e){let t=await K(G.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function yb(e){let t=await K(G.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function bb(e){let t=(await K(G.MESSAGES)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,`￿`],!1,!1);return new Promise((e,r)=>{let i=t.getAll(n);i.onsuccess=()=>e(i.result),i.onerror=()=>r(i.error)})}const xb=`wm1:`;function Sb(e){if(!e)return{ts:``,ids:new Set};if(e.startsWith(xb))try{let t=JSON.parse(e.slice(4));return{ts:t.ts,ids:new Set(t.ids)}}catch{}return{ts:e,ids:null}}function Cb(e){let t=e.ids?Array.from(e.ids):[];return`${xb}${JSON.stringify({ts:e.ts,ids:t})}`}function wb(e,t){return e.timestamp>t.ts?!0:e.timestamp<t.ts||t.ids===null?!1:!t.ids.has(e.id)}function Tb(e,t){if(t.length===0)return e;let n=e.ts;for(let e of t)e.timestamp>n&&(n=e.timestamp);let r=new Set;if(e.ts===n&&e.ids)for(let t of e.ids)r.add(t);for(let e of t)e.timestamp===n&&r.add(e.id);return{ts:n,ids:r}}async function Eb(e,t,n){let r=(await K(G.MESSAGES)).index(`chatJid_timestamp`),i=Sb(t),a=IDBKeyRange.bound([e,i.ts],[e,`￿`],!1,!1);return new Promise((e,t)=>{let o=r.getAll(a);o.onsuccess=()=>{let t=o.result.filter(e=>wb(e,i));n&&(t=t.filter(e=>e.senderName!==n)),e(t)},o.onerror=()=>t(o.error)})}async function Db(e){let t=await K(G.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Ob(e){let t=await K(G.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function kb(){let e=await K(G.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function Ab(e){let t=await K(G.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function jb(e){let t=await K(G.STATE);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result?.value??null),i.onerror=()=>r(i.error)})}async function Mb(e,t){let n=await K(G.STATE,`readwrite`);return new Promise((r,i)=>{let a=n.put({key:e,value:t});a.onsuccess=()=>r(),a.onerror=()=>i(a.error)})}async function Nb(){await fb()}async function Pb(e){let t=await K(G.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Fb(e){let t=await K(G.WEBHOOKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function Ib(){try{let e=await K(G.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Lb(e){let t=await K(G.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Rb(e){let t=await K(G.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function zb(e){let t=await K(G.CRONTASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function Bb(){try{let e=await K(G.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Vb(e){let t=await K(G.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}_(`tray-leader`);function Hb(){return Ub(Tr(),Te())}function Ub(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const Wb=`__slicc_binary__`;function Gb(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Wb]===`b64`&&typeof t.data==`string`}function Kb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function qb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)&&!Gb(e)}function Jb(e){if(e instanceof Uint8Array)return{[Wb]:`b64`,data:ie(e)};if(Array.isArray(e))return e.map(Jb);if(Kb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Jb(r);return t}return e}function Yb(e){if(Gb(e))return ae(e.data);if(Array.isArray(e))return e.map(Yb);if(qb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Yb(r);return t}return e}const Xb=_(`panel-transport`);function Zb(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Qb(){return{onMessage:e=>{let t=(t,n,r)=>(Zb(t)&&e(Yb(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Jb(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||Xb.error(`Offscreen → panel transport send failed`,{error:t})})}}}const $b=_(`kernel-bridge`);function ex(){return globalThis}function tx(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var nx=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;conesBeingCreated=new Map;currentMessageId=new Map;compactionRows=new py(e=>`compaction-${e}-${rx()}`);pendingMarkers=new Map;scoopPresentation=new nb;transcriptsPublished=!1;agentEventStream=new eb;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=Qb(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new dy;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.flushPendingMarkers(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${rx()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&e.currentMessageId.delete(t),(n===`ready`||n===`error`)&&e.flushPendingMarkers(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n,r)=>{let i=e.compactionRows.apply(t,n,r);e.emit({type:`compaction-state`,scoopJid:t,state:n,trigger:r.trigger,...r.transcriptPath?{transcriptPath:r.transcriptPath}:{},...r.failure?{failure:r.failure}:{},...r.roundId?{roundId:r.roundId}:{},...i?{rowId:i.messageId}:{}}),e.recordCompactionRow(t,i)},onError:(t,n,r)=>{e.recordErrorCard(t,n),e.emit({type:`error`,scoopJid:t,error:n,...r?.endTurn===!1?{endTurn:!1}:{}})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r,i)=>{$_.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{$_.has(n)||e.bufferToolEnd(t,n,r,i,a)},onToolUI:(t,n,r,i,a)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i,...a?{displayScoopJid:a}:{}})},onToolUIDone:(t,n,r)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n,...r?{displayScoopJid:r}:{}})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=nv(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??rx(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=rv(n),e.isError=r)}}this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:iv(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(Vn(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],Hb())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...Hb()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=tx(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=te(e),s=[];n&&s.push({source:`explicit target`,value:n}),o&&o!==n&&s.push({source:`configured route`,value:o});let c=[],l;for(let e of s){if(l=io(a,e.value),l)break;c.push(e)}if(l||=this.originRootOf(a,r?.unitJid)??k(a)[0],c.length>0&&$b.warn(`Sprinkle lick target could not be resolved; using fallback`,{sprinkleName:e,unresolvedTargets:c,fallbackJid:l?.jid}),!l)return;let u=`sprinkle-${e}-${Date.now()}`,d=By({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r?.label})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,f=c.map(({source:e,value:t})=>`${e} ${JSON.stringify(t)}`).join(` and `),p=d+(f?`\n\n> Delivery note: ${f} could not be resolved; delivered to fallback ${JSON.stringify(l.folder)}.`:``),m={id:u,chatJid:l.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:p,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(l.jid).push({id:u,role:`user`,content:p,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),await this.orchestrator.handleMessage(m)}originRootOf(e,t){if(t)return jn(e,e.find(e=>e.jid===t))}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=k(this.orchestrator.getScoops())[0];if(!t)return;let n=ax(e).map((t,n)=>({...t,isStreaming:e[n]?.isStreaming}));this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?k(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromCanonicalRecord(e){let t=this.orchestrator?.getConversationStore?.();if(!t)return null;let{conversationKeyFor:n}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),r=await t.load(n(e));if(!r)return null;let{toChatMessages:i}=await Promise.resolve().then(()=>BC),a=await i(r,{source:Bn(e)});return a.length===0?null:this.overlayPersistedLickDecisionsOn(e,ax(a))}async overlayPersistedLickDecisionsOn(e,t){if(!t.some(e=>e.channel===`sudo-request`||e.lickId||e.lickState))return t;let n=[];try{let t=await this.orchestrator?.getMessagesForScoop?.(e.jid);if(t)for(let e of t)n.push({id:e.id,content:e.content,channel:e.channel,lickId:e.lickId,lickState:e.lickState})}catch{}return ux(t,n)}async hydrateBuffersFromRecords(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromCanonicalRecord(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid))}}publishHydratedTranscripts(){if(this.transcriptsPublished||!this.orchestrator)return;let e=this.orchestrator.getScoops();if(e.length!==0){for(let t of e){let e=this.messageBuffers.get(t.jid);!e||e.length===0||this.emitTranscript(t.jid,e)}this.emitScoopList(),this.transcriptsPublished=!0}}emitTranscript(e,t){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t,queuedIds:this.queuedIdsFor(e)})}queuedIdsFor(e){if(!(this.followerSync||!this.orchestrator))return this.orchestrator.getQueuedMessageIds(e)}async handleRequestScoopMessages(e){if(await this.conesBeingCreated.get(e),!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emitTranscript(e,n);return}let r=await this.buildBufferFromCanonicalRecord(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emitTranscript(e,r);return}this.emitTranscript(e,[])}async handleConeCreate(e,t,n,r){if(!this.orchestrator)return;let i=this.orchestrator.getScoops(),a=Wn(e,i),o=a===Kn,s=k(i)[0],c=r??(s?Gn(s):void 0),l=t?.trim(),u={...Vy({parentId:null,name:e,folder:a}),assistantLabel:o?`sliccy`:e,...l?{config:{systemPromptAppend:`This cone is for: ${l}`}}:{},...c?{model:c}:{}},d=()=>{};this.conesBeingCreated.set(u.jid,new Promise(e=>{d=e}));let f=()=>{this.conesBeingCreated.delete(u.jid),d()};try{await this.orchestrator.registerScoop(u),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(u)});let e=n?.trim();if(!e)return;let t=this.handleUserMessage({type:`user-message`,scoopJid:u.jid,text:e,messageId:`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});f(),await t}finally{f()}}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=t.approver;if(r&&r.kind!==`user`){let i=this.orchestrator;if(!i)console.warn(`[kernel-bridge] directed approval before orchestrator init — denying`);else try{n=await i.enqueueDirectedApproval(r,t)}catch(e){console.warn(`[kernel-bridge] directed approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n});return}let i=this.orchestrator?.getSudoManager()??null;if(!i)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await i.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}async handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}let o=await this.resolveBudgetWindow();this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a,...o?{budget:o}:{}})}budgetProbePending=!0;async resolveBudgetWindow(){return this.budgetProbePending?(this.budgetProbePending=!1,await Promise.race([q_().catch(()=>null),new Promise(e=>setTimeout(()=>e(null),2500))])??void 0):(q_().catch(()=>null),K_()??void 0)}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:ix(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await Promise.resolve().then(()=>ov),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:Bn(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:ix(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromCanonicalRecord(r);if(a){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}n()}async recordCompactionRow(e,t){if(!t||t.kind===`open`)return;let n=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n)return;let r=this.getBuffer(e);if(t.kind===`retract`){let e=r.findIndex(e=>e.id===t.messageId);e>=0&&r.splice(e,1)}else{let e=r.find(e=>e.id===t.messageId);e?e.compaction=t.marker:r.push({id:t.messageId,role:`assistant`,content:``,timestamp:Date.now(),compaction:t.marker})}let i=this.orchestrator?.getConversationStore?.();if(!i)return;let{conversationKeyFor:a}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),o=a(n);if(t.kind===`retract`){this.dropPendingMarker(e,t.messageId),await i.deleteMarker(o,t.messageId);return}let s={id:t.messageId,kind:`compaction`,timestamp:Date.now(),compaction:t.marker};await i.putMarker(o,s)||this.holdPendingMarker(e,s)}holdPendingMarker(e,t){let n=this.pendingMarkers.get(e)??[];this.pendingMarkers.set(e,[...n.filter(e=>e.id!==t.id),t].slice(-4))}dropPendingMarker(e,t){let n=this.pendingMarkers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,r)}async flushPendingMarkers(e){let t=this.pendingMarkers.get(e);if(!t||t.length===0)return;let n=this.orchestrator?.getConversationStore?.(),r=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n||!r)return;let{conversationIdentityFor:i,conversationKeyFor:a}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),o=a(r);for(let a of t){let t=!1;try{t=await n.putMarker(o,a,a.kind===`error`?{createWith:i(r)}:void 0)}catch(t){$b.warn(`Conversation marker retry threw`,{scoopJid:e,folder:r.folder,markerId:a.id,kind:a.kind,errorName:t instanceof Error?t.name:`unknown`})}t?this.dropPendingMarker(e,a.id):$b.warn(`Conversation marker retry deferred`,{scoopJid:e,folder:r.folder,markerId:a.id,kind:a.kind})}}async recordErrorCard(e,t){let n=rx(),r=Date.now();this.getBuffer(e).push({id:n,role:`assistant`,content:t,timestamp:r,error:!0});let i={id:n,kind:`error`,timestamp:r,text:t};this.holdPendingMarker(e,i);let a=this.orchestrator?.getConversationStore?.(),o=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!a||!o){$b.warn(`Error marker is waiting for a canonical target`,{scoopJid:e,markerId:i.id,hasStore:!!a,hasScoop:!!o});return}let{conversationIdentityFor:s}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),c=s(o),l=!1;try{l=await a.putMarker(c.key,i,{createWith:c})}catch(t){$b.warn(`Error marker write threw; queued for retry`,{scoopJid:e,folder:o.folder,markerId:i.id,errorName:t instanceof Error?t.name:`unknown`})}l?this.dropPendingMarker(e,i.id):$b.warn(`Error marker write deferred`,{scoopJid:e,folder:o.folder,markerId:i.id})}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${rx()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?Bn(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{e.source===`panel`&&this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name,e.description,e.prompt,e.model);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId,e.scoopJid,e.discardLiveSnapshot===!0);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`set-model`:case`refresh-model`:this.orchestrator.refreshModels();break;case`set-scoop-model`:await this.handleSetScoopModel(e);break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.handleWebhookEventMsg(e);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value)),Va(e.key);break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key)),Va(e.key);break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear()),Va()}}handleWebhookEventMsg(e){let t=this.orchestrator?.handleWebhookEvent(e.webhookId,e.headers,e.body);e.requestId&&this.emit({type:`lick-webhook-delivery`,requestId:e.requestId,disposition:t??`unknown-webhook`})}async handleAgentSpawn(e){let t=ex()[kv];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetScoopModel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopModel(e.scoopJid,e.model)}catch(e){console.error(`[kernel-bridge] set-scoop-model failed:`,e)}e.requestId&&this.emit({type:`set-scoop-model-ack`,requestId:e.requestId,scoopJid:e.scoopJid,model:e.model,applied:t})}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&this.messageBuffers.set(e,r)}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.guestGate?{guestGate:e.guestGate}:{},...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&On(n)){if(k(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);let i=new Set(this.orchestrator.getScoops().map(e=>e.jid));for(let e of[...r,n])i.has(e.jid)||this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=Vn({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e,t,n=!1){let r=this.orchestrator?.getScoops()??[],i=(t?r.find(e=>e.jid===t):void 0)??k(r)[0],a=i?.jid;a&&(n?await this.orchestrator?.clearScoopMessages(a,{discardLiveSnapshot:!0}):await this.orchestrator?.clearScoopMessages(a)),this.sessionStore&&await this.sessionStore.delete(Vn({folder:i?.folder??`cone`})),a&&(this.messageBuffers.delete(a),this.currentMessageId.delete(a),this.agentEventStream.clear(a)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.origin)}handleSetFollowerForwarding(e){let t=ex().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=ex().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){_n.markMounted(t);return}try{await _n.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),_n.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function rx(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function ix(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
898
- `)}function ax(e){return e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,lickId:e.lickId,lickState:e.lickState,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1,compaction:e.compaction,error:e.error}))}function ox(e){return e===`confirmed`||e===`dismissed`}function sx(e){return e.channel===`sudo-request`||!!e.lickId||!!e.lickState||e.id.startsWith(`sudo-request-`)}function cx(e){return e.lickId?e.lickId:sx(e)?/^(?:Lick ID|Request ID): (\S+)/m.exec(e.content)?.[1]||(e.id.startsWith(`sudo-request-`)?e.id.slice(13):void 0):void 0}function lx(e,t,n){let r=e.get(t);(!r||ox(n.lickState)&&!ox(r.lickState))&&e.set(t,n)}function ux(e,t){if(!t||t.length===0)return e;let n=new Map,r=new Map,i=new Map;for(let e of t){if(!sx(e))continue;let t=cx(e);t&&lx(n,t,e),lx(r,e.id,e),lx(i,e.content,e)}return e.map(e=>{if(!sx(e))return e;let t=cx(e),a=(t?n.get(t):void 0)??r.get(e.id)??i.get(e.content);if(!a||!a.lickId&&!a.lickState)return e;let o=a.lickId??t??cx(a),s=ox(a.lickState)?a.lickState:e.lickState??a.lickState;return o===e.lickId&&s===e.lickState&&a.id===e.id?e:{...e,id:a.id,lickId:o,lickState:s}})}const dx=_(`navigation-watcher`);function fx(e){if(!e)return null;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:null}catch{return null}}function px(e){return e.replace(/\/+$/,``)||`/`}function mx(e){return t=>{let n=fx(e()??void 0);if(!n)return!1;let r=fx(t.url);return r?n.origin===r.origin&&px(n.pathname)===px(r.pathname):!1}}function hx(e,t){return se(e,t)}var gx=class{transport;onEvent;sessions=new Map;started=!1;unsubscribeState=null;rearming=!1;rearmQueued=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;isOwnTab;probedOrigins=new Set;pendingAttachTargetIds=new Set;ownSessionIds=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);this.sessions.delete(t),this.ownSessionIds.delete(t),n&&this.pendingAttachTargetIds.delete(n.targetId)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId){for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url));this.reconcileTargetNetwork(t)}};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameRequestedNavigation=e=>{let t=e;this.maybeArmNetwork(t.sessionId,t.frameId,t.url)};onFrameStartedNavigating=e=>{let t=e;this.maybeArmNetwork(t.sessionId,t.frameId,t.url)};onFrameNavigated=e=>{let t=e,n=t.sessionId;if(!n)return;let r=this.sessions.get(n);if(!r)return;let i=t.frame;i?.id&&(i.parentId||(r.rootFrameId=i.id,typeof i.url==`string`&&(r.url=i.url)))};onResponseReceived=e=>{let t=e,n=t.sessionId;if(!n)return;let r=this.sessions.get(n);if(!r||t.type!==`Document`)return;let i=t.frameId;if(!i||i!==r.rootFrameId)return;let a=t.response;if(!a)return;let o=typeof a.url==`string`&&a.url.length>0?a.url:r.url;if(!o)return;let{match:s,links:c}=hx(a.headers,o);if(s){let e={url:o,verb:s.verb,target:s.target,links:c,targetId:r.targetId};s.instruction!=null&&(e.instruction=s.instruction),s.branch!=null&&(e.branch=s.branch),s.path!=null&&(e.path=s.path),r.title!=null&&(e.title=r.title),this.onEvent(e)}this.maybeRunDiscovery(o,c,r.targetId)};eventBindings=[[`Target.attachedToTarget`,this.onAttachedToTarget],[`Target.detachedFromTarget`,this.onDetachedFromTarget],[`Target.targetInfoChanged`,this.onTargetInfoChanged],[`Target.targetCreated`,this.onTargetCreated],[`Page.frameNavigated`,this.onFrameNavigated],[`Page.frameRequestedNavigation`,this.onFrameRequestedNavigation],[`Page.frameStartedNavigating`,this.onFrameStartedNavigating],[`Network.responseReceived`,this.onResponseReceived]];constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs,this.isOwnTab=n.isOwnTab??(()=>!1)}maybeRunDiscovery(e,t,n){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let r;try{r=new URL(e).origin}catch{return}let i=Oi(t);i&&this.onDiscovery({origin:r,kind:i.kind,url:i.url,targetId:n}),this.probeFetch&&!this.probedOrigins.has(r)&&(this.probedOrigins.add(r),this.runWellKnownProbe(r,n))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await ji(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){dx.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){if(this.registerListeners(),!await this.enableDiscovery()){this.unregisterListeners();return}this.started=!0,this.subscribeTransportState(),await this.enumeratePreexistingTargets()}}registerListeners(){for(let[e,t]of this.eventBindings)this.transport.off(e,t),this.transport.on(e,t)}unregisterListeners(){for(let[e,t]of this.eventBindings)this.transport.off(e,t)}async enableDiscovery(){try{return await this.transport.send(`Target.setDiscoverTargets`,{discover:!0}),!0}catch(e){return dx.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),!1}}async enumeratePreexistingTargets(){try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;e||typeof n!=`string`||await this.requestAttach(n,`Failed to attach to preexisting target`)}}catch(e){dx.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}subscribeTransportState(){this.unsubscribeState||=this.transport.onStateChange?.(e=>{if(e===`disconnected`){this.clearConnectionScopedState();return}e===`connected`&&(this.rearming?this.rearmQueued=!0:this.rearmAfterReconnect())})??null}clearConnectionScopedState(){this.sessions.clear(),this.pendingAttachTargetIds.clear(),this.ownSessionIds.clear()}async rearmAfterReconnect(){if(!(!this.started||this.rearming)){this.rearming=!0;try{if(this.clearConnectionScopedState(),this.registerListeners(),!await this.enableDiscovery())return;await this.enumeratePreexistingTargets()}finally{this.rearming=!1,this.rearmQueued&&(this.rearmQueued=!1,this.rearmAfterReconnect())}}}async stop(){if(this.started){this.started=!1,this.unsubscribeState?.(),this.unsubscribeState=null,this.unregisterListeners(),this.clearConnectionScopedState();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){dx.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;t?.type===`page`&&typeof t.targetId==`string`&&(t.attached||await this.requestAttach(t.targetId,`Failed to attach to discovered target`))}maybeArmNetwork(e,t,n){if(!e||!t)return;let r=this.sessions.get(e);!r||r.networkEnabled||!this.ownSessionIds.has(e)||r.rootFrameId===t&&(this.isOwnTabSafe({targetId:r.targetId,url:n})||this.setSessionNetwork(e,r,!0))}reconcileTargetNetwork(e){let t=this.isOwnTabSafe(e);for(let[n,r]of this.sessions)r.targetId===e.targetId&&this.ownSessionIds.has(n)&&r.networkEnabled!==!t&&this.setSessionNetwork(n,r,!t)}async setSessionNetwork(e,t,n){t.networkEnabled=n;try{await this.transport.send(n?`Network.enable`:`Network.disable`,{},e)}catch(r){t.networkEnabled=!n,dx.debug(`Failed to ${n?`enable`:`disable`} Network on session`,{sessionId:e,targetId:t.targetId,error:r instanceof Error?r.message:String(r)})}}isOwnTabSafe(e){try{return this.isOwnTab(e)}catch(t){return dx.debug(`isOwnTab predicate threw; treating target as foreign`,{targetId:e.targetId,error:t instanceof Error?t.message:String(t)}),!1}}async requestAttach(e,t){this.pendingAttachTargetIds.add(e);try{let t=(await this.transport.send(`Target.attachToTarget`,{targetId:e,flatten:!0}))?.sessionId;typeof t==`string`&&t.length>0&&(this.ownSessionIds.add(t),this.pendingAttachTargetIds.delete(e))}catch(n){this.pendingAttachTargetIds.delete(e),dx.debug(t,{targetId:e,error:n instanceof Error?n.message:String(n)})}}claimOwnSession(e,t){return this.ownSessionIds.has(e)?!0:this.pendingAttachTargetIds.has(t)?(this.pendingAttachTargetIds.delete(t),this.ownSessionIds.add(e),!0):!1}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!t||!n||n.type!==`page`||typeof n.targetId!=`string`||(this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,networkEnabled:!1,title:n.title,url:n.url}),!this.claimOwnSession(t,n.targetId)))return;let r=this.isOwnTabSafe(n);r&&dx.debug(`Attaching to the SLICC app tab with Network off`,{targetId:n.targetId,url:n.url});try{if(await this.transport.send(`Page.enable`,{},t),!r){let e=this.sessions.get(t);e&&await this.setSessionNetwork(t,e,!0)}let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){dx.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}};function _x(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var vx=`# /etc/llmstxtignore — llms.txt discovery suppression
890
+ `)}`:r.firstLine,t=sv(e);t?n.push({sender:t.sender,body:t.body}):n.push({sender:null,body:e}),r=null};for(let e of t){if(e.startsWith(`[`)&&/^\[[^\]\n]+\] /.test(e)&&e.includes(`: `)&&sv(e)){i(),r={firstLine:e,rest:[]};continue}r?r.rest.push(e):r={firstLine:e,rest:[]}}return i(),n.length===0?[{sender:null,body:e}]:n}function lv(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t);return B_(n)?n:null}function uv(e){let t=/^\[@[^\]\s]+ (completed|idle)\]/.exec(e);return t?t[1]===`idle`?`scoop-idle`:`scoop-notify`:/^\[@[^\]\s]+ sudo-request\]/.test(e)?`sudo-request`:/^\[scoop_wait [^\]]+\]/.test(e)?`scoop-wait`:e.startsWith(`[Session Reload]`)?`session-reload`:null}function dv(e){return/^(?:Lick ID|Request ID): (\S+)/m.exec(e)?.[1]}function fv(e){let t=Y_(e.messages,{source:e.name}),n=t.filter(e=>e.role===`assistant`).length,r=[`# Agent session: ${e.name}`,``,`- jid: ${e.jid}`,`- exit code: ${e.exitCode}`,`- turns: ${n}`,`- messages: ${e.messages.length}`,`- timestamp: ${e.timestamp}`,``,`## Prompt`,``,e.prompt.length>0?e.prompt:`_(empty prompt)_`,``,`---`,``];if(t.length===0)r.push(`_(no messages captured)_`,``);else for(let e of t)pv(r,e);return Se(r.join(`
891
+ `),Ce())}function pv(e,t){e.push(`## ${t.role}`,``);let n=t.content.trim();n.length>0&&e.push(n,``);for(let n of t.toolCalls??[])mv(e,n)}function mv(e,t){e.push(`### tool: ${t.name}`,``,`Input:`,``,"```json",hv(t.input),"```",``),t.result!==void 0&&e.push(t.isError?`Result (error):`:`Result:`,``,"```",t.result,"```",``)}function hv(e){try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}const gv=_(`agent-bridge`),_v=`__slicc_agent`;function vv(e){for(let t=0;t<8;t++){let t=e.generateName(),n=`agent_${Hv(t)}`;if(!e.orchestrator.getScoops().some(e=>e.jid===n))return t}return e.generateUid()}function yv(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=Ln(n);if(!r||r.length===0)return null;let i=Hn(n);return i?{modelId:r,providerId:i}:{modelId:r}}function bv(e,t){let n=e.getWorkUnits(),r=(t===null?null:n.rootOf(t))??n.resolveDefaultRoot();return or(r?.descriptor.workspace??ar)}function xv(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=Vn(n).level;return r&&ur(r)?r:null}function Sv(e,t){let n=e.modelId,r,i;if(n!==void 0){let a=e.modelProviderId!==void 0&&n!==``?`${e.modelProviderId}:${n}`:n,o=a===``?{ok:!1,error:`unknown model: ${n}`}:t(a);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};r=o.selection.modelId,i=o.selection.providerId}let a=e.thinkingLevel;if(a!==void 0&&!ur(a))return{error:{finalText:`agent: invalid thinking level: ${String(a)} (one of: ${dr.join(`, `)})`,exitCode:1}};let o=kn(e.workspaceMode);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};let s=e.backgroundAfterSeconds;if(s!==void 0&&(typeof s!=`number`||!Number.isFinite(s)||s<0))return{error:{finalText:`agent: invalid backgroundAfterSeconds: ${String(s)} (seconds >= 0)`,exitCode:1}};let c=Cv(e);if(c)return c;let l=e.name;if(l!==void 0&&!kv(l))return{error:{finalText:`agent: invalid name: ${l} (lowercase tokens joined by single dashes)`,exitCode:1}};for(let[t,n]of[[`maxTurns`,e.maxTurns],[`maxWallClockMs`,e.maxWallClockMs]])if(n!==void 0&&(!Number.isInteger(n)||n<=0))return{error:{finalText:`agent: ${t} must be a positive integer: ${String(n)}`,exitCode:1}};return{resolvedModelId:r,resolvedProviderId:i}}function Cv(e){let t=e.mergeOnSuccess,n=[[`successReceiptPath`,e.successReceiptPath],[`outcomeReceiptPath`,e.outcomeReceiptPath],[`mergeOnSuccess.targetPath`,t?.targetPath],[`mergeOnSuccess.basePath`,t?.basePath],[`mergeOnSuccess.draftPath`,t?.draftPath]],r=t===void 0?void 0:``;for(let[e,t]of n){let n=t??(e.startsWith(`mergeOnSuccess`)?r:void 0);if(n!==void 0&&!n.startsWith(`/`))return{error:{finalText:`agent: ${e} must be absolute: ${String(t)}`,exitCode:1}}}return null}function wv(e){return/^agent run terminated: .*\bbound\b.*\bexceeded\b/.test(e)}async function Tv(e,t){let n=async t=>{try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){if(Xv(e,`ENOENT`))return``;throw e}},r=async()=>{for(let n of[t.basePath,t.draftPath])try{await e.rm(n)}catch{}},i=async t=>{try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch(e){if(Xv(e,`ENOENT`))return null;throw e}};try{let a=await i(t.draftPath);if(a===null)return await r(),{applied:!1,conflicts:0};let o=await n(t.targetPath);if(a===o)return await r(),{applied:!1,conflicts:0};let s=await i(t.basePath);if(s===null)return{applied:!1,conflicts:0,error:`base snapshot missing; target left as-is`};if(a===s)return await r(),{applied:!1,conflicts:0};if(o===s)return await e.writeFile(t.targetPath,a),await r(),{applied:!0,conflicts:0};let c=En(o,s,a,{favor:`theirs`});return await e.writeFile(t.targetPath,c.content),await r(),{applied:!0,conflicts:c.conflicts}}catch(e){let n=Yv(e);return gv.warn(`mergeOnSuccess failed; target left as-is, staging kept`,{target:t.targetPath,error:n}),{applied:!1,conflicts:0,error:n}}}async function Ev(e,t,n,r){try{let i=t.slice(0,t.lastIndexOf(`/`));i&&await e.mkdir(i,{recursive:!0}),await e.writeFile(t,JSON.stringify({status:n.exitCode===0?`ok`:`failed`,exitCode:n.exitCode,finishedAt:new Date().toISOString(),...n.exitCode===0&&!r?.promotedOnTrip?{}:{reason:n.finalText.slice(0,500)},...r?{merge:r}:{}},null,2))}catch(e){gv.warn(`outcome receipt write failed`,{path:t,error:Yv(e)})}}async function Dv(e,t){try{let n=t.slice(0,t.lastIndexOf(`/`));n&&await e.mkdir(n,{recursive:!0}),await e.writeFile(t,new Date().toISOString())}catch(e){gv.warn(`success receipt write failed`,{path:t,error:Yv(e)})}}const Ov=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function kv(e){return Ov.test(e)}const Av=`agent: name already in use`;async function jv(e,t,n,r,i){if(t.persistSession===!1)return;let a=t.persistSession===!0?`/sessions`:`/tmp`,o=new Date().toISOString().replace(/[:.]/g,`-`),s=`${a}/agent-${r}-${o}.md`;try{let c=e.orchestrator.getScoopContext(n),l=typeof c?.getAgentMessages==`function`?c.getAgentMessages():[],u=fv({name:r,jid:n,prompt:t.prompt,exitCode:i.exitCode,messages:l,timestamp:o});await e.sharedFs.mkdir(a,{recursive:!0}),await e.sharedFs.writeFile(s,u)}catch(e){gv.warn(`agent session archive write failed`,{path:s,error:Yv(e)})}}function Mv(e,t,n,r,i,a){let o=Wv(e.cwd),s=Gv(e.workspaceMode),c={visiblePaths:qv(e,a,s),writablePaths:Jv([...Kv(e.writablePaths,o,s),`${i}/`,`/tmp/`]),workspaceMode:s,allowedCommands:e.allowedCommands};return e.maxTurns!==void 0&&(c.maxTurns=e.maxTurns),e.maxWallClockMs!==void 0&&(c.maxWallClockMs=e.maxWallClockMs),e.backgroundAfterSeconds!==void 0&&(c.backgroundAfterSeconds=e.backgroundAfterSeconds),t&&(c.modelId=t,n!==void 0&&(c.modelProviderId=n)),r!==void 0&&(c.thinkingLevel=r),e.structuredOutputSchema!==void 0&&(c.structuredOutputSchema=e.structuredOutputSchema),c}function Nv(e,t){let n={sendMessages:[],responseBuffer:``,scoopError:null,unsubscribe:null};return n.unsubscribe=e.observeScoop(t,{onSendMessage:e=>{n.sendMessages.push(e)},onResponse:(e,t)=>{t?n.responseBuffer+=e:n.responseBuffer=e},onError:e=>{n.scoopError===null&&(n.scoopError=e)}}),n}async function Pv(e,t,n,r,i){if(await e.sendPrompt(t,n,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};if(r){let n=e.getScoopContext(t),r=n?.getStructuredOutput?.();for(let a=0;a<2&&!r?.captured;a++){if(await e.sendPrompt(t,`You did not call StructuredOutput. Call it now with your result, matching the schema.`,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};r=n?.getStructuredOutput?.()}return r?.captured?{finalText:JSON.stringify(r.value),exitCode:0}:{finalText:`agent: scoop did not produce StructuredOutput`,exitCode:1}}return{finalText:i.sendMessages.length>0?i.sendMessages[i.sendMessages.length-1]:i.responseBuffer,exitCode:0}}async function Fv(e,t,n,r){try{await e.orchestrator.unregisterScoop(t)}catch(e){gv.warn(`unregisterScoop failed`,{jid:t,error:Yv(e)})}try{await e.sharedFs.rm(r,{recursive:!0})}catch(e){Xv(e,`ENOENT`)||gv.warn(`scratch folder cleanup failed`,{folder:n,error:Yv(e)})}if(e.sessionStore)try{await e.sessionStore.delete(t)}catch(e){gv.warn(`sessionStore.delete failed`,{jid:t,error:Yv(e)})}}async function Iv(e,t,n,r,i){let a=await Lv(e,t,n,r,i),o;return a.exitCode===0&&t.mergeOnSuccess?(o=await Tv(e.sharedFs,t.mergeOnSuccess),o.error!==void 0&&(a={finalText:`agent: mergeOnSuccess failed: ${o.error}`,exitCode:1})):t.mergeOnSuccess&&wv(a.finalText)&&(o=await Tv(e.sharedFs,t.mergeOnSuccess),o.applied?(o.promotedOnTrip=!0,gv.info(`run tripped its bound; staged rewrite promoted`,{target:t.mergeOnSuccess.targetPath,conflicts:o.conflicts}),a={finalText:`${a.finalText} — staged rewrite promoted`,exitCode:0}):o.error===void 0&&(o=void 0)),a.exitCode===0&&t.successReceiptPath&&await Dv(e.sharedFs,t.successReceiptPath),t.outcomeReceiptPath&&await Ev(e.sharedFs,t.outcomeReceiptPath,a,o),a}async function Lv(e,t,n,r,i){try{await e.orchestrator.registerScoop(n)}catch(e){return{finalText:i.scoopError??Yv(e),exitCode:1}}try{let n=await Pv(e.orchestrator,r,t.prompt,t.structuredOutputSchema,i);return t.signal?.aborted?{finalText:`agent: aborted`,exitCode:1}:n||{finalText:i.scoopError??``,exitCode:1}}catch(e){return{finalText:i.scoopError??Yv(e),exitCode:1}}}function Rv(e,t,n=null,r={}){let i={orchestrator:e,sharedFs:t,sessionStore:n,generateName:r.generateName??Vv,generateUid:r.generateUid??Bv,resolveModel:r.resolveModel??Uv};async function a(e){let t=Sv(e,i.resolveModel);if(`error`in t)return t.error;let n=yv(i.orchestrator,e.parentJid),r=t.resolvedModelId??n?.modelId??``,a=t.resolvedModelId===void 0?n?.providerId:t.resolvedProviderId,o=e.thinkingLevel??xv(i.orchestrator,e.parentJid)??void 0,s=e.name===void 0?vv(i):e.name,c=`agent-${s}`,l=`agent_${Hv(s)}`,u=new Set(i.orchestrator.getScoops().map(e=>e.jid));if(e.name!==void 0&&u.has(l))return{finalText:`${Av}: ${s}`,exitCode:1};let d=(e.exclusiveWith??[]).find(e=>u.has(`agent_${Hv(e)}`));if(d!==void 0)return{finalText:`${Av}: ${d}`,exitCode:1};let f=`/scoops/${c}`,p=e.parentJid??k(i.orchestrator.getScoops())[0]?.jid??null,m=Mv(e,r,a,o,f,bv(i.orchestrator,p)),h={jid:l,name:c,folder:c,requiresTrigger:!1,assistantLabel:c,addedAt:new Date().toISOString(),config:m,configSchemaVersion:3,notifyOnComplete:e.notifyOnComplete===!0,parentJid:p},ee=Nv(i.orchestrator,l),g=()=>{try{i.orchestrator.stopScoop(l)}catch(e){gv.warn(`stopScoop on abort failed`,{jid:l,error:Yv(e)})}};if(e.signal?.addEventListener(`abort`,g,{once:!0}),e.signal?.aborted)return e.signal.removeEventListener(`abort`,g),ee.unsubscribe?.(),{finalText:`agent: aborted before start`,exitCode:1};let te={finalText:``,exitCode:1};try{return te=await Iv(i,e,h,l,ee),te}finally{e.signal?.removeEventListener(`abort`,g),ee.unsubscribe?.(),await jv(i,e,l,s,te),await Fv(i,l,c,f)}}return{spawn:a}}function zv(e,t,n=null,r={}){let i=Rv(e,t,n,r);return globalThis[_v]=i,gv.info(`agent bridge published on globalThis.__slicc_agent`),i}function Bv(){let e=globalThis;return typeof e.crypto?.randomUUID==`function`?e.crypto.randomUUID().replace(/-/g,``).slice(0,12):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function Vv(){return`${L_[Math.floor(Math.random()*L_.length)]}-${R_[Math.floor(Math.random()*R_.length)]}`}function Hv(e){return e.replace(/-/g,`_`)}function Uv(e){try{return de(e)}catch(t){return gv.warn(`defaultResolveModel: provider/account lookup threw; treating model as unknown`,{modelId:e,error:t instanceof Error?t.message:String(t)}),{ok:!1,error:`unknown model: ${e}`}}}function Wv(e){let t=wn(e);return t.endsWith(`/`)?t:`${t}/`}function Gv(e){let t=kn(e);return t.ok?t.mode:An}function Kv(e,t,n=An){let r=n===`private`?[t]:[t,`/shared/`];return e===void 0||e.some(e=>typeof e!=`string`||!e.startsWith(`/`)||e.includes(`\0`))?r:e.map(Wv)}function qv(e,t,n=An){if(e.visiblePaths!==void 0)return e.visiblePaths.map(Wv);if(n===`private`)return[];let r=[...t];return e.invokingCwd&&e.invokingCwd.length>0&&r.push(Wv(e.invokingCwd)),Jv(r)}function Jv(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function Yv(e){return e instanceof Error?e.message:String(e)}function Xv(e,t){if(typeof e!=`object`||!e)return!1;let n=e.code;return typeof n==`string`&&n===t}const Zv=`sessions`;function Qv(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Zv)||e.createObjectStore(Zv,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var $v=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Qv();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Zv,`readwrite`);i.objectStore(Zv).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Zv,`readonly`).objectStore(Zv).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(Zv,`readonly`).objectStore(Zv).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(Zv,`readwrite`);i.objectStore(Zv).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};const ey={summarizing:`summarizing`,fallback:`fallback`,cancelled:`discarded`,idle:`summarized`};var ty=class{mintId;open=new Map;settled=new Map;constructor(e){this.mintId=e}apply(e,t,n,r){if(t===`extracting-memory`)return null;let i=this.open.get(e)??this.lateRetraction(e,t,n)??r;if(t!==`summarizing`&&!i)return null;t!==`summarizing`&&(this.open.delete(e),this.settled.delete(e));let a=i??this.mintId(e);if(t===`summarizing`&&this.open.set(e,a),(t===`idle`||t===`fallback`)&&n.roundId&&this.settled.set(e,{messageId:a,roundId:n.roundId}),t===`cancelled`)return{kind:`retract`,messageId:a};let o={trigger:n.trigger,state:ey[t],...n.transcriptPath?{transcriptPath:n.transcriptPath}:{}};return t===`summarizing`?{kind:`open`,messageId:a,marker:o}:{kind:`settle`,messageId:a,marker:o}}forget(e){this.open.delete(e),this.settled.delete(e)}lateRetraction(e,t,n){if(t!==`cancelled`||!n.roundId)return;let r=this.settled.get(e);return r?.roundId===n.roundId?r.messageId:void 0}},ny=e({formatMountRecoveryPrompt:()=>ly,mdInlineCode:()=>cy,recoverMounts:()=>oy,shellQuote:()=>sy});function ry(e){return e instanceof Error?e.message:String(e)}async function iy(e,t,n,r){let i=await br(t.idbHandleKey),a=typeof i?.name==`string`?i.name:``,o={kind:`local`,path:e,dirName:a};if(!i||!(`queryPermission`in i))return{entry:o,ok:!1};let s;try{s=await i.queryPermission({mode:`readwrite`})}catch(t){return r?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:ry(t)}),{entry:o,ok:!1}}if(s!==`granted`)return{entry:o,ok:!1};try{let s=fr.fromHandle(i,{mountId:t.mountId});return await n.mount(e,s,{limits:pr}),r?.info?.(`Restored mount from previous session`,{path:e,name:a}),{entry:o,ok:!0}}catch(t){return r?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:ry(t)}),{entry:o,ok:!1}}}async function ay(e,t,n,r){let{kind:i,source:a,profile:o,mountId:s}=t,c=i===`s3`?`S3`:i===`aem`?`AEM`:`DA`;try{let t={source:a,profile:o,cache:new xr({mountId:s,ttlMs:3e4}),mountId:s},l=i===`s3`?new hr({...t,signedFetch:gr(o)}):i===`aem`?new vr({...t,signedFetch:yr()}):new mr({...t,signedFetch:yr()});return await n.mount(e,l),r?.info?.(`Restored ${c} mount from previous session`,{path:e,source:a}),{entry:{kind:i,path:e,source:a,profile:o,reason:``},ok:!0}}catch(t){let n=ry(t);return r?.warn?.(`Failed to restore ${c} mount`,{path:e,error:n}),{entry:{kind:i,path:e,source:a,profile:o,reason:n},ok:!1}}}async function oy(e,t,n){let r=[],i=[];for(let{targetPath:a,descriptor:o}of e){if(o.kind===`hostfs`)continue;let e=o.kind===`local`?await iy(a,o,t,n):await ay(a,o,t,n);(e.ok?r:i).push(e.entry)}return{restored:r,needsRecovery:i}}function sy(e){return`'${e.replace(/'/g,`'\\''`)}'`}function cy(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function ly(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`||e.kind===`aem`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${cy(t)})`:``;return`- ${cy(e)}${n}`}),i=r.map(({path:e})=>` mount ${sy(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${sy(n)}`,a=`mount --source ${sy(t)}${i} ${sy(e)}`;return`- ${cy(e)} (${cy(t)}, profile ${cy(n)}) — ${r}\n Retry: ${cy(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
892
+ `)}const uy=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`bash`,`jshd`,`sudo-request`,`preview`,`discovery`]);function dy(e){return e!=null&&uy.has(e)}const fy={webhook:`Webhook Event`,sprinkle:`Sprinkle Event`,fswatch:`File Watch Event`,"session-reload":`Session Reload`,navigate:`Navigate Event`,upgrade:`Upgrade Event`,cherry:`Cherry Event`,workflow:`Workflow Event`,bash:`Background Command`,jshd:`jshd Unit`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`,preview:`Preview`,discovery:`Discovery Event`};function py(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`session-reload`:return my(e);case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`cherry`:return e.cherryName;case`workflow`:return e.workflowName;case`bash`:return e.bashJobId;case`jshd`:return e.jshdName;case`sudo-request`:return e.sudoScoopName;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function my(e){let t=e.body?.reason;return typeof t==`string`&&t?t:`mount-recovery`}function hy(e){let t=e.body,n=Array.isArray(t?.tools)?t.tools:[],r=n.map(e=>{let t=e.args?` ${e.args}`:``;return`- \`${e.toolName??`unknown`}\`${t}`});return`[Session Reload: tool-call-interrupted]\nThe page reloaded while your last turn was running. ${n.length===1?`A tool call was`:`${n.length} tool calls were`} still in flight, so ${n.length===1?`its result was`:`their results were`} lost:\n${r.join(`
893
+ `)}\n\nThey were NOT re-run automatically, because tool calls can have side effects — each may or may not have completed. Check the current state (files, tabs, processes) before deciding whether to run any of them again, then continue the task.`}function gy(e,t){let n=e.body,r=e.lickId;if(n?.reason===`tool-call-interrupted`){let n=r?`\n\nLick ID: ${r}\nCall \`lick_dismiss\` with this lick id once you have dealt with it.`:``;return{label:t,content:`${hy(e)}${n}`}}if(n?.reason===`mount-recovery`){let e=ly(n.mounts??[]);return e===null?null:{label:t,content:`${e}${r?`\n\nLick ID: ${r}\nThis card is actionable: call \`lick_confirm\` with this lick id to re-run the listed \`mount …\` command(s) so the user can re-authorize, or \`lick_dismiss\` to leave them unmounted. The card flips to ✓ on confirm / muted ✗ on dismiss.`:``}`}}let i=Ty(e,t);if(!r)return i;let a=`\n\nLick ID: ${r}\nThis card is informational — there is NO confirm action. Call \`lick_dismiss\` with this lick id to acknowledge and clear it. The card flips to muted ✗ on dismiss.`;return{label:i.label,content:`${i.content}${a}`}}function _y(e,t){let n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`,i=e.body?.releasedAt??null,a=i?`\nReleased: ${i}`:``,o=e.lickId;return{label:t,content:`[${t}: ${n}→${r}]\n\nSLICC was upgraded from \`${n}\` to \`${r}\`.${a}${o?`\n\nLick ID: ${o}\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`). The card is a binary action: call \`lick_confirm\` with this lick id to **Update workspace files** (it runs the three-way merge of bundled vfs-root content into the user's VFS), or \`lick_dismiss\` to clear it. The card flips to ✓ on confirm / muted ✗ on dismiss. Reviewing the changelog is a separate step you can run first — it is NOT a card action.`:`
894
+
895
+ Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function vy(e,t){let n=e.cherryOrigin??`unknown origin`,r=e.cherryRuntimeId??`unknown`;return{label:t,content:`[${t}: ${e.cherryName??`unnamed`}] from ${n} (runtime ${r})\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function yy(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function by(e,t){let n=e.workflowName??`workflow`,r=e.resultPath??`(no result file)`,i=e.preview??``;return{label:t,content:`[${t}: ${n}] ${e.body?.status??`complete`} — ${i}\nFull result: ${r} (read it only if you need the whole thing).`}}function xy(e,t){let n=e.jshdName??`unknown`,r=e.jshdRestarts??0,i=e.resultPath;return{label:t,content:`[${t}: ${n}] marked errored after ${r} restarts.\nThe restart policy stopped trying so the unit does not crash-loop.\n${i?`Logs: ${i} (page with \`jshd logs ${n}\`).`:`No log file was written.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nInspect with \`jshd status ${n}\`; start it again with \`jshd start -n ${n}\` after fixing the script.`}}function Sy(e,t){let n=e.bashJobId??`unknown job`,r=e.bashJobPid===void 0?``:` (pid ${e.bashJobPid})`,i=e.bashCommand??`(unknown command)`,a=e.bashExitCode,o=a===0?`succeeded`:a===130||a===137||a===143?`was terminated (exit code ${a}) — killed by a signal, not by its own failure`:`failed (exit code ${a??`unknown`})`,s=e.resultPath;return{label:t,content:`[${t}: ${n}${r}] \`${i}\` ${o}.\n${s?`Full output: ${s} (page it with \`sed -n\`/\`tail\`/\`grep\` if the preview below is cut).`:`Its output could NOT be written to a file — the preview below is all that survived.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nThis is the delayed result of a command that was detached earlier in this session — do not re-run it. Act on it if it still matters, otherwise acknowledge and move on.`}}function Cy(e,t){let n=e.sudoScoopName??`a scoop`,r=e.lickId??`(unknown)`,i=e.sudoKind??`unknown`,a=e.sudoDetail??``,o=[`[${t}: ${n}]`,`Lick ID: ${r}`,`Kind: ${i}`,`Detail: ${a}`];return e.sudoReason&&o.push(`Reason given: ${e.sudoReason}`),e.sudoSuggestedPattern&&o.push(`Suggested pattern: ${e.sudoSuggestedPattern}`),o.push(``,`Use the lick_confirm tool with lick_id="${r}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${r}" and a reason to deny.`),{label:t,content:o.join(`
896
+ `)}}function wy(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.${e.discoveryKind===`llms-txt`&&e.lickId?`\n\nLick ID: ${e.lickId}\nThis card is dismiss-only: call \`lick_dismiss\` to add the advertising host to \`/etc/llmstxtignore\` and silence future discoveries without a prompt. There is NO confirm action.`:`
897
+ This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function Ty(e,t){let n=py(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Ey(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Ty(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Dy(e,t){let n=Ty(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill … --all\` with any branch/path scope from the body, so it installs EVERY skill under that scope — a broad path can be many); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Oy(e){let t=fy[e.type];return e.type===`session-reload`?gy(e,t):e.type===`upgrade`?_y(e,t):e.type===`cherry`?vy(e,t):e.type===`preview`?yy(e,t):e.type===`workflow`?by(e,t):e.type===`bash`?Sy(e,t):e.type===`jshd`?xy(e,t):e.type===`sudo-request`?Cy(e,t):e.type===`navigate`?Dy(e,t):e.type===`webhook`?Ey(e,t):e.type===`discovery`?wy(e,t):Ty(e,t)}function ky(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i=n?e.config:Ay(e,r),a={jid:e.id??(n?`cone_${t()}`:`scoop_${r}_${t()}`),name:e.name,folder:r,requiresTrigger:!n,assistantLabel:n?`sliccy`:r,addedAt:new Date(t()).toISOString(),parentJid:e.parentId,...i?{config:i,configSchemaVersion:3}:{},...e.notifyOnComplete===!1?{notifyOnComplete:!1}:{},...!n&&e.onParentClose===`detach`?{onParentClose:`detach`}:{}};return n||(a.trigger=`@${r}`),a}function Ay(e,t){let n=Dn(e.workspace?.mode??e.config?.workspaceMode),r=e.workspace?.from??`/workspace`,i=er(n,t,{root:r},e.workspace?.from),a=e.config;return{...a,workspaceMode:n,visiblePaths:a?.visiblePaths===void 0?i.visiblePaths:a.visiblePaths,writablePaths:a?.writablePaths===void 0?i.writablePaths:a.writablePaths}}function jy(e,t){if(e.parentId===null||e.workspace?.from!==void 0)return e;let n=t.getScoop(e.parentId);return n?{...e,workspace:{mode:e.workspace?.mode??e.config?.workspaceMode??`shared-readonly`,from:lr(n).root}}:e}var My=class{host;constructor(e){this.host=e}async create(e){e.parentId===null&&e.workspace?.mode!==void 0&&Dn(e.workspace.mode);let t=ky(jy(e,this.host));if(Ly(t.jid,e=>this.host.getScoop(e)),e.parentId!==null){let n=this.host.getScoop(e.parentId);if(!n)throw Error(`Parent work unit not found: ${e.parentId}`);Fn(t,n)}return await this.host.registerScoop(t),this.get(t.jid).descriptor}async createMany(e){if(e.length===0)return[];Ry(e,e=>this.host.getScoop(e),()=>this.host.getScoops());let t=Iy(e);for(let e of t)e.id&&Ly(e.id,e=>this.host.getScoop(e));let n=By(t),r=[],i=new Map;try{for(let e of n){let t=await this.create(e);r.push(t.id),i.set(e,t)}}catch(e){for(let e=r.length-1;e>=0;e--)await this.close(r[e]).catch(()=>void 0);throw e}return t.map(e=>i.get(e))}async join(e,t){return(await this.host.waitForScoops(e,t?.timeoutMs)).map(e=>({id:e.jid,summary:e.summary,timedOut:e.timedOut}))}list(){return this.host.getScoops().map(e=>this.get(e.jid).descriptor)}get(e){return this.host.getScoop(e)?this.host.ensureLiveUnit(e):null}getParent(e){let t=this.host.getScoop(e)?.parentJid;return t?this.get(t):null}getChildren(e){return $n(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return k(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=new Set,n=this.host.getScoop(e);for(;n&&n.parentJid!==null;){if(t.has(n.jid))return null;t.add(n.jid),n=this.host.getScoop(n.parentJid)}return n?this.get(n.jid):null}abort(e,t){let n=this.get(e);return n?n.abort(t):Promise.resolve()}async promote(e){let t=this.host.getScoop(e);if(!t)throw Error(`Work unit not found: ${e}`);if(t.parentJid===null)return this.get(e).descriptor;let n=Er(t),r=Py(t,t.parentJid);t.parentJid=null,Xn(t);try{await this.host.persistScoop(t)}catch(e){throw Fy(t,r),e}return await this.host.rekeyConversation?.(n,{key:Er(t),workUnitId:t.jid,workspaceId:Tr(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:Wn(t)}}),await this.host.reinitLiveUnit(e),this.get(e).descriptor}detach(e){return this.promote(e)}async close(e,t){let n=this.get(e);if(!n)return;let r=this.getChildren(e);for(let e of r)Ny(e,t)===`detach`?await this.promote(e.descriptor.id):await this.close(e.descriptor.id,t);await n.close()}};function Ny(e,t){return t?.descendants??e.descriptor.onParentClose}function Py(e,t){return{parentJid:t,trigger:e.trigger,requiresTrigger:e.requiresTrigger,approvesGuestRequests:e.approvesGuestRequests,onParentClose:e.onParentClose}}function Fy(e,t){e.parentJid=t.parentJid,e.trigger=t.trigger,e.requiresTrigger=t.requiresTrigger,e.approvesGuestRequests=t.approvesGuestRequests,e.onParentClose=t.onParentClose}function Iy(e){let t=Date.now();return e.map(e=>{if(e.id)return e;let n=e.folder??e.name,r=e.parentId===null?`cone_${t++}`:`scoop_${n}_${t++}`;return{...e,id:r}})}function Ly(e,t){if(t(e))throw Error(`Work unit already exists: ${e}`)}function Ry(e,t,n){let r=new Set;for(let n of e)if(n.id){if(r.has(n.id))throw Error(`Duplicate work unit id in createMany: ${n.id}`);Ly(n.id,t),r.add(n.id)}zy(e,n);let i=[],a=new Set;for(let n of e)n.parentId!==null&&(t(n.parentId)||r.has(n.parentId)||a.has(n.parentId)||(a.add(n.parentId),i.push(n.parentId)));if(i.length>0)throw Error(`Parent work unit not found: ${i.join(`, `)}`)}function zy(e,t){let n=new Set(t().map(e=>e.folder)),r=new Set;for(let t of e){let e=t.folder??t.name;if(r.has(e)||n.has(e))throw Error(`Duplicate work unit folder in createMany: ${e}`);r.add(e)}}function By(e){let t=e.length;if(t<=1)return e.slice();let n=new Map;for(let r=0;r<t;r++){let t=e[r].id;t&&n.set(t,r)}let r=Array(t).fill(0),i=Array.from({length:t},()=>[]);for(let a=0;a<t;a++){let t=e[a].parentId;if(t===null)continue;let o=n.get(t);o!==void 0&&(i[o].push(a),r[a]+=1)}let a=[];for(let e=0;e<t;e++)r[e]===0&&a.push(e);let o=[];for(let t=0;t<a.length;t++){let n=a[t];o.push(e[n]);for(let e of i[n])--r[e],r[e]===0&&a.push(e)}if(o.length!==t)throw Error(`createMany cycle: parentId edges in this batch form a cycle`);return o}const Vy=_(`kernel-agent-event-stream`);var Hy=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){Vy.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${Uy()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=e.displayScoopJid?`tool-ui-${e.requestId??``}`:i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=e.displayScoopJid?`tool-ui-${e.requestId??``}`:this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function Uy(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Wy=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Gy(e);return{jid:e.jid,name:e.name,folder:e.folder,parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=k(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Gy(e){let t=Ln(e),n=Hn(e),{level:r,effortOverride:i}=Vn(e);if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{modelProviderId:n},...r===void 0?{}:{thinkingLevel:r},...i===void 0?{}:{effortOverride:i}}}const W={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Ky=null;function qy(e){if(!e.objectStoreNames.contains(W.MESSAGES)){let t=e.createObjectStore(W.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(W.SESSIONS)||e.createObjectStore(W.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(W.TASKS)||e.createObjectStore(W.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(W.STATE)||e.createObjectStore(W.STATE,{keyPath:`key`})}function Jy(e,t){let n=e.isMain??!1;return{jid:e.jid,name:e.name,folder:e.folder,trigger:n?void 0:e.trigger||`@${e.folder}`,requiresTrigger:!n&&(e.requiresTrigger??!0),parentJid:n?null:t??null,assistantLabel:n?`sliccy`:e.config?.assistantName||e.folder,addedAt:e.addedAt,config:e.config?{systemPromptAppend:e.config.systemPromptAppend,timeout:e.config.timeout,assistantName:e.config.assistantName}:void 0}}function Yy(e,t){if(t.objectStoreNames.contains(`groups`)){let n=e.target.transaction.objectStore(`groups`).getAll();n.onsuccess=()=>{let e=n.result;t.deleteObjectStore(`groups`);let r=t.createObjectStore(W.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);let i=e.find(e=>e.isMain)?.jid;for(let t of e)r.put(Jy(t,i))};return}t.objectStoreNames.contains(W.SCOOPS)||t.createObjectStore(W.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function Xy(e){e.objectStoreNames.contains(W.WEBHOOKS)||e.createObjectStore(W.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(W.CRONTASKS)||e.createObjectStore(W.CRONTASKS,{keyPath:`id`})}function Zy(e){let t=e.target.result,n=e.oldVersion;n<1&&qy(t),n<2&&Yy(e,t),n<3&&Xy(t)}function Qy(){if(!Ky)return null;let e=Object.values(W).every(e=>Ky.objectStoreNames.contains(e));return Ky.version===3&&e?Ky:(Ky.close(),Ky=null,null)}function $y(e){e.onversionchange=()=>{e.close(),Ky===e&&(Ky=null)},e.onclose=()=>{Ky===e&&(Ky=null)}}async function eb(){return Qy()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=Zy,n.onsuccess=()=>{let t=n.result;$y(t),Ky=t,e(t)},n.onerror=()=>t(n.error)})}async function G(e,t=`readonly`){return(await eb()).transaction(e,t).objectStore(e)}async function tb(e){let t=await G(W.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function nb(){let e=await G(W.SCOOPS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>{let e={};for(let t of r.result)e[t.jid]=t;t(e)},r.onerror=()=>n(r.error)})}async function rb(e){let t=await G(W.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ib(){let e=await G(W.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function ab(e){let t=(await G(W.MESSAGES,`readwrite`)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,`￿`],!1,!1);return new Promise((e,r)=>{let i=t.openCursor(n);i.onsuccess=()=>{let t=i.result;if(!t){e();return}t.delete(),t.continue()},i.onerror=()=>r(i.error)})}async function ob(e){let t=await G(W.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function sb(e){let t=await G(W.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function cb(e){let t=(await G(W.MESSAGES)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,`￿`],!1,!1);return new Promise((e,r)=>{let i=t.getAll(n);i.onsuccess=()=>e(i.result),i.onerror=()=>r(i.error)})}const lb=`wm1:`;function ub(e){if(!e)return{ts:``,ids:new Set};if(e.startsWith(lb))try{let t=JSON.parse(e.slice(4));return{ts:t.ts,ids:new Set(t.ids)}}catch{}return{ts:e,ids:null}}function db(e){let t=e.ids?Array.from(e.ids):[];return`${lb}${JSON.stringify({ts:e.ts,ids:t})}`}function fb(e,t){return e.timestamp>t.ts?!0:e.timestamp<t.ts||t.ids===null?!1:!t.ids.has(e.id)}function pb(e,t){if(t.length===0)return e;let n=e.ts;for(let e of t)e.timestamp>n&&(n=e.timestamp);let r=new Set;if(e.ts===n&&e.ids)for(let t of e.ids)r.add(t);for(let e of t)e.timestamp===n&&r.add(e.id);return{ts:n,ids:r}}async function mb(e,t,n){let r=(await G(W.MESSAGES)).index(`chatJid_timestamp`),i=ub(t),a=IDBKeyRange.bound([e,i.ts],[e,`￿`],!1,!1);return new Promise((e,t)=>{let o=r.getAll(a);o.onsuccess=()=>{let t=o.result.filter(e=>fb(e,i));n&&(t=t.filter(e=>e.senderName!==n)),e(t)},o.onerror=()=>t(o.error)})}async function hb(e){let t=await G(W.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function gb(e){let t=await G(W.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function _b(){let e=await G(W.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function vb(e){let t=await G(W.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function yb(e){let t=await G(W.STATE);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result?.value??null),i.onerror=()=>r(i.error)})}async function bb(e,t){let n=await G(W.STATE,`readwrite`);return new Promise((r,i)=>{let a=n.put({key:e,value:t});a.onsuccess=()=>r(),a.onerror=()=>i(a.error)})}async function xb(){await eb()}async function Sb(e){let t=await G(W.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Cb(e){let t=await G(W.WEBHOOKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function wb(){try{let e=await G(W.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Tb(e){let t=await G(W.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Eb(e){let t=await G(W.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Db(e){let t=await G(W.CRONTASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function Ob(){try{let e=await G(W.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function kb(e){let t=await G(W.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}_(`tray-leader`);function Ab(){return jb(Or(),Te())}function jb(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const Mb=`__slicc_binary__`;function Nb(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Mb]===`b64`&&typeof t.data==`string`}function Pb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function Fb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)&&!Nb(e)}function Ib(e){if(e instanceof Uint8Array)return{[Mb]:`b64`,data:ie(e)};if(Array.isArray(e))return e.map(Ib);if(Pb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ib(r);return t}return e}function Lb(e){if(Nb(e))return ae(e.data);if(Array.isArray(e))return e.map(Lb);if(Fb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Lb(r);return t}return e}const Rb=_(`panel-transport`);function zb(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Bb(){return{onMessage:e=>{let t=(t,n,r)=>(zb(t)&&e(Lb(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Ib(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||Rb.error(`Offscreen → panel transport send failed`,{error:t})})}}}const Vb=_(`kernel-bridge`);function Hb(){return globalThis}function Ub(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var Wb=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;conesBeingCreated=new Map;currentMessageId=new Map;compactionRows=new ty(e=>`compaction-${e}-${Gb()}`);pendingMarkers=new Map;scoopPresentation=new Wy;transcriptsPublished=!1;agentEventStream=new Hy;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=Bb(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new $v;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.flushPendingMarkers(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Gb()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&e.currentMessageId.delete(t),(n===`ready`||n===`error`)&&e.flushPendingMarkers(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n,r)=>{let i=e.compactionRows.apply(t,n,r);e.emit({type:`compaction-state`,scoopJid:t,state:n,trigger:r.trigger,...r.transcriptPath?{transcriptPath:r.transcriptPath}:{},...r.failure?{failure:r.failure}:{},...r.roundId?{roundId:r.roundId}:{},...i?{rowId:i.messageId}:{}}),e.recordCompactionRow(t,i)},onError:(t,n,r)=>{e.recordErrorCard(t,n),e.emit({type:`error`,scoopJid:t,error:n,...r?.endTurn===!1?{endTurn:!1}:{}})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r,i)=>{V_.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{V_.has(n)||e.bufferToolEnd(t,n,r,i,a)},onToolUI:(t,n,r,i,a)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i,...a?{displayScoopJid:a}:{}})},onToolUIDone:(t,n,r)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n,...r?{displayScoopJid:r}:{}})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=W_(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??Gb(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=G_(n),e.isError=r)}}this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:K_(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(Wn(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],Ab())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...Ab()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Ub(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=te(e),s=[];n&&s.push({source:`explicit target`,value:n}),o&&o!==n&&s.push({source:`configured route`,value:o});let c=[],l;for(let e of s){if(l=Ga(a,e.value),l)break;c.push(e)}if(l||=this.originRootOf(a,r?.unitJid)??k(a)[0],c.length>0&&Vb.warn(`Sprinkle lick target could not be resolved; using fallback`,{sprinkleName:e,unresolvedTargets:c,fallbackJid:l?.jid}),!l)return;let u=`sprinkle-${e}-${Date.now()}`,d=Oy({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r?.label})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,f=c.map(({source:e,value:t})=>`${e} ${JSON.stringify(t)}`).join(` and `),p=d+(f?`\n\n> Delivery note: ${f} could not be resolved; delivered to fallback ${JSON.stringify(l.folder)}.`:``),m={id:u,chatJid:l.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:p,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(l.jid).push({id:u,role:`user`,content:p,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),await this.orchestrator.handleMessage(m)}originRootOf(e,t){if(t)return Pn(e,e.find(e=>e.jid===t))}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=k(this.orchestrator.getScoops())[0];if(!t)return;let n=qb(e).map((t,n)=>({...t,isStreaming:e[n]?.isStreaming}));this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?k(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromCanonicalRecord(e){let t=this.orchestrator?.getConversationStore?.();if(!t)return null;let{conversationKeyFor:n}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),r=await t.load(n(e));if(!r)return null;let{toChatMessages:i}=await Promise.resolve().then(()=>OC),a=await i(r,{source:Un(e)});return a.length===0?null:this.overlayPersistedLickDecisionsOn(e,qb(a))}async overlayPersistedLickDecisionsOn(e,t){if(!t.some(e=>e.channel===`sudo-request`||e.lickId||e.lickState))return t;let n=[];try{let t=await this.orchestrator?.getMessagesForScoop?.(e.jid);if(t)for(let e of t)n.push({id:e.id,content:e.content,channel:e.channel,lickId:e.lickId,lickState:e.lickState})}catch{}return Qb(t,n)}async hydrateBuffersFromRecords(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromCanonicalRecord(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid))}}publishHydratedTranscripts(){if(this.transcriptsPublished||!this.orchestrator)return;let e=this.orchestrator.getScoops();if(e.length!==0){for(let t of e){let e=this.messageBuffers.get(t.jid);!e||e.length===0||this.emitTranscript(t.jid,e)}this.emitScoopList(),this.transcriptsPublished=!0}}emitTranscript(e,t){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t,queuedIds:this.queuedIdsFor(e)})}queuedIdsFor(e){if(!(this.followerSync||!this.orchestrator))return this.orchestrator.getQueuedMessageIds(e)}async handleRequestScoopMessages(e){if(await this.conesBeingCreated.get(e),!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emitTranscript(e,n);return}let r=await this.buildBufferFromCanonicalRecord(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emitTranscript(e,r);return}this.emitTranscript(e,[])}async handleConeCreate(e,t,n,r){if(!this.orchestrator)return;let i=this.orchestrator.getScoops(),a=qn(e,i),o=a===Yn,s=k(i)[0],c=r??(s?Jn(s):void 0),l=t?.trim(),u={...ky({parentId:null,name:e,folder:a}),assistantLabel:o?`sliccy`:e,...l?{config:{systemPromptAppend:`This cone is for: ${l}`}}:{},...c?{model:c}:{}},d=()=>{};this.conesBeingCreated.set(u.jid,new Promise(e=>{d=e}));let f=()=>{this.conesBeingCreated.delete(u.jid),d()};try{await this.orchestrator.registerScoop(u),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(u)});let e=n?.trim();if(!e)return;let t=this.handleUserMessage({type:`user-message`,scoopJid:u.jid,text:e,messageId:`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});f(),await t}finally{f()}}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=t.approver;if(r&&r.kind!==`user`){let i=this.orchestrator;if(!i)console.warn(`[kernel-bridge] directed approval before orchestrator init — denying`);else try{n=await i.enqueueDirectedApproval(r,t)}catch(e){console.warn(`[kernel-bridge] directed approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n});return}let i=this.orchestrator?.getSudoManager()??null;if(!i)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await i.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}async handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}let o=await this.resolveBudgetWindow();this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a,...o?{budget:o}:{}})}budgetProbePending=!0;async resolveBudgetWindow(){return this.budgetProbePending?(this.budgetProbePending=!1,await Promise.race([F_().catch(()=>null),new Promise(e=>setTimeout(()=>e(null),2500))])??void 0):(F_().catch(()=>null),P_()??void 0)}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Kb(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await Promise.resolve().then(()=>J_),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:Un(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Kb(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromCanonicalRecord(r);if(a){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}n()}async recordCompactionRow(e,t){if(!t||t.kind===`open`)return;let n=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n)return;let r=this.getBuffer(e);if(t.kind===`retract`){let e=r.findIndex(e=>e.id===t.messageId);e>=0&&r.splice(e,1)}else{let e=r.find(e=>e.id===t.messageId);e?e.compaction=t.marker:r.push({id:t.messageId,role:`assistant`,content:``,timestamp:Date.now(),compaction:t.marker})}let i=this.orchestrator?.getConversationStore?.();if(!i)return;let{conversationKeyFor:a}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),o=a(n);if(t.kind===`retract`){this.dropPendingMarker(e,t.messageId),await i.deleteMarker(o,t.messageId);return}let s={id:t.messageId,kind:`compaction`,timestamp:Date.now(),compaction:t.marker};await i.putMarker(o,s)||this.holdPendingMarker(e,s)}holdPendingMarker(e,t){let n=this.pendingMarkers.get(e)??[];this.pendingMarkers.set(e,[...n.filter(e=>e.id!==t.id),t].slice(-4))}dropPendingMarker(e,t){let n=this.pendingMarkers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,r)}async flushPendingMarkers(e){let t=this.pendingMarkers.get(e);if(!t||t.length===0)return;let n=this.orchestrator?.getConversationStore?.(),r=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n||!r)return;let{conversationIdentityFor:i,conversationKeyFor:a}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),o=a(r);for(let a of t){let t=!1;try{t=await n.putMarker(o,a,a.kind===`error`?{createWith:i(r)}:void 0)}catch(t){Vb.warn(`Conversation marker retry threw`,{scoopJid:e,folder:r.folder,markerId:a.id,kind:a.kind,errorName:t instanceof Error?t.name:`unknown`})}t?this.dropPendingMarker(e,a.id):Vb.warn(`Conversation marker retry deferred`,{scoopJid:e,folder:r.folder,markerId:a.id,kind:a.kind})}}async recordErrorCard(e,t){let n=Gb(),r=Date.now();this.getBuffer(e).push({id:n,role:`assistant`,content:t,timestamp:r,error:!0});let i={id:n,kind:`error`,timestamp:r,text:t};this.holdPendingMarker(e,i);let a=this.orchestrator?.getConversationStore?.(),o=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!a||!o){Vb.warn(`Error marker is waiting for a canonical target`,{scoopJid:e,markerId:i.id,hasStore:!!a,hasScoop:!!o});return}let{conversationIdentityFor:s}=await import(`./key-6HWbWSGF.js`).then(e=>e.r),c=s(o),l=!1;try{l=await a.putMarker(c.key,i,{createWith:c})}catch(t){Vb.warn(`Error marker write threw; queued for retry`,{scoopJid:e,folder:o.folder,markerId:i.id,errorName:t instanceof Error?t.name:`unknown`})}l?this.dropPendingMarker(e,i.id):Vb.warn(`Error marker write deferred`,{scoopJid:e,folder:o.folder,markerId:i.id})}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${Gb()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?Un(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{e.source===`panel`&&this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name,e.description,e.prompt,e.model);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId,e.scoopJid,e.discardLiveSnapshot===!0);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`set-model`:case`refresh-model`:this.orchestrator.refreshModels();break;case`set-scoop-model`:await this.handleSetScoopModel(e);break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.handleWebhookEventMsg(e);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value)),Oa(e.key);break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key)),Oa(e.key);break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear()),Oa()}}handleWebhookEventMsg(e){let t=this.orchestrator?.handleWebhookEvent(e.webhookId,e.headers,e.body);e.requestId&&this.emit({type:`lick-webhook-delivery`,requestId:e.requestId,disposition:t??`unknown-webhook`})}async handleAgentSpawn(e){let t=Hb()[_v];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetScoopModel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopModel(e.scoopJid,e.model)}catch(e){console.error(`[kernel-bridge] set-scoop-model failed:`,e)}e.requestId&&this.emit({type:`set-scoop-model-ack`,requestId:e.requestId,scoopJid:e.scoopJid,model:e.model,applied:t})}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&this.messageBuffers.set(e,r)}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.guestGate?{guestGate:e.guestGate}:{},...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&jn(n)){if(k(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);let i=new Set(this.orchestrator.getScoops().map(e=>e.jid));for(let e of[...r,n])i.has(e.jid)||this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=Wn({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e,t,n=!1){let r=this.orchestrator?.getScoops()??[],i=(t?r.find(e=>e.jid===t):void 0)??k(r)[0],a=i?.jid;a&&(n?await this.orchestrator?.clearScoopMessages(a,{discardLiveSnapshot:!0}):await this.orchestrator?.clearScoopMessages(a)),this.sessionStore&&await this.sessionStore.delete(Wn({folder:i?.folder??`cone`})),a&&(this.messageBuffers.delete(a),this.currentMessageId.delete(a),this.agentEventStream.clear(a)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.origin)}handleSetFollowerForwarding(e){let t=Hb().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=Hb().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){bn.markMounted(t);return}try{await bn.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),bn.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function Gb(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Kb(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
898
+ `)}function qb(e){return e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,lickId:e.lickId,lickState:e.lickState,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1,compaction:e.compaction,error:e.error}))}function Jb(e){return e===`confirmed`||e===`dismissed`}function Yb(e){return e.channel===`sudo-request`||!!e.lickId||!!e.lickState||e.id.startsWith(`sudo-request-`)}function Xb(e){return e.lickId?e.lickId:Yb(e)?/^(?:Lick ID|Request ID): (\S+)/m.exec(e.content)?.[1]||(e.id.startsWith(`sudo-request-`)?e.id.slice(13):void 0):void 0}function Zb(e,t,n){let r=e.get(t);(!r||Jb(n.lickState)&&!Jb(r.lickState))&&e.set(t,n)}function Qb(e,t){if(!t||t.length===0)return e;let n=new Map,r=new Map,i=new Map;for(let e of t){if(!Yb(e))continue;let t=Xb(e);t&&Zb(n,t,e),Zb(r,e.id,e),Zb(i,e.content,e)}return e.map(e=>{if(!Yb(e))return e;let t=Xb(e),a=(t?n.get(t):void 0)??r.get(e.id)??i.get(e.content);if(!a||!a.lickId&&!a.lickState)return e;let o=a.lickId??t??Xb(a),s=Jb(a.lickState)?a.lickState:e.lickState??a.lickState;return o===e.lickId&&s===e.lickState&&a.id===e.id?e:{...e,id:a.id,lickId:o,lickState:s}})}const $b=_(`navigation-watcher`);function ex(e){if(!e)return null;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:null}catch{return null}}function tx(e){return e.replace(/\/+$/,``)||`/`}function nx(e){return t=>{let n=ex(e()??void 0);if(!n)return!1;let r=ex(t.url);return r?n.origin===r.origin&&tx(n.pathname)===tx(r.pathname):!1}}function rx(e,t){return se(e,t)}var ix=class{transport;onEvent;sessions=new Map;started=!1;unsubscribeState=null;rearming=!1;rearmQueued=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;isOwnTab;probedOrigins=new Set;pendingAttachTargetIds=new Set;ownSessionIds=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);this.sessions.delete(t),this.ownSessionIds.delete(t),n&&this.pendingAttachTargetIds.delete(n.targetId)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId){for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url));this.reconcileTargetNetwork(t)}};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameRequestedNavigation=e=>{let t=e;this.maybeArmNetwork(t.sessionId,t.frameId,t.url)};onFrameStartedNavigating=e=>{let t=e;this.maybeArmNetwork(t.sessionId,t.frameId,t.url)};onFrameNavigated=e=>{let t=e,n=t.sessionId;if(!n)return;let r=this.sessions.get(n);if(!r)return;let i=t.frame;i?.id&&(i.parentId||(r.rootFrameId=i.id,typeof i.url==`string`&&(r.url=i.url)))};onResponseReceived=e=>{let t=e,n=t.sessionId;if(!n)return;let r=this.sessions.get(n);if(!r||t.type!==`Document`)return;let i=t.frameId;if(!i||i!==r.rootFrameId)return;let a=t.response;if(!a)return;let o=typeof a.url==`string`&&a.url.length>0?a.url:r.url;if(!o)return;let{match:s,links:c}=rx(a.headers,o);if(s){let e={url:o,verb:s.verb,target:s.target,links:c,targetId:r.targetId};s.instruction!=null&&(e.instruction=s.instruction),s.branch!=null&&(e.branch=s.branch),s.path!=null&&(e.path=s.path),r.title!=null&&(e.title=r.title),this.onEvent(e)}this.maybeRunDiscovery(o,c,r.targetId)};eventBindings=[[`Target.attachedToTarget`,this.onAttachedToTarget],[`Target.detachedFromTarget`,this.onDetachedFromTarget],[`Target.targetInfoChanged`,this.onTargetInfoChanged],[`Target.targetCreated`,this.onTargetCreated],[`Page.frameNavigated`,this.onFrameNavigated],[`Page.frameRequestedNavigation`,this.onFrameRequestedNavigation],[`Page.frameStartedNavigating`,this.onFrameStartedNavigating],[`Network.responseReceived`,this.onResponseReceived]];constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs,this.isOwnTab=n.isOwnTab??(()=>!1)}maybeRunDiscovery(e,t,n){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let r;try{r=new URL(e).origin}catch{return}let i=ji(t);i&&this.onDiscovery({origin:r,kind:i.kind,url:i.url,targetId:n}),this.probeFetch&&!this.probedOrigins.has(r)&&(this.probedOrigins.add(r),this.runWellKnownProbe(r,n))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await Pi(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){$b.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){if(this.registerListeners(),!await this.enableDiscovery()){this.unregisterListeners();return}this.started=!0,this.subscribeTransportState(),await this.enumeratePreexistingTargets()}}registerListeners(){for(let[e,t]of this.eventBindings)this.transport.off(e,t),this.transport.on(e,t)}unregisterListeners(){for(let[e,t]of this.eventBindings)this.transport.off(e,t)}async enableDiscovery(){try{return await this.transport.send(`Target.setDiscoverTargets`,{discover:!0}),!0}catch(e){return $b.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),!1}}async enumeratePreexistingTargets(){try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;e||typeof n!=`string`||await this.requestAttach(n,`Failed to attach to preexisting target`)}}catch(e){$b.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}subscribeTransportState(){this.unsubscribeState||=this.transport.onStateChange?.(e=>{if(e===`disconnected`){this.clearConnectionScopedState();return}e===`connected`&&(this.rearming?this.rearmQueued=!0:this.rearmAfterReconnect())})??null}clearConnectionScopedState(){this.sessions.clear(),this.pendingAttachTargetIds.clear(),this.ownSessionIds.clear()}async rearmAfterReconnect(){if(!(!this.started||this.rearming)){this.rearming=!0;try{if(this.clearConnectionScopedState(),this.registerListeners(),!await this.enableDiscovery())return;await this.enumeratePreexistingTargets()}finally{this.rearming=!1,this.rearmQueued&&(this.rearmQueued=!1,this.rearmAfterReconnect())}}}async stop(){if(this.started){this.started=!1,this.unsubscribeState?.(),this.unsubscribeState=null,this.unregisterListeners(),this.clearConnectionScopedState();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){$b.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;t?.type===`page`&&typeof t.targetId==`string`&&(t.attached||await this.requestAttach(t.targetId,`Failed to attach to discovered target`))}maybeArmNetwork(e,t,n){if(!e||!t)return;let r=this.sessions.get(e);!r||r.networkEnabled||!this.ownSessionIds.has(e)||r.rootFrameId===t&&(this.isOwnTabSafe({targetId:r.targetId,url:n})||this.setSessionNetwork(e,r,!0))}reconcileTargetNetwork(e){let t=this.isOwnTabSafe(e);for(let[n,r]of this.sessions)r.targetId===e.targetId&&this.ownSessionIds.has(n)&&r.networkEnabled!==!t&&this.setSessionNetwork(n,r,!t)}async setSessionNetwork(e,t,n){t.networkEnabled=n;try{await this.transport.send(n?`Network.enable`:`Network.disable`,{},e)}catch(r){t.networkEnabled=!n,$b.debug(`Failed to ${n?`enable`:`disable`} Network on session`,{sessionId:e,targetId:t.targetId,error:r instanceof Error?r.message:String(r)})}}isOwnTabSafe(e){try{return this.isOwnTab(e)}catch(t){return $b.debug(`isOwnTab predicate threw; treating target as foreign`,{targetId:e.targetId,error:t instanceof Error?t.message:String(t)}),!1}}async requestAttach(e,t){this.pendingAttachTargetIds.add(e);try{let t=(await this.transport.send(`Target.attachToTarget`,{targetId:e,flatten:!0}))?.sessionId;typeof t==`string`&&t.length>0&&(this.ownSessionIds.add(t),this.pendingAttachTargetIds.delete(e))}catch(n){this.pendingAttachTargetIds.delete(e),$b.debug(t,{targetId:e,error:n instanceof Error?n.message:String(n)})}}claimOwnSession(e,t){return this.ownSessionIds.has(e)?!0:this.pendingAttachTargetIds.has(t)?(this.pendingAttachTargetIds.delete(t),this.ownSessionIds.add(e),!0):!1}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!t||!n||n.type!==`page`||typeof n.targetId!=`string`||(this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,networkEnabled:!1,title:n.title,url:n.url}),!this.claimOwnSession(t,n.targetId)))return;let r=this.isOwnTabSafe(n);r&&$b.debug(`Attaching to the SLICC app tab with Network off`,{targetId:n.targetId,url:n.url});try{if(await this.transport.send(`Page.enable`,{},t),!r){let e=this.sessions.get(t);e&&await this.setSessionNetwork(t,e,!0)}let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){$b.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}};function ax(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var ox=`# /etc/llmstxtignore — llms.txt discovery suppression
899
899
  #
900
900
  # One advertising hostname or glob per line. Matching is case-insensitive.
901
901
  # \`#\` starts a comment; blank lines are ignored.
@@ -906,10 +906,10 @@ This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`c
906
906
 
907
907
  github.com
908
908
  app.slack.com
909
- `;const yx=_(`llms-txt-ignore`),bx=`/etc/llmstxtignore`;function xx(e){return typeof e==`string`?e.split(/\r?\n/).map(e=>e.slice(0,e.indexOf(`#`)===-1?void 0:e.indexOf(`#`)).trim()).filter(Boolean).map(e=>e.toLowerCase()):[]}function Sx(e){return`.+^$()[]|\\{}`.includes(e)?`\\${e}`:e}function Cx(e){let t=``;for(let n of e)t+=n===`*`?`.*`:n===`?`?`.`:Sx(n);return RegExp(`^${t}$`,`i`)}function wx(e,t){return t.some(t=>Cx(t).test(e))}function Tx(e){if(e.parentJid===null)return!0;let t=e.config?.allowedCommands;return t===void 0||t.includes(`*`)?!0:t.some(e=>[`curl`,`wget`,`discover`,`playwright-cli`,`playwright`,`puppeteer`].includes(e))}function Ex(e,t){for(let n of[e,t])if(n)try{return new URL(n).hostname.toLowerCase()}catch{}return null}async function Dx(e,t){let n=t.trim().toLowerCase();if(!n||n.includes(`
910
- `)||n.includes(`\r`)||n.includes(`#`))throw Error(`Invalid llms.txt ignore hostname.`);let r=``;try{r=await e.readFile(bx,{encoding:`utf-8`})}catch(e){if(!(e instanceof A)||e.code!==`ENOENT`)throw e}if(wx(n,xx(r)))return!1;let i=r.length>0&&!r.endsWith(`
909
+ `;const sx=_(`llms-txt-ignore`),cx=`/etc/llmstxtignore`;function lx(e){return typeof e==`string`?e.split(/\r?\n/).map(e=>e.slice(0,e.indexOf(`#`)===-1?void 0:e.indexOf(`#`)).trim()).filter(Boolean).map(e=>e.toLowerCase()):[]}function ux(e){return`.+^$()[]|\\{}`.includes(e)?`\\${e}`:e}function dx(e){let t=``;for(let n of e)t+=n===`*`?`.*`:n===`?`?`.`:ux(n);return RegExp(`^${t}$`,`i`)}function fx(e,t){return t.some(t=>dx(t).test(e))}function px(e){if(e.parentJid===null)return!0;let t=e.config?.allowedCommands;return t===void 0||t.includes(`*`)?!0:t.some(e=>[`curl`,`wget`,`discover`,`playwright-cli`,`playwright`,`puppeteer`].includes(e))}function mx(e,t){for(let n of[e,t])if(n)try{return new URL(n).hostname.toLowerCase()}catch{}return null}async function hx(e,t){let n=t.trim().toLowerCase();if(!n||n.includes(`
910
+ `)||n.includes(`\r`)||n.includes(`#`))throw Error(`Invalid llms.txt ignore hostname.`);let r=``;try{r=await e.readFile(cx,{encoding:`utf-8`})}catch(e){if(!(e instanceof A)||e.code!==`ENOENT`)throw e}if(fx(n,lx(r)))return!1;let i=r.length>0&&!r.endsWith(`
911
911
  `)?`
912
- `:``;return await e.writeFile(bx,`${r}${i}${n}\n`),!0}var Ox=class{fs;watcher;entries=[];unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/llmstxtignore`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}ignores(e){if(e.type!==`discovery`||e.discoveryKind!==`llms-txt`)return!1;let t=Ex(e.discoveryOrigin,e.discoveryUrl);return t!==null&&wx(t,this.entries)}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/llmstxtignore`)||await this.fs.writeFile(bx,vx)}catch(e){yx.warn(`Failed to seed default llms.txt ignore policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(bx,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);this.entries=xx(t)}catch(e){this.entries=[],yx.warn(`Failed to read llms.txt ignore policy`,{error:e instanceof Error?e.message:String(e)})}}};const kx=`gelatiere`,Ax=`gelatiere`,jx=`gelatiere-nightly`,Mx=`system:gelatiere`;function Nx(e){return e.parentJid===`system:gelatiere`&&e.folder===`gelatiere`}var Px=`# /etc/sudoers — SLICC agent approval policy
912
+ `:``;return await e.writeFile(cx,`${r}${i}${n}\n`),!0}var gx=class{fs;watcher;entries=[];unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/llmstxtignore`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}ignores(e){if(e.type!==`discovery`||e.discoveryKind!==`llms-txt`)return!1;let t=mx(e.discoveryOrigin,e.discoveryUrl);return t!==null&&fx(t,this.entries)}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/llmstxtignore`)||await this.fs.writeFile(cx,ox)}catch(e){sx.warn(`Failed to seed default llms.txt ignore policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(cx,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);this.entries=lx(t)}catch(e){this.entries=[],sx.warn(`Failed to read llms.txt ignore policy`,{error:e instanceof Error?e.message:String(e)})}}};const _x=`gelatiere`,vx=`gelatiere`,yx=`gelatiere-nightly`,bx=`system:gelatiere`;function xx(e){return e.parentJid===`system:gelatiere`&&e.folder===`gelatiere`}var Sx=`# /etc/sudoers — SLICC agent approval policy
913
913
  #
914
914
  # This file controls which agent actions require a native human approval
915
915
  # prompt (an OS dialog in CLI/Electron, a window.confirm/prompt in the Chrome
@@ -983,12 +983,12 @@ Write /etc/models
983
983
  #
984
984
  # Let connected followers export the live transcript without a prompt:
985
985
  # NOPASSWD Export active
986
- `;const Fx=_(`sudo:manager`);function Ix(e){return e===`/etc/sudoers`||e===`/etc/sudoers.d`||e.startsWith(`/etc/sudoers.d/`)}function Lx(e){if(!e.startsWith(`/etc/sudoers.d/`))return null;let t=e.slice(Hr.length+1);return t.includes(`/`)?null:Nr(t)}function Rx(e){return e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e}const zx=[`# Approved "Always" grants for one scoop. Loaded only for that scoop.`,`# Sandbox grants come from ScoopConfig, in memory — not here.`,`# Writes always require approval (self-protected).`,``].join(`
987
- `);function Bx(e){let t=[],n=e?.allowedCommands;if(n===void 0||n.includes(`*`))t.push(`NOPASSWD Cmnd *`);else for(let e of n){let n=Rr(e);n&&(t.push(`NOPASSWD Cmnd ${n}`),t.push(`NOPASSWD Cmnd ${n} *`))}for(let n of e?.writablePaths??[]){let e=Rr(n);e&&(t.push(`NOPASSWD Write ${Rx(e)}`),t.push(`NOPASSWD Write ${Rx(e)}/**`))}for(let n of e?.visiblePaths??[]){let e=Rr(n);e&&(t.push(`NOPASSWD Read ${Rx(e)}`),t.push(`NOPASSWD Read ${Rx(e)}/**`))}return`${t.join(`
988
- `)}\n`}var Vx=class{fs;watcher;broker;onPolicyReload;policy=Fr();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`&&Lr(this.policy,e.detail)===`nopasswd-allow`)return Fx.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 Fx.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(Gr(e.kind),n)}catch(n){return Fx.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=[Pr(),this.policy];return n&&r.push(n),t&&r.push(t),Vr(...r)}registerScoopConfig(e,t){this.scoopConfigPolicies.set(e,zr(Bx(t??void 0))),this.onPolicyReload(e)}async initScoopPolicy(e,t){this.registerScoopConfig(e,t);let n=qr(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=Rr(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=Jr(e);if(!a)return Fx.warn(`Unspellable scoop folder; not persisting`,{folder:e}),null;let o=await this.readTextOrEmpty(a),s=`NOPASSWD ${i} ${r}`;if(o.split(`
989
- `).some(e=>e.trim()===s))return Fx.info(`Per-scoop grant already present; skipping duplicate append`,{folder:e,kind:t,pattern:r}),r;try{await this.fs.mkdir(Hr,{recursive:!0})}catch{}let c=o?o.endsWith(`
990
- `)?o:`${o}\n`:zx;return await this.fs.writeFile(a,`${c}${s}\n`),await this.reloadScoopPolicy(e),Fx.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 A&&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=Jr(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(Wr)];try{let t=(await this.fs.readDir(Hr)).filter(e=>e.type===`file`).filter(e=>Nr(e.name)===null).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${Hr}/${n}`))}catch{}this.policy=Vr(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return Fr();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return zr(n)}catch(t){return Fx.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),Fr()}}async ensureDefaults(){try{await this.fs.mkdir(Hr,{recursive:!0})}catch{}await this.seedWhenAbsent(Wr,()=>Px),await this.seedWhenAbsent(Kr,async()=>(await import(`./approver-agent-CvnFt_s6.js`)).DEFAULT_APPROVALS_MD)}async seedWhenAbsent(e,t){try{if(await this.fs.exists(e))return;await this.fs.writeFile(e,await t()),Fx.info(`Seeded bundled policy default`,{path:e})}catch(t){Fx.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=Rr(t);if(!n)return;let r=``;try{if(await this.fs.exists(Zr)){let e=await this.fs.readFile(Zr,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof A&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(Hr,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
991
- `)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(Zr,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,Ix,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=Lx(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 Hx(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Ux(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wx(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)Wx(e[r],`${t}/${r}`,n);return}if(Ux(e))for(let[r,i]of Object.entries(e))Wx(i,`${t}/${Hx(r)}`,n)}function Gx(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=Gx(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(Ux(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=Gx(o,`${t}/${Hx(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function Kx(e,t,n){if(Ux(e))return Gx(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=Kx(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function qx(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 Jx(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 Yx(e,t,n,r){let i=[],a=qx(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=qx(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 Xx(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 Zx(e,t,n,r){if(r?.aborted)throw new a(`redaction-unavailable`);let{privacy:i,...o}=e,s=[];Wx(o,``,s);let c=s.filter(e=>!ne(e.pointer)),l=[...t.entries()],u=await Jx([...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=Yx(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)}Xx(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=Yx(n,u[g+e],{kind:`attachment`,attachmentId:t},p);p=r.nextId,ee.set(t,r.finalText),te.push(r)}Xx(te,d,f);let re=Kx(e,``,m);return{document:{...re,privacy:{...re.privacy,redactionCounts:f,redactions:d}},textAttachments:ee}}function Qx(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 $x(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 eS={"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 tS(e,t){return eS[e]??(t===`text-redacted`?`.txt`:`.bin`)}function nS(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${tS(t,n)}`}function rS(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 iS(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 aS(e,t,n,r,i){let a=Qx(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(rS(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=rS(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 oS(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:rS(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(aS(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function sS(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 cS(e,t,n,r,i,a,o){let s=sS(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(aS(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function lS(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=cS(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 uS(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,nS(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 dS(e,t,n,r,i){let{rawAttachments:o,textMap:s}=uS(e,n),c,l;try{let e=await Zx({...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 $x(n);return d.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...c,attachments:f},bundleFiles:d}}async function fS(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}=oS(iS(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}=lS(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 dS(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 pS(e){return Vn(e)}function mS(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 hS(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:On(t)?`cone`:`scoop`,name:t.name,...t.folder&&!On(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=pS(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function gS(e,t,n={}){let r=e=>n.rootJid===void 0?e:kn(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=mS(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===mS(c,e))return hS(c,o,s,e)}}var _S=e({SESSIONS_DIR:()=>vS,SESSIONS_INDEX_PATH:()=>yS,parseFrozenArchive:()=>xS,readSessionsIndex:()=>bS});const vS=`/sessions`,yS=`/sessions/index.json`;async function bS(e){try{let t=await e.readFile(yS,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function xS(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,SS(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=CS(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:TS(t),...r})}function SS(e){let t={},n=wS(e,`cost`),r=wS(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=CS(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 CS(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 wS(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function TS(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 ES(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function DS(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function OS(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(DS(t,r++));return n}function kS(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=DS(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 AS(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=DS(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 jS(e,t,n){let r=ES(t,n),i=OS(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 MS(e,t,n){let r=ES(t,n),{blocks:i,excluded:a,images:o}=kS(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 NS(e,t,n){let r=ES(t,n),{blocks:i,images:a}=AS(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function PS(e,t,n){return e.role===`user`?jS(e,t,n):e.role===`assistant`?MS(e,t,n):e.role===`toolResult`?NS(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function FS(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 IS(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=PS(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:FS(e),excludedReasoningBlocks:t,canonicalImages:n}}const LS=(()=>{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 RS(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^LS[(t^e[n])&255];return~t>>>0}const zS=new TextEncoder;function q(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function BS(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function VS(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,q(r,4,20),q(r,6,2048),q(r,8,0),q(r,10,0),q(r,12,0),BS(r,14,n),BS(r,18,t),BS(r,22,t),q(r,26,e.length),q(r,28,0),r.set(e,30),r}function HS(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,q(i,4,20),q(i,6,20),q(i,8,2048),q(i,10,0),q(i,12,0),q(i,14,0),BS(i,16,n),BS(i,20,t),BS(i,24,t),q(i,28,e.length),q(i,30,0),q(i,32,0),q(i,34,0),q(i,36,0),BS(i,38,0),BS(i,42,r),i.set(e,46),i}function US(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,q(r,4,0),q(r,6,0),q(r,8,e),q(r,10,e),BS(r,12,t),BS(r,16,n),q(r,20,0),r}function WS(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function GS(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*KS(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=$r.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=zS.encode(`transcript.json`),p=RS(i),m=VS(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=zS.encode(e),i=RS(r),o=VS(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(HS(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new a(`transfer-aborted`);yield*f(US(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 qS(e,t,n){for(let e of t.keys())if(!WS(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:GS(e),chunks:KS(e,t,n,r,i),completion:o}}function JS(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 YS(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 XS(e){let t=n(e);if(!t.ok)throw new a(`schema-invalid`,t.error)}function ZS(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 QS(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 $S(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 eC=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),XS(i.document),r?.({phase:`packaging`}),qS(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await gS(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=IS(n.sources),{document:i,bundleFiles:a}=await fS({document:JS(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});XS(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 gS(this.deps.collection,e),r=IS(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=JS(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),fS({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 Zx(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new a(`redaction-unavailable`)}let o=ZS(r.attachments,i,e.attachments),s=await QS(r.attachments,o);return{document:{...r,attachments:s},bundleFiles:o}}async buildLegacyPartial(e,t,n){let r=(await bS(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-Dx1wwk9X.js`),{title:s,messages:c}=await o(this.deps.vfs,i,r.filename),l=`legacy-cone`,u=YS(c,l),d=$S(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`}),fS({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 tC=`/sessions/data`,nC=`document.json`;async function rC(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 iC(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 aC(e){return`${tC}/${e}`}function oC(e){return`${tC}/.tmp-${e}`}async function sC(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function cC(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 cC(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function lC(e,t,n){await sC(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 lC(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function uC(e,t,n){iC(t);let r=oC(t),i=aC(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 cC(e,i),await sC(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await rC(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}/${nC}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await sC(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await lC(e,r,i),await e.flush()}catch(t){throw await cC(e,r),t}await cC(e,r)}async function dC(e,t){iC(t);let r=aC(t),i=`${r}/${nC}`,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 rC(i)!==t.sha256)throw new a(`transfer-corrupt`);c.set(t.path,i)}return{document:s,attachments:c}}function fC(e){return`error`in e}function pC(){throw new a(`redaction-unavailable`)}function mC(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&pC(),e.texts}function hC(){return{async redact(e){let t;try{t=await fetch(Pe(`/api/secrets/redact-export`),{method:`POST`,headers:Fe({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{pC()}t.ok||pC();let n;try{n=await t.json()}catch{pC()}return mC(n,e.length)}}}function gC(){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{pC()}return typeof t==`object`&&t&&fC(t)&&pC(),mC(t,e.length)}}}function _C(){return{async redact(e){let t;try{t=await mn(`secrets.redact-export`,{texts:e})}catch{pC()}return t??pC(),typeof t==`object`&&t&&fC(t)&&pC(),mC(t,e.length)}}}function vC(){return{async redact(e){pC()}}}function yC(){let e=sn();return e===`connect`?vC():e===`extension-direct`?gC():e===`extension-delegate`?_C():hC()}const bC=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function xC(e){return`e${e}`}function SC(e){let t=[];for(let n of e){let e=TC(n),r=DC(n);if(e===`assistant`){let e=t.length,i=xC(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:AC(n),message:n,model:kC(n)});for(let e of jC(n)){let n=t.length;t.push({id:xC(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:xC(i),seq:i,kind:`tool-result`,timestamp:r,text:AC(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=AC(n),a=e===`user`?wC(i):null,o=t.length,s=xC(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):bC.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 CC(e){let t=[];for(let n of e){let e=t.length,r=xC(e),i=OC(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:xC(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&Q_(n.channel)?n.channel:wC(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):bC.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 wC(e){for(let t of bv(e)){let e=(t.sender?xv(t.sender):null)??Sv(t.body);if(e)return e}return null}function TC(e){return e.role??``}function EC(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 DC(e){return EC(e.timestamp)}function OC(e){return EC(e.timestamp)}function kC(e){let t=e.model;return typeof t==`string`?t:void 0}function AC(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 jC(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 MC(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function NC(e){return e!==null&&e.version<=2}const PC=_(`work-unit-conversation`);var FC=class extends Error{};const IC=`conversations`;async function LC(e){let t=e.now??(()=>Date.now()),n=await zC(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=Cr(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await RC(e,s,c,t());n===`migrated`?r.migrated++:n===`already`?r.alreadyDone++:r.empty++}catch(i){let o=i instanceof Error?i.message:String(i);if(r.skipped++,n.skipped=[...n.skipped.filter(e=>e.key!==c),{key:c,reason:o}],PC.warn(`Skipping a unit whose conversation could not be migrated`,{key:c,folder:s.folder,error:o}),i instanceof FC){a=!0,n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${s.jid}`);continue}}i.add(c),n.completedKeys=[...i],n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${s.jid}`)}return n.done=!a,n.updatedAt=t(),await e.store.putMigrationState(n),PC.info(`Canonical conversation migration complete`,{...r}),r}async function RC(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return PC.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw new FC(`canonical record unreadable: ${i.reason}`);let a=wr(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:SC(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:CC(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function zC(e,t){let n=await e.getMigrationState(IC);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:IC,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var BC=e({applyAttachmentOverlays:()=>WC,interleaveMarkers:()=>GC,toAgentMessages:()=>HC,toChatMessages:()=>UC});const VC=new Set([`summarized`,`fallback`]);function HC(e){if(!NC(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 UC(e,t={}){if(!NC(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 GC(t,e.markers)}let n=e.projectionPrefix??[],r=HC(e);if(r.length===0)return GC([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>ov),a=WC(i(r,t),e.attachments);return GC([...n,...a],e.markers)}function WC(e,t){if(!t?.length)return e;let n=[...t].sort((e,t)=>e.timestamp-t.timestamp),r=new Set;return e.map(e=>{if(e.role!==`user`||e.attachments?.length)return e;let t=e.content.trim(),i=n.findIndex((e,n)=>!r.has(n)&&e.body.trim()===t);return i<0?e:(r.add(i),{...e,attachments:n[i].attachments})})}function GC(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||VC.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=KC(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(qC(r[a++]));i.push(t)}for(;a<r.length;)i.push(qC(r[a++]));return i}function KC(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 qC(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 JC(e){return{id:e.legacyKeys.chatSessionId,messages:await UC(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function YC(e){return{id:e.workUnitId,messages:HC(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var XC=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(YC)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(JC))}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(or({parentJid:null,folder:e}).root);return t?JC(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const ZC=_(`work-unit-conversation`),QC=`conversations`,$C=`migrations`;var ew=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 sw((await this.getDb()).transaction(QC,`readonly`).objectStore(QC).get(e));return t?NC(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(ZC.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(ZC.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return ZC.warn(`Conversation record read failed`,{key:e,error:lw(t)}),{status:`error`,reason:lw(t)}}}async save(e){let t=e.version>2?e.version:MC(e),n={...e,version:t},r=(await this.getDb()).transaction(QC,`readwrite`);return r.objectStore(QC).put(n),await cw(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(QC,`readwrite`);t.objectStore(QC).delete(e),await cw(t)}catch(t){ZC.warn(`Conversation record delete failed`,{key:e,error:lw(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`){ZC.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){ZC.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:lw(n)})}}async loadAll(){try{return(await sw((await this.getDb()).transaction(QC,`readonly`).objectStore(QC).getAll())).filter(e=>NC(e)&&Array.isArray(e.entries))}catch(e){return ZC.warn(`Conversation record listing failed`,{error:lw(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await sw((await this.getDb()).transaction(QC,`readonly`).objectStore(QC).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)!NC(e)||!Array.isArray(e.entries)||(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return ZC.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:lw(t)}),null}}async listKeys(){try{return(await sw((await this.getDb()).transaction(QC,`readonly`).objectStore(QC).getAllKeys())).map(String)}catch(e){return ZC.warn(`Conversation key listing failed`,{error:lw(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=SC(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=tw(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return ZC.warn(`Conversation record write failed`,{key:e.key,error:lw(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?nw(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 ZC.warn(`Conversation marker write failed`,{key:e,error:lw(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 sw((await this.getDb()).transaction($C,`readonly`).objectStore($C).get(e))??null}catch(t){return ZC.warn(`Migration state read failed`,{id:e,error:lw(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction($C,`readwrite`);t.objectStore($C).put(e),await cw(t)}catch(t){ZC.warn(`Migration state write failed`,{id:e.id,error:lw(t)})}}async clearAll(){let e=(await this.getDb()).transaction([QC,$C],`readwrite`);e.objectStore(QC).clear(),e.objectStore($C).clear(),await cw(e)}getDb(){return this.dbPromise||(this.dbPromise=ow(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 tw(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??[],...rw(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&iw(a,t))return null;let o=t.length>a.length&&iw(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 nw(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 rw(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function iw(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!aw(e[n],t[n]))return!1;return!0}function aw(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 ow(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(QC)||e.createObjectStore(QC,{keyPath:`key`}),e.objectStoreNames.contains($C)||e.createObjectStore($C,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function sw(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function cw(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function lw(e){return e instanceof Error?e.message:String(e)}var uw=e({CONE_MEMORY_PATH:()=>pw,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>fw,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>mw,applyConeMemoryBudget:()=>yw,readSessionCount:()=>_w,restructureConeMemory:()=>vw,splitConeMemory:()=>gw});const dw=_(`cone-memory-budget`),fw=1.25,pw=nr.memoryPath,mw=`/sessions/index.json`,hw=/^## Auto-extracted/m;function gw(e){let t=hw.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function _w(e){try{let t=await e.readFile(mw,{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 vw(e){let{header:t,autoExtracted:n}=gw(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.
986
+ `;const Cx=_(`sudo:manager`);function wx(e){return e===`/etc/sudoers`||e===`/etc/sudoers.d`||e.startsWith(`/etc/sudoers.d/`)}function Tx(e){if(!e.startsWith(`/etc/sudoers.d/`))return null;let t=e.slice(Gr.length+1);return t.includes(`/`)?null:Ir(t)}function Ex(e){return e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e}const Dx=[`# Approved "Always" grants for one scoop. Loaded only for that scoop.`,`# Sandbox grants come from ScoopConfig, in memory — not here.`,`# Writes always require approval (self-protected).`,``].join(`
987
+ `);function Ox(e){let t=[],n=e?.allowedCommands;if(n===void 0||n.includes(`*`))t.push(`NOPASSWD Cmnd *`);else for(let e of n){let n=Vr(e);n&&(t.push(`NOPASSWD Cmnd ${n}`),t.push(`NOPASSWD Cmnd ${n} *`))}for(let n of e?.writablePaths??[]){let e=Vr(n);e&&(t.push(`NOPASSWD Write ${Ex(e)}`),t.push(`NOPASSWD Write ${Ex(e)}/**`))}for(let n of e?.visiblePaths??[]){let e=Vr(n);e&&(t.push(`NOPASSWD Read ${Ex(e)}`),t.push(`NOPASSWD Read ${Ex(e)}/**`))}return`${t.join(`
988
+ `)}\n`}var kx=class{fs;watcher;broker;onPolicyReload;policy=Rr();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`&&Br(this.policy,e.detail)===`nopasswd-allow`)return Cx.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 Cx.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(Jr(e.kind),n)}catch(n){return Cx.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=[Lr(),this.policy];return n&&r.push(n),t&&r.push(t),Wr(...r)}registerScoopConfig(e,t){this.scoopConfigPolicies.set(e,Hr(Ox(t??void 0))),this.onPolicyReload(e)}async initScoopPolicy(e,t){this.registerScoopConfig(e,t);let n=Xr(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=Vr(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=Zr(e);if(!a)return Cx.warn(`Unspellable scoop folder; not persisting`,{folder:e}),null;let o=await this.readTextOrEmpty(a),s=`NOPASSWD ${i} ${r}`;if(o.split(`
989
+ `).some(e=>e.trim()===s))return Cx.info(`Per-scoop grant already present; skipping duplicate append`,{folder:e,kind:t,pattern:r}),r;try{await this.fs.mkdir(Gr,{recursive:!0})}catch{}let c=o?o.endsWith(`
990
+ `)?o:`${o}\n`:Dx;return await this.fs.writeFile(a,`${c}${s}\n`),await this.reloadScoopPolicy(e),Cx.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 A&&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=Zr(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(qr)];try{let t=(await this.fs.readDir(Gr)).filter(e=>e.type===`file`).filter(e=>Ir(e.name)===null).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${Gr}/${n}`))}catch{}this.policy=Wr(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return Rr();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return Hr(n)}catch(t){return Cx.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),Rr()}}async ensureDefaults(){try{await this.fs.mkdir(Gr,{recursive:!0})}catch{}await this.seedWhenAbsent(qr,()=>Sx),await this.seedWhenAbsent(Yr,async()=>(await import(`./approver-agent-CvnFt_s6.js`)).DEFAULT_APPROVALS_MD)}async seedWhenAbsent(e,t){try{if(await this.fs.exists(e))return;await this.fs.writeFile(e,await t()),Cx.info(`Seeded bundled policy default`,{path:e})}catch(t){Cx.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=Vr(t);if(!n)return;let r=``;try{if(await this.fs.exists(ei)){let e=await this.fs.readFile(ei,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof A&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(Gr,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
991
+ `)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(ei,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,wx,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=Tx(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 Ax(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function jx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mx(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++)Mx(e[r],`${t}/${r}`,n);return}if(jx(e))for(let[r,i]of Object.entries(e))Mx(i,`${t}/${Ax(r)}`,n)}function Nx(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=Nx(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(jx(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=Nx(o,`${t}/${Ax(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function Px(e,t,n){if(jx(e))return Nx(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=Px(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function Fx(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 Ix(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 Lx(e,t,n,r){let i=[],a=Fx(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Fx(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 Rx(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 zx(e,t,n,r){if(r?.aborted)throw new a(`redaction-unavailable`);let{privacy:i,...o}=e,s=[];Mx(o,``,s);let c=s.filter(e=>!ne(e.pointer)),l=[...t.entries()],u=await Ix([...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=Lx(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)}Rx(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=Lx(n,u[g+e],{kind:`attachment`,attachmentId:t},p);p=r.nextId,ee.set(t,r.finalText),te.push(r)}Rx(te,d,f);let re=Px(e,``,m);return{document:{...re,privacy:{...re.privacy,redactionCounts:f,redactions:d}},textAttachments:ee}}function Bx(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 Vx(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 Hx={"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 Ux(e,t){return Hx[e]??(t===`text-redacted`?`.txt`:`.bin`)}function Wx(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${Ux(t,n)}`}function Gx(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 Kx(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 qx(e,t,n,r,i){let a=Bx(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(Gx(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=Gx(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 Jx(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:Gx(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(qx(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function Yx(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 Xx(e,t,n,r,i,a,o){let s=Yx(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(qx(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function Zx(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=Xx(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 Qx(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,Wx(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 $x(e,t,n,r,i){let{rawAttachments:o,textMap:s}=Qx(e,n),c,l;try{let e=await zx({...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 Vx(n);return d.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...c,attachments:f},bundleFiles:d}}async function eS(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}=Jx(Kx(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}=Zx(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 $x(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 tS(e){return Wn(e)}function nS(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 rS(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:jn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!jn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=tS(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function iS(e,t,n={}){let r=e=>n.rootJid===void 0?e:Mn(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=nS(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===nS(c,e))return rS(c,o,s,e)}}var aS=e({SESSIONS_DIR:()=>oS,SESSIONS_INDEX_PATH:()=>sS,parseFrozenArchive:()=>lS,readSessionsIndex:()=>cS});const oS=`/sessions`,sS=`/sessions/index.json`;async function cS(e){try{let t=await e.readFile(sS,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function lS(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,uS(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=dS(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:pS(t),...r})}function uS(e){let t={},n=fS(e,`cost`),r=fS(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=dS(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 dS(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 fS(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function pS(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 mS(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function hS(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function gS(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(hS(t,r++));return n}function _S(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=hS(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 vS(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=hS(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 yS(e,t,n){let r=mS(t,n),i=gS(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 bS(e,t,n){let r=mS(t,n),{blocks:i,excluded:a,images:o}=_S(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 xS(e,t,n){let r=mS(t,n),{blocks:i,images:a}=vS(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 SS(e,t,n){return e.role===`user`?yS(e,t,n):e.role===`assistant`?bS(e,t,n):e.role===`toolResult`?xS(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function CS(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 wS(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=SS(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:CS(e),excludedReasoningBlocks:t,canonicalImages:n}}const TS=(()=>{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 ES(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^TS[(t^e[n])&255];return~t>>>0}const DS=new TextEncoder;function K(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function OS(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 kS(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),OS(r,14,n),OS(r,18,t),OS(r,22,t),K(r,26,e.length),K(r,28,0),r.set(e,30),r}function AS(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),OS(i,16,n),OS(i,20,t),OS(i,24,t),K(i,28,e.length),K(i,30,0),K(i,32,0),K(i,34,0),K(i,36,0),OS(i,38,0),OS(i,42,r),i.set(e,46),i}function jS(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),OS(r,12,t),OS(r,16,n),K(r,20,0),r}function MS(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 NS(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*PS(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=ni.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=DS.encode(`transcript.json`),p=ES(i),m=kS(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=DS.encode(e),i=ES(r),o=kS(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(AS(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new a(`transfer-aborted`);yield*f(jS(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 FS(e,t,n){for(let e of t.keys())if(!MS(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:NS(e),chunks:PS(e,t,n,r,i),completion:o}}function IS(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 LS(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 RS(e){let t=n(e);if(!t.ok)throw new a(`schema-invalid`,t.error)}function zS(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 BS(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 VS(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 HS=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),RS(i.document),r?.({phase:`packaging`}),FS(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await iS(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=wS(n.sources),{document:i,bundleFiles:a}=await eS({document:IS(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});RS(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 iS(this.deps.collection,e),r=wS(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=IS(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),eS({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 zx(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new a(`redaction-unavailable`)}let o=zS(r.attachments,i,e.attachments),s=await BS(r.attachments,o);return{document:{...r,attachments:s},bundleFiles:o}}async buildLegacyPartial(e,t,n){let r=(await cS(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-DK-0Hm8U.js`),{title:s,messages:c}=await o(this.deps.vfs,i,r.filename),l=`legacy-cone`,u=LS(c,l),d=VS(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`}),eS({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 US=`/sessions/data`,WS=`document.json`;async function GS(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 KS(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 qS(e){return`${US}/${e}`}function JS(e){return`${US}/.tmp-${e}`}async function YS(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function XS(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 XS(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function ZS(e,t,n){await YS(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 ZS(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function QS(e,t,n){KS(t);let r=JS(t),i=qS(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 XS(e,i),await YS(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await GS(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}/${WS}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await YS(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await ZS(e,r,i),await e.flush()}catch(t){throw await XS(e,r),t}await XS(e,r)}async function $S(e,t){KS(t);let r=qS(t),i=`${r}/${WS}`,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 GS(i)!==t.sha256)throw new a(`transfer-corrupt`);c.set(t.path,i)}return{document:s,attachments:c}}function eC(e){return`error`in e}function tC(){throw new a(`redaction-unavailable`)}function nC(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&tC(),e.texts}function rC(){return{async redact(e){let t;try{t=await fetch(Le(`/api/secrets/redact-export`),{method:`POST`,headers:Re({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{tC()}t.ok||tC();let n;try{n=await t.json()}catch{tC()}return nC(n,e.length)}}}function iC(){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{tC()}return typeof t==`object`&&t&&eC(t)&&tC(),nC(t,e.length)}}}function aC(){return{async redact(e){let t;try{t=await _n(`secrets.redact-export`,{texts:e})}catch{tC()}return t??tC(),typeof t==`object`&&t&&eC(t)&&tC(),nC(t,e.length)}}}function oC(){return{async redact(e){tC()}}}function sC(){let e=un();return e===`connect`?oC():e===`extension-direct`?iC():e===`extension-delegate`?aC():rC()}const cC=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function lC(e){return`e${e}`}function uC(e){let t=[];for(let n of e){let e=pC(n),r=hC(n);if(e===`assistant`){let e=t.length,i=lC(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:vC(n),message:n,model:_C(n)});for(let e of yC(n)){let n=t.length;t.push({id:lC(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:lC(i),seq:i,kind:`tool-result`,timestamp:r,text:vC(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=vC(n),a=e===`user`?fC(i):null,o=t.length,s=lC(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):cC.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 dC(e){let t=[];for(let n of e){let e=t.length,r=lC(e),i=gC(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:lC(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&B_(n.channel)?n.channel:fC(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):cC.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 fC(e){for(let t of cv(e)){let e=(t.sender?lv(t.sender):null)??uv(t.body);if(e)return e}return null}function pC(e){return e.role??``}function mC(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 hC(e){return mC(e.timestamp)}function gC(e){return mC(e.timestamp)}function _C(e){let t=e.model;return typeof t==`string`?t:void 0}function vC(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 yC(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 bC(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function xC(e){return e!==null&&e.version<=2}const SC=_(`work-unit-conversation`);var CC=class extends Error{};const wC=`conversations`;async function TC(e){let t=e.now??(()=>Date.now()),n=await DC(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=Er(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await EC(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}],SC.warn(`Skipping a unit whose conversation could not be migrated`,{key:c,folder:s.folder,error:o}),i instanceof CC){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),SC.info(`Canonical conversation migration complete`,{...r}),r}async function EC(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return SC.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw new CC(`canonical record unreadable: ${i.reason}`);let a=Dr(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:uC(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:dC(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function DC(e,t){let n=await e.getMigrationState(wC);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:wC,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var OC=e({applyAttachmentOverlays:()=>MC,interleaveMarkers:()=>NC,toAgentMessages:()=>AC,toChatMessages:()=>jC});const kC=new Set([`summarized`,`fallback`]);function AC(e){if(!xC(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 jC(e,t={}){if(!xC(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 NC(t,e.markers)}let n=e.projectionPrefix??[],r=AC(e);if(r.length===0)return NC([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>J_),a=MC(i(r,t),e.attachments);return NC([...n,...a],e.markers)}function MC(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 NC(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||kC.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=PC(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(FC(r[a++]));i.push(t)}for(;a<r.length;)i.push(FC(r[a++]));return i}function PC(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 FC(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 IC(e){return{id:e.legacyKeys.chatSessionId,messages:await jC(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function LC(e){return{id:e.workUnitId,messages:AC(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var RC=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(LC)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(IC))}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(lr({parentJid:null,folder:e}).root);return t?IC(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const zC=_(`work-unit-conversation`),q=`conversations`,BC=`migrations`;var VC=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 JC((await this.getDb()).transaction(q,`readonly`).objectStore(q).get(e));return t?xC(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(zC.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(zC.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return zC.warn(`Conversation record read failed`,{key:e,error:XC(t)}),{status:`error`,reason:XC(t)}}}async save(e){let t=e.version>2?e.version:bC(e),n={...e,version:t},r=(await this.getDb()).transaction(q,`readwrite`);return r.objectStore(q).put(n),await YC(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(q,`readwrite`);t.objectStore(q).delete(e),await YC(t)}catch(t){zC.warn(`Conversation record delete failed`,{key:e,error:XC(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`){zC.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){zC.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:XC(n)})}}async loadAll(){try{return(await JC((await this.getDb()).transaction(q,`readonly`).objectStore(q).getAll())).filter(e=>xC(e)&&Array.isArray(e.entries))}catch(e){return zC.warn(`Conversation record listing failed`,{error:XC(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await JC((await this.getDb()).transaction(q,`readonly`).objectStore(q).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)!xC(e)||!Array.isArray(e.entries)||(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return zC.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:XC(t)}),null}}async listKeys(){try{return(await JC((await this.getDb()).transaction(q,`readonly`).objectStore(q).getAllKeys())).map(String)}catch(e){return zC.warn(`Conversation key listing failed`,{error:XC(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=uC(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=HC(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return zC.warn(`Conversation record write failed`,{key:e.key,error:XC(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?UC(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 zC.warn(`Conversation marker write failed`,{key:e,error:XC(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 JC((await this.getDb()).transaction(BC,`readonly`).objectStore(BC).get(e))??null}catch(t){return zC.warn(`Migration state read failed`,{id:e,error:XC(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(BC,`readwrite`);t.objectStore(BC).put(e),await YC(t)}catch(t){zC.warn(`Migration state write failed`,{id:e.id,error:XC(t)})}}async clearAll(){let e=(await this.getDb()).transaction([q,BC],`readwrite`);e.objectStore(q).clear(),e.objectStore(BC).clear(),await YC(e)}getDb(){return this.dbPromise||(this.dbPromise=qC(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 HC(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??[],...WC(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&GC(a,t))return null;let o=t.length>a.length&&GC(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 UC(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 WC(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function GC(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!KC(e[n],t[n]))return!1;return!0}function KC(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 qC(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(q)||e.createObjectStore(q,{keyPath:`key`}),e.objectStoreNames.contains(BC)||e.createObjectStore(BC,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function JC(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function YC(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function XC(e){return e instanceof Error?e.message:String(e)}var ZC=e({CONE_MEMORY_PATH:()=>ew,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>$C,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>tw,applyConeMemoryBudget:()=>ow,readSessionCount:()=>iw,restructureConeMemory:()=>aw,splitConeMemory:()=>rw});const QC=_(`cone-memory-budget`),$C=1.25,ew=ar.memoryPath,tw=`/sessions/index.json`,nw=/^## Auto-extracted/m;function rw(e){let t=nw.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function iw(e){try{let t=await e.readFile(tw,{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 aw(e){let{header:t,autoExtracted:n}=rw(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}
@@ -999,13 +999,13 @@ Rules:
999
999
  - One fact per bullet. Drop duplicates and superseded facts. Keep the most recent / specific phrasing.
1000
1000
  - Preserve concrete identifiers (file paths, URLs, IDs, names) verbatim.
1001
1001
  - Be terse. Aim well under the original size.
1002
- - Do NOT add preamble, commentary, or any heading other than the single consolidated one.`}],timestamp:Date.now()},a=await on(e.model,{systemPrompt:r,messages:[i]},{apiKey:e.apiKey,maxTokens:4096,headers:e.headers,signal:e.signal});if(a.stopReason===`error`)throw Error(`Restructure call failed: ${a.errorMessage||`Unknown error`}`);let o=a.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
1002
+ - Do NOT add preamble, commentary, or any heading other than the single consolidated one.`}],timestamp:Date.now()},a=await ln(e.model,{systemPrompt:r,messages:[i]},{apiKey:e.apiKey,maxTokens:4096,headers:e.headers,signal:e.signal});if(a.stopReason===`error`)throw Error(`Restructure call failed: ${a.errorMessage||`Unknown error`}`);let o=a.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
1003
1003
  `).trim();if(!o)throw Error(`Restructure call returned empty content`);return`${t}${t.length===0||t.endsWith(`
1004
1004
  `)?``:`
1005
- `}${o}\n`}async function yw(e){if(!e.model||!e.apiKey)return{restructured:!1,reason:`no-llm`};let t=e.memoryPath??pw,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 _w(e.vfs),i=ei(r),a=i*fw;if(n.length<=a)return{restructured:!1,reason:`under-threshold`};dw.info(`Cone memory over threshold — restructuring`,{size:n.length,budget:i,threshold:a,sessionCount:r});try{let r=await vw({currentContent:n,budget:i,model:e.model,apiKey:e.apiKey,headers:e.headers,signal:e.signal});return await e.vfs.writeFile(t,r),dw.info(`Cone memory restructured`,{before:n.length,after:r.length}),{restructured:!0}}catch(e){return dw.warn(`Cone memory restructure failed — leaving appended content in place`,{error:e instanceof Error?e.message:String(e)}),{restructured:!1,reason:`error`}}}const bw=`.skill`,xw=`/workspace/skills`,Sw=`SKILL.md`,Cw=_(`skills-discovery`),ww=[`native`,`agents`,`claude`,`marketplace`,`plugin`],Tw=new Map([[`.agents`,`agents`],[`.claude`,`claude`]]),Ew=new Set([`.git`,`.slicc`,`node_modules`]),Dw=2e4,Ow=[`mkdir`,`mount`,`rename`,`rm`,`unmount`,`writeFile`],kw=new WeakMap,Aw=new WeakSet,jw=new WeakMap,Mw=new WeakMap,Nw=new Set([`.agents`,`.claude`,`.claude-plugin`]),Pw=new Set([`mount`,`rename`,`rm`,`unmount`]);async function Fw(e,t=xw){let n=await Ww(e,t),r=await Vw(e),i=await Iw(e);return[...ww.flatMap(e=>(e===`native`?n:e===`plugin`?i:r.filter(t=>t.source===e)).sort((e,t)=>e.path.localeCompare(t.path)))]}async function Iw(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 Zw(e,t);for(let r of i){if(r.type!==`directory`)continue;let i=`${t}/${r.name}`,a=`${i}/${Sw}`;await Xw(e,a)&&n.push({source:`plugin`,sourceRoot:t,path:i,skillFilePath:a})}}return n}function Lw(e){return e.map(e=>({...e}))}function Rw(e){kw.delete(e),Mw.delete(e),jw.set(e,(jw.get(e)??0)+1)}function zw(e){let t=e.split(`/`);for(let e of t)if(Nw.has(e))return!0;return t[t.length-1]===`SKILL.md`||t.includes(`skills`)}function Bw(e,t){if(Pw.has(e))return!0;let n=t[0];return typeof n==`string`&&zw(n)}async function Vw(e){if(Hw(e))return Lw(await Jw(e));Yw(e);let t=e,n=kw.get(t);if(n)return Lw(n);let r=jw.get(t)??0,i=Mw.get(t);if(i&&i.generation===r)return Lw(await i.promise);let a=Jw(e).then(e=>((jw.get(t)??0)===r&&kw.set(t,e),e)),o;return o=a.finally(()=>{Mw.get(t)?.promise===o&&Mw.delete(t)}),Mw.set(t,{generation:r,promise:o}),Lw(await o)}function Hw(e){try{return e[Yr]===!0}catch{return!1}}function Uw(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 Ww(e,t){let n=await Zw(e,t),r=[];for(let i of n){if(i.type!==`directory`)continue;let n=`${t}/${i.name}`,a=`${n}/${Sw}`;await Xw(e,a)&&r.push({source:`native`,sourceRoot:t,path:n,skillFilePath:a})}return r}async function Gw(e,t){let n;try{n=await e.readTextFile(t)}catch{return[]}let r;try{r=JSON.parse(n)}catch{return[]}if(typeof r!=`object`||!r)return[];let i=r.plugins;if(!Array.isArray(i))return[];let a=t.replace(/\/[^/]+$/,``).replace(/\/.claude-plugin$/,``),o=[];for(let e of i){if(typeof e!=`object`||!e)continue;let t=e.source;if(typeof t!=`string`||t.startsWith(`/`)||t.split(`/`).includes(`..`))continue;let n=t.replace(/^\.\//,``).replace(/\/$/,``).replace(/^\.$/,``);o.push(n?`${a}/${n}`:a)}return o}async function Kw(e,t,n){let r=await Gw(e,`${t}/marketplace.json`),i=[];for(let t of r){let r=`${t}/skills`,a=await Zw(e,r);for(let t of a){if(t.type!==`directory`)continue;let a=`${r}/${t.name}`,o=`${a}/${Sw}`;!await Xw(e,o)||n.has(a)||(n.add(a),i.push({source:`marketplace`,sourceRoot:r,path:a,skillFilePath:o}))}}return i}async function qw(e,t,n,r){let i=`${t}/skills`,a=await Zw(e,i),o=[];for(let t of a){if(t.type!==`directory`)continue;let a=`${i}/${t.name}`,s=`${a}/${Sw}`;!await Xw(e,s)||r.has(a)||(r.add(a),o.push({source:n,sourceRoot:i,path:a,skillFilePath:s}))}return o}async function Jw(e){let t=[],n=new Set,r=new Set([`/`]),i=[{path:`/`,depth:0}];for(let a=0;a<i.length;a+=1){if(a>=Dw){Cw.warn(`skills discovery: directory budget exhausted; walk truncated`,{budget:Dw});break}let{path:o,depth:s}=i[a],c=await Zw(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=Tw.get(a.name);if(l){let r=await qw(e,c,l,n);t.push(...r)}if(a.name===`.claude-plugin`){let r=await Kw(e,c,n);t.push(...r);continue}!Ew.has(a.name)&&s<24&&!r.has(c)&&(r.add(c),i.push({path:c,depth:s+1}))}}return t}function Yw(e){if(Hw(e))return;let t=e;if(Aw.has(t))return;Aw.add(t);let n=e;for(let r of Ow){let i=n[r];if(typeof i==`function`)try{n[r]=async(...n)=>{let a=await i.apply(e,n);return Bw(r,n)&&Rw(t),a}}catch{}}}async function Xw(e,t){try{return await e.stat(t),!0}catch{return!1}}async function Zw(e,t){try{return[...await e.readDir(t)].sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}async function Qw(e,t=`/workspace/skills`){let n=await Fw(e,t),r=[];for(let t of n){let n=t.path.split(`/`).pop()??t.path,i=``;if(t.skillFilePath)try{i=tT(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}=Uw(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 $w(e,t,n=`/workspace/skills`){return(await Qw(e,n)).find(e=>e.name===t)||null}async function eT(e,t,n=`/workspace/skills`){let r=await $w(e,t,n);if(!r?.skillFilePath)return null;try{return await e.readTextFile(r.skillFilePath)}catch{return null}}function tT(e){let t=e.replace(/^\uFEFF/,``).replace(/\r\n?/g,`
1005
+ `}${o}\n`}async function ow(e){if(!e.model||!e.apiKey)return{restructured:!1,reason:`no-llm`};let t=e.memoryPath??ew,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 iw(e.vfs),i=ri(r),a=i*$C;if(n.length<=a)return{restructured:!1,reason:`under-threshold`};QC.info(`Cone memory over threshold — restructuring`,{size:n.length,budget:i,threshold:a,sessionCount:r});try{let r=await aw({currentContent:n,budget:i,model:e.model,apiKey:e.apiKey,headers:e.headers,signal:e.signal});return await e.vfs.writeFile(t,r),QC.info(`Cone memory restructured`,{before:n.length,after:r.length}),{restructured:!0}}catch(e){return QC.warn(`Cone memory restructure failed — leaving appended content in place`,{error:e instanceof Error?e.message:String(e)}),{restructured:!1,reason:`error`}}}const sw=`.skill`,cw=`/workspace/skills`,lw=`SKILL.md`,uw=_(`skills-discovery`),dw=[`native`,`agents`,`claude`,`marketplace`,`plugin`],fw=new Map([[`.agents`,`agents`],[`.claude`,`claude`]]),pw=new Set([`.git`,`.slicc`,`node_modules`]),mw=2e4,hw=[`mkdir`,`mount`,`rename`,`rm`,`unmount`,`writeFile`],gw=new WeakMap,_w=new WeakSet,vw=new WeakMap,yw=new WeakMap,bw=new Set([`.agents`,`.claude`,`.claude-plugin`]),xw=new Set([`mount`,`rename`,`rm`,`unmount`]);async function Sw(e,t=cw){let n=await jw(e,t),r=await Ow(e),i=await Cw(e);return[...dw.flatMap(e=>(e===`native`?n:e===`plugin`?i:r.filter(t=>t.source===e)).sort((e,t)=>e.path.localeCompare(t.path)))]}async function Cw(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 Rw(e,t);for(let r of i){if(r.type!==`directory`)continue;let i=`${t}/${r.name}`,a=`${i}/${lw}`;await Lw(e,a)&&n.push({source:`plugin`,sourceRoot:t,path:i,skillFilePath:a})}}return n}function ww(e){return e.map(e=>({...e}))}function Tw(e){gw.delete(e),yw.delete(e),vw.set(e,(vw.get(e)??0)+1)}function Ew(e){let t=e.split(`/`);for(let e of t)if(bw.has(e))return!0;return t[t.length-1]===`SKILL.md`||t.includes(`skills`)}function Dw(e,t){if(xw.has(e))return!0;let n=t[0];return typeof n==`string`&&Ew(n)}async function Ow(e){if(kw(e))return ww(await Fw(e));Iw(e);let t=e,n=gw.get(t);if(n)return ww(n);let r=vw.get(t)??0,i=yw.get(t);if(i&&i.generation===r)return ww(await i.promise);let a=Fw(e).then(e=>((vw.get(t)??0)===r&&gw.set(t,e),e)),o;return o=a.finally(()=>{yw.get(t)?.promise===o&&yw.delete(t)}),yw.set(t,{generation:r,promise:o}),ww(await o)}function kw(e){try{return e[Qr]===!0}catch{return!1}}function Aw(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 jw(e,t){let n=await Rw(e,t),r=[];for(let i of n){if(i.type!==`directory`)continue;let n=`${t}/${i.name}`,a=`${n}/${lw}`;await Lw(e,a)&&r.push({source:`native`,sourceRoot:t,path:n,skillFilePath:a})}return r}async function Mw(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 Nw(e,t,n){let r=await Mw(e,`${t}/marketplace.json`),i=[];for(let t of r){let r=`${t}/skills`,a=await Rw(e,r);for(let t of a){if(t.type!==`directory`)continue;let a=`${r}/${t.name}`,o=`${a}/${lw}`;!await Lw(e,o)||n.has(a)||(n.add(a),i.push({source:`marketplace`,sourceRoot:r,path:a,skillFilePath:o}))}}return i}async function Pw(e,t,n,r){let i=`${t}/skills`,a=await Rw(e,i),o=[];for(let t of a){if(t.type!==`directory`)continue;let a=`${i}/${t.name}`,s=`${a}/${lw}`;!await Lw(e,s)||r.has(a)||(r.add(a),o.push({source:n,sourceRoot:i,path:a,skillFilePath:s}))}return o}async function Fw(e){let t=[],n=new Set,r=new Set([`/`]),i=[{path:`/`,depth:0}];for(let a=0;a<i.length;a+=1){if(a>=mw){uw.warn(`skills discovery: directory budget exhausted; walk truncated`,{budget:mw});break}let{path:o,depth:s}=i[a],c=await Rw(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=fw.get(a.name);if(l){let r=await Pw(e,c,l,n);t.push(...r)}if(a.name===`.claude-plugin`){let r=await Nw(e,c,n);t.push(...r);continue}!pw.has(a.name)&&s<24&&!r.has(c)&&(r.add(c),i.push({path:c,depth:s+1}))}}return t}function Iw(e){if(kw(e))return;let t=e;if(_w.has(t))return;_w.add(t);let n=e;for(let r of hw){let i=n[r];if(typeof i==`function`)try{n[r]=async(...n)=>{let a=await i.apply(e,n);return Dw(r,n)&&Tw(t),a}}catch{}}}async function Lw(e,t){try{return await e.stat(t),!0}catch{return!1}}async function Rw(e,t){try{return[...await e.readDir(t)].sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}async function zw(e,t=`/workspace/skills`){let n=await Sw(e,t),r=[];for(let t of n){let n=t.path.split(`/`).pop()??t.path,i=``;if(t.skillFilePath)try{i=Hw(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}=Aw(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 Bw(e,t,n=`/workspace/skills`){return(await zw(e,n)).find(e=>e.name===t)||null}async function Vw(e,t,n=`/workspace/skills`){let r=await Bw(e,t,n);if(!r?.skillFilePath)return null;try{return await e.readTextFile(r.skillFilePath)}catch{return null}}function Hw(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
- `)){let t=e.match(/^description:\s*(.*)$/);if(t)return t[1].trim()}return null}const nT=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function rT(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 iT=class extends Error{};function aT(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 oT(e){if(!nT.test(e))throw Error(`Invalid skill: skill name "${e}" must be a simple directory name.`)}function sT(e){let t=[];for(let[n,r]of Object.entries(e)){let e=aT(n);e&&(rT(e)||t.push({originalPath:n,path:e,bytes:r}))}return t}function cT(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 ${Sw}.`);if(t.length>1)throw Error(`Skill archive contains multiple ${Sw} files.`);return t[0]}function lT(e){let t=0,n=0;return ii(e,{filter(e){if(t++,t>1e3)throw new iT(`Skill archives may contain at most 1000 entries.`);if(n+=e.originalSize,n>52428800)throw new iT(`Skill archives must expand to 50 MB or smaller after extraction.`);return!0}})}function uT(e){let t=`${Date.now()}-${Math.random().toString(16).slice(2,8)}`;return Sn(xw,`.${e}.tmp-${t}`)}function dT(e,t){return t===`SKILL.md`?e.replace(/\.skill$/i,``):t.slice(0,-9).split(`/`).pop()??``}function fT(e){if(!e.name.toLowerCase().endsWith(`.skill`))throw Error(`Only ${bw} archives can be installed with drag and drop.`);if(e.size>52428800)throw Error(`Skill archives must be 50 MB or smaller.`)}async function pT(e){try{return lT(new Uint8Array(await e.arrayBuffer()))}catch(e){if(e instanceof iT)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Invalid .skill archive: ${t}`)}}function mT(e){return e.path===`SKILL.md`?``:e.path.slice(0,-9)}function hT(e,t){return t&&(e===t||!e.startsWith(`${t}/`))?null:(t?e.slice(t.length+1):e)||null}async function gT(e,t,n,r){let i=Sn(t,n),{dir:a}=bn(i);a!==`/`&&await e.mkdir(a,{recursive:!0}),await e.writeFile(i,r)}async function _T(e,t,n,r){let i=0;for(let a of t){let t=hT(a.path,n);t&&(await gT(e,r,t,a.bytes),i++)}return i}async function vT(e,t){await e.exists(t)&&await e.rm(t,{recursive:!0})}async function yT(e,t){let n=Sn(xw,t);if(await e.exists(n))throw Error(`Skill "${t}" already exists at ${n}.`);return n}async function bT(e,t){fT(t);let n=sT(await pT(t)),r=cT(n),i=dT(t.name,r.path);oT(i);let a=await yT(e,i),o=uT(i),s=mT(r);await e.mkdir(o,{recursive:!0});try{let t=await _T(e,n,s,o);return await e.rename(o,a),{skillName:i,destinationPath:a,fileCount:t}}catch(t){throw await vT(e,o),t}}var xT=e({MAX_SKILL_ARCHIVE_SIZE_BYTES:()=>52428800,SKILLS_DIR:()=>`skills`,SKILL_ARCHIVE_EXTENSION:()=>bw,SKILL_FILE:()=>Sw,WORKSPACE_SKILLS_PATH:()=>xw,discoverSkillCandidates:()=>Fw,discoverSkills:()=>Qw,getSkillInfo:()=>$w,installSkillFromDrop:()=>bT,readSkillInstructions:()=>eT,resolveSkillNameCollisions:()=>Uw});const ST=_(`skills`),CT=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-BMBoR1hd.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-BMBoR1hd.js`).then(e=>e.default),"/packages/vfs-root/etc/APPROVALS.md":()=>import(`./APPROVALS-CoZKeFYV.js`).then(e=>e.default),"/packages/vfs-root/etc/MEMORY.md":()=>import(`./MEMORY-Dl8Y_nOo.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/etc/slicc/keys.json":()=>import(`./keys-BMebW-sj.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-Bzu6oiWk.js`).then(e=>e.default),"/packages/vfs-root/shared/GELATIERE.md":()=>import(`./GELATIERE-CLK_MA5a.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/suggestions/suggestions.shtml":()=>import(`./suggestions-B34zKgsF.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-BzW33ZtP.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/WIKI.md":()=>import(`./WIKI-DoBxwf2u.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/index.md":()=>import(`./wiki-BXN4hgmw.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/log.md":()=>import(`./log-DEDI5t_h.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-cOU0zXaK.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BNnF2azP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-BTVvFyRd.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/computer/SKILL.md":()=>import(`./SKILL-BpMlcVho.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-CWxUIsrD.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-Be-LbAuP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-D3hRMDs3.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-BS0BC3cr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-DGelbGt_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-CX_QtSBf.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-DOE4hLxi.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-wvtABi3i.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-BIdAO7Ya.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)}),wT=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function TT(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 ET={};function DT(){let e={};for(let[t,n]of Object.entries(CT))e[t]=n;for(let[t,n]of Object.entries(wT))e[t]=async()=>TT(await n());for(let[t,n]of Object.entries(ET)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function OT(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){ST.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 kT(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 AT=new WeakMap;function jT(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 MT(e,t){let n=await NT(e,t),r=await PT(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=OT([...i,...r,...a]);return ST.info(`Skills loaded`,{count:o.length,dir:t}),o}async function NT(e,t){let n=await Qw(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=kT(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}),ST.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{ST.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function PT(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}=kT(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}),ST.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{ST.debug(`Standalone skills directory not found`,{dir:t})}return n}function FT(e){return e.length===0?``:`
1007
+ `)){let t=e.match(/^description:\s*(.*)$/);if(t)return t[1].trim()}return null}const Uw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Ww(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 Gw=class extends Error{};function Kw(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 qw(e){if(!Uw.test(e))throw Error(`Invalid skill: skill name "${e}" must be a simple directory name.`)}function Jw(e){let t=[];for(let[n,r]of Object.entries(e)){let e=Kw(n);e&&(Ww(e)||t.push({originalPath:n,path:e,bytes:r}))}return t}function Yw(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 ${lw}.`);if(t.length>1)throw Error(`Skill archive contains multiple ${lw} files.`);return t[0]}function Xw(e){let t=0,n=0;return si(e,{filter(e){if(t++,t>1e3)throw new Gw(`Skill archives may contain at most 1000 entries.`);if(n+=e.originalSize,n>52428800)throw new Gw(`Skill archives must expand to 50 MB or smaller after extraction.`);return!0}})}function Zw(e){let t=`${Date.now()}-${Math.random().toString(16).slice(2,8)}`;return Tn(cw,`.${e}.tmp-${t}`)}function Qw(e,t){return t===`SKILL.md`?e.replace(/\.skill$/i,``):t.slice(0,-9).split(`/`).pop()??``}function $w(e){if(!e.name.toLowerCase().endsWith(`.skill`))throw Error(`Only ${sw} archives can be installed with drag and drop.`);if(e.size>52428800)throw Error(`Skill archives must be 50 MB or smaller.`)}async function eT(e){try{return Xw(new Uint8Array(await e.arrayBuffer()))}catch(e){if(e instanceof Gw)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Invalid .skill archive: ${t}`)}}function tT(e){return e.path===`SKILL.md`?``:e.path.slice(0,-9)}function nT(e,t){return t&&(e===t||!e.startsWith(`${t}/`))?null:(t?e.slice(t.length+1):e)||null}async function rT(e,t,n,r){let i=Tn(t,n),{dir:a}=Cn(i);a!==`/`&&await e.mkdir(a,{recursive:!0}),await e.writeFile(i,r)}async function iT(e,t,n,r){let i=0;for(let a of t){let t=nT(a.path,n);t&&(await rT(e,r,t,a.bytes),i++)}return i}async function aT(e,t){await e.exists(t)&&await e.rm(t,{recursive:!0})}async function oT(e,t){let n=Tn(cw,t);if(await e.exists(n))throw Error(`Skill "${t}" already exists at ${n}.`);return n}async function sT(e,t){$w(t);let n=Jw(await eT(t)),r=Yw(n),i=Qw(t.name,r.path);qw(i);let a=await oT(e,i),o=Zw(i),s=tT(r);await e.mkdir(o,{recursive:!0});try{let t=await iT(e,n,s,o);return await e.rename(o,a),{skillName:i,destinationPath:a,fileCount:t}}catch(t){throw await aT(e,o),t}}var cT=e({MAX_SKILL_ARCHIVE_SIZE_BYTES:()=>52428800,SKILLS_DIR:()=>`skills`,SKILL_ARCHIVE_EXTENSION:()=>sw,SKILL_FILE:()=>lw,WORKSPACE_SKILLS_PATH:()=>cw,discoverSkillCandidates:()=>Sw,discoverSkills:()=>zw,getSkillInfo:()=>Bw,installSkillFromDrop:()=>sT,readSkillInstructions:()=>Vw,resolveSkillNameCollisions:()=>Aw});const lT=_(`skills`),uT=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-BMBoR1hd.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-BMBoR1hd.js`).then(e=>e.default),"/packages/vfs-root/etc/APPROVALS.md":()=>import(`./APPROVALS-CoZKeFYV.js`).then(e=>e.default),"/packages/vfs-root/etc/MEMORY.md":()=>import(`./MEMORY-Dl8Y_nOo.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/etc/slicc/keys.json":()=>import(`./keys-BMebW-sj.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-Bzu6oiWk.js`).then(e=>e.default),"/packages/vfs-root/shared/GELATIERE.md":()=>import(`./GELATIERE-CLK_MA5a.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/suggestions/suggestions.shtml":()=>import(`./suggestions-B34zKgsF.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-BzW33ZtP.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/WIKI.md":()=>import(`./WIKI-DoBxwf2u.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/index.md":()=>import(`./wiki-BXN4hgmw.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/log.md":()=>import(`./log-DEDI5t_h.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-cOU0zXaK.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BNnF2azP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-BTVvFyRd.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/computer/SKILL.md":()=>import(`./SKILL-BpMlcVho.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-CWxUIsrD.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-Be-LbAuP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-D3hRMDs3.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-BS0BC3cr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-DGelbGt_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-CX_QtSBf.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-DOE4hLxi.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-wvtABi3i.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-BIdAO7Ya.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)}),dT=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function fT(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 pT={};function mT(){let e={};for(let[t,n]of Object.entries(uT))e[t]=n;for(let[t,n]of Object.entries(dT))e[t]=async()=>fT(await n());for(let[t,n]of Object.entries(pT)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function hT(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){lT.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 gT(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 _T=new WeakMap;function vT(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 yT(e,t){let n=await bT(e,t),r=await xT(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=hT([...i,...r,...a]);return lT.info(`Skills loaded`,{count:o.length,dir:t}),o}async function bT(e,t){let n=await zw(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=gT(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}),lT.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{lT.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function xT(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}=gT(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}),lT.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{lT.debug(`Standalone skills directory not found`,{dir:t})}return n}function ST(e){return e.length===0?``:`
1009
1009
  ---
1010
1010
  AVAILABLE SKILLS
1011
1011
 
@@ -1014,9 +1014,9 @@ The following skills are available. To use a skill, first read its full instruct
1014
1014
 
1015
1015
  ${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowedTools.join(`, `)}\n`:``;return`- **${e.metadata.name}**: ${e.metadata.description}\n${t} Path: ${e.path}`}).join(`
1016
1016
  `)}
1017
- ---`}function IT(e,t=`/workspace/skills`){return jT(AT,e,t,()=>LT(e,t))}async function LT(e,t){let n=DT();for(let[r,i]of Object.entries(n)){let n=r.slice(18),a=n.startsWith(`/workspace/skills`),o=n.startsWith(`/workspace/scripts`);if(!a&&!o)continue;let s=n;a&&t!==`/workspace/skills`&&(s=n.replace(`/workspace/skills`,t)),o&&t!==`/workspace/skills`&&(s=t.replace(`/workspace/skills`,``)+n);try{await e.stat(s)}catch{let t=s.substring(0,s.lastIndexOf(`/`));try{await e.mkdir(t,{recursive:!0})}catch{}await e.writeFile(s,await i()),ST.info(`Created default file`,{path:s})}}}const RT=new Set([`/shared/sprinkles/welcome/welcome.shtml`,`/shared/sprinkles/welcome/connect-llm.shtml`,`/shared/sprinkles/suggestions/suggestions.shtml`]);async function zT(e){let t=DT();for(let[n,r]of Object.entries(t)){let t=n.slice(18);if(!t.startsWith(`/shared/`))continue;let i=RT.has(t);if(!i)try{await e.stat(t);continue}catch{}let a=t.substring(0,t.lastIndexOf(`/`));try{await e.mkdir(a,{recursive:!0})}catch{}await e.writeFile(t,await r()),ST.info(i?`Refreshed bundled shared file`:`Created default shared file`,{path:t})}}const BT=_(`cone-memory-store`);function VT(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}var HT=class{globalMemoryCache=``;memoryWriteChain=Promise.resolve();deps;constructor(e){this.deps=e}async ensureGlobalMemory(){let e=this.deps.getSharedFs();if(e){await zT(e);try{let t=await e.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof t==`string`?t:new TextDecoder().decode(t)}catch{BT.warn(`Global memory file not found after creating defaults`)}}}async getGlobalMemory(){if(this.globalMemoryCache)return this.globalMemoryCache;let e=this.deps.getSharedFs();if(e)try{let t=await e.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}return this.globalMemoryCache}async setGlobalMemory(e){let t=this.deps.getSharedFs();t&&(await t.writeFile(`/shared/CLAUDE.md`,e),this.globalMemoryCache=e,BT.info(`Global memory updated`))}async appendConeMemory(e,t){if(!this.deps.getSharedFs())return;let n=e.trim();if(!n)return;let r=t.memoryPath??pw,i=this.memoryWriteChain.then(async()=>{let e=this.deps.getSharedFs();if(!e)return;let i=``;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch(t){if(!(t instanceof A)||t.code!==`ENOENT`)throw t;await e.mkdir(VT(r),{recursive:!0})}let a=`## Auto-extracted (${new Date().toISOString().slice(0,10)}, ${t.source})`,o=`${i.length===0||i.endsWith(`
1017
+ ---`}function CT(e,t=`/workspace/skills`){return vT(_T,e,t,()=>wT(e,t))}async function wT(e,t){let n=mT();for(let[r,i]of Object.entries(n)){let n=r.slice(18),a=n.startsWith(`/workspace/skills`),o=n.startsWith(`/workspace/scripts`);if(!a&&!o)continue;let s=n;a&&t!==`/workspace/skills`&&(s=n.replace(`/workspace/skills`,t)),o&&t!==`/workspace/skills`&&(s=t.replace(`/workspace/skills`,``)+n);try{await e.stat(s)}catch{let t=s.substring(0,s.lastIndexOf(`/`));try{await e.mkdir(t,{recursive:!0})}catch{}await e.writeFile(s,await i()),lT.info(`Created default file`,{path:s})}}}const TT=new Set([`/shared/sprinkles/welcome/welcome.shtml`,`/shared/sprinkles/welcome/connect-llm.shtml`,`/shared/sprinkles/suggestions/suggestions.shtml`]);async function ET(e){let t=mT();for(let[n,r]of Object.entries(t)){let t=n.slice(18);if(!t.startsWith(`/shared/`))continue;let i=TT.has(t);if(!i)try{await e.stat(t);continue}catch{}let a=t.substring(0,t.lastIndexOf(`/`));try{await e.mkdir(a,{recursive:!0})}catch{}await e.writeFile(t,await r()),lT.info(i?`Refreshed bundled shared file`:`Created default shared file`,{path:t})}}const DT=_(`cone-memory-store`);function OT(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}var kT=class{globalMemoryCache=``;memoryWriteChain=Promise.resolve();deps;constructor(e){this.deps=e}async ensureGlobalMemory(){let e=this.deps.getSharedFs();if(e){await ET(e);try{let t=await e.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof t==`string`?t:new TextDecoder().decode(t)}catch{DT.warn(`Global memory file not found after creating defaults`)}}}async getGlobalMemory(){if(this.globalMemoryCache)return this.globalMemoryCache;let e=this.deps.getSharedFs();if(e)try{let t=await e.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}return this.globalMemoryCache}async setGlobalMemory(e){let t=this.deps.getSharedFs();t&&(await t.writeFile(`/shared/CLAUDE.md`,e),this.globalMemoryCache=e,DT.info(`Global memory updated`))}async appendConeMemory(e,t){if(!this.deps.getSharedFs())return;let n=e.trim();if(!n)return;let r=t.memoryPath??ew,i=this.memoryWriteChain.then(async()=>{let e=this.deps.getSharedFs();if(!e)return;let i=``;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch(t){if(!(t instanceof A)||t.code!==`ENOENT`)throw t;await e.mkdir(OT(r),{recursive:!0})}let a=`## Auto-extracted (${new Date().toISOString().slice(0,10)}, ${t.source})`,o=`${i.length===0||i.endsWith(`
1018
1018
  `)?``:`
1019
- `}\n${a}\n\n${n}\n`;await e.writeFile(r,i+o),BT.info(`Cone memory appended`,{source:t.source,length:n.length,path:r});try{await yw({vfs:e,memoryPath:r,model:t.model,apiKey:t.apiKey,headers:t.headers,signal:t.signal})}catch(e){BT.warn(`applyConeMemoryBudget threw — ignored`,{error:e instanceof Error?e.message:String(e)})}});this.memoryWriteChain=i.catch(e=>{BT.warn(`Cone memory append failed`,{error:e instanceof Error?e.message:String(e)})}),await i}async migrateLegacyConeMemory(){let e=this.deps.getSharedFs();if(!e)return;let t=`/workspace/.cone-memory-migrated`;try{await e.stat(t);return}catch{}let n=``;try{let t=await e.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});n=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}if(!/^## Auto-extracted[^\n]*$/m.test(n)){await this.writeMigrationSentinel(t);return}let r=n.split(`
1019
+ `}\n${a}\n\n${n}\n`;await e.writeFile(r,i+o),DT.info(`Cone memory appended`,{source:t.source,length:n.length,path:r});try{await ow({vfs:e,memoryPath:r,model:t.model,apiKey:t.apiKey,headers:t.headers,signal:t.signal})}catch(e){DT.warn(`applyConeMemoryBudget threw — ignored`,{error:e instanceof Error?e.message:String(e)})}});this.memoryWriteChain=i.catch(e=>{DT.warn(`Cone memory append failed`,{error:e instanceof Error?e.message:String(e)})}),await i}async migrateLegacyConeMemory(){let e=this.deps.getSharedFs();if(!e)return;let t=`/workspace/.cone-memory-migrated`;try{await e.stat(t);return}catch{}let n=``;try{let t=await e.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});n=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}if(!/^## Auto-extracted[^\n]*$/m.test(n)){await this.writeMigrationSentinel(t);return}let r=n.split(`
1020
1020
  `),i=[],a=[],o=0;for(;o<r.length;)if(/^## Auto-extracted/.test(r[o])){let e=o;for(o++;o<r.length&&!/^#{1,2}\s/.test(r[o]);)o++;i.push(r.slice(e,o).join(`
1021
1021
  `).trimEnd())}else a.push(r[o]),o++;if(i.length===0){await this.writeMigrationSentinel(t);return}let s=``;try{let t=await e.readFile(`/workspace/CLAUDE.md`,{encoding:`utf-8`});s=typeof t==`string`?t:new TextDecoder().decode(t)}catch(t){if(!(t instanceof A)||t.code!==`ENOENT`)throw t;await e.mkdir(`/workspace`,{recursive:!0})}let c=s.length===0||s.endsWith(`
1022
1022
  `)?``:`
@@ -1026,9 +1026,9 @@ ${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowed
1026
1026
  `)+`
1027
1027
  `;await e.writeFile(`/workspace/CLAUDE.md`,l);let u=a.length;for(;u>0&&a[u-1]===``;)u--;let d=u===0?``:a.slice(0,u).join(`
1028
1028
  `)+`
1029
- `;await e.writeFile(`/shared/CLAUDE.md`,d),this.globalMemoryCache=d,await this.writeMigrationSentinel(t),BT.info(`Migrated legacy cone memory from /shared/CLAUDE.md to /workspace/CLAUDE.md`,{blockCount:i.length})}async writeMigrationSentinel(e){let t=this.deps.getSharedFs();if(t){try{await t.mkdir(`/workspace`,{recursive:!0})}catch{}await t.writeFile(e,`Migration completed at ${new Date().toISOString()}\n`)}}};function UT(e){return Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)}function WT(e,t){return e.y===t.y&&e.m===t.m&&e.d===t.d&&e.h===t.h&&e.i===t.i&&e.s===t.s}function GT(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`Invalid ISO8601 passed to timezone parser.`);let r=e.substring(9);return r.includes(`Z`)||r.includes(`+`)||r.includes(`-`)?YT(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):YT(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}function KT(e,t,n){return qT(GT(e,t),n)}function qT(e,t){let n=new Date(UT(e)),r=JT(n,e.tz),i=UT(e)-UT(r),a=new Date(n.getTime()+i),o=JT(a,e.tz);if(WT(o,e)){let t=new Date(a.getTime()-36e5);return WT(JT(t,e.tz),e)?t:a}let s=new Date(a.getTime()+UT(e)-UT(o));if(WT(JT(s,e.tz),e))return s;if(t)throw Error(`Invalid date passed to fromTZ()`);return a.getTime()>s.getTime()?a:s}function JT(e,t){let n,r;try{n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,hour12:!1}),r=n.formatToParts(e)}catch(e){let n=e instanceof Error?e.message:String(e);throw RangeError(`toTZ: Invalid timezone '${t}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${n}`)}let i={year:0,month:0,day:0,hour:0,minute:0,second:0};for(let e of r)(e.type===`year`||e.type===`month`||e.type===`day`||e.type===`hour`||e.type===`minute`||e.type===`second`)&&(i[e.type]=parseInt(e.value,10));if(isNaN(i.year)||isNaN(i.month)||isNaN(i.day)||isNaN(i.hour)||isNaN(i.minute)||isNaN(i.second))throw Error(`toTZ: Failed to parse all date components from timezone '${t}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(i)}`);return i.hour===24&&(i.hour=0),{y:i.year,m:i.month,d:i.day,h:i.hour,i:i.minute,s:i.second,tz:t}}function YT(e,t,n,r,i,a,o){return{y:e,m:t,d:n,h:r,i,s:a,tz:o}}var XT=[1,2,4,8,16],ZT=class{pattern;timezone;mode;alternativeWeekdays;sloppyRanges;second;minute;hour;day;month;dayOfWeek;year;lastDayOfMonth;lastWeekday;nearestWeekdays;starDOM;starDOW;starYear;useAndLogic;constructor(e,t,n){this.pattern=e,this.timezone=t,this.mode=n?.mode??`auto`,this.alternativeWeekdays=n?.alternativeWeekdays??!1,this.sloppyRanges=n?.sloppyRanges??!1,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.year=Array(1e4).fill(0),this.lastDayOfMonth=!1,this.lastWeekday=!1,this.nearestWeekdays=Array(31).fill(0),this.starDOM=!1,this.starDOW=!1,this.starYear=!1,this.useAndLogic=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.match(/\S+/g)||[``],t=e.length;if(e.length<5||e.length>7)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five, six, or seven space separated parts are required.`);if(this.mode!==`auto`){let e;switch(this.mode){case`5-part`:e=5;break;case`6-part`:e=6;break;case`7-part`:e=7;break;case`5-or-6-parts`:e=[5,6];break;case`6-or-7-parts`:e=[6,7];break;default:e=0}if(!(Array.isArray(e)?e.includes(t):t===e)){let n=Array.isArray(e)?e.join(` or `):e.toString();throw TypeError(`CronPattern: mode '${this.mode}' requires exactly ${n} parts, but pattern '${this.pattern}' has ${t} parts.`)}}if(e.length===5&&e.unshift(`0`),e.length===6&&e.push(`*`),e[3].toUpperCase()===`LW`?(this.lastWeekday=!0,e[3]=``):e[3].toUpperCase().indexOf(`L`)>=0&&(e[3]=e[3].replace(/L/gi,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[6]==`*`&&(this.starYear=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.alternativeWeekdays?this.replaceAlphaDaysQuartz(e[5]):this.replaceAlphaDays(e[5])),e[5].startsWith(`+`)&&(this.useAndLogic=!0,e[5]=e[5].substring(1),e[5]===``))throw TypeError(`CronPattern: Day-of-week field cannot be empty after '+' modifier.`);switch(e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0&&(e[0]=e[0].replace(/\?/g,`*`),e[1]=e[1].replace(/\?/g,`*`),e[2]=e[2].replace(/\?/g,`*`),e[3]=e[3].replace(/\?/g,`*`),e[4]=e[4].replace(/\?/g,`*`),e[5]=e[5].replace(/\?/g,`*`),e[6]&&=e[6].replace(/\?/g,`*`)),this.mode){case`5-part`:e[0]=`0`,e[6]=`*`;break;case`6-part`:e[6]=`*`;break;case`5-or-6-parts`:e[6]=`*`}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1);let n=this.alternativeWeekdays?-1:0;this.partToArray(`dayOfWeek`,e[5],n,63),this.partToArray(`year`,e[6],0,1),!this.alternativeWeekdays&&this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth,o=e===`day`&&this.lastWeekday;if(t===``&&!a&&!o)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let s=t.split(`,`);if(s.length>1)for(let t=0;t<s.length;t++)this.partToArray(e,s[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===3?/[^/*0-9,\-WwLl]+/:t===5?/[^/*0-9,\-#Ll]+/:/[^/*0-9,\-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=e.toUpperCase().includes(`W`);if(t!==`day`&&a)throw TypeError(`CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.`);a&&(t=`nearestWeekdays`);let o=parseInt(i[0],10)+n;if(isNaN(o))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,o,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`||e===`nearestWeekdays`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`){if(t<0||t>=12)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`year`&&(t<1||t>=1e4))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t+` (supported range: 1-9999)`);this[e][t]=n}validateNotNaN(e,t){if(isNaN(e))throw TypeError(t)}validateRange(e,t,n,r,i){if(e>t)throw TypeError(`CronPattern: From value is larger than to value: '`+i+`'`);if(n!==void 0){if(n===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(n>this[r].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[r].length+`)`)}}handleRangeWithStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in ranges with stepping.`);let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);this.validateNotNaN(l,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(u,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateNotNaN(d,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(l,u,d,t,e);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}else if(n.toUpperCase().endsWith(`L`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)`);r=`L`,n=n.slice(0,-1)}return[n,r]}handleRange(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in a range.`);let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;this.validateNotNaN(o,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(s,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateRange(o,s,void 0,t,e);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in parts with stepping.`);let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);if(this.sloppyRanges)a[0]===``&&(a[0]=`*`);else{if(a[0]===``)throw TypeError(`CronPattern: Syntax error, stepping with missing prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`);if(a[0]!==`*`)throw TypeError(`CronPattern: Syntax error, stepping with numeric prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`)}let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);this.validateNotNaN(s,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(0,this[t].length-1,s,t,e);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaDaysQuartz(e){return e.replace(/sun/gi,`1`).replace(/mon/gi,`2`).replace(/tue/gi,`3`).replace(/wed/gi,`4`).replace(/thu/gi,`5`).replace(/fri/gi,`6`).replace(/sat/gi,`7`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();if(t===`@yearly`||t===`@annually`)return`0 0 1 1 *`;if(t===`@monthly`)return`0 0 1 * *`;if(t===`@weekly`)return`0 0 * * 0`;if(t===`@daily`||t===`@midnight`)return`0 0 * * *`;if(t===`@hourly`)return`0 * * * *`;if(t===`@reboot`)throw TypeError(`CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.`);return e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t.toUpperCase()===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|32;else if(t===63)this.dayOfWeek[e]=63;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|XT[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},QT=[31,28,31,30,31,30,31,31,30,31,30,31],J=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Y=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date){if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`)}else if(t==null)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}getLastDayOfMonth(e,t){return t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():QT[t]}getLastWeekday(e,t){let n=this.getLastDayOfMonth(e,t),r=new Date(Date.UTC(e,t,n)).getUTCDay();return r===0?n-2:r===6?n-1:n}getNearestWeekday(e,t,n){let r=this.getLastDayOfMonth(e,t);if(n>r)return-1;let i=new Date(Date.UTC(e,t,n)).getUTCDay();return i===0?n===r?n-2:n+1:i===6?n===1?n+2:n-1:n}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&63&&XT[a-1]&r)return!0;if(r&32){let r=this.getLastDayOfMonth(e,t);for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0){if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else try{let t=JT(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${t}`)}}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.month<0||this.day>QT[this.month]||this.day<1||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}return!1}fromString(e){if(typeof this.tz==`number`){let t=KT(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(KT(e,this.tz))}findNext(e,t,n,r){return this._findMatch(e,t,n,r,1)}_findMatch(e,t,n,r,i){let a=this[t],o;n.lastDayOfMonth&&(o=this.getLastDayOfMonth(this.year,this.month));let s=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0,c=this[t]+r,l=i===1?e=>e<n[t].length:e=>e>=0;for(let u=c;l(u);u+=i){let i=n[t][u];if(t===`day`&&!i){for(let e=0;e<n.nearestWeekdays.length;e++)if(n.nearestWeekdays[e]){let t=this.getNearestWeekday(this.year,this.month,e-r);if(t===-1)continue;if(t===u-r){i=1;break}}}if(t===`day`&&n.lastWeekday){let e=this.getLastWeekday(this.year,this.month);u-r===e&&(i=1)}if(t===`day`&&n.lastDayOfMonth&&u-r==o&&(i=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(s+(u-r-1))%7];if(t&&t&63)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,u-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);n.useAndLogic?i&&=t:!e.domAndDow&&!n.starDOM?i||=t:i&&=t}if(i)return this[t]=u-r,a===this[t]?1:2}return 3}recurse(e,t,n){if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year+1;n<e.year.length&&n<1e4;n++)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=0,this.day=1,this.hour=0,this.minute=0,this.second=0,this.ms=0}if(this.year>=1e4)return null}let r=this.findNext(t,J[n][0],e,J[n][2]);if(r>1){let i=n+1;for(;i<J.length;)this[J[i][0]]=-J[i][2],i++;if(r===3){if(this[J[n][1]]++,this[J[n][0]]=-J[n][2],this.apply(),n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0&&this.year<1e4;)this.year++;if(this.year>=1e4||this.year>=e.year.length)return null}return this.recurse(e,t,0)}if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=J.length?this:(e.starYear?this.year>=3e3:this.year>=1e4)?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}decrement(e,t){return this.second-=t.interval!==void 0&&t.interval>1?t.interval:1,this.ms=0,this.apply(),this.recurseBackward(e,t,0,0)}recurseBackward(e,t,n,r=0){if(r>1e4)return null;if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year-1;n>=0;n--)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=11,this.day=31,this.hour=23,this.minute=59,this.second=59,this.ms=0}if(this.year<0)return null}let i=this.findPrevious(t,J[n][0],e,J[n][2]);if(i>1){let a=n+1;for(;a<J.length;){let t=J[a][0],n=J[a][2],r=this.getMaxPatternValue(t,e,n);this[t]=r,a++}if(i===3){if(this[J[n][1]]--,n===0){let e=this.getLastDayOfMonth(this.year,this.month);this.day>e&&(this.day=e)}if(n===1){if(this.day<=0)this.day=1;else{let e=this.year,t=this.month;for(;t<0;)t+=12,e--;for(;t>11;)t-=12,e++;let n=t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():QT[t];this.day>n&&(this.day=n)}}this.apply();let i=J[n][0],a=J[n][2],o=this.getMaxPatternValue(i,e,a);if(i===`day`){let e=this.getLastDayOfMonth(this.year,this.month);this[i]=Math.min(o,e)}else this[i]=o;if(this.apply(),n===0){let t=J[1][2],n=this.getMaxPatternValue(`day`,e,t),r=this.getLastDayOfMonth(this.year,this.month),i=Math.min(n,r);i!==this.day&&(this.day=i,this.hour=this.getMaxPatternValue(`hour`,e,J[2][2]),this.minute=this.getMaxPatternValue(`minute`,e,J[3][2]),this.second=this.getMaxPatternValue(`second`,e,J[4][2]))}if(n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0;)this.year--;if(this.year<0)return null}return this.recurseBackward(e,t,0,r+1)}if(this.apply())return this.recurseBackward(e,t,n-1,r+1)}return n+=1,n>=J.length?this:this.year<0?null:this.recurseBackward(e,t,n,r+1)}getMaxPatternValue(e,t,n){if(e===`day`&&t.lastDayOfMonth||e===`day`&&!t.starDOW)return this.getLastDayOfMonth(this.year,this.month);for(let r=t[e].length-1;r>=0;r--)if(t[e][r])return r-n;return t[e].length-1-n}findPrevious(e,t,n,r){return this._findMatch(e,t,n,r,-1)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):qT(YT(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}match(e,t){if(!e.starYear&&(this.year<0||this.year>=e.year.length||e.year[this.year]===0))return!1;for(let n=0;n<J.length;n++){let r=J[n][0],i=J[n][2],a=this[r];if(a+i<0||a+i>=e[r].length)return!1;let o=e[r][a+i];if(r===`day`){if(!o){for(let t=0;t<e.nearestWeekdays.length;t++)if(e.nearestWeekdays[t]){let e=this.getNearestWeekday(this.year,this.month,t-i);if(e!==-1&&e===a){o=1;break}}}if(e.lastWeekday&&a===this.getLastWeekday(this.year,this.month)&&(o=1),e.lastDayOfMonth&&a===this.getLastDayOfMonth(this.year,this.month)&&(o=1),!e.starDOW){let n=new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay(),r=e.dayOfWeek[(n+(a-1))%7];r&&r&63&&(r=+!!this.isNthWeekdayOfMonth(this.year,this.month,a,r)),e.useAndLogic?o&&=r:!t.domAndDow&&!e.starDOM?o||=r:o&&=r}}if(!o)return!1}return!0}};function $T(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode!==void 0&&e.domAndDow===void 0?e.domAndDow=!e.legacyMode:e.domAndDow===void 0&&(e.domAndDow=!1),e.legacyMode=!e.domAndDow,e.paused=e.paused!==void 0&&e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch!==void 0&&e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.dayOffset=e.dayOffset===void 0?0:parseInt(e.dayOffset.toString(),10),e.unref=e.unref!==void 0&&e.unref,e.mode=e.mode===void 0?`auto`:e.mode,e.alternativeWeekdays=e.alternativeWeekdays!==void 0&&e.alternativeWeekdays,e.sloppyRanges=e.sloppyRanges!==void 0&&e.sloppyRanges,![`auto`,`5-part`,`6-part`,`7-part`,`5-or-6-parts`,`6-or-7-parts`].includes(e.mode))throw Error(`CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.`);if(e.startAt&&(e.startAt=new Y(e.startAt,e.timezone)),e.stopAt&&(e.stopAt=new Y(e.stopAt,e.timezone)),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);if(e.dayOffset!==void 0&&e.dayOffset!==0&&isNaN(e.dayOffset))throw Error(`CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.`);return e}function eE(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function tE(e){return eE(e)}function nE(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var rE=3e4,iE=[],aE=class{name;options;_states;fn;getTz(){return this.options.timezone||this.options.utcOffset}applyDayOffset(e){if(this.options.dayOffset!==void 0&&this.options.dayOffset!==0){let t=this.options.dayOffset*24*60*60*1e3;return new Date(e.getTime()+t)}return e}constructor(e,t,n){let r,i;if(eE(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(eE(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=$T(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new ZT(`* * * * *`,void 0,{mode:`auto`})},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Y(e,this.getTz()):this._states.pattern=new ZT(e,this.options.timezone,{mode:this.options.mode,alternativeWeekdays:this.options.alternativeWeekdays,sloppyRanges:this.options.sloppyRanges}),this.name){if(iE.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);iE.push(this)}return i!==void 0&&tE(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?this.applyDayOffset(t.getDate(!1)):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=t||this._states.currentRun||void 0;return this._enumerateRuns(e,n,`next`)}previousRuns(e,t){return this._enumerateRuns(e,t||void 0,`previous`)}_enumerateRuns(e,t,n){let r=[],i=t?new Y(t,this.getTz()):null,a=n===`next`?this._next:this._previous;for(;e--;){let e=a.call(this,i);if(!e)break;let t=e.getDate(!1);r.push(this.applyDayOffset(t)),i=e}return r}match(e){if(this._states.once){let t=new Y(e,this.getTz());t.ms=0;let n=new Y(this._states.once,this.getTz());return n.ms=0,t.getTime()===n.getTime()}let t=new Y(e,this.getTz());return t.ms=0,t.match(this._states.pattern,this.options)}getPattern(){if(!this._states.once)return this._states.pattern?this._states.pattern.pattern:void 0}getOnce(){return this._states.once?this._states.once.getDate():null}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Y||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Y(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=iE.indexOf(this);e>=0&&iE.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>rE&&(t=rE),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&nE(this._states.currentTimeout),this)}async _trigger(e){this._states.blocking=!0,this._states.currentRun=new Y(void 0,this.getTz());try{if(this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){if(eE(this.options.catch))try{this.options.catch(e,this)}catch{}}else this.fn!==void 0&&await this.fn(this,this.options.context)}finally{this._states.previousRun=new Y(e,this.getTz()),this._states.blocking=!1}}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&eE(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Y(e,this.getTz()),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Y(e,this.getTz());return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_previous(e){let t=new Y(e,this.getTz());this.options.stopAt&&t.getTime()>this.options.stopAt.getTime()&&(t=this.options.stopAt);let n=new Y(t,this.getTz());return this._states.once?this._states.once.getTime()<t.getTime()?this._states.once:null:(n=n.decrement(this._states.pattern,this.options),n===null||this.options.startAt&&n.getTime()<this.options.startAt.getTime()?null:n)}_calculatePreviousRun(e,t){let n=new Y(void 0,this.getTz()),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Y(r,this.getTz()).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function oE(e,t){try{return new aE(e.trim(),{domAndDow:!0}).nextRun(t)??null}catch{return null}}var sE=e({FORWARDABLE_TO_LEADER:()=>cE,LickManager:()=>dE,buildActiveLicksError:()=>mE,getLickManager:()=>gE,lickScoopMatches:()=>fE,lickTargetCandidates:()=>pE});const X=_(`lick-manager`),cE=new Set([`navigate`,`discovery`]);function lE(e){if(typeof e!=`object`||!e)return null;let t=e;return typeof t.verb!=`string`||typeof t.target!=`string`?null:oe({verb:t.verb,target:t.target,branch:typeof t.branch==`string`?t.branch:void 0,path:typeof t.path==`string`?t.path:void 0,instruction:typeof t.instruction==`string`?t.instruction:void 0})}function uE(e){return!e.discoveryKind&&!e.discoveryUrl&&!e.discoveryOrigin?null:ki({origin:e.discoveryOrigin,kind:e.discoveryKind,url:e.discoveryUrl})}var dE=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;forwarder=null;seenNavigateFingerprints=new Set;seenDiscoveryFingerprints=new Set;unitRoster=null;discoveryIgnore=null;async init(){await Nb();let e=await Ib();for(let t of e)this.webhooks.set(t.id,t);X.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Bb();for(let e of t)this.crontasks.set(e.id,e);X.info(`Loaded crontasks`,{count:this.crontasks.size}),await this.reconcileOrphans(),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),X.info(`Cron scheduler started`)}setUnitRosterProvider(e){this.unitRoster=e}resolveLickTarget(e){let t=this.unitRoster?.();return t?t.some(t=>fE(e,t.name,t.folder))?{status:`resolved`}:{status:`unresolved`,candidates:pE(t)}:{status:`unverifiable`}}setDiscoveryIgnore(e){this.discoveryIgnore=e}isOrphanedLick(e){return e?this.resolveLickTarget(e).status===`unresolved`:!1}async reconcileOrphans(){if(this.unitRoster){for(let e of Array.from(this.webhooks.values()))if(this.isOrphanedLick(e.scoop)){X.warn(`Removing orphaned webhook at init; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.webhooks.delete(e.id);try{await Lb(e.id)}catch(t){X.warn(`Failed to delete orphaned webhook from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}for(let e of Array.from(this.crontasks.values()))if(this.isOrphanedLick(e.scoop)){X.warn(`Removing orphaned cron task at init; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.crontasks.delete(e.id);try{await Vb(e.id)}catch(t){X.warn(`Failed to delete orphaned cron task from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}}}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}setForwarder(e){this.forwarder=e}dispatch(e){if(!(e.type===`discovery`&&this.shouldSuppressDiscovery(e))){if(this.forwarder&&cE.has(e.type)){this.forwarder(e);return}this.eventHandler?.(e)}}handleForwardedEvent(e){e.type===`discovery`&&this.shouldSuppressDiscovery(e)||this.isDuplicateFingerprint(e)||this.eventHandler?.(e)}emitEvent(e){e.type===`discovery`&&this.shouldSuppressDiscovery(e)||this.isDuplicateFingerprint(e)||(X.info(`External lick event`,{type:e.type,target:e.targetScoop}),this.dispatch(e))}isDuplicateFingerprint(e){let t=null,n,r;if(e.type===`navigate`)t=lE(e.body),n=this.seenNavigateFingerprints,r=`navigate`;else if(e.type===`discovery`)t=uE(e),n=this.seenDiscoveryFingerprints,r=`discovery`;else return!1;return t===null?!1:n.has(t)?(X.debug(`Suppressing duplicate ${r} lick`,{fingerprint:t}),!0):(n.add(t),!1)}shouldSuppressDiscovery(e){return e.discoverySource===`live-navigation`?this.discoveryIgnore?.(e)?(X.debug(`Suppressing ignored llms.txt discovery`,{origin:e.discoveryOrigin}),!0):!1:(X.debug(`Suppressing discovery without live-navigation provenance`),!0)}async createWebhook(e,t,n){let r=this.generateId(),i={id:r,name:e,createdAt:new Date().toISOString(),filter:n,scoop:t};return n&&this.compileFilter(n,!0),this.webhooks.set(r,i),await Pb(i),X.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await Lb(e),X.info(`Webhook deleted`,{id:e}),!0):await Fb(e)!==null&&(await Lb(e),X.info(`Webhook deleted`,{id:e}),!0)}listWebhooks(){return Array.from(this.webhooks.values())}getWebhook(e){return this.webhooks.get(e)}handleWebhookEvent(e,t,n){let r=this.webhooks.get(e);if(!r)return X.warn(`Webhook not found`,{webhookId:e}),`unknown-webhook`;if(this.isOrphanedLick(r.scoop))return X.warn(`Webhook target scoop not found — dropping delivery`,{webhookId:e,name:r.name,scoop:r.scoop}),`unresolved-target`;let i={type:`webhook`,webhookId:e,webhookName:r.name,targetScoop:r.scoop,timestamp:new Date().toISOString(),headers:t,body:n};if(r.filter)try{let t=this.compileFilter(r.filter,!0)(i);if(t===!1)return X.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name}),`filtered`;typeof t==`object`&&t&&(i=t)}catch(t){X.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}return X.info(`Webhook event received`,{webhookId:e,name:r.name,targetScoop:r.scoop}),this.dispatch(i),`delivered`}async createCronTask(e,t,n,r){let i=oE(t,new Date);if(!i)throw Error(`Invalid cron expression`);r&&this.compileFilter(r,!1);let a=this.generateId(),o={id:a,name:e,cron:t,scoop:n,filter:r,nextRun:i.toISOString(),lastRun:null,status:`active`,createdAt:new Date().toISOString()};return this.crontasks.set(a,o),await Rb(o),X.info(`Cron task created`,{id:a,name:e,cron:t,scoop:n}),o}async deleteCronTask(e){return this.crontasks.has(e)?(this.crontasks.delete(e),await Vb(e),X.info(`Cron task deleted`,{id:e}),!0):await zb(e)!==null&&(await Vb(e),X.info(`Cron task deleted`,{id:e}),!0)}listCronTasks(){return Array.from(this.crontasks.values())}getCronTask(e){return this.crontasks.get(e)}getLicksForScoop(e,t){return{webhooks:Array.from(this.webhooks.values()).filter(n=>fE(n.scoop,e,t)),cronTasks:Array.from(this.crontasks.values()).filter(n=>fE(n.scoop,e,t))}}async getLicksForScoopFromDb(e,t){let[n,r]=await Promise.all([Ib(),Bb()]);return{webhooks:n.filter(n=>fE(n.scoop,e,t)),cronTasks:r.filter(n=>fE(n.scoop,e,t))}}async deleteIfOrphanedCron(e){if(!this.isOrphanedLick(e.scoop))return!1;X.warn(`Deleting orphaned cron task; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.crontasks.delete(e.id);try{await Vb(e.id)}catch(t){X.warn(`Failed to delete orphaned cron task from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}return!0}async runCronScheduler(){let e=new Date;for(let t of this.crontasks.values())await this.deleteIfOrphanedCron(t)||t.status===`active`&&t.nextRun&&(new Date(t.nextRun)>e||await this.runDueCronTask(t,e))}async runDueCronTask(e,t){let n={time:t.toISOString()};if(e.filter)try{let r=this.compileFilter(e.filter,!1)(null);if(r===!1){X.debug(`Cron task skipped by filter`,{id:e.id,name:e.name}),e.nextRun=oE(e.cron,t)?.toISOString()??null,e.lastRun=t.toISOString(),await Rb(e);return}typeof r==`object`&&r&&(n=r)}catch(t){X.error(`Cron filter error`,{id:e.id,error:t instanceof Error?t.message:String(t)})}let r={type:`cron`,cronId:e.id,cronName:e.name,targetScoop:e.scoop,timestamp:t.toISOString(),body:n};X.info(`Cron task running`,{id:e.id,name:e.name}),this.dispatch(r),e.nextRun=oE(e.cron,t)?.toISOString()??null,e.lastRun=t.toISOString(),await Rb(e)}generateId(){let e=``;for(let t=0;t<12;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return e}compileFilter(e,t){try{return t?Function(`event`,`return (${e})(event);`):Function(`return (${e})();`)}catch(e){throw Error(`Invalid filter function: ${e instanceof Error?e.message:String(e)}`)}}};function fE(e,t,n){return e?e===t||e===n||`${e}-scoop`===n:!1}function pE(e){let t=new Set;for(let n of e)t.add(n.folder),n.name&&n.name!==n.folder&&t.add(n.name);return Array.from(t)}function mE(e,t,n){if(t.length===0&&n.length===0)return null;let r=[];t.length>0&&r.push(`${t.length} active webhook${t.length>1?`s`:``}`),n.length>0&&r.push(`${n.length} active cron task${n.length>1?`s`:``}`);let i=[...t.map(e=>` webhook delete ${e.id}`),...n.map(e=>` crontask delete ${e.id}`)].join(`
1030
- `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}let hE=null;function gE(){return hE||=new dE,hE}function _E(e){if(e.kind===`local`)return`mount ${yy(e.path)}`;let t=e.profile==="default"?``:` --profile ${yy(e.profile)}`;return`mount --source ${yy(e.source)}${t} ${yy(e.path)}`}function vE(){return`lick-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}var yE=class{deps;entries=new Map;constructor(e){this.deps=e}hasHandoff(e){return this.entries.get(e)?.kind===`navigate-handoff`}registerNavigate(e){let t=vE(),n=e.body??{},r=typeof n.verb==`string`?n.verb:void 0,i=typeof n.target==`string`?n.target:void 0;return r===`upskill`&&i?this.entries.set(t,{kind:`navigate-upskill`,target:i,branch:typeof n.branch==`string`?n.branch:void 0,path:typeof n.path==`string`?n.path:void 0}):r===`handoff`&&this.entries.set(t,{kind:`navigate-handoff`}),t}registerSessionReload(e){let t=vE(),n=e.body??{},r=Array.isArray(n.mounts)?n.mounts:[];return n.reason===`mount-recovery`?r.length>0&&this.entries.set(t,{kind:`session-reload-mount`,mounts:r}):this.entries.set(t,{kind:`session-reload-plain`}),t}registerUpgrade(e){let t=vE(),n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`;return this.entries.set(t,{kind:`upgrade`,from:n,to:r}),t}registerDiscovery(e){if(e.discoveryKind!==`llms-txt`)return null;let t=Ex(e.discoveryOrigin,e.discoveryUrl);if(!t)return null;let n=vE();return this.entries.set(n,{kind:`discovery-llms-txt`,hostname:t}),n}async resolve(e,t){let n=this.entries.get(e);if(!n)return null;switch(n.kind){case`navigate-upskill`:return this.resolveUpskill(e,n,t);case`session-reload-mount`:return this.resolveMountRecovery(e,n,t);case`session-reload-plain`:return this.resolveSessionReloadPlain(e,t);case`upgrade`:return this.resolveUpgrade(e,n,t);case`discovery-llms-txt`:return this.resolveDiscovery(e,n,t);case`navigate-handoff`:return null}}async resolveHandoffByHuman(e,t){return this.hasHandoff(e)?(this.entries.delete(e),await this.deps.persistLickDecision(e,t?`allow`:`deny`),!0):!1}async resolveUpskill(e,t,n){this.entries.delete(e);let r;return n.decision!==`deny`&&(r=await this.runUpskillInstall(t)),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async runUpskillInstall(e){let t=this.deps.getConeShell();if(!t)return`upskill could not run: no cone shell available.`;let n=e=>`'${e.replace(/'/g,`'\\''`)}'`,r=[`upskill`];e.branch&&r.push(`--branch`,n(e.branch)),e.path&&r.push(`--path`,n(e.path)),r.push(n(e.target)),r.push(`--all`);try{let e=await t.executeCommand(r.join(` `)),n=`${e.stdout}${e.stderr}`.trim();return n.length>0?n:`upskill exited ${e.exitCode}.`}catch(e){return`upskill failed: ${e instanceof Error?e.message:String(e)}`}}async resolveMountRecovery(e,t,n){this.entries.delete(e);let r;return n.decision!==`deny`&&(r=await this.runMountRecovery(t.mounts)),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async runMountRecovery(e){let t=this.deps.getConeShell();if(!t)return`mount recovery could not run: no cone shell available.`;let n=[];for(let r of e){let e=_E(r);try{let r=await t.executeCommand(e),i=`${r.stdout}${r.stderr}`.trim();n.push(i.length>0?i:`${e} exited ${r.exitCode}.`)}catch(t){n.push(`${e} failed: ${t instanceof Error?t.message:String(t)}`)}}return n.join(`
1031
- `)}async resolveSessionReloadPlain(e,t){return t.decision===`deny`?(this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:!1,message:`Session-reload notice acknowledged.`}):{settled:!0,persisted:!1,message:`Nothing to confirm — the reload already completed. Use lick_dismiss to acknowledge and clear this notice.`}}async resolveUpgrade(e,t,n){this.entries.delete(e);let r;return r=n.decision===`deny`?`Upgrade dismissed — workspace files were left unchanged.`:await this.runUpgrade(t),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async resolveDiscovery(e,t,n){if(n.decision!==`deny`)return{settled:!0,persisted:!1,message:`Nothing to confirm — use lick_dismiss to ignore this llms.txt host.`};let r=this.deps.getConeFs();if(!r)throw Error(`llms.txt dismissal could not persist: cone filesystem unavailable.`);let i=await Dx(r,t.hostname);return this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:i,message:i?`Dismissed — ${t.hostname} was added to /etc/llmstxtignore.`:`Dismissed — ${t.hostname} is already ignored.`}}async runUpgrade(e){let t=this.deps.getConeShell();if(!t)return`upgrade could not run: no cone shell available.`;let n=`upgrade apply --from=${yy(e.from)} --to=${yy(e.to)}`;try{let e=await t.executeCommand(n),r=`${e.stdout}${e.stderr}`.trim();return r.length>0?r:`upgrade exited ${e.exitCode}.`}catch(e){return`upgrade failed: ${e instanceof Error?e.message:String(e)}`}}},bE=`# /etc/models — which models a scoop may be spawned with
1029
+ `;await e.writeFile(`/shared/CLAUDE.md`,d),this.globalMemoryCache=d,await this.writeMigrationSentinel(t),DT.info(`Migrated legacy cone memory from /shared/CLAUDE.md to /workspace/CLAUDE.md`,{blockCount:i.length})}async writeMigrationSentinel(e){let t=this.deps.getSharedFs();if(t){try{await t.mkdir(`/workspace`,{recursive:!0})}catch{}await t.writeFile(e,`Migration completed at ${new Date().toISOString()}\n`)}}};function AT(e){return Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)}function jT(e,t){return e.y===t.y&&e.m===t.m&&e.d===t.d&&e.h===t.h&&e.i===t.i&&e.s===t.s}function MT(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`Invalid ISO8601 passed to timezone parser.`);let r=e.substring(9);return r.includes(`Z`)||r.includes(`+`)||r.includes(`-`)?IT(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):IT(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}function NT(e,t,n){return PT(MT(e,t),n)}function PT(e,t){let n=new Date(AT(e)),r=FT(n,e.tz),i=AT(e)-AT(r),a=new Date(n.getTime()+i),o=FT(a,e.tz);if(jT(o,e)){let t=new Date(a.getTime()-36e5);return jT(FT(t,e.tz),e)?t:a}let s=new Date(a.getTime()+AT(e)-AT(o));if(jT(FT(s,e.tz),e))return s;if(t)throw Error(`Invalid date passed to fromTZ()`);return a.getTime()>s.getTime()?a:s}function FT(e,t){let n,r;try{n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,hour12:!1}),r=n.formatToParts(e)}catch(e){let n=e instanceof Error?e.message:String(e);throw RangeError(`toTZ: Invalid timezone '${t}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${n}`)}let i={year:0,month:0,day:0,hour:0,minute:0,second:0};for(let e of r)(e.type===`year`||e.type===`month`||e.type===`day`||e.type===`hour`||e.type===`minute`||e.type===`second`)&&(i[e.type]=parseInt(e.value,10));if(isNaN(i.year)||isNaN(i.month)||isNaN(i.day)||isNaN(i.hour)||isNaN(i.minute)||isNaN(i.second))throw Error(`toTZ: Failed to parse all date components from timezone '${t}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(i)}`);return i.hour===24&&(i.hour=0),{y:i.year,m:i.month,d:i.day,h:i.hour,i:i.minute,s:i.second,tz:t}}function IT(e,t,n,r,i,a,o){return{y:e,m:t,d:n,h:r,i,s:a,tz:o}}var LT=[1,2,4,8,16],RT=class{pattern;timezone;mode;alternativeWeekdays;sloppyRanges;second;minute;hour;day;month;dayOfWeek;year;lastDayOfMonth;lastWeekday;nearestWeekdays;starDOM;starDOW;starYear;useAndLogic;constructor(e,t,n){this.pattern=e,this.timezone=t,this.mode=n?.mode??`auto`,this.alternativeWeekdays=n?.alternativeWeekdays??!1,this.sloppyRanges=n?.sloppyRanges??!1,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.year=Array(1e4).fill(0),this.lastDayOfMonth=!1,this.lastWeekday=!1,this.nearestWeekdays=Array(31).fill(0),this.starDOM=!1,this.starDOW=!1,this.starYear=!1,this.useAndLogic=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.match(/\S+/g)||[``],t=e.length;if(e.length<5||e.length>7)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five, six, or seven space separated parts are required.`);if(this.mode!==`auto`){let e;switch(this.mode){case`5-part`:e=5;break;case`6-part`:e=6;break;case`7-part`:e=7;break;case`5-or-6-parts`:e=[5,6];break;case`6-or-7-parts`:e=[6,7];break;default:e=0}if(!(Array.isArray(e)?e.includes(t):t===e)){let n=Array.isArray(e)?e.join(` or `):e.toString();throw TypeError(`CronPattern: mode '${this.mode}' requires exactly ${n} parts, but pattern '${this.pattern}' has ${t} parts.`)}}if(e.length===5&&e.unshift(`0`),e.length===6&&e.push(`*`),e[3].toUpperCase()===`LW`?(this.lastWeekday=!0,e[3]=``):e[3].toUpperCase().indexOf(`L`)>=0&&(e[3]=e[3].replace(/L/gi,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[6]==`*`&&(this.starYear=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.alternativeWeekdays?this.replaceAlphaDaysQuartz(e[5]):this.replaceAlphaDays(e[5])),e[5].startsWith(`+`)&&(this.useAndLogic=!0,e[5]=e[5].substring(1),e[5]===``))throw TypeError(`CronPattern: Day-of-week field cannot be empty after '+' modifier.`);switch(e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0&&(e[0]=e[0].replace(/\?/g,`*`),e[1]=e[1].replace(/\?/g,`*`),e[2]=e[2].replace(/\?/g,`*`),e[3]=e[3].replace(/\?/g,`*`),e[4]=e[4].replace(/\?/g,`*`),e[5]=e[5].replace(/\?/g,`*`),e[6]&&=e[6].replace(/\?/g,`*`)),this.mode){case`5-part`:e[0]=`0`,e[6]=`*`;break;case`6-part`:e[6]=`*`;break;case`5-or-6-parts`:e[6]=`*`}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1);let n=this.alternativeWeekdays?-1:0;this.partToArray(`dayOfWeek`,e[5],n,63),this.partToArray(`year`,e[6],0,1),!this.alternativeWeekdays&&this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth,o=e===`day`&&this.lastWeekday;if(t===``&&!a&&!o)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let s=t.split(`,`);if(s.length>1)for(let t=0;t<s.length;t++)this.partToArray(e,s[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===3?/[^/*0-9,\-WwLl]+/:t===5?/[^/*0-9,\-#Ll]+/:/[^/*0-9,\-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=e.toUpperCase().includes(`W`);if(t!==`day`&&a)throw TypeError(`CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.`);a&&(t=`nearestWeekdays`);let o=parseInt(i[0],10)+n;if(isNaN(o))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,o,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`||e===`nearestWeekdays`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`){if(t<0||t>=12)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`year`&&(t<1||t>=1e4))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t+` (supported range: 1-9999)`);this[e][t]=n}validateNotNaN(e,t){if(isNaN(e))throw TypeError(t)}validateRange(e,t,n,r,i){if(e>t)throw TypeError(`CronPattern: From value is larger than to value: '`+i+`'`);if(n!==void 0){if(n===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(n>this[r].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[r].length+`)`)}}handleRangeWithStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in ranges with stepping.`);let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);this.validateNotNaN(l,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(u,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateNotNaN(d,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(l,u,d,t,e);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}else if(n.toUpperCase().endsWith(`L`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)`);r=`L`,n=n.slice(0,-1)}return[n,r]}handleRange(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in a range.`);let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;this.validateNotNaN(o,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(s,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateRange(o,s,void 0,t,e);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in parts with stepping.`);let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);if(this.sloppyRanges)a[0]===``&&(a[0]=`*`);else{if(a[0]===``)throw TypeError(`CronPattern: Syntax error, stepping with missing prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`);if(a[0]!==`*`)throw TypeError(`CronPattern: Syntax error, stepping with numeric prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`)}let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);this.validateNotNaN(s,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(0,this[t].length-1,s,t,e);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaDaysQuartz(e){return e.replace(/sun/gi,`1`).replace(/mon/gi,`2`).replace(/tue/gi,`3`).replace(/wed/gi,`4`).replace(/thu/gi,`5`).replace(/fri/gi,`6`).replace(/sat/gi,`7`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();if(t===`@yearly`||t===`@annually`)return`0 0 1 1 *`;if(t===`@monthly`)return`0 0 1 * *`;if(t===`@weekly`)return`0 0 * * 0`;if(t===`@daily`||t===`@midnight`)return`0 0 * * *`;if(t===`@hourly`)return`0 * * * *`;if(t===`@reboot`)throw TypeError(`CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.`);return e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t.toUpperCase()===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|32;else if(t===63)this.dayOfWeek[e]=63;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|LT[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},zT=[31,28,31,30,31,30,31,31,30,31,30,31],J=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Y=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date){if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`)}else if(t==null)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}getLastDayOfMonth(e,t){return t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():zT[t]}getLastWeekday(e,t){let n=this.getLastDayOfMonth(e,t),r=new Date(Date.UTC(e,t,n)).getUTCDay();return r===0?n-2:r===6?n-1:n}getNearestWeekday(e,t,n){let r=this.getLastDayOfMonth(e,t);if(n>r)return-1;let i=new Date(Date.UTC(e,t,n)).getUTCDay();return i===0?n===r?n-2:n+1:i===6?n===1?n+2:n-1:n}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&63&&LT[a-1]&r)return!0;if(r&32){let r=this.getLastDayOfMonth(e,t);for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0){if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else try{let t=FT(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${t}`)}}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.month<0||this.day>zT[this.month]||this.day<1||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}return!1}fromString(e){if(typeof this.tz==`number`){let t=NT(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(NT(e,this.tz))}findNext(e,t,n,r){return this._findMatch(e,t,n,r,1)}_findMatch(e,t,n,r,i){let a=this[t],o;n.lastDayOfMonth&&(o=this.getLastDayOfMonth(this.year,this.month));let s=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0,c=this[t]+r,l=i===1?e=>e<n[t].length:e=>e>=0;for(let u=c;l(u);u+=i){let i=n[t][u];if(t===`day`&&!i){for(let e=0;e<n.nearestWeekdays.length;e++)if(n.nearestWeekdays[e]){let t=this.getNearestWeekday(this.year,this.month,e-r);if(t===-1)continue;if(t===u-r){i=1;break}}}if(t===`day`&&n.lastWeekday){let e=this.getLastWeekday(this.year,this.month);u-r===e&&(i=1)}if(t===`day`&&n.lastDayOfMonth&&u-r==o&&(i=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(s+(u-r-1))%7];if(t&&t&63)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,u-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);n.useAndLogic?i&&=t:!e.domAndDow&&!n.starDOM?i||=t:i&&=t}if(i)return this[t]=u-r,a===this[t]?1:2}return 3}recurse(e,t,n){if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year+1;n<e.year.length&&n<1e4;n++)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=0,this.day=1,this.hour=0,this.minute=0,this.second=0,this.ms=0}if(this.year>=1e4)return null}let r=this.findNext(t,J[n][0],e,J[n][2]);if(r>1){let i=n+1;for(;i<J.length;)this[J[i][0]]=-J[i][2],i++;if(r===3){if(this[J[n][1]]++,this[J[n][0]]=-J[n][2],this.apply(),n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0&&this.year<1e4;)this.year++;if(this.year>=1e4||this.year>=e.year.length)return null}return this.recurse(e,t,0)}if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=J.length?this:(e.starYear?this.year>=3e3:this.year>=1e4)?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}decrement(e,t){return this.second-=t.interval!==void 0&&t.interval>1?t.interval:1,this.ms=0,this.apply(),this.recurseBackward(e,t,0,0)}recurseBackward(e,t,n,r=0){if(r>1e4)return null;if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year-1;n>=0;n--)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=11,this.day=31,this.hour=23,this.minute=59,this.second=59,this.ms=0}if(this.year<0)return null}let i=this.findPrevious(t,J[n][0],e,J[n][2]);if(i>1){let a=n+1;for(;a<J.length;){let t=J[a][0],n=J[a][2],r=this.getMaxPatternValue(t,e,n);this[t]=r,a++}if(i===3){if(this[J[n][1]]--,n===0){let e=this.getLastDayOfMonth(this.year,this.month);this.day>e&&(this.day=e)}if(n===1){if(this.day<=0)this.day=1;else{let e=this.year,t=this.month;for(;t<0;)t+=12,e--;for(;t>11;)t-=12,e++;let n=t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():zT[t];this.day>n&&(this.day=n)}}this.apply();let i=J[n][0],a=J[n][2],o=this.getMaxPatternValue(i,e,a);if(i===`day`){let e=this.getLastDayOfMonth(this.year,this.month);this[i]=Math.min(o,e)}else this[i]=o;if(this.apply(),n===0){let t=J[1][2],n=this.getMaxPatternValue(`day`,e,t),r=this.getLastDayOfMonth(this.year,this.month),i=Math.min(n,r);i!==this.day&&(this.day=i,this.hour=this.getMaxPatternValue(`hour`,e,J[2][2]),this.minute=this.getMaxPatternValue(`minute`,e,J[3][2]),this.second=this.getMaxPatternValue(`second`,e,J[4][2]))}if(n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0;)this.year--;if(this.year<0)return null}return this.recurseBackward(e,t,0,r+1)}if(this.apply())return this.recurseBackward(e,t,n-1,r+1)}return n+=1,n>=J.length?this:this.year<0?null:this.recurseBackward(e,t,n,r+1)}getMaxPatternValue(e,t,n){if(e===`day`&&t.lastDayOfMonth||e===`day`&&!t.starDOW)return this.getLastDayOfMonth(this.year,this.month);for(let r=t[e].length-1;r>=0;r--)if(t[e][r])return r-n;return t[e].length-1-n}findPrevious(e,t,n,r){return this._findMatch(e,t,n,r,-1)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):PT(IT(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}match(e,t){if(!e.starYear&&(this.year<0||this.year>=e.year.length||e.year[this.year]===0))return!1;for(let n=0;n<J.length;n++){let r=J[n][0],i=J[n][2],a=this[r];if(a+i<0||a+i>=e[r].length)return!1;let o=e[r][a+i];if(r===`day`){if(!o){for(let t=0;t<e.nearestWeekdays.length;t++)if(e.nearestWeekdays[t]){let e=this.getNearestWeekday(this.year,this.month,t-i);if(e!==-1&&e===a){o=1;break}}}if(e.lastWeekday&&a===this.getLastWeekday(this.year,this.month)&&(o=1),e.lastDayOfMonth&&a===this.getLastDayOfMonth(this.year,this.month)&&(o=1),!e.starDOW){let n=new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay(),r=e.dayOfWeek[(n+(a-1))%7];r&&r&63&&(r=+!!this.isNthWeekdayOfMonth(this.year,this.month,a,r)),e.useAndLogic?o&&=r:!t.domAndDow&&!e.starDOM?o||=r:o&&=r}}if(!o)return!1}return!0}};function BT(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode!==void 0&&e.domAndDow===void 0?e.domAndDow=!e.legacyMode:e.domAndDow===void 0&&(e.domAndDow=!1),e.legacyMode=!e.domAndDow,e.paused=e.paused!==void 0&&e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch!==void 0&&e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.dayOffset=e.dayOffset===void 0?0:parseInt(e.dayOffset.toString(),10),e.unref=e.unref!==void 0&&e.unref,e.mode=e.mode===void 0?`auto`:e.mode,e.alternativeWeekdays=e.alternativeWeekdays!==void 0&&e.alternativeWeekdays,e.sloppyRanges=e.sloppyRanges!==void 0&&e.sloppyRanges,![`auto`,`5-part`,`6-part`,`7-part`,`5-or-6-parts`,`6-or-7-parts`].includes(e.mode))throw Error(`CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.`);if(e.startAt&&(e.startAt=new Y(e.startAt,e.timezone)),e.stopAt&&(e.stopAt=new Y(e.stopAt,e.timezone)),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);if(e.dayOffset!==void 0&&e.dayOffset!==0&&isNaN(e.dayOffset))throw Error(`CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.`);return e}function VT(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function HT(e){return VT(e)}function UT(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var WT=3e4,GT=[],KT=class{name;options;_states;fn;getTz(){return this.options.timezone||this.options.utcOffset}applyDayOffset(e){if(this.options.dayOffset!==void 0&&this.options.dayOffset!==0){let t=this.options.dayOffset*24*60*60*1e3;return new Date(e.getTime()+t)}return e}constructor(e,t,n){let r,i;if(VT(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(VT(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=BT(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new RT(`* * * * *`,void 0,{mode:`auto`})},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Y(e,this.getTz()):this._states.pattern=new RT(e,this.options.timezone,{mode:this.options.mode,alternativeWeekdays:this.options.alternativeWeekdays,sloppyRanges:this.options.sloppyRanges}),this.name){if(GT.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);GT.push(this)}return i!==void 0&&HT(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?this.applyDayOffset(t.getDate(!1)):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=t||this._states.currentRun||void 0;return this._enumerateRuns(e,n,`next`)}previousRuns(e,t){return this._enumerateRuns(e,t||void 0,`previous`)}_enumerateRuns(e,t,n){let r=[],i=t?new Y(t,this.getTz()):null,a=n===`next`?this._next:this._previous;for(;e--;){let e=a.call(this,i);if(!e)break;let t=e.getDate(!1);r.push(this.applyDayOffset(t)),i=e}return r}match(e){if(this._states.once){let t=new Y(e,this.getTz());t.ms=0;let n=new Y(this._states.once,this.getTz());return n.ms=0,t.getTime()===n.getTime()}let t=new Y(e,this.getTz());return t.ms=0,t.match(this._states.pattern,this.options)}getPattern(){if(!this._states.once)return this._states.pattern?this._states.pattern.pattern:void 0}getOnce(){return this._states.once?this._states.once.getDate():null}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Y||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Y(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=GT.indexOf(this);e>=0&&GT.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>WT&&(t=WT),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&UT(this._states.currentTimeout),this)}async _trigger(e){this._states.blocking=!0,this._states.currentRun=new Y(void 0,this.getTz());try{if(this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){if(VT(this.options.catch))try{this.options.catch(e,this)}catch{}}else this.fn!==void 0&&await this.fn(this,this.options.context)}finally{this._states.previousRun=new Y(e,this.getTz()),this._states.blocking=!1}}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&VT(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Y(e,this.getTz()),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Y(e,this.getTz());return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_previous(e){let t=new Y(e,this.getTz());this.options.stopAt&&t.getTime()>this.options.stopAt.getTime()&&(t=this.options.stopAt);let n=new Y(t,this.getTz());return this._states.once?this._states.once.getTime()<t.getTime()?this._states.once:null:(n=n.decrement(this._states.pattern,this.options),n===null||this.options.startAt&&n.getTime()<this.options.startAt.getTime()?null:n)}_calculatePreviousRun(e,t){let n=new Y(void 0,this.getTz()),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Y(r,this.getTz()).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function qT(e,t){try{return new KT(e.trim(),{domAndDow:!0}).nextRun(t)??null}catch{return null}}var JT=e({FORWARDABLE_TO_LEADER:()=>YT,LickManager:()=>QT,buildActiveLicksError:()=>tE,getLickManager:()=>rE,lickScoopMatches:()=>$T,lickTargetCandidates:()=>eE});const X=_(`lick-manager`),YT=new Set([`navigate`,`discovery`]);function XT(e){if(typeof e!=`object`||!e)return null;let t=e;return typeof t.verb!=`string`||typeof t.target!=`string`?null:oe({verb:t.verb,target:t.target,branch:typeof t.branch==`string`?t.branch:void 0,path:typeof t.path==`string`?t.path:void 0,instruction:typeof t.instruction==`string`?t.instruction:void 0})}function ZT(e){return!e.discoveryKind&&!e.discoveryUrl&&!e.discoveryOrigin?null:Mi({origin:e.discoveryOrigin,kind:e.discoveryKind,url:e.discoveryUrl})}var QT=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;forwarder=null;seenNavigateFingerprints=new Set;seenDiscoveryFingerprints=new Set;unitRoster=null;discoveryIgnore=null;async init(){await xb();let e=await wb();for(let t of e)this.webhooks.set(t.id,t);X.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Ob();for(let e of t)this.crontasks.set(e.id,e);X.info(`Loaded crontasks`,{count:this.crontasks.size}),await this.reconcileOrphans(),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),X.info(`Cron scheduler started`)}setUnitRosterProvider(e){this.unitRoster=e}resolveLickTarget(e){let t=this.unitRoster?.();return t?t.some(t=>$T(e,t.name,t.folder))?{status:`resolved`}:{status:`unresolved`,candidates:eE(t)}:{status:`unverifiable`}}setDiscoveryIgnore(e){this.discoveryIgnore=e}isOrphanedLick(e){return e?this.resolveLickTarget(e).status===`unresolved`:!1}async reconcileOrphans(){if(this.unitRoster){for(let e of Array.from(this.webhooks.values()))if(this.isOrphanedLick(e.scoop)){X.warn(`Removing orphaned webhook at init; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.webhooks.delete(e.id);try{await Tb(e.id)}catch(t){X.warn(`Failed to delete orphaned webhook from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}for(let e of Array.from(this.crontasks.values()))if(this.isOrphanedLick(e.scoop)){X.warn(`Removing orphaned cron task at init; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.crontasks.delete(e.id);try{await kb(e.id)}catch(t){X.warn(`Failed to delete orphaned cron task from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}}}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}setForwarder(e){this.forwarder=e}dispatch(e){if(!(e.type===`discovery`&&this.shouldSuppressDiscovery(e))){if(this.forwarder&&YT.has(e.type)){this.forwarder(e);return}this.eventHandler?.(e)}}handleForwardedEvent(e){e.type===`discovery`&&this.shouldSuppressDiscovery(e)||this.isDuplicateFingerprint(e)||this.eventHandler?.(e)}emitEvent(e){e.type===`discovery`&&this.shouldSuppressDiscovery(e)||this.isDuplicateFingerprint(e)||(X.info(`External lick event`,{type:e.type,target:e.targetScoop}),this.dispatch(e))}isDuplicateFingerprint(e){let t=null,n,r;if(e.type===`navigate`)t=XT(e.body),n=this.seenNavigateFingerprints,r=`navigate`;else if(e.type===`discovery`)t=ZT(e),n=this.seenDiscoveryFingerprints,r=`discovery`;else return!1;return t===null?!1:n.has(t)?(X.debug(`Suppressing duplicate ${r} lick`,{fingerprint:t}),!0):(n.add(t),!1)}shouldSuppressDiscovery(e){return e.discoverySource===`live-navigation`?this.discoveryIgnore?.(e)?(X.debug(`Suppressing ignored llms.txt discovery`,{origin:e.discoveryOrigin}),!0):!1:(X.debug(`Suppressing discovery without live-navigation provenance`),!0)}async createWebhook(e,t,n){let r=this.generateId(),i={id:r,name:e,createdAt:new Date().toISOString(),filter:n,scoop:t};return n&&this.compileFilter(n,!0),this.webhooks.set(r,i),await Sb(i),X.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await Tb(e),X.info(`Webhook deleted`,{id:e}),!0):await Cb(e)!==null&&(await Tb(e),X.info(`Webhook deleted`,{id:e}),!0)}listWebhooks(){return Array.from(this.webhooks.values())}getWebhook(e){return this.webhooks.get(e)}handleWebhookEvent(e,t,n){let r=this.webhooks.get(e);if(!r)return X.warn(`Webhook not found`,{webhookId:e}),`unknown-webhook`;if(this.isOrphanedLick(r.scoop))return X.warn(`Webhook target scoop not found — dropping delivery`,{webhookId:e,name:r.name,scoop:r.scoop}),`unresolved-target`;let i={type:`webhook`,webhookId:e,webhookName:r.name,targetScoop:r.scoop,timestamp:new Date().toISOString(),headers:t,body:n};if(r.filter)try{let t=this.compileFilter(r.filter,!0)(i);if(t===!1)return X.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name}),`filtered`;typeof t==`object`&&t&&(i=t)}catch(t){X.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}return X.info(`Webhook event received`,{webhookId:e,name:r.name,targetScoop:r.scoop}),this.dispatch(i),`delivered`}async createCronTask(e,t,n,r){let i=qT(t,new Date);if(!i)throw Error(`Invalid cron expression`);r&&this.compileFilter(r,!1);let a=this.generateId(),o={id:a,name:e,cron:t,scoop:n,filter:r,nextRun:i.toISOString(),lastRun:null,status:`active`,createdAt:new Date().toISOString()};return this.crontasks.set(a,o),await Eb(o),X.info(`Cron task created`,{id:a,name:e,cron:t,scoop:n}),o}async deleteCronTask(e){return this.crontasks.has(e)?(this.crontasks.delete(e),await kb(e),X.info(`Cron task deleted`,{id:e}),!0):await Db(e)!==null&&(await kb(e),X.info(`Cron task deleted`,{id:e}),!0)}listCronTasks(){return Array.from(this.crontasks.values())}getCronTask(e){return this.crontasks.get(e)}getLicksForScoop(e,t){return{webhooks:Array.from(this.webhooks.values()).filter(n=>$T(n.scoop,e,t)),cronTasks:Array.from(this.crontasks.values()).filter(n=>$T(n.scoop,e,t))}}async getLicksForScoopFromDb(e,t){let[n,r]=await Promise.all([wb(),Ob()]);return{webhooks:n.filter(n=>$T(n.scoop,e,t)),cronTasks:r.filter(n=>$T(n.scoop,e,t))}}async deleteIfOrphanedCron(e){if(!this.isOrphanedLick(e.scoop))return!1;X.warn(`Deleting orphaned cron task; target scoop no longer exists`,{id:e.id,name:e.name,scoop:e.scoop}),this.crontasks.delete(e.id);try{await kb(e.id)}catch(t){X.warn(`Failed to delete orphaned cron task from DB`,{id:e.id,error:t instanceof Error?t.message:String(t)})}return!0}async runCronScheduler(){let e=new Date;for(let t of this.crontasks.values())await this.deleteIfOrphanedCron(t)||t.status===`active`&&t.nextRun&&(new Date(t.nextRun)>e||await this.runDueCronTask(t,e))}async runDueCronTask(e,t){let n={time:t.toISOString()};if(e.filter)try{let r=this.compileFilter(e.filter,!1)(null);if(r===!1){X.debug(`Cron task skipped by filter`,{id:e.id,name:e.name}),e.nextRun=qT(e.cron,t)?.toISOString()??null,e.lastRun=t.toISOString(),await Eb(e);return}typeof r==`object`&&r&&(n=r)}catch(t){X.error(`Cron filter error`,{id:e.id,error:t instanceof Error?t.message:String(t)})}let r={type:`cron`,cronId:e.id,cronName:e.name,targetScoop:e.scoop,timestamp:t.toISOString(),body:n};X.info(`Cron task running`,{id:e.id,name:e.name}),this.dispatch(r),e.nextRun=qT(e.cron,t)?.toISOString()??null,e.lastRun=t.toISOString(),await Eb(e)}generateId(){let e=``;for(let t=0;t<12;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return e}compileFilter(e,t){try{return t?Function(`event`,`return (${e})(event);`):Function(`return (${e})();`)}catch(e){throw Error(`Invalid filter function: ${e instanceof Error?e.message:String(e)}`)}}};function $T(e,t,n){return e?e===t||e===n||`${e}-scoop`===n:!1}function eE(e){let t=new Set;for(let n of e)t.add(n.folder),n.name&&n.name!==n.folder&&t.add(n.name);return Array.from(t)}function tE(e,t,n){if(t.length===0&&n.length===0)return null;let r=[];t.length>0&&r.push(`${t.length} active webhook${t.length>1?`s`:``}`),n.length>0&&r.push(`${n.length} active cron task${n.length>1?`s`:``}`);let i=[...t.map(e=>` webhook delete ${e.id}`),...n.map(e=>` crontask delete ${e.id}`)].join(`
1030
+ `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}let nE=null;function rE(){return nE||=new QT,nE}function iE(e){if(e.kind===`local`)return`mount ${sy(e.path)}`;let t=e.profile==="default"?``:` --profile ${sy(e.profile)}`;return`mount --source ${sy(e.source)}${t} ${sy(e.path)}`}function aE(){return`lick-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}var oE=class{deps;entries=new Map;constructor(e){this.deps=e}hasHandoff(e){return this.entries.get(e)?.kind===`navigate-handoff`}registerNavigate(e){let t=aE(),n=e.body??{},r=typeof n.verb==`string`?n.verb:void 0,i=typeof n.target==`string`?n.target:void 0;return r===`upskill`&&i?this.entries.set(t,{kind:`navigate-upskill`,target:i,branch:typeof n.branch==`string`?n.branch:void 0,path:typeof n.path==`string`?n.path:void 0}):r===`handoff`&&this.entries.set(t,{kind:`navigate-handoff`}),t}registerSessionReload(e){let t=aE(),n=e.body??{},r=Array.isArray(n.mounts)?n.mounts:[];return n.reason===`mount-recovery`?r.length>0&&this.entries.set(t,{kind:`session-reload-mount`,mounts:r}):this.entries.set(t,{kind:`session-reload-plain`}),t}registerUpgrade(e){let t=aE(),n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`;return this.entries.set(t,{kind:`upgrade`,from:n,to:r}),t}registerDiscovery(e){if(e.discoveryKind!==`llms-txt`)return null;let t=mx(e.discoveryOrigin,e.discoveryUrl);if(!t)return null;let n=aE();return this.entries.set(n,{kind:`discovery-llms-txt`,hostname:t}),n}async resolve(e,t){let n=this.entries.get(e);if(!n)return null;switch(n.kind){case`navigate-upskill`:return this.resolveUpskill(e,n,t);case`session-reload-mount`:return this.resolveMountRecovery(e,n,t);case`session-reload-plain`:return this.resolveSessionReloadPlain(e,t);case`upgrade`:return this.resolveUpgrade(e,n,t);case`discovery-llms-txt`:return this.resolveDiscovery(e,n,t);case`navigate-handoff`:return null}}async resolveHandoffByHuman(e,t){return this.hasHandoff(e)?(this.entries.delete(e),await this.deps.persistLickDecision(e,t?`allow`:`deny`),!0):!1}async resolveUpskill(e,t,n){this.entries.delete(e);let r;return n.decision!==`deny`&&(r=await this.runUpskillInstall(t)),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async runUpskillInstall(e){let t=this.deps.getConeShell();if(!t)return`upskill could not run: no cone shell available.`;let n=e=>`'${e.replace(/'/g,`'\\''`)}'`,r=[`upskill`];e.branch&&r.push(`--branch`,n(e.branch)),e.path&&r.push(`--path`,n(e.path)),r.push(n(e.target)),r.push(`--all`);try{let e=await t.executeCommand(r.join(` `)),n=`${e.stdout}${e.stderr}`.trim();return n.length>0?n:`upskill exited ${e.exitCode}.`}catch(e){return`upskill failed: ${e instanceof Error?e.message:String(e)}`}}async resolveMountRecovery(e,t,n){this.entries.delete(e);let r;return n.decision!==`deny`&&(r=await this.runMountRecovery(t.mounts)),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async runMountRecovery(e){let t=this.deps.getConeShell();if(!t)return`mount recovery could not run: no cone shell available.`;let n=[];for(let r of e){let e=iE(r);try{let r=await t.executeCommand(e),i=`${r.stdout}${r.stderr}`.trim();n.push(i.length>0?i:`${e} exited ${r.exitCode}.`)}catch(t){n.push(`${e} failed: ${t instanceof Error?t.message:String(t)}`)}}return n.join(`
1031
+ `)}async resolveSessionReloadPlain(e,t){return t.decision===`deny`?(this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:!1,message:`Session-reload notice acknowledged.`}):{settled:!0,persisted:!1,message:`Nothing to confirm — the reload already completed. Use lick_dismiss to acknowledge and clear this notice.`}}async resolveUpgrade(e,t,n){this.entries.delete(e);let r;return r=n.decision===`deny`?`Upgrade dismissed — workspace files were left unchanged.`:await this.runUpgrade(t),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async resolveDiscovery(e,t,n){if(n.decision!==`deny`)return{settled:!0,persisted:!1,message:`Nothing to confirm — use lick_dismiss to ignore this llms.txt host.`};let r=this.deps.getConeFs();if(!r)throw Error(`llms.txt dismissal could not persist: cone filesystem unavailable.`);let i=await hx(r,t.hostname);return this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:i,message:i?`Dismissed — ${t.hostname} was added to /etc/llmstxtignore.`:`Dismissed — ${t.hostname} is already ignored.`}}async runUpgrade(e){let t=this.deps.getConeShell();if(!t)return`upgrade could not run: no cone shell available.`;let n=`upgrade apply --from=${sy(e.from)} --to=${sy(e.to)}`;try{let e=await t.executeCommand(n),r=`${e.stdout}${e.stderr}`.trim();return r.length>0?r:`upgrade exited ${e.exitCode}.`}catch(e){return`upgrade failed: ${e instanceof Error?e.message:String(e)}`}}},sE=`# /etc/models — which models a scoop may be spawned with
1032
1032
  #
1033
1033
  # \`agent --model\` and \`scoop_scoop\` accept a \`provider:model\` id, so a scoop can
1034
1034
  # run on a provider OTHER than the selected one. That moves spend onto another
@@ -1061,17 +1061,17 @@ ${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowed
1061
1061
  # openrouter:*
1062
1062
  # -openrouter:openai/o3-pro
1063
1063
  # -adobe:claude-opus-5
1064
- `;const xE=_(`model-policy-file`);var SE=class{fs;watcher;unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/models`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/models`)||(await this.fs.writeFile(ge,bE),xE.info(`Seeded default /etc/models policy`))}catch(e){xE.warn(`Failed to seed default model policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(ge,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);_e(le(t))}catch(e){_e(ve()),xE.warn(`Failed to read model policy; falling back to own-catalogue-only`,{error:e instanceof Error?e.message:String(e)})}}};function CE(){try{let e=ue();if(!e||!ce(e))return;let t=me().id;return t?{provider:e,id:t}:void 0}catch{return}}async function wE(e,t,n={}){if(!t)return e(()=>{});let r=n.intervalMs??5e3,i=n.maxBeats??24,a=n.stagePrefix??`shared-fs-mount`;t(`${a}:start`);let o=0,s=0,c=0,l=0,u=()=>{c+=1},d=setInterval(()=>{if(c>l)l=c,s=0;else if(s+=1,s>i){clearInterval(d);return}o+=1,t(`${a}:${o}`)},r);try{return await e(u)}finally{clearInterval(d)}}const TE=_(`scheduler`);var EE=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=setInterval(()=>this.pollTasks(),6e4),this.pollTasks(),TE.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,TE.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await Db(i),TE.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await Ob(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await Db(r),TE.info(`Task updated`,{id:e,updates:Object.keys(t)}),r}async pauseTask(e){return await this.updateTask(e,{status:`paused`})!==null}async resumeTask(e){return await Ob(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await Ob(e)?(await Ab(e),TE.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await kb()).filter(t=>t.groupFolder===e)}async getAllTasks(){return kb()}pollTasks(){this.checkTasks().catch(e=>{TE.error(`Task poll failed`,{error:e instanceof Error?e.message:String(e)})})}async checkTasks(){let e=await kb(),t=new Date;for(let n of e)n.status===`active`&&n.nextRun&&(new Date(n.nextRun)>t||await this.runTask(n))}async runTask(e){let t=this.callbacks.getScoop(e.groupFolder);if(!t){TE.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}TE.info(`Running task`,{id:e.id,groupFolder:e.groupFolder});try{let n=new Date().toISOString(),r=this.calculateNextRun(e.scheduleType,e.scheduleValue),i=e.scheduleType===`once`?`completed`:e.status;await Db({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),TE.info(`Task completed`,{id:e.id})}catch(t){TE.error(`Task execution failed`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}calculateNextRun(e,t){let n=new Date;switch(e){case`cron`:return oE(t,n)?.toISOString()??null;case`interval`:{let e=parseInt(t,10);return isNaN(e)||e<=0?null:new Date(n.getTime()+e).toISOString()}case`once`:return new Date(t)>n?t:null;default:return null}}};const Z=_(`scoop-approval-router`);var DE=class{deps;registry;constructor(e){this.deps=e,this.registry=new d({onAutoSettle:(e,t,n)=>this.handleAutoSettle(e,t,n)})}handleAutoSettle(e,t,n){Z.info(`Sudo request auto-settled fail-closed; retiring lick card`,{id:e,reason:t}),this.persistLickDecision(e,`deny`,n).catch(n=>{Z.warn(`Failed to persist auto-settled lick decision`,{id:e,reason:t,error:n instanceof Error?n.message:String(n)})})}getConeSudoBroker(e){return l(e,this)}listPendingSudoRequests(e){let t=this.registry.list();return e===void 0?t:t.filter(t=>t.approverJid===e)}maySettle(e,t){return t===void 0||this.registry.get(e)?.approverJid===t}failScoop(e){return this.registry.failScoop(e)}failAll(){return this.registry.failAll()}settleGrantedRequests(e){let t=this.deps.getSudoManager();if(!t)return 0;let n=this.deps.getScoops(),r=0;for(let i of this.registry.list()){let a=n.get(i.scoopJid);if(!a||e!==void 0&&a.folder!==e||!OE(t.getPolicyForScoop(a.folder),i.request))continue;let{kind:o,detail:s}=i.request;this.registry.resolve(i.id,{decision:`allow`})&&(r++,Z.info(`Sudo request auto-settled: policy now grants it`,{id:i.id,folder:a.folder,kind:o,detail:s.slice(0,80)}),this.persistLickDecision(i.id,`allow`,i.scoopJid).catch(e=>{Z.warn(`Failed to persist auto-granted lick decision`,{id:i.id,error:e instanceof Error?e.message:String(e)})}))}return r}admitIfAlreadyGranted(e,t){let n=this.deps.getScoops().get(e),r=this.deps.getSudoManager();return!n||!r||!OE(r.getPolicyForScoop(n.folder),t)?null:(Z.info(`Sudo request already granted by policy — skipping cone`,{scoopJid:e,folder:n.folder,kind:t.kind,detailPreview:t.detail.slice(0,80)}),{decision:`allow`})}async enqueueSudoRequest(e,t,n={}){let r=this.deps.getScoops(),i=n.approver??this.deps.findApprover(e);if(!i)return Z.warn(`Sudo request received but no approver is registered — failing closed`,{scoopJid:e,kind:t.kind}),{decision:`deny`};if(!r.has(e))return Z.warn(`Sudo request from unknown scoop — failing closed`,{scoopJid:e,kind:t.kind}),{decision:`deny`};if(t.kind===`write`&&Br(t.detail))return Z.warn(`Refusing sudo request for an unhonoured sudoers path`,{scoopJid:e,detail:t.detail}),{decision:`deny`};let a=this.admitIfAlreadyGranted(e,t);if(a)return a;let{id:o,pending:s}=this.registry.register(e,t,i.jid);Z.info(`Sudo request enqueued for cone`,{id:o,scoopJid:e,kind:t.kind,detailPreview:t.detail.slice(0,80)});let c=r.get(e);this.deps.getLickManager()?.emitEvent({type:`sudo-request`,lickId:o,sudoKind:t.kind,sudoDetail:t.detail,sudoScoopName:t.requester??c?.assistantLabel??c?.name??e,sudoSuggestedPattern:t.suggestedPattern,sudoReason:t.reason,targetScoop:i.name,timestamp:new Date().toISOString(),body:{requestId:o,kind:t.kind,detail:t.detail,suggestedPattern:t.suggestedPattern,reason:t.reason,scoopJid:e}});try{await this.deliverSudoRequestToCone(i,e,o,t)}catch(t){let n=t instanceof Error?t.message:String(t);Z.error(`Failed to deliver sudo request to cone — failing closed`,{id:o,scoopJid:e,error:n}),this.registry.resolve(o,{decision:`deny`})}return s}resolveSudoRequest(e,t,n){if(!this.maySettle(e,n))return Z.warn(`Refusing a settle from a unit the request was not routed to`,{id:e,approverJid:n}),!1;let r=this.registry.resolve(e,t);return r?Z.info(`Sudo request resolved by cone`,{id:e,decision:t.decision}):Z.warn(`Sudo request resolve: unknown / already-settled id`,{id:e,decision:t.decision}),r}async resolveSudoRequestAndPersist(e,t,n){let r=this.registry.get(e);if(!r)return{settled:!1,persisted:!1};if(!this.maySettle(e,n))return Z.warn(`Refusing a settle+persist from a unit the request was not routed to`,{id:e,approverJid:n}),{settled:!1,persisted:!1};let i=r.scoopJid,a=r.approverJid,o=this.resolveSudoRequest(e,t,n);if(!o)return{settled:!1,persisted:!1};let s=this.deps.getScoops().get(r.scoopJid),c=r.request.kind,l=s?.folder,u=this.deps.getSudoManager(),d=!1,f,p;if(t.decision===`always`&&u&&s&&s.parentJid!==null){if(c===`command`||c===`read`||c===`write`){let n=t.pattern?.trim()||r.request.suggestedPattern?.trim()||r.request.detail.trim();try{let e=await u.appendScoopRule(s.folder,c,n);e?(d=!0,f=e):p=`pattern collapsed to empty after sanitization`}catch(t){p=t instanceof Error?t.message:String(t),Z.warn(`Failed to persist always grant`,{id:e,folder:s.folder,kind:c,error:p})}}else p=`cannot persist always grant for kind "${c}" (no matching sudoers directive)`}return await this.persistLickDecision(e,t.decision,i,a),{settled:o,persisted:d,persistedPattern:f,persistError:p,scoopFolder:l,kind:c}}async persistLickDecision(e,t,n,r){let i=t===`deny`?`dismissed`:`confirmed`,a=r??this.registry.get(e)?.approverJid,o=a?this.deps.getScoops().get(a):this.deps.findApprover(n??this.registry.get(e)?.scoopJid);if(o)try{let t=(await this.deps.getMessagesForScoop(o.jid)).find(t=>t.lickId===e||t.id===`sudo-request-${e}`);if(!t){Z.warn(`Lick decision: no stored message found to flip`,{lickId:e});return}t.lickState=i,await this.deps.saveMessage(t),this.deps.onMessageUpdate(o.jid,{messageId:t.id,lickId:e,lickState:i})}catch(t){Z.warn(`Failed to persist lick decision`,{lickId:e,error:t instanceof Error?t.message:String(t)})}}async deliverSudoRequestToCone(e,t,n,r){let i=this.deps.getScoops().get(t),a=r.requester??i?.assistantLabel??t,o=i?.folder??t,s=kE(a,n,r),c={id:`sudo-request-${n}`,chatJid:e.jid,senderId:o,senderName:a,content:s,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sudo-request`,lickId:n,lickState:`pending`};await this.deps.handleMessage(c)}};function OE(e,t){let{kind:n,detail:r}=t;return n===`command`?Ir(e,r)===`nopasswd-allow`:n===`read`||n===`write`?Ur(e,n,r)===`nopasswd-allow`:!1}function kE(e,t,n){let r=[`[@${e} sudo-request]`,`Lick ID: ${t}`,`Kind: ${n.kind}`,`Detail: ${n.detail}`];return n.reason&&r.push(`Reason given: ${n.reason}`),n.suggestedPattern&&r.push(`Suggested pattern: ${n.suggestedPattern}`),r.push(``,`Use the lick_confirm tool with lick_id="${t}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${t}" and a reason to deny. A denial without a reason tells the scoop nothing it can act on.`),r.join(`
1065
- `)}async function AE(e,t,n){if(e.length===0||t<=0)return;let r=0,i=Math.min(t,e.length),a=async()=>{for(;r<e.length;){let t=r;r+=1;let i=e[t];if(i===void 0)return;await n(i)}};await Promise.all(Array.from({length:i},()=>a()))}let jE=null;function ME(e){jE=e}function NE(e,t,n){jE?.(e,t,n)}const PE=_(`scoop-completion-service`),FE=`/shared/scoop-notifications`,IE=1e3,LE=2e4;function RE(e){let t=e.replace(/\r\n?/g,`
1064
+ `;const cE=_(`model-policy-file`);var lE=class{fs;watcher;unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/models`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/models`)||(await this.fs.writeFile(ge,sE),cE.info(`Seeded default /etc/models policy`))}catch(e){cE.warn(`Failed to seed default model policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(ge,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);_e(le(t))}catch(e){_e(ve()),cE.warn(`Failed to read model policy; falling back to own-catalogue-only`,{error:e instanceof Error?e.message:String(e)})}}};function uE(){try{let e=ue();if(!e||!ce(e))return;let t=me().id;return t?{provider:e,id:t}:void 0}catch{return}}async function dE(e,t,n={}){if(!t)return e(()=>{});let r=n.intervalMs??5e3,i=n.maxBeats??24,a=n.stagePrefix??`shared-fs-mount`;t(`${a}:start`);let o=0,s=0,c=0,l=0,u=()=>{c+=1},d=setInterval(()=>{if(c>l)l=c,s=0;else if(s+=1,s>i){clearInterval(d);return}o+=1,t(`${a}:${o}`)},r);try{return await e(u)}finally{clearInterval(d)}}const fE=_(`scheduler`);var pE=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=setInterval(()=>this.pollTasks(),6e4),this.pollTasks(),fE.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,fE.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await hb(i),fE.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await gb(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await hb(r),fE.info(`Task updated`,{id:e,updates:Object.keys(t)}),r}async pauseTask(e){return await this.updateTask(e,{status:`paused`})!==null}async resumeTask(e){return await gb(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await gb(e)?(await vb(e),fE.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await _b()).filter(t=>t.groupFolder===e)}async getAllTasks(){return _b()}pollTasks(){this.checkTasks().catch(e=>{fE.error(`Task poll failed`,{error:e instanceof Error?e.message:String(e)})})}async checkTasks(){let e=await _b(),t=new Date;for(let n of e)n.status===`active`&&n.nextRun&&(new Date(n.nextRun)>t||await this.runTask(n))}async runTask(e){let t=this.callbacks.getScoop(e.groupFolder);if(!t){fE.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}fE.info(`Running task`,{id:e.id,groupFolder:e.groupFolder});try{let n=new Date().toISOString(),r=this.calculateNextRun(e.scheduleType,e.scheduleValue),i=e.scheduleType===`once`?`completed`:e.status;await hb({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),fE.info(`Task completed`,{id:e.id})}catch(t){fE.error(`Task execution failed`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}calculateNextRun(e,t){let n=new Date;switch(e){case`cron`:return qT(t,n)?.toISOString()??null;case`interval`:{let e=parseInt(t,10);return isNaN(e)||e<=0?null:new Date(n.getTime()+e).toISOString()}case`once`:return new Date(t)>n?t:null;default:return null}}};const Z=_(`scoop-approval-router`);var mE=class{deps;registry;constructor(e){this.deps=e,this.registry=new d({onAutoSettle:(e,t,n)=>this.handleAutoSettle(e,t,n)})}handleAutoSettle(e,t,n){Z.info(`Sudo request auto-settled fail-closed; retiring lick card`,{id:e,reason:t}),this.persistLickDecision(e,`deny`,n).catch(n=>{Z.warn(`Failed to persist auto-settled lick decision`,{id:e,reason:t,error:n instanceof Error?n.message:String(n)})})}getConeSudoBroker(e){return l(e,this)}listPendingSudoRequests(e){let t=this.registry.list();return e===void 0?t:t.filter(t=>t.approverJid===e)}maySettle(e,t){return t===void 0||this.registry.get(e)?.approverJid===t}failScoop(e){return this.registry.failScoop(e)}failAll(){return this.registry.failAll()}settleGrantedRequests(e){let t=this.deps.getSudoManager();if(!t)return 0;let n=this.deps.getScoops(),r=0;for(let i of this.registry.list()){let a=n.get(i.scoopJid);if(!a||e!==void 0&&a.folder!==e||!hE(t.getPolicyForScoop(a.folder),i.request))continue;let{kind:o,detail:s}=i.request;this.registry.resolve(i.id,{decision:`allow`})&&(r++,Z.info(`Sudo request auto-settled: policy now grants it`,{id:i.id,folder:a.folder,kind:o,detail:s.slice(0,80)}),this.persistLickDecision(i.id,`allow`,i.scoopJid).catch(e=>{Z.warn(`Failed to persist auto-granted lick decision`,{id:i.id,error:e instanceof Error?e.message:String(e)})}))}return r}admitIfAlreadyGranted(e,t){let n=this.deps.getScoops().get(e),r=this.deps.getSudoManager();return!n||!r||!hE(r.getPolicyForScoop(n.folder),t)?null:(Z.info(`Sudo request already granted by policy — skipping cone`,{scoopJid:e,folder:n.folder,kind:t.kind,detailPreview:t.detail.slice(0,80)}),{decision:`allow`})}async enqueueSudoRequest(e,t,n={}){let r=this.deps.getScoops(),i=n.approver??this.deps.findApprover(e);if(!i)return Z.warn(`Sudo request received but no approver is registered — failing closed`,{scoopJid:e,kind:t.kind}),{decision:`deny`};if(!r.has(e))return Z.warn(`Sudo request from unknown scoop — failing closed`,{scoopJid:e,kind:t.kind}),{decision:`deny`};if(t.kind===`write`&&Ur(t.detail))return Z.warn(`Refusing sudo request for an unhonoured sudoers path`,{scoopJid:e,detail:t.detail}),{decision:`deny`};let a=this.admitIfAlreadyGranted(e,t);if(a)return a;let{id:o,pending:s}=this.registry.register(e,t,i.jid);Z.info(`Sudo request enqueued for cone`,{id:o,scoopJid:e,kind:t.kind,detailPreview:t.detail.slice(0,80)});let c=r.get(e);this.deps.getLickManager()?.emitEvent({type:`sudo-request`,lickId:o,sudoKind:t.kind,sudoDetail:t.detail,sudoScoopName:t.requester??c?.assistantLabel??c?.name??e,sudoSuggestedPattern:t.suggestedPattern,sudoReason:t.reason,targetScoop:i.name,timestamp:new Date().toISOString(),body:{requestId:o,kind:t.kind,detail:t.detail,suggestedPattern:t.suggestedPattern,reason:t.reason,scoopJid:e}});try{await this.deliverSudoRequestToCone(i,e,o,t)}catch(t){let n=t instanceof Error?t.message:String(t);Z.error(`Failed to deliver sudo request to cone — failing closed`,{id:o,scoopJid:e,error:n}),this.registry.resolve(o,{decision:`deny`})}return s}resolveSudoRequest(e,t,n){if(!this.maySettle(e,n))return Z.warn(`Refusing a settle from a unit the request was not routed to`,{id:e,approverJid:n}),!1;let r=this.registry.resolve(e,t);return r?Z.info(`Sudo request resolved by cone`,{id:e,decision:t.decision}):Z.warn(`Sudo request resolve: unknown / already-settled id`,{id:e,decision:t.decision}),r}async resolveSudoRequestAndPersist(e,t,n){let r=this.registry.get(e);if(!r)return{settled:!1,persisted:!1};if(!this.maySettle(e,n))return Z.warn(`Refusing a settle+persist from a unit the request was not routed to`,{id:e,approverJid:n}),{settled:!1,persisted:!1};let i=r.scoopJid,a=r.approverJid,o=this.resolveSudoRequest(e,t,n);if(!o)return{settled:!1,persisted:!1};let s=this.deps.getScoops().get(r.scoopJid),c=r.request.kind,l=s?.folder,u=this.deps.getSudoManager(),d=!1,f,p;if(t.decision===`always`&&u&&s&&s.parentJid!==null){if(c===`command`||c===`read`||c===`write`){let n=t.pattern?.trim()||r.request.suggestedPattern?.trim()||r.request.detail.trim();try{let e=await u.appendScoopRule(s.folder,c,n);e?(d=!0,f=e):p=`pattern collapsed to empty after sanitization`}catch(t){p=t instanceof Error?t.message:String(t),Z.warn(`Failed to persist always grant`,{id:e,folder:s.folder,kind:c,error:p})}}else p=`cannot persist always grant for kind "${c}" (no matching sudoers directive)`}return await this.persistLickDecision(e,t.decision,i,a),{settled:o,persisted:d,persistedPattern:f,persistError:p,scoopFolder:l,kind:c}}async persistLickDecision(e,t,n,r){let i=t===`deny`?`dismissed`:`confirmed`,a=r??this.registry.get(e)?.approverJid,o=a?this.deps.getScoops().get(a):this.deps.findApprover(n??this.registry.get(e)?.scoopJid);if(o)try{let t=(await this.deps.getMessagesForScoop(o.jid)).find(t=>t.lickId===e||t.id===`sudo-request-${e}`);if(!t){Z.warn(`Lick decision: no stored message found to flip`,{lickId:e});return}t.lickState=i,await this.deps.saveMessage(t),this.deps.onMessageUpdate(o.jid,{messageId:t.id,lickId:e,lickState:i})}catch(t){Z.warn(`Failed to persist lick decision`,{lickId:e,error:t instanceof Error?t.message:String(t)})}}async deliverSudoRequestToCone(e,t,n,r){let i=this.deps.getScoops().get(t),a=r.requester??i?.assistantLabel??t,o=i?.folder??t,s=gE(a,n,r),c={id:`sudo-request-${n}`,chatJid:e.jid,senderId:o,senderName:a,content:s,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sudo-request`,lickId:n,lickState:`pending`};await this.deps.handleMessage(c)}};function hE(e,t){let{kind:n,detail:r}=t;return n===`command`?zr(e,r)===`nopasswd-allow`:n===`read`||n===`write`?Kr(e,n,r)===`nopasswd-allow`:!1}function gE(e,t,n){let r=[`[@${e} sudo-request]`,`Lick ID: ${t}`,`Kind: ${n.kind}`,`Detail: ${n.detail}`];return n.reason&&r.push(`Reason given: ${n.reason}`),n.suggestedPattern&&r.push(`Suggested pattern: ${n.suggestedPattern}`),r.push(``,`Use the lick_confirm tool with lick_id="${t}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${t}" and a reason to deny. A denial without a reason tells the scoop nothing it can act on.`),r.join(`
1065
+ `)}async function _E(e,t,n){if(e.length===0||t<=0)return;let r=0,i=Math.min(t,e.length),a=async()=>{for(;r<e.length;){let t=r;r+=1;let i=e[t];if(i===void 0)return;await n(i)}};await Promise.all(Array.from({length:i},()=>a()))}let vE=null;function yE(e){vE=e}function bE(e,t,n){vE?.(e,t,n)}const xE=_(`scoop-completion-service`),SE=`/shared/scoop-notifications`,CE=1e3,wE=2e4;function TE(e){let t=e.replace(/\r\n?/g,`
1066
1066
  `);if(t.length===0)return 0;let n=1;for(let e=0;e<t.length;e++)t[e]===`
1067
1067
  `&&n++;return t.endsWith(`
1068
- `)?n-1:n}function zE(e){return e.length>LE?e.slice(0,LE)+`
1069
- ... (truncated)`:e}var BE=class{scoopResponseBuffer=new Map;mutedScoops=new Set;pendingCompletions=new Map;completionWaiters=new Map;deps;constructor(e){this.deps=e}appendResponseChunk(e,t){let n=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,n+t)}setResponseFull(e,t){this.scoopResponseBuffer.set(e,t)}clearResponse(e){this.scoopResponseBuffer.delete(e)}muteScoops(e){for(let t of e)this.mutedScoops.add(t);PE.info(`Scoops muted`,{count:e.length})}isScoopMuted(e){return this.mutedScoops.has(e)}forgetScoop(e,t){this.scoopResponseBuffer.delete(e),this.mutedScoops.delete(e),this.pendingCompletions.delete(e);let n=this.completionWaiters.get(e);if(n&&n.length>0){this.completionWaiters.delete(e);for(let r of n)try{r(null)}catch(n){PE.warn(`completion waiter threw on cleanup`,{jid:e,reason:t,error:n instanceof Error?n.message:String(n)})}}}shutdown(){for(let e of this.completionWaiters.values())for(let t of e)try{t(null)}catch(e){PE.warn(`completion waiter threw during shutdown`,{error:e instanceof Error?e.message:String(e)})}this.completionWaiters.clear(),this.mutedScoops.clear(),this.pendingCompletions.clear(),this.scoopResponseBuffer.clear()}async notifyCompletion(e){let t=this.deps.getScoop(e);if(!t||t.parentJid===null)return;NE(`complete`,t.folder);let n=this.scoopResponseBuffer.get(e);if(this.scoopResponseBuffer.delete(e),!n||t.notifyOnComplete===!1)return;let r=this.completionWaiters.get(e);if(r&&r.length>0){this.completionWaiters.delete(e);let t=zE(n);for(let n of r)try{n(t)}catch(t){PE.warn(`completion waiter threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}return}if(this.mutedScoops.has(e)){this.pendingCompletions.set(e,{responseText:n,timestamp:new Date().toISOString()}),PE.info(`Scoop completion stashed (muted)`,{scoop:t.folder,responseLength:n.length});return}await this.deliverCompletionToParent(t,n)}async deliverCompletionToParent(e,t){let n=this.deps.findParent(e.jid);if(!n)return;let r=RE(t),i=t.slice(0,IE),a,o=null,s=null;try{s=await this.writeScoopCompletionArtifact(e,t),PE.info(`Routing scoop completion to cone`,{scoop:e.folder,responseLength:t.length,lineCount:r,notificationPath:s})}catch(t){o=t instanceof Error?t.message:String(t),PE.warn(`Failed to persist scoop completion artifact, falling back to inline preview`,{scoop:e.folder,error:o})}a=o===null?VE(e.assistantLabel,s??`unavailable`,r,i):HE(e.assistantLabel,r,i,o);let c={id:`scoop-done-${e.jid}-${Date.now()}`,chatJid:n.jid,senderId:e.folder,senderName:e.assistantLabel,content:a,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-notify`};try{this.deps.notifyIncomingMessage(n.jid,c)}catch(t){PE.warn(`onIncomingMessage for scoop-notify threw`,{scoop:e.folder,error:t instanceof Error?t.message:String(t)})}try{await this.deps.handleMessage(c)}catch(t){let r=t instanceof Error?t.message:String(t);PE.error(`Failed to route scoop completion to cone`,{scoop:e.folder,error:r}),this.deps.reportError(n.jid,`Scoop ${e.folder} completed but notification failed: ${r}`)}}async writeScoopCompletionArtifact(e,t){let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);await n.mkdir(FE,{recursive:!0}),await this.pruneScoopCompletionArtifacts(199);let r=new Date().toISOString().replace(/[:.]/g,`-`),i=Math.random().toString(36).slice(2,8),a=`${FE}/${r}-${e.folder}-${i}.md`;return await n.writeFile(a,t),await this.pruneScoopCompletionArtifacts(),a}async pruneScoopCompletionArtifacts(e=200){let t=this.deps.getSharedFs();if(!t)return;let n;try{n=await t.readDir(FE)}catch{return}let r=n.filter(e=>e.type===`file`).map(e=>e.name).sort(),i=r.length-e;if(!(i<=0))for(let e of r.slice(0,i)){let n=`${FE}/${e}`;try{await t.rm(n)}catch(e){PE.warn(`Failed to prune scoop completion artifact`,{path:n,error:e instanceof Error?e.message:String(e)})}}}async unmuteScoops(e){let t=[],n=[];for(let r of e){this.mutedScoops.delete(r);let e=this.pendingCompletions.get(r);if(!e)continue;this.pendingCompletions.delete(r);let i=this.deps.getScoop(r);if(!i||i.parentJid===null)continue;let a={jid:r,summary:zE(e.responseText),timestamp:e.timestamp,notificationPath:null};t.push(a),n.push(this.writeScoopCompletionArtifact(i,e.responseText).then(e=>{a.notificationPath=e}).catch(e=>{PE.warn(`unmute artifact persist failed`,{jid:r,error:e instanceof Error?e.message:String(e)})}))}return await Promise.all(n),PE.info(`Scoops unmuted`,{count:e.length,consumed:t.length}),t}async waitForScoops(e,t){if(e.length===0)return[];let n=Array.from(new Set(e)),r=new Map,i=[];for(let e of n)this.mutedScoops.has(e)||(this.mutedScoops.add(e),i.push(e));this.claimPendingSummaries(n,r);let a=n.filter(e=>!r.has(e)),o=a.filter(e=>this.deps.hasScoop(e)),s=a.filter(e=>!this.deps.hasScoop(e));for(let e of s)r.set(e,{summary:null,timedOut:!0});let c=[],l=o.map(e=>new Promise(t=>{let n=n=>{r.has(e)||(r.set(e,{summary:n,timedOut:n===null}),t())};c.push({jid:e,waiter:n});let i=this.completionWaiters.get(e);i||(i=[],this.completionWaiters.set(e,i)),i.push(n)}));try{await this.awaitScoopWaiters(l,t)}finally{this.removeCompletionWaiters(c);for(let e of i)this.mutedScoops.delete(e)}for(let e of o)r.has(e)||r.set(e,{summary:null,timedOut:!0});return e.map(e=>{let t=r.get(e)??{summary:null,timedOut:!0};return{jid:e,summary:t.summary,timedOut:t.timedOut}})}claimPendingSummaries(e,t){for(let n of e){let e=this.pendingCompletions.get(n);e&&(this.pendingCompletions.delete(n),t.set(n,{summary:zE(e.responseText),timedOut:!1}))}}async awaitScoopWaiters(e,t){if(e.length===0)return;if(t==null||t<0){await Promise.all(e);return}let n=null;try{await Promise.race([Promise.all(e),new Promise(e=>{n=setTimeout(()=>e(),t)})])}finally{n&&clearTimeout(n)}}removeCompletionWaiters(e){for(let{jid:t,waiter:n}of e){let e=this.completionWaiters.get(t);if(!e)continue;let r=e.indexOf(n);r!==-1&&e.splice(r,1),e.length===0&&this.completionWaiters.delete(t)}}scheduleScoopWait(e,t,n){let r=Array.from(new Set(e)),i=r.filter(e=>this.deps.hasScoop(e)),a=r.filter(e=>!this.deps.hasScoop(e));return this.waitForScoops(i,t).then(e=>this.deliverWaitResultsToCone(e,n)).catch(e=>{PE.error(`scheduleScoopWait failed`,{error:e instanceof Error?e.message:String(e)})}),{scheduled:i,unknown:a}}async deliverWaitResultsToCone(e,t){if(e.length===0)return;let n=t===void 0?void 0:this.deps.getScoop(t);if(n){await this.deliverWaitResultsTo(n,e);return}let r=new Map;for(let t of e){let e=this.deps.findParent(t.jid);if(!e)continue;let n=r.get(e.jid)??{parent:e,results:[]};n.results.push(t),r.set(e.jid,n)}for(let{parent:e,results:t}of r.values())await this.deliverWaitResultsTo(e,t)}async deliverWaitResultsTo(e,t){let n=[`[scoop_wait completed]`],r=0,i=0;for(let e of t){let t=this.deps.getScoop(e.jid)?.folder??e.jid;e.timedOut?(r+=1,n.push(`--- ${t} (timed out) ---`)):(i+=1,n.push(`--- ${t} ---`),n.push(e.summary??`(no output)`))}let a=`${i} completed, ${r} timed out`;n.splice(1,0,a);let o={id:`scoop-wait-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,chatJid:e.jid,senderId:`scoop-wait`,senderName:`scoop-wait`,content:n.join(`
1070
- `),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-wait`};try{this.deps.notifyIncomingMessage(e.jid,o)}catch(e){PE.warn(`onIncomingMessage for scoop-wait threw`,{error:e instanceof Error?e.message:String(e)})}try{await this.deps.handleMessage(o)}catch(t){let n=t instanceof Error?t.message:String(t);PE.error(`Failed to route scoop-wait result to cone`,{error:n}),this.deps.reportError(e.jid,`scoop_wait completed but notification failed: ${n}`)}}};function VE(e,t,n,r){return[`[@${e} completed]`,`VFS path: ${t}`,`Total lines: ${n}`,`Preview (up to ${IE} chars):`,r].join(`
1071
- `)}function HE(e,t,n,r){return[`[@${e} completed]`,`VFS path: unavailable`,`Artifact persistence error: ${r}`,`Total lines: ${t}`,`Preview (up to ${IE} chars):`,n].join(`
1072
- `)}const UE=9e5,WE=36e5;function GE(e,t,n){let r=yn(t),i=e.get(r);if(!i){e.set(r,{ids:[t],cost:n});return}i.ids.includes(t)||i.ids.push(t),i.cost+=n}function KE(e,t){let n=[...e.values()].sort((e,t)=>t.cost-e.cost||(e.ids[0]??``).localeCompare(t.ids[0]??``)).map(e=>vn(e.ids,t)),r=e.get(yn(t));return{current:r?vn(r.ids,t):t,models:n}}function qE(e,t){let n=Pn(e);return!n||!zn(e)&&yn(t)!==yn(n)?t:n}function JE(e,t,n=`live`){let r=t.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)return null;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,GE(a,e.model,e.usage.cost.total);let o=KE(a,qE(e,r.reduce((e,t)=>t.timestamp>=e.timestamp?t:e).model)),s=r.map(e=>e.timestamp).sort((e,t)=>e-t),c=s[0],l=s[s.length-1],u=l-c,d=Math.max(1,Math.ceil(u/UE))*UE;return{name:e.assistantLabel,type:On(e)?`cone`:`scoop`,model:o.current,models:o.models,source:n,usage:i,turns:r.length,firstActivity:c,lastActivity:l,activeTimeMs:d}}var YE=class{dropped=[];droppedMessages=[];deps;constructor(e){this.deps=e}snapshot(e){let t=this.deps.getScoops().get(e),n=this.deps.getContexts().get(e);if(!t||!n)return;let r=JE(t,n,`dropped`);r&&this.dropped.push(r);let i=n.getAgentMessages().filter(e=>e.role===`assistant`);i.length>0&&this.droppedMessages.push(i)}getSessionCosts(e={}){let t=[],n=this.deps.getContexts();for(let e of this.deps.getScoops().values()){let r=n.get(e.jid);if(!r)continue;let i=JE(e,r);i&&t.push(i)}return e.includeDropped&&t.push(...this.dropped),t}getBurnRate(e=Date.now()){let t=this.droppedMessages.flat();for(let e of this.deps.getContexts().values())for(let n of e.getAgentMessages())n.role===`assistant`&&t.push(n);if(t.length===0)return 0;let n=t[0].timestamp;for(let e of t)n=Math.min(n,e.timestamp);let r=Math.max(e-n,6e4),i=Math.min(9e5,r),a=Math.min(36e5,r),o=e-i,s=e-a,c=0,l=0,u=0;for(let e of t){let t=e.usage.cost.total;u+=t,e.timestamp>=o&&(c+=t),e.timestamp>=s&&(l+=t)}let d=c*WE/i,f=l*WE/a,p=u*WE/r,m=d*.5+f*.3+p*.2;return Math.max(m,p)}getContextFills(){return[...this.deps.getContexts().entries()].map(([e,t])=>({jid:e,fill:t.getContextFill()}))}getModelCosts(e={}){let t=new Map,n=new Map,r=this.deps.getContexts();for(let e of r.values()){let r=e.getAgentMessages().filter(e=>e.role===`assistant`);this.aggregateMessages(r,t,n)}if(e.includeDropped)for(let e of this.droppedMessages)this.aggregateMessages(e,t,n);for(let[e,r]of n){let n=t.get(e);n&&(n.model=vn(r.ids))}return Array.from(t.values()).sort((e,t)=>t.cost-e.cost)}aggregateMessages(e,t,n){for(let r of e){let e=yn(r.model);GE(n,r.model,r.usage.cost.total);let i=t.get(e);i?(i.input+=r.usage.input,i.output+=r.usage.output,i.cacheRead+=r.usage.cacheRead,i.cacheWrite+=r.usage.cacheWrite,i.cost+=r.usage.cost.total,i.turns+=1):t.set(e,{model:r.model,input:r.usage.input,output:r.usage.output,cacheRead:r.usage.cacheRead,cacheWrite:r.usage.cacheWrite,cost:r.usage.cost.total,turns:1})}}reset(){this.dropped=[],this.droppedMessages=[]}};const XE=_(`scoop-idle-timers`);var ZE=class{deps;timers=new Map;constructor(e){this.deps=e}start(e){if(this.clear(e),this.deps.getTabs().get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.timers.delete(e),this.fire(e)},12e4);this.timers.set(e,t)}clear(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.keys())this.clear(e)}fire(e){let t=this.deps.getScoops().get(e);if(!t||t.parentJid===null||this.deps.getTabs().get(e)?.status!==`ready`)return;let n=this.deps.findParent(e);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};XE.info(`Scoop idle timeout`,{jid:e,scoop:t.folder});try{this.deps.notifyIncomingMessage(n.jid,r)}catch(t){XE.warn(`onIncomingMessage for scoop-idle threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}this.deps.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);XE.error(`Failed to send idle notification`,{jid:e,error:n})})}};const QE=_(`work-unit`),$E={initializing:new Set([`ready`,`error`]),ready:new Set([`processing`,`error`,`initializing`]),processing:new Set([`ready`,`error`]),error:new Set([`initializing`,`ready`,`processing`])};var eD=class{id;deps;tab=null;context=null;observers=new Set;closed=!1;constructor(e,t){this.id=e,this.deps=t}get descriptor(){let e=this.deps.getScoop(this.id);if(!e)throw Error(`Work unit not found: ${this.id}`);let t=tr(e,this.tab??void 0);return this.closed?{...t,status:`closed`}:t}get status(){return this.closed?`closed`:$n(this.tab?.status)}get isClosed(){return this.closed}transition(e,t={}){if(this.closed)return QE.debug(`ignoring transition on closed unit`,{jid:this.id,next:e}),!1;let n=this.tab?.status;if(n!==void 0&&n!==e&&!$E[n].has(e))return QE.warn(`illegal work-unit transition ignored`,{jid:this.id,from:n,to:e}),!1;let r=new Date().toISOString();return this.tab={jid:this.id,contextId:this.tab?.contextId??`scoop-${this.id}`,...this.tab,...t,status:e,lastActivity:t.lastActivity??r},e!==`error`&&delete this.tab.error,!0}touch(){this.tab&&={...this.tab,lastActivity:new Date().toISOString()}}attachContext(e,t){if(this.closed)throw Error(`Cannot attach a context to closed unit ${this.id}`);this.context=e,this.tab={jid:this.id,contextId:t,status:`initializing`,lastActivity:new Date().toISOString()}}detachContext(){this.deps.clearIdleTimer(this.id),this.context?.stop(),this.context=null}disposeContext(){this.deps.clearIdleTimer(this.id),this.context?.dispose(),this.context=null,this.tab=null}observe(e){return this.closed?()=>{}:(this.observers.add(e),()=>{this.observers.delete(e)})}get observerCount(){return this.observers.size}dispatch(e,...t){for(let n of this.observers){let r=n[e];if(r)try{r(...t)}catch(t){QE.warn(`scoop observer threw`,{jid:this.id,event:e,error:t instanceof Error?t.message:String(t)})}}}send(e){if(this.closed)return Promise.reject(Error(`Work unit is closed: ${this.id}`));let t=this.deps.getScoop(this.id);return this.deps.sendPrompt(this.id,e.text,e.senderId??`user`,e.senderName??t?.assistantLabel??this.id,e.steer===void 0?void 0:{steer:e.steer})}subscribe(e){return this.observe({onStatusChange:t=>e({type:`status`,status:$n(t)}),onResponse:(t,n)=>e({type:`response`,text:t,isPartial:n}),onSendMessage:t=>e({type:`send-message`,text:t}),onError:t=>e({type:`error`,error:t})})}async abort(e){this.context?.stop()}close(){return this.closed?Promise.resolve():this.deps.unregister(this.id)}async teardown(){if(this.closed)return;this.closed=!0,this.deps.clearIdleTimer(this.id);let e=this.context;this.context=null;try{e?.stop(),e?.dispose()}catch(e){QE.warn(`context dispose threw during close`,{jid:this.id,error:e instanceof Error?e.message:String(e)})}this.observers.clear(),this.deps.forgetCompletion(this.id,`close`),QE.info(`Work unit closed`,{jid:this.id})}async snapshot(){return{descriptor:this.descriptor,messages:this.context?this.context.getAgentMessages():[],contextFill:this.context?this.context.getContextFill():0}}};let tD=null;function nD(e){tD=e}function rD(e,t){tD?.(e,t)}function iD(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function aD(e){if(typeof e!=`string`||!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function oD(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}const sD=[`run out of available resources`,`ran out of available resources`,`run out of credits`,`ran out of credits`],cD=[`active grok subscription`,`need a grok subscription`,`needs a grok subscription`];function lD(e){if(typeof e!=`string`||!e)return!1;let t=e.toLowerCase();return t.includes(`quota_exceeded`)?!0:sD.some(e=>t.includes(e))&&cD.some(e=>t.includes(e))}function uD(e){return iD(e)||aD(e)||oD(e)||lD(e)}function dD(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}function fD(e){return lD(e)?!0:/\b(401|403|404|405|410|422)\b/.test(e)||/unauthorized|forbidden|authentication.*failed|invalid.*api.?key/i.test(e)||/session expired|log in again|re-?authenticate/i.test(e)||/model.*not.*found|invalid.*model|unknown.*model|does.*not.*exist/i.test(e)||/decommissioned|no longer supported|deprecated.*model|model.*deprecated|model.*retired/i.test(e)||/insufficient.*quota|billing|payment.*required|account.*suspended/i.test(e)||/invalid.*request|malformed|bad.*request/i.test(e)}function pD(e){return lD(e)?!1:/\b429\b|rate.*limit|too.*many.*requests|quota.*exceeded/i.test(e)||/\b(500|502|503|504)\b|internal.*server|bad.*gateway|service.*unavailable|gateway.*timeout/i.test(e)||/network.*error|failed to fetch|connection.*refused|timeout|econnreset|socket.*hang.*up/i.test(e)||/overloaded|temporarily.*unavailable|try.*again/i.test(e)}function mD(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}function hD(e,t,n){let r=e[e.length-1];if(r){let i=r.role===`assistant`?r.errorMessage:void 0;if(i){if(gD(i,e,t,n))return}else t.imageRecovery.markSettled(),t.overflow.markSettled(),r.role===`assistant`&&t.overflow.markAssistantSucceeded()}t.persist(e)}function gD(e,t,n,r){let i=n.imageRecovery.isActive||n.overflow.isActive;return!i&&dD(e)?(n.imageRecovery.recover(t),!0):n.overflow.shouldRecover(t[t.length-1])?(n.overflow.recover(t,r),!0):!i&&n.isProcessing()&&!n.didStreamDeltas()?(n.latchStreamError(e),!0):(n.imageRecovery.markSettled(),n.overflow.markSettled(),rD(`llm`,e),n.onError(e),!1)}function _D(e,t,n){switch(e.type){case`message_update`:{let n=e.assistantMessageEvent;n.type===`text_delta`&&t.textDelta(n.delta);break}case`tool_execution_start`:return t.toolStart(e.toolName,e.args,e.toolCallId);case`tool_execution_update`:vD(e,t);break;case`tool_execution_end`:yD(e,t),t.checkpoint();break;case`message_end`:e.message.role===`assistant`&&t.assistantMessageEnd(e.message),t.checkpoint(e.message);break;case`turn_start`:t.turnStart();break;case`turn_end`:if(t.turnCompleted(),e.message.role===`assistant`&&rs(e.message))break;t.responseDone();break;case`agent_end`:t.agentEnd(e.messages,n)}}function vD(e,t){let n=e.partialResult;for(let r of n?.content??[])r.type===`tool_ui`&&r.requestId&&r.html?t.toolUI(e.toolName,r.requestId,r.html):r.type===`tool_ui_done`&&r.requestId?t.toolUIDone(r.requestId):r.type===`progress`&&r.progress&&t.toolProgress(e.toolName,r.progress,e.toolCallId)}function yD(e,t){let n=e.result,r=[];for(let e of n?.content??[])e.type===`text`&&e.text&&r.push(e.text),e.type===`image`&&e.data&&e.mimeType&&r.push(`<img:data:${e.mimeType};base64,${e.data}>`);let i=r.join(`
1068
+ `)?n-1:n}function EE(e){return e.length>wE?e.slice(0,wE)+`
1069
+ ... (truncated)`:e}var DE=class{scoopResponseBuffer=new Map;mutedScoops=new Set;pendingCompletions=new Map;completionWaiters=new Map;deps;constructor(e){this.deps=e}appendResponseChunk(e,t){let n=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,n+t)}setResponseFull(e,t){this.scoopResponseBuffer.set(e,t)}clearResponse(e){this.scoopResponseBuffer.delete(e)}muteScoops(e){for(let t of e)this.mutedScoops.add(t);xE.info(`Scoops muted`,{count:e.length})}isScoopMuted(e){return this.mutedScoops.has(e)}forgetScoop(e,t){this.scoopResponseBuffer.delete(e),this.mutedScoops.delete(e),this.pendingCompletions.delete(e);let n=this.completionWaiters.get(e);if(n&&n.length>0){this.completionWaiters.delete(e);for(let r of n)try{r(null)}catch(n){xE.warn(`completion waiter threw on cleanup`,{jid:e,reason:t,error:n instanceof Error?n.message:String(n)})}}}shutdown(){for(let e of this.completionWaiters.values())for(let t of e)try{t(null)}catch(e){xE.warn(`completion waiter threw during shutdown`,{error:e instanceof Error?e.message:String(e)})}this.completionWaiters.clear(),this.mutedScoops.clear(),this.pendingCompletions.clear(),this.scoopResponseBuffer.clear()}async notifyCompletion(e){let t=this.deps.getScoop(e);if(!t||t.parentJid===null)return;bE(`complete`,t.folder);let n=this.scoopResponseBuffer.get(e);if(this.scoopResponseBuffer.delete(e),!n||t.notifyOnComplete===!1)return;let r=this.completionWaiters.get(e);if(r&&r.length>0){this.completionWaiters.delete(e);let t=EE(n);for(let n of r)try{n(t)}catch(t){xE.warn(`completion waiter threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}return}if(this.mutedScoops.has(e)){this.pendingCompletions.set(e,{responseText:n,timestamp:new Date().toISOString()}),xE.info(`Scoop completion stashed (muted)`,{scoop:t.folder,responseLength:n.length});return}await this.deliverCompletionToParent(t,n)}async deliverCompletionToParent(e,t){let n=this.deps.findParent(e.jid);if(!n)return;let r=TE(t),i=t.slice(0,CE),a,o=null,s=null;try{s=await this.writeScoopCompletionArtifact(e,t),xE.info(`Routing scoop completion to cone`,{scoop:e.folder,responseLength:t.length,lineCount:r,notificationPath:s})}catch(t){o=t instanceof Error?t.message:String(t),xE.warn(`Failed to persist scoop completion artifact, falling back to inline preview`,{scoop:e.folder,error:o})}a=o===null?OE(e.assistantLabel,s??`unavailable`,r,i):kE(e.assistantLabel,r,i,o);let c={id:`scoop-done-${e.jid}-${Date.now()}`,chatJid:n.jid,senderId:e.folder,senderName:e.assistantLabel,content:a,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-notify`};try{this.deps.notifyIncomingMessage(n.jid,c)}catch(t){xE.warn(`onIncomingMessage for scoop-notify threw`,{scoop:e.folder,error:t instanceof Error?t.message:String(t)})}try{await this.deps.handleMessage(c)}catch(t){let r=t instanceof Error?t.message:String(t);xE.error(`Failed to route scoop completion to cone`,{scoop:e.folder,error:r}),this.deps.reportError(n.jid,`Scoop ${e.folder} completed but notification failed: ${r}`)}}async writeScoopCompletionArtifact(e,t){let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);await n.mkdir(SE,{recursive:!0}),await this.pruneScoopCompletionArtifacts(199);let r=new Date().toISOString().replace(/[:.]/g,`-`),i=Math.random().toString(36).slice(2,8),a=`${SE}/${r}-${e.folder}-${i}.md`;return await n.writeFile(a,t),await this.pruneScoopCompletionArtifacts(),a}async pruneScoopCompletionArtifacts(e=200){let t=this.deps.getSharedFs();if(!t)return;let n;try{n=await t.readDir(SE)}catch{return}let r=n.filter(e=>e.type===`file`).map(e=>e.name).sort(),i=r.length-e;if(!(i<=0))for(let e of r.slice(0,i)){let n=`${SE}/${e}`;try{await t.rm(n)}catch(e){xE.warn(`Failed to prune scoop completion artifact`,{path:n,error:e instanceof Error?e.message:String(e)})}}}async unmuteScoops(e){let t=[],n=[];for(let r of e){this.mutedScoops.delete(r);let e=this.pendingCompletions.get(r);if(!e)continue;this.pendingCompletions.delete(r);let i=this.deps.getScoop(r);if(!i||i.parentJid===null)continue;let a={jid:r,summary:EE(e.responseText),timestamp:e.timestamp,notificationPath:null};t.push(a),n.push(this.writeScoopCompletionArtifact(i,e.responseText).then(e=>{a.notificationPath=e}).catch(e=>{xE.warn(`unmute artifact persist failed`,{jid:r,error:e instanceof Error?e.message:String(e)})}))}return await Promise.all(n),xE.info(`Scoops unmuted`,{count:e.length,consumed:t.length}),t}async waitForScoops(e,t){if(e.length===0)return[];let n=Array.from(new Set(e)),r=new Map,i=[];for(let e of n)this.mutedScoops.has(e)||(this.mutedScoops.add(e),i.push(e));this.claimPendingSummaries(n,r);let a=n.filter(e=>!r.has(e)),o=a.filter(e=>this.deps.hasScoop(e)),s=a.filter(e=>!this.deps.hasScoop(e));for(let e of s)r.set(e,{summary:null,timedOut:!0});let c=[],l=o.map(e=>new Promise(t=>{let n=n=>{r.has(e)||(r.set(e,{summary:n,timedOut:n===null}),t())};c.push({jid:e,waiter:n});let i=this.completionWaiters.get(e);i||(i=[],this.completionWaiters.set(e,i)),i.push(n)}));try{await this.awaitScoopWaiters(l,t)}finally{this.removeCompletionWaiters(c);for(let e of i)this.mutedScoops.delete(e)}for(let e of o)r.has(e)||r.set(e,{summary:null,timedOut:!0});return e.map(e=>{let t=r.get(e)??{summary:null,timedOut:!0};return{jid:e,summary:t.summary,timedOut:t.timedOut}})}claimPendingSummaries(e,t){for(let n of e){let e=this.pendingCompletions.get(n);e&&(this.pendingCompletions.delete(n),t.set(n,{summary:EE(e.responseText),timedOut:!1}))}}async awaitScoopWaiters(e,t){if(e.length===0)return;if(t==null||t<0){await Promise.all(e);return}let n=null;try{await Promise.race([Promise.all(e),new Promise(e=>{n=setTimeout(()=>e(),t)})])}finally{n&&clearTimeout(n)}}removeCompletionWaiters(e){for(let{jid:t,waiter:n}of e){let e=this.completionWaiters.get(t);if(!e)continue;let r=e.indexOf(n);r!==-1&&e.splice(r,1),e.length===0&&this.completionWaiters.delete(t)}}scheduleScoopWait(e,t,n){let r=Array.from(new Set(e)),i=r.filter(e=>this.deps.hasScoop(e)),a=r.filter(e=>!this.deps.hasScoop(e));return this.waitForScoops(i,t).then(e=>this.deliverWaitResultsToCone(e,n)).catch(e=>{xE.error(`scheduleScoopWait failed`,{error:e instanceof Error?e.message:String(e)})}),{scheduled:i,unknown:a}}async deliverWaitResultsToCone(e,t){if(e.length===0)return;let n=t===void 0?void 0:this.deps.getScoop(t);if(n){await this.deliverWaitResultsTo(n,e);return}let r=new Map;for(let t of e){let e=this.deps.findParent(t.jid);if(!e)continue;let n=r.get(e.jid)??{parent:e,results:[]};n.results.push(t),r.set(e.jid,n)}for(let{parent:e,results:t}of r.values())await this.deliverWaitResultsTo(e,t)}async deliverWaitResultsTo(e,t){let n=[`[scoop_wait completed]`],r=0,i=0;for(let e of t){let t=this.deps.getScoop(e.jid)?.folder??e.jid;e.timedOut?(r+=1,n.push(`--- ${t} (timed out) ---`)):(i+=1,n.push(`--- ${t} ---`),n.push(e.summary??`(no output)`))}let a=`${i} completed, ${r} timed out`;n.splice(1,0,a);let o={id:`scoop-wait-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,chatJid:e.jid,senderId:`scoop-wait`,senderName:`scoop-wait`,content:n.join(`
1070
+ `),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-wait`};try{this.deps.notifyIncomingMessage(e.jid,o)}catch(e){xE.warn(`onIncomingMessage for scoop-wait threw`,{error:e instanceof Error?e.message:String(e)})}try{await this.deps.handleMessage(o)}catch(t){let n=t instanceof Error?t.message:String(t);xE.error(`Failed to route scoop-wait result to cone`,{error:n}),this.deps.reportError(e.jid,`scoop_wait completed but notification failed: ${n}`)}}};function OE(e,t,n,r){return[`[@${e} completed]`,`VFS path: ${t}`,`Total lines: ${n}`,`Preview (up to ${CE} chars):`,r].join(`
1071
+ `)}function kE(e,t,n,r){return[`[@${e} completed]`,`VFS path: unavailable`,`Artifact persistence error: ${r}`,`Total lines: ${t}`,`Preview (up to ${CE} chars):`,n].join(`
1072
+ `)}const AE=9e5,jE=36e5;function ME(e,t,n){let r=Sn(t),i=e.get(r);if(!i){e.set(r,{ids:[t],cost:n});return}i.ids.includes(t)||i.ids.push(t),i.cost+=n}function NE(e,t){let n=[...e.values()].sort((e,t)=>t.cost-e.cost||(e.ids[0]??``).localeCompare(t.ids[0]??``)).map(e=>xn(e.ids,t)),r=e.get(Sn(t));return{current:r?xn(r.ids,t):t,models:n}}function PE(e,t){let n=Ln(e);return!n||!Hn(e)&&Sn(t)!==Sn(n)?t:n}function FE(e,t,n=`live`){let r=t.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)return null;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,ME(a,e.model,e.usage.cost.total);let o=NE(a,PE(e,r.reduce((e,t)=>t.timestamp>=e.timestamp?t:e).model)),s=r.map(e=>e.timestamp).sort((e,t)=>e-t),c=s[0],l=s[s.length-1],u=l-c,d=Math.max(1,Math.ceil(u/AE))*AE;return{name:e.assistantLabel,type:jn(e)?`cone`:`scoop`,model:o.current,models:o.models,source:n,usage:i,turns:r.length,firstActivity:c,lastActivity:l,activeTimeMs:d}}var IE=class{dropped=[];droppedMessages=[];deps;constructor(e){this.deps=e}snapshot(e){let t=this.deps.getScoops().get(e),n=this.deps.getContexts().get(e);if(!t||!n)return;let r=FE(t,n,`dropped`);r&&this.dropped.push(r);let i=n.getAgentMessages().filter(e=>e.role===`assistant`);i.length>0&&this.droppedMessages.push(i)}getSessionCosts(e={}){let t=[],n=this.deps.getContexts();for(let e of this.deps.getScoops().values()){let r=n.get(e.jid);if(!r)continue;let i=FE(e,r);i&&t.push(i)}return e.includeDropped&&t.push(...this.dropped),t}getBurnRate(e=Date.now()){let t=this.droppedMessages.flat();for(let e of this.deps.getContexts().values())for(let n of e.getAgentMessages())n.role===`assistant`&&t.push(n);if(t.length===0)return 0;let n=t[0].timestamp;for(let e of t)n=Math.min(n,e.timestamp);let r=Math.max(e-n,6e4),i=Math.min(9e5,r),a=Math.min(36e5,r),o=e-i,s=e-a,c=0,l=0,u=0;for(let e of t){let t=e.usage.cost.total;u+=t,e.timestamp>=o&&(c+=t),e.timestamp>=s&&(l+=t)}let d=c*jE/i,f=l*jE/a,p=u*jE/r,m=d*.5+f*.3+p*.2;return Math.max(m,p)}getContextFills(){return[...this.deps.getContexts().entries()].map(([e,t])=>({jid:e,fill:t.getContextFill()}))}getModelCosts(e={}){let t=new Map,n=new Map,r=this.deps.getContexts();for(let e of r.values()){let r=e.getAgentMessages().filter(e=>e.role===`assistant`);this.aggregateMessages(r,t,n)}if(e.includeDropped)for(let e of this.droppedMessages)this.aggregateMessages(e,t,n);for(let[e,r]of n){let n=t.get(e);n&&(n.model=xn(r.ids))}return Array.from(t.values()).sort((e,t)=>t.cost-e.cost)}aggregateMessages(e,t,n){for(let r of e){let e=Sn(r.model);ME(n,r.model,r.usage.cost.total);let i=t.get(e);i?(i.input+=r.usage.input,i.output+=r.usage.output,i.cacheRead+=r.usage.cacheRead,i.cacheWrite+=r.usage.cacheWrite,i.cost+=r.usage.cost.total,i.turns+=1):t.set(e,{model:r.model,input:r.usage.input,output:r.usage.output,cacheRead:r.usage.cacheRead,cacheWrite:r.usage.cacheWrite,cost:r.usage.cost.total,turns:1})}}reset(){this.dropped=[],this.droppedMessages=[]}};const LE=_(`scoop-idle-timers`);var RE=class{deps;timers=new Map;constructor(e){this.deps=e}start(e){if(this.clear(e),this.deps.getTabs().get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.timers.delete(e),this.fire(e)},12e4);this.timers.set(e,t)}clear(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.keys())this.clear(e)}fire(e){let t=this.deps.getScoops().get(e);if(!t||t.parentJid===null||this.deps.getTabs().get(e)?.status!==`ready`)return;let n=this.deps.findParent(e);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};LE.info(`Scoop idle timeout`,{jid:e,scoop:t.folder});try{this.deps.notifyIncomingMessage(n.jid,r)}catch(t){LE.warn(`onIncomingMessage for scoop-idle threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}this.deps.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);LE.error(`Failed to send idle notification`,{jid:e,error:n})})}};const zE=_(`work-unit`),BE={initializing:new Set([`ready`,`error`]),ready:new Set([`processing`,`error`,`initializing`]),processing:new Set([`ready`,`error`]),error:new Set([`initializing`,`ready`,`processing`])};var VE=class{id;deps;tab=null;context=null;observers=new Set;closed=!1;constructor(e,t){this.id=e,this.deps=t}get descriptor(){let e=this.deps.getScoop(this.id);if(!e)throw Error(`Work unit not found: ${this.id}`);let t=ir(e,this.tab??void 0);return this.closed?{...t,status:`closed`}:t}get status(){return this.closed?`closed`:nr(this.tab?.status)}get isClosed(){return this.closed}transition(e,t={}){if(this.closed)return zE.debug(`ignoring transition on closed unit`,{jid:this.id,next:e}),!1;let n=this.tab?.status;if(n!==void 0&&n!==e&&!BE[n].has(e))return zE.warn(`illegal work-unit transition ignored`,{jid:this.id,from:n,to:e}),!1;let r=new Date().toISOString();return this.tab={jid:this.id,contextId:this.tab?.contextId??`scoop-${this.id}`,...this.tab,...t,status:e,lastActivity:t.lastActivity??r},e!==`error`&&delete this.tab.error,!0}touch(){this.tab&&={...this.tab,lastActivity:new Date().toISOString()}}attachContext(e,t){if(this.closed)throw Error(`Cannot attach a context to closed unit ${this.id}`);this.context=e,this.tab={jid:this.id,contextId:t,status:`initializing`,lastActivity:new Date().toISOString()}}detachContext(){this.deps.clearIdleTimer(this.id),this.context?.stop(),this.context=null}disposeContext(){this.deps.clearIdleTimer(this.id),this.context?.dispose(),this.context=null,this.tab=null}observe(e){return this.closed?()=>{}:(this.observers.add(e),()=>{this.observers.delete(e)})}get observerCount(){return this.observers.size}dispatch(e,...t){for(let n of this.observers){let r=n[e];if(r)try{r(...t)}catch(t){zE.warn(`scoop observer threw`,{jid:this.id,event:e,error:t instanceof Error?t.message:String(t)})}}}send(e){if(this.closed)return Promise.reject(Error(`Work unit is closed: ${this.id}`));let t=this.deps.getScoop(this.id);return this.deps.sendPrompt(this.id,e.text,e.senderId??`user`,e.senderName??t?.assistantLabel??this.id,e.steer===void 0?void 0:{steer:e.steer})}subscribe(e){return this.observe({onStatusChange:t=>e({type:`status`,status:nr(t)}),onResponse:(t,n)=>e({type:`response`,text:t,isPartial:n}),onSendMessage:t=>e({type:`send-message`,text:t}),onError:t=>e({type:`error`,error:t})})}async abort(e){this.context?.stop()}close(){return this.closed?Promise.resolve():this.deps.unregister(this.id)}async teardown(){if(this.closed)return;this.closed=!0,this.deps.clearIdleTimer(this.id);let e=this.context;this.context=null;try{e?.stop(),e?.dispose()}catch(e){zE.warn(`context dispose threw during close`,{jid:this.id,error:e instanceof Error?e.message:String(e)})}this.observers.clear(),this.deps.forgetCompletion(this.id,`close`),zE.info(`Work unit closed`,{jid:this.id})}async snapshot(){return{descriptor:this.descriptor,messages:this.context?this.context.getAgentMessages():[],contextFill:this.context?this.context.getContextFill():0}}};let HE=null;function UE(e){HE=e}function WE(e,t){HE?.(e,t)}function GE(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function KE(e){if(typeof e!=`string`||!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function qE(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}const JE=[`run out of available resources`,`ran out of available resources`,`run out of credits`,`ran out of credits`],YE=[`active grok subscription`,`need a grok subscription`,`needs a grok subscription`];function XE(e){if(typeof e!=`string`||!e)return!1;let t=e.toLowerCase();return t.includes(`quota_exceeded`)?!0:JE.some(e=>t.includes(e))&&YE.some(e=>t.includes(e))}function ZE(e){return GE(e)||KE(e)||qE(e)||XE(e)}function QE(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}function $E(e){return XE(e)?!0:/\b(401|403|404|405|410|422)\b/.test(e)||/unauthorized|forbidden|authentication.*failed|invalid.*api.?key/i.test(e)||/session expired|log in again|re-?authenticate/i.test(e)||/model.*not.*found|invalid.*model|unknown.*model|does.*not.*exist/i.test(e)||/decommissioned|no longer supported|deprecated.*model|model.*deprecated|model.*retired/i.test(e)||/insufficient.*quota|billing|payment.*required|account.*suspended/i.test(e)||/invalid.*request|malformed|bad.*request/i.test(e)}function eD(e){return XE(e)?!1:/\b429\b|rate.*limit|too.*many.*requests|quota.*exceeded/i.test(e)||/\b(500|502|503|504)\b|internal.*server|bad.*gateway|service.*unavailable|gateway.*timeout/i.test(e)||/network.*error|failed to fetch|connection.*refused|timeout|econnreset|socket.*hang.*up/i.test(e)||/overloaded|temporarily.*unavailable|try.*again/i.test(e)}function tD(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}function nD(e,t,n){let r=e[e.length-1];if(r){let i=r.role===`assistant`?r.errorMessage:void 0;if(i){if(rD(i,e,t,n))return}else t.imageRecovery.markSettled(),t.overflow.markSettled(),r.role===`assistant`&&t.overflow.markAssistantSucceeded()}t.persist(e)}function rD(e,t,n,r){let i=n.imageRecovery.isActive||n.overflow.isActive;return!i&&QE(e)?(n.imageRecovery.recover(t),!0):n.overflow.shouldRecover(t[t.length-1])?(n.overflow.recover(t,r),!0):!i&&n.isProcessing()&&!n.didStreamDeltas()?(n.latchStreamError(e),!0):(n.imageRecovery.markSettled(),n.overflow.markSettled(),WE(`llm`,e),n.onError(e),!1)}function iD(e,t,n){switch(e.type){case`message_update`:{let n=e.assistantMessageEvent;n.type===`text_delta`&&t.textDelta(n.delta);break}case`tool_execution_start`:return t.toolStart(e.toolName,e.args,e.toolCallId);case`tool_execution_update`:aD(e,t);break;case`tool_execution_end`:oD(e,t),t.checkpoint();break;case`message_end`:e.message.role===`assistant`&&t.assistantMessageEnd(e.message),t.checkpoint(e.message);break;case`turn_start`:t.turnStart();break;case`turn_end`:if(t.turnCompleted(),e.message.role===`assistant`&&Go(e.message))break;t.responseDone();break;case`agent_end`:t.agentEnd(e.messages,n)}}function aD(e,t){let n=e.partialResult;for(let r of n?.content??[])r.type===`tool_ui`&&r.requestId&&r.html?t.toolUI(e.toolName,r.requestId,r.html):r.type===`tool_ui_done`&&r.requestId?t.toolUIDone(r.requestId):r.type===`progress`&&r.progress&&t.toolProgress(e.toolName,r.progress,e.toolCallId)}function oD(e,t){let n=e.result,r=[];for(let e of n?.content??[])e.type===`text`&&e.text&&r.push(e.text),e.type===`image`&&e.data&&e.mimeType&&r.push(`<img:data:${e.mimeType};base64,${e.data}>`);let i=r.join(`
1073
1073
  `);if(e.isError){let t=r.filter(e=>!e.startsWith(`<img:`)).join(`
1074
- `);rD(`tool`,`${e.toolName}: ${t}`)}t.toolResult(e.toolName,i,e.isError,e.toolCallId)}const bD=_(`scoop-context`);var xD=class{deps;livePids=new Set;constructor(e){this.deps=e}spawn(e){let t=this.deps.processManager;if(!t)return null;let n=e=>{this.livePids.delete(e)},r=t.spawn({kind:`shell`,argv:[`bash`,`-c`,e],cwd:this.deps.cwd,owner:this.deps.owner,ppid:this.deps.getTurnPid()});return this.livePids.add(r.pid),{pid:r.pid,signal:r.abort.signal,kill:()=>{n(r.pid),t.signal(r.pid,`SIGKILL`)},exit:e=>{n(r.pid),t.exit(r.pid,e)}}}reapAll(){let e=this.deps.processManager;if(!e||this.livePids.size===0)return;let t=[...this.livePids];this.livePids.clear(),bD.info(`Reaping background bash jobs on dispose`,{folder:this.deps.folder,pids:t});for(let n of t)e.signal(n,`SIGKILL`)}};const SD=_(`scoop-context`);var CD=class{deps;active=!1;constructor(e){this.deps=e}get isActive(){return this.active}markSettled(){this.active=!1}recover(e){let t=this.deps.getAgent();if(t){SD.warn(`Image processing error detected, attempting recovery`,{folder:this.deps.folder,messageCount:e.length}),this.active=!0,this.deps.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let n=e.slice(0,-1),r=wD(n);t.state.messages=n;let i=`[System: An image was rejected by the API and has been removed from the conversation (${r} message(s) affected). The conversation continues without the image.]`;t.prompt(i).catch(e=>{SD.error(`Image recovery re-prompt failed`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.fail(e)})}catch(e){SD.error(`Image recovery failed`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.fail(e)}}}fail(e){this.active=!1,this.deps.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}};function wD(e){let t=0,n=Math.max(0,e.length-10);for(let r=e.length-1;r>=n;r--){let n=e[r];if(!Array.isArray(n.content)||!n.content.some(e=>e.type===`image`))continue;let i=n.content.filter(e=>e.type!==`image`);i.length===0?e[r]={...n,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:e[r]={...n,content:i},t++}return t}async function TD(e,t){try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch{return``}}async function ED(e,t,n){let r=await TD(e,t.workspace.memoryPath),i=await n();if(i&&t.policy.canWriteSharedMemory)try{await(`getUnderlyingFS`in e?e.getUnderlyingFS():e).writeFile(`/shared/CLAUDE.md`,i)}catch{}return{scoopMemory:r,globalMemory:i}}const DD=_(`scoop-context`);function OD(e){let t=zn(e);return!t&&Nx(e)?null:t?ce(t):pe()}function kD(e){let t=Pn(e);if(t)return fe(t,zn(e));if(Nx(e))throw Error(`The gelatiere has no leading-cone model`);return me()}function AD(e,t){let n=Pn(e),r=zn(e),i=kD(e),a=t.display.role===`primary`?`Cone`:`Scoop "${e.name}"`;if(console.log(`[model] ${a} using model: ${i.id} (provider: ${i.provider})`),r&&(i.id!==n||!he(i,r)))throw Error(`Configured model ${r}:${n} resolved to ${i.provider}:${i.id}; refusing to run on a different model`);return!r&&n&&i.id!==n&&DD.warn(`Configured scoop model did not resolve; using resolved model instead`,{folder:e.folder,configuredModelId:n,resolvedModelId:i.id}),i}function jD(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role!==`assistant`||!r.usage)continue;let i=r.usage.input+r.usage.cacheRead+r.usage.output,a=2e5;try{let e=kD(t);typeof e.contextWindow==`number`&&e.contextWindow>0&&(a=e.contextWindow)}catch{}return Math.min(1,i/a)}return 0}function MD(e){if(Nx(e)&&!Pn(e))return`The gelatiere cannot run until the leading cone has a model.`;let t=zn(e)??``;try{t||=ue()}catch{}return t?`No API key configured for provider "${t}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`}function ND(e,t,n,r,i){let a=e.config?.assistantName||e.assistantLabel,o=t.display.role===`primary`,{policy:s,workspace:c}=t,l=`# ${a}
1074
+ `);WE(`tool`,`${e.toolName}: ${t}`)}t.toolResult(e.toolName,i,e.isError,e.toolCallId)}const sD=_(`scoop-context`);var cD=class{deps;livePids=new Set;constructor(e){this.deps=e}spawn(e){let t=this.deps.processManager;if(!t)return null;let n=e=>{this.livePids.delete(e)},r=t.spawn({kind:`shell`,argv:[`bash`,`-c`,e],cwd:this.deps.cwd,owner:this.deps.owner,ppid:this.deps.getTurnPid()});return this.livePids.add(r.pid),{pid:r.pid,signal:r.abort.signal,kill:()=>{n(r.pid),t.signal(r.pid,`SIGKILL`)},exit:e=>{n(r.pid),t.exit(r.pid,e)}}}reapAll(){let e=this.deps.processManager;if(!e||this.livePids.size===0)return;let t=[...this.livePids];this.livePids.clear(),sD.info(`Reaping background bash jobs on dispose`,{folder:this.deps.folder,pids:t});for(let n of t)e.signal(n,`SIGKILL`)}};const lD=_(`scoop-context`);var uD=class{deps;active=!1;constructor(e){this.deps=e}get isActive(){return this.active}markSettled(){this.active=!1}recover(e){let t=this.deps.getAgent();if(t){lD.warn(`Image processing error detected, attempting recovery`,{folder:this.deps.folder,messageCount:e.length}),this.active=!0,this.deps.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let n=e.slice(0,-1),r=dD(n);t.state.messages=n;let i=`[System: An image was rejected by the API and has been removed from the conversation (${r} message(s) affected). The conversation continues without the image.]`;t.prompt(i).catch(e=>{lD.error(`Image recovery re-prompt failed`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.fail(e)})}catch(e){lD.error(`Image recovery failed`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.fail(e)}}}fail(e){this.active=!1,this.deps.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}};function dD(e){let t=0,n=Math.max(0,e.length-10);for(let r=e.length-1;r>=n;r--){let n=e[r];if(!Array.isArray(n.content)||!n.content.some(e=>e.type===`image`))continue;let i=n.content.filter(e=>e.type!==`image`);i.length===0?e[r]={...n,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:e[r]={...n,content:i},t++}return t}async function fD(e,t){try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch{return``}}async function pD(e,t,n){let r=await fD(e,t.workspace.memoryPath),i=await n();if(i&&t.policy.canWriteSharedMemory)try{await(`getUnderlyingFS`in e?e.getUnderlyingFS():e).writeFile(`/shared/CLAUDE.md`,i)}catch{}return{scoopMemory:r,globalMemory:i}}const mD=_(`scoop-context`);function hD(e){let t=Hn(e);return!t&&xx(e)?null:t?ce(t):pe()}function gD(e){let t=Ln(e);if(t)return fe(t,Hn(e));if(xx(e))throw Error(`The gelatiere has no leading-cone model`);return me()}function _D(e,t){let n=Ln(e),r=Hn(e),i=gD(e),a=t.display.role===`primary`?`Cone`:`Scoop "${e.name}"`;if(console.log(`[model] ${a} using model: ${i.id} (provider: ${i.provider})`),r&&(i.id!==n||!he(i,r)))throw Error(`Configured model ${r}:${n} resolved to ${i.provider}:${i.id}; refusing to run on a different model`);return!r&&n&&i.id!==n&&mD.warn(`Configured scoop model did not resolve; using resolved model instead`,{folder:e.folder,configuredModelId:n,resolvedModelId:i.id}),i}function vD(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role!==`assistant`||!r.usage)continue;let i=r.usage.input+r.usage.cacheRead+r.usage.output,a=2e5;try{let e=gD(t);typeof e.contextWindow==`number`&&e.contextWindow>0&&(a=e.contextWindow)}catch{}return Math.min(1,i/a)}return 0}function yD(e){if(xx(e)&&!Ln(e))return`The gelatiere cannot run until the leading cone has a model.`;let t=Hn(e)??``;try{t||=ue()}catch{}return t?`No API key configured for provider "${t}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`}function bD(e,t,n,r,i){let a=e.config?.assistantName||e.assistantLabel,o=t.display.role===`primary`,{policy:s,workspace:c}=t,l=`# ${a}
1075
1075
 
1076
1076
  You are ${a}, ${o?`the main assistant (cone)`:`a scoop assistant`} in SLICC (Self-Licking Ice Cream Cone).
1077
1077
 
@@ -1146,7 +1146,7 @@ ${n}
1146
1146
  ---
1147
1147
  ${o?`CONE`:`SCOOP`} MEMORY (${e.name}):
1148
1148
  ${r}
1149
- ---`);let u=FT(i);return u&&(l+=u),l}const PD=_(`scoop-context`);function FD(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!rn(t).includes(`xhigh`)?`high`:e}function ID(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(cr.includes(e))return e;PD.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}const LD=_(`scoop-context`);function RD(e,t){let n=kD(t);e.state.model=n;let r=Rn(t),i=ID()??r.level;return e.state.thinkingLevel=FD(i,n),LD.info(`Model updated on running agent`,{folder:t.folder,model:n.id,thinkingLevel:e.state.thinkingLevel}),n.reasoning?r.effortOverride:void 0}function zD(e,t){if(ID())return e.state.thinkingLevel;let n=FD(t,e.state.model);return e.state.thinkingLevel=n,n}async function BD(e,t){let n=await MT(t.skillsFs??t.fs,ir),r=await TD(t.fs,t.unit.workspace.memoryPath),i=await t.getGlobalMemory();e.state.systemPrompt=ND(t.scoop,t.unit,i,r,n),LD.info(`Skills reloaded`,{folder:t.scoop.folder,skillCount:n.length})}const VD=_(`scoop-context`);var HD=class{deps;attempted=!1;active=!1;escalated=!1;pending=null;constructor(e){this.deps=e}resetForRun(){this.attempted=!1,this.active=!1,this.pending=null,this.escalated=!1}get pendingRecovery(){return this.pending}clearPendingRecovery(e){this.pending===e&&(this.pending=null)}get isActive(){return this.active}get hasAttempted(){return this.attempted}markSettled(){this.active=!1}markAssistantSucceeded(){this.attempted=!1}shouldRecover(e){return!this.deps.isImageRecoveryActive()&&rs(e)}recover(e,t){let n=this.deps.getTurnSignal(),r=t&&n?AbortSignal.any([t,n]):t??n,i=this.deps.getAgent();if(!i||this.deps.isDisposed()||r?.aborted)return;if(this.attempted){this.escalate(r);return}this.attempted=!0,this.active=!0,VD.warn(`Context overflow detected, attempting recovery`,{folder:this.deps.folder,messageCount:e.length});let a=this.deps.getCompactFn(),o=i.state.messages,s=o[o.length-1],c=s?.role===`assistant`&&rs(s)?o.slice(0,-1):o;if(i.state.messages=c,!a||!i.state.model||!this.deps.getCompactionApiKey()){this.escalate(r,Error(`Compaction is unavailable`));return}this.pending=this.compactAndResume(i,a,c,r)}async compactAndResume(e,t,n,r){try{let i=await t(n,r,{force:!0});if(this.deps.isDisposed()||r?.aborted||this.deps.getAgent()!==e)return;if(!fn(n,i)){this.escalate(r,Error(`Forced compaction did not reduce the context`));return}e.state.messages=i,this.deps.onResponse(`Context window exceeded — compacting history and continuing...`,!1),await new Promise(t=>{setTimeout(()=>{if(this.deps.isDisposed()||r?.aborted||this.deps.getAgent()!==e){t();return}e.continue().then(t).catch(e=>{!this.deps.isDisposed()&&!r?.aborted&&this.escalate(r,e),t()})},100)})}catch(e){!this.deps.isDisposed()&&!r?.aborted&&this.escalate(r,e)}finally{this.active=!1}}escalate(e,t){if(this.active=!1,this.deps.isDisposed()||e?.aborted||this.escalated)return;this.escalated=!0;let n=t instanceof Error?t.message:t?String(t):void 0;VD.error(`Context overflow recovery exhausted`,{folder:this.deps.folder,error:n}),this.deps.setStatus(`error`),this.deps.onExhausted(`Scoop "${this.deps.scoopName}" context window was exceeded and could not be reduced. Re-delegate with a narrower task.`)}},UD=class{deps;turnCount=0;exceededNote=null;wallClockTimer=null;constructor(e){this.deps=e}arm(){this.turnCount=0,this.exceededNote=null;let e=this.deps.getConfig()?.maxWallClockMs;typeof e==`number`&&Number.isFinite(e)&&e>0&&(this.wallClockTimer=setTimeout(()=>{this.wallClockTimer=null,this.trip(`wall-clock bound (${e} ms) exceeded`)},e))}recordCompletedTurn(){this.turnCount+=1}enforceOnTurnStart(){let e=this.deps.getConfig()?.maxTurns;typeof e==`number`&&e>0&&this.turnCount>=e&&this.trip(`turn bound (${e}) exceeded`)}disarm(){this.wallClockTimer!==null&&(clearTimeout(this.wallClockTimer),this.wallClockTimer=null)}takeExceededNote(){let e=this.exceededNote;return this.exceededNote=null,e}trip(e){this.exceededNote!==null||this.deps.isDisposed()||(this.exceededNote=e,this.deps.onTripped())}};function WD(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function GD(e,t){return!WD(e,t)}function KD(e){let t=e.captureStructuredOutput,n;return n=new M_({initialState:{model:e.model,tools:e.tools,systemPrompt:e.systemPrompt,messages:e.messages,thinkingLevel:e.thinkingLevel},getApiKey:e.getApiKey,transformContext:async(t,r)=>{let i=await e.transformContext(t,r);return r?.aborted||!GD(t,i)?t:WD(n.state.messages,t)?(t.splice(0,t.length,...i),n.state.messages=[...i],e.onContextCompacted?.(),t):i},streamFn:e.streamFn,afterToolCall:async e=>{t&&e.toolCall.name===`StructuredOutput`&&t(e.args)}}),n}const qD=_(`scoop-context`);async function JD(e,t,n,r){if(!e)return;let i=n.policy.filesystem.kind===`full-workspace`?[n.workspace.root,`/shared`,`/scoops`,`/home`,`/home/user`,er,r,`/mnt`]:[`/scoops/${t.folder}`,`/scoops/${t.folder}/workspace`,`/scoops/${t.folder}/home`,`/scoops/${t.folder}/tmp`,`/shared`,er,r];for(let t of i)try{await e.mkdir(t,{recursive:!0})}catch{}let a=n.workspace.memoryPath;try{await e.readFile(a)}catch{let r=`# ${t.assistantLabel} Memory
1149
+ ---`);let u=ST(i);return u&&(l+=u),l}const xD=_(`scoop-context`);function SD(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!sn(t).includes(`xhigh`)?`high`:e}function CD(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(dr.includes(e))return e;xD.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}const wD=_(`scoop-context`);function TD(e,t){let n=gD(t);e.state.model=n;let r=Vn(t),i=CD()??r.level;return e.state.thinkingLevel=SD(i,n),wD.info(`Model updated on running agent`,{folder:t.folder,model:n.id,thinkingLevel:e.state.thinkingLevel}),n.reasoning?r.effortOverride:void 0}function ED(e,t){if(CD())return e.state.thinkingLevel;let n=SD(t,e.state.model);return e.state.thinkingLevel=n,n}async function DD(e,t){let n=await yT(t.skillsFs??t.fs,sr),r=await fD(t.fs,t.unit.workspace.memoryPath),i=await t.getGlobalMemory();e.state.systemPrompt=bD(t.scoop,t.unit,i,r,n),wD.info(`Skills reloaded`,{folder:t.scoop.folder,skillCount:n.length})}const OD=_(`scoop-context`);var kD=class{deps;attempted=!1;active=!1;escalated=!1;pending=null;constructor(e){this.deps=e}resetForRun(){this.attempted=!1,this.active=!1,this.pending=null,this.escalated=!1}get pendingRecovery(){return this.pending}clearPendingRecovery(e){this.pending===e&&(this.pending=null)}get isActive(){return this.active}get hasAttempted(){return this.attempted}markSettled(){this.active=!1}markAssistantSucceeded(){this.attempted=!1}shouldRecover(e){return!this.deps.isImageRecoveryActive()&&Go(e)}recover(e,t){let n=this.deps.getTurnSignal(),r=t&&n?AbortSignal.any([t,n]):t??n,i=this.deps.getAgent();if(!i||this.deps.isDisposed()||r?.aborted)return;if(this.attempted){this.escalate(r);return}this.attempted=!0,this.active=!0,OD.warn(`Context overflow detected, attempting recovery`,{folder:this.deps.folder,messageCount:e.length});let a=this.deps.getCompactFn(),o=i.state.messages,s=o[o.length-1],c=s?.role===`assistant`&&Go(s)?o.slice(0,-1):o;if(i.state.messages=c,!a||!i.state.model||!this.deps.getCompactionApiKey()){this.escalate(r,Error(`Compaction is unavailable`));return}this.pending=this.compactAndResume(i,a,c,r)}async compactAndResume(e,t,n,r){try{let i=await t(n,r,{force:!0});if(this.deps.isDisposed()||r?.aborted||this.deps.getAgent()!==e)return;if(!hn(n,i)){this.escalate(r,Error(`Forced compaction did not reduce the context`));return}e.state.messages=i,this.deps.onResponse(`Context window exceeded — compacting history and continuing...`,!1),await new Promise(t=>{setTimeout(()=>{if(this.deps.isDisposed()||r?.aborted||this.deps.getAgent()!==e){t();return}e.continue().then(t).catch(e=>{!this.deps.isDisposed()&&!r?.aborted&&this.escalate(r,e),t()})},100)})}catch(e){!this.deps.isDisposed()&&!r?.aborted&&this.escalate(r,e)}finally{this.active=!1}}escalate(e,t){if(this.active=!1,this.deps.isDisposed()||e?.aborted||this.escalated)return;this.escalated=!0;let n=t instanceof Error?t.message:t?String(t):void 0;OD.error(`Context overflow recovery exhausted`,{folder:this.deps.folder,error:n}),this.deps.setStatus(`error`),this.deps.onExhausted(`Scoop "${this.deps.scoopName}" context window was exceeded and could not be reduced. Re-delegate with a narrower task.`)}},AD=class{deps;turnCount=0;exceededNote=null;wallClockTimer=null;constructor(e){this.deps=e}arm(){this.turnCount=0,this.exceededNote=null;let e=this.deps.getConfig()?.maxWallClockMs;typeof e==`number`&&Number.isFinite(e)&&e>0&&(this.wallClockTimer=setTimeout(()=>{this.wallClockTimer=null,this.trip(`wall-clock bound (${e} ms) exceeded`)},e))}recordCompletedTurn(){this.turnCount+=1}enforceOnTurnStart(){let e=this.deps.getConfig()?.maxTurns;typeof e==`number`&&e>0&&this.turnCount>=e&&this.trip(`turn bound (${e}) exceeded`)}disarm(){this.wallClockTimer!==null&&(clearTimeout(this.wallClockTimer),this.wallClockTimer=null)}takeExceededNote(){let e=this.exceededNote;return this.exceededNote=null,e}trip(e){this.exceededNote!==null||this.deps.isDisposed()||(this.exceededNote=e,this.deps.onTripped())}};function jD(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function MD(e,t){return!jD(e,t)}function ND(e){let t=e.captureStructuredOutput,n;return n=new b_({initialState:{model:e.model,tools:e.tools,systemPrompt:e.systemPrompt,messages:e.messages,thinkingLevel:e.thinkingLevel},getApiKey:e.getApiKey,transformContext:async(t,r)=>{let i=await e.transformContext(t,r);return r?.aborted||!MD(t,i)?t:jD(n.state.messages,t)?(t.splice(0,t.length,...i),n.state.messages=[...i],e.onContextCompacted?.(),t):i},streamFn:e.streamFn,afterToolCall:async e=>{t&&e.toolCall.name===`StructuredOutput`&&t(e.args)}}),n}const PD=_(`scoop-context`);async function FD(e,t,n,r){if(!e)return;let i=n.policy.filesystem.kind===`full-workspace`?[n.workspace.root,`/shared`,`/scoops`,`/home`,`/home/user`,rr,r,`/mnt`]:[`/scoops/${t.folder}`,`/scoops/${t.folder}/workspace`,`/scoops/${t.folder}/home`,`/scoops/${t.folder}/tmp`,`/shared`,rr,r];for(let t of i)try{await e.mkdir(t,{recursive:!0})}catch{}let a=n.workspace.memoryPath;try{await e.readFile(a)}catch{let r=`# ${t.assistantLabel} Memory
1150
1150
 
1151
1151
  ${n.display.role===`primary`?`Role: Cone (main orchestrator)`:`Scoop: ${t.name}`}
1152
1152
  Folder: ${t.folder}
@@ -1157,30 +1157,30 @@ Created: ${new Date().toISOString()}
1157
1157
 
1158
1158
  ## Context
1159
1159
  (Add important context here)
1160
- `;try{await e.writeFile(a,r)}catch(r){let i=r?.code;if(i===`EACCES`)qD.debug(`Skipping default memory write (sandbox is read-only)`,{folder:t.folder,path:a});else if(await YD(e,n.workspace.root))throw r;else throw Error(`workspace filesystem unavailable: ${n.workspace.root} is missing and could not be created (${i??`unknown error`}) — reload the session`,{cause:r})}}}async function YD(e,t){try{return await e.exists(t)}catch{return!1}}async function XD(e,t){let n=await Qr(t.scoop,t.coneJid),r=(e,r,i)=>{let a=t.getEffortOverride(),o=a?{...i,effort:a}:i;return e.provider===`adobe`?an(e,r,{...o,headers:{...i?.headers,"X-Session-Id":n}}):an(e,r,o)},i=e.provider===`adobe`?{"X-Session-Id":n}:void 0,a=()=>t.getModelApiKey()??void 0,o=t.appendConeMemory,s=t.unit.policy.canWriteSharedMemory&&o?n=>o(n,{source:`compaction`,model:e,apiKey:t.getModelApiKey()??void 0,headers:i}):void 0;return{streamWithSessionId:r,compactFn:pn({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:a,headers:i,onMemoryUpdates:s,shouldExtractMemories:()=>!Na(`agentic-memory`),onCompactionStateChange:(e,n)=>{t.onCompactionStateChange?.(e,n)},onBeforeCompaction:t.onBeforeCompaction}),getCompactionApiKey:a}}_(`secret-env`);function ZD(e){let t={},n;for(let r of e)!r?.name||!r?.maskedValue||(r.name===`oauth.github.token`&&(n=r.maskedValue),g(r.name)&&(t[r.name]=r.maskedValue));return n&&(t.GITHUB_TOKEN===void 0&&(t.GITHUB_TOKEN=n),t.GH_TOKEN===void 0&&(t.GH_TOKEN=n)),t}const QD={writeFile:0,appendFile:0,rename:1,copyFile:1,symlink:1};function $D(e){return new A(`EACCES`,ni,xn(e))}async function eO(e,t){let n=xn(t);try{return xn(await e.realpath(n))}catch{}let r=n.lastIndexOf(`/`);if(r<=0)return n;try{let t=xn(await e.realpath(n.slice(0,r)));return`${t===`/`?``:t}/${n.slice(r+1)}`}catch{return n}}function tO(e){let t={};for(let n of Object.keys(QD)){let r=e[n];if(typeof r!=`function`)continue;let i=QD[n];t[n]=async(...t)=>{let n=t[i];if(typeof n==`string`){if(ri(n))throw $D(n);let t=await eO(e,n);if(ri(t))throw $D(n)}return r.apply(e,t)}}return new Proxy(e,{get(e,n,r){if(n===Yr)return!0;if(typeof n==`string`&&n in t)return t[n];let i=Reflect.get(e,n,r);return typeof i==`function`?i.bind(e):i}})}function nO(e){let{isCone:t,folder:n,secretEnv:r,tmpDir:i,lickTarget:a}=e,o=a?{[xi]:a}:{};return t?{...r,TMPDIR:i,...o}:{...r,HOME:`/scoops/${n}/home`,TMPDIR:i,USER:n,PATH:[`/usr/bin`,`/scoops/${n}/workspace/skills`,`/scoops/${n}/workspace/bin`,...ai].join(`:`),...o}}function rO(e,t,n){return e.display.role===`child`?t.folder:t.jid===n?void 0:t.folder}function iO({sudoManager:e,unit:t,folder:n,onSudoRequest:r}){if(!e)return null;let i=e,{policy:a}=t,o=a.approvalAuthority===`user`,s=r,c=o||!s?i.getBroker():{requestApproval:e=>s(e)},l=o?()=>i.getPolicy():()=>i.getPolicyForScoop(n),u=a.sudoDefaultDisposition,d=i.getShellConfig(),f=a.persistCommandGrants?d.persistCommandGrant:async()=>{},p={broker:c,getPolicy:l,defaultDisposition:u,shellConfig:{...d,broker:c,getPolicy:l,defaultDisposition:u,persistCommandGrant:f}};return a.persistCommandGrants||(p.onGrant=async()=>{}),p}const aO=_(`scoop-context`);async function oO(e){try{let t=await e.secrets.listMaskedEnv();return t.ok?Array.isArray(t.value.entries)?ZD(t.value.entries):(aO.warn(`Masked secrets response was not an array`,{entriesType:typeof t.value.entries}),{}):(aO.warn(`Failed to fetch masked secrets`,{capability:t.capability,operation:t.operation,message:t.message,status:`status`in t?t.status:void 0}),{})}catch(e){return aO.warn(`Failed to fetch masked secrets`,{error:e instanceof Error?e.message:String(e)}),{}}}async function sO(e){let{scoop:t,unit:n,fs:i,skillsFs:a}=e,o=n.workspace.root,s=e.getBrowserAPI();n.policy.filesystem.kind===`full-workspace`&&await IT(i,ir);let c=a??i,l=e.capabilityBroker??r(),u=await oO(l),d=await l.network.localNodeServer(),f=()=>d.ok,p=iO({sudoManager:e.sudoManager,unit:n,folder:t.folder,onSudoRequest:e.onSudoRequest}),m=p?Xr(i,{broker:p.broker,getPolicy:p.getPolicy,defaultDisposition:p.defaultDisposition,...p.onGrant?{onGrant:p.onGrant}:{}}):i,h=tO(m),g=nO({isCone:n.policy.filesystem.kind===`full-workspace`,folder:t.folder,secretEnv:u,tmpDir:e.tmpDir,...e.lickTarget?{lickTarget:e.lickTarget}:{}}),te=new ee({fs:h,cwd:o,env:Object.keys(g).length>0?g:void 0,browserAPI:s,webhook:{hasLocalNodeServer:f,getLeaderStatus:Dr},crontask:{hasLocalNodeServer:f},jshDiscoveryFs:a?c:void 0,allowedCommands:t.config?.allowedCommands,getParentJid:()=>t.jid,isScoop:()=>n.display.role===`child`,sudo:p?.shellConfig,scrubProgressLabel:cn(),processManager:e.processManager??void 0,processOwner:e.processOwner,getCurrentShellPid:e.getTurnPid});return aO.info(`AlmostBashShell initialized`,{folder:t.folder}),{shell:te,gatedFs:h,memoryFs:m,skills:await MT(c,ir)}}const cO={anthropic:`Anthropic`,openai:`OpenAI`,google:`Google`,adobe:`Adobe`,github:`GitHub`,bedrock:`AWS Bedrock`,azure:`Azure`,"azure-openai":`Azure OpenAI`,"azure-ai-foundry":`Azure AI Foundry`,groq:`Groq`,xai:`xAI`,openrouter:`OpenRouter`,local:`your local model`};function lO(e){if(e)return cO[e]??e}const uO=51200;function dO(e){if(e.length===0)return[];let t=e.split(`
1160
+ `;try{await e.writeFile(a,r)}catch(r){let i=r?.code;if(i===`EACCES`)PD.debug(`Skipping default memory write (sandbox is read-only)`,{folder:t.folder,path:a});else if(await ID(e,n.workspace.root))throw r;else throw Error(`workspace filesystem unavailable: ${n.workspace.root} is missing and could not be created (${i??`unknown error`}) — reload the session`,{cause:r})}}}async function ID(e,t){try{return await e.exists(t)}catch{return!1}}async function LD(e,t){let n=await ti(t.scoop,t.coneJid),r=(e,r,i)=>{let a=t.getEffortOverride(),o=a?{...i,effort:a}:i;return e.provider===`adobe`?cn(e,r,{...o,headers:{...i?.headers,"X-Session-Id":n}}):cn(e,r,o)},i=e.provider===`adobe`?{"X-Session-Id":n}:void 0,a=()=>t.getModelApiKey()??void 0,o=t.appendConeMemory,s=t.unit.policy.canWriteSharedMemory&&o?n=>o(n,{source:`compaction`,model:e,apiKey:t.getModelApiKey()??void 0,headers:i}):void 0;return{streamWithSessionId:r,compactFn:gn({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:a,headers:i,onMemoryUpdates:s,shouldExtractMemories:()=>!ke(`agentic-memory`),onCompactionStateChange:(e,n)=>{t.onCompactionStateChange?.(e,n)},onBeforeCompaction:t.onBeforeCompaction}),getCompactionApiKey:a}}_(`secret-env`);function RD(e){let t={},n;for(let r of e)!r?.name||!r?.maskedValue||(r.name===`oauth.github.token`&&(n=r.maskedValue),g(r.name)&&(t[r.name]=r.maskedValue));return n&&(t.GITHUB_TOKEN===void 0&&(t.GITHUB_TOKEN=n),t.GH_TOKEN===void 0&&(t.GH_TOKEN=n)),t}const zD={writeFile:0,appendFile:0,rename:1,copyFile:1,symlink:1};function BD(e){return new A(`EACCES`,ai,wn(e))}async function VD(e,t){let n=wn(t);try{return wn(await e.realpath(n))}catch{}let r=n.lastIndexOf(`/`);if(r<=0)return n;try{let t=wn(await e.realpath(n.slice(0,r)));return`${t===`/`?``:t}/${n.slice(r+1)}`}catch{return n}}function HD(e){let t={};for(let n of Object.keys(zD)){let r=e[n];if(typeof r!=`function`)continue;let i=zD[n];t[n]=async(...t)=>{let n=t[i];if(typeof n==`string`){if(oi(n))throw BD(n);let t=await VD(e,n);if(oi(t))throw BD(n)}return r.apply(e,t)}}return new Proxy(e,{get(e,n,r){if(n===Qr)return!0;if(typeof n==`string`&&n in t)return t[n];let i=Reflect.get(e,n,r);return typeof i==`function`?i.bind(e):i}})}function UD(e){let{isCone:t,folder:n,secretEnv:r,tmpDir:i,lickTarget:a}=e,o=a?{[wi]:a}:{};return t?{...r,TMPDIR:i,...o}:{...r,HOME:`/scoops/${n}/home`,TMPDIR:i,USER:n,PATH:[`/usr/bin`,`/scoops/${n}/workspace/skills`,`/scoops/${n}/workspace/bin`,...ci].join(`:`),...o}}function WD(e,t,n){return e.display.role===`child`?t.folder:t.jid===n?void 0:t.folder}function GD({sudoManager:e,unit:t,folder:n,onSudoRequest:r}){if(!e)return null;let i=e,{policy:a}=t,o=a.approvalAuthority===`user`,s=r,c=o||!s?i.getBroker():{requestApproval:e=>s(e)},l=o?()=>i.getPolicy():()=>i.getPolicyForScoop(n),u=a.sudoDefaultDisposition,d=i.getShellConfig(),f=a.persistCommandGrants?d.persistCommandGrant:async()=>{},p={broker:c,getPolicy:l,defaultDisposition:u,shellConfig:{...d,broker:c,getPolicy:l,defaultDisposition:u,persistCommandGrant:f}};return a.persistCommandGrants||(p.onGrant=async()=>{}),p}const KD=_(`scoop-context`);async function qD(e){try{let t=await e.secrets.listMaskedEnv();return t.ok?Array.isArray(t.value.entries)?RD(t.value.entries):(KD.warn(`Masked secrets response was not an array`,{entriesType:typeof t.value.entries}),{}):(KD.warn(`Failed to fetch masked secrets`,{capability:t.capability,operation:t.operation,message:t.message,status:`status`in t?t.status:void 0}),{})}catch(e){return KD.warn(`Failed to fetch masked secrets`,{error:e instanceof Error?e.message:String(e)}),{}}}async function JD(e){let{scoop:t,unit:n,fs:i,skillsFs:a}=e,o=n.workspace.root,s=e.getBrowserAPI();n.policy.filesystem.kind===`full-workspace`&&await CT(i,sr);let c=a??i,l=e.capabilityBroker??r(),u=await qD(l),d=await l.network.localNodeServer(),f=()=>d.ok,p=GD({sudoManager:e.sudoManager,unit:n,folder:t.folder,onSudoRequest:e.onSudoRequest}),m=p?$r(i,{broker:p.broker,getPolicy:p.getPolicy,defaultDisposition:p.defaultDisposition,...p.onGrant?{onGrant:p.onGrant}:{}}):i,h=HD(m),g=UD({isCone:n.policy.filesystem.kind===`full-workspace`,folder:t.folder,secretEnv:u,tmpDir:e.tmpDir,...e.lickTarget?{lickTarget:e.lickTarget}:{}}),te=new ee({fs:h,cwd:o,env:Object.keys(g).length>0?g:void 0,browserAPI:s,webhook:{hasLocalNodeServer:f,getLeaderStatus:Ar},crontask:{hasLocalNodeServer:f},jshDiscoveryFs:a?c:void 0,allowedCommands:t.config?.allowedCommands,getParentJid:()=>t.jid,isScoop:()=>n.display.role===`child`,sudo:p?.shellConfig,scrubProgressLabel:dn(),processManager:e.processManager??void 0,processOwner:e.processOwner,getCurrentShellPid:e.getTurnPid});return KD.info(`AlmostBashShell initialized`,{folder:t.folder}),{shell:te,gatedFs:h,memoryFs:m,skills:await yT(c,sr)}}const YD={anthropic:`Anthropic`,openai:`OpenAI`,google:`Google`,adobe:`Adobe`,github:`GitHub`,bedrock:`AWS Bedrock`,azure:`Azure`,"azure-openai":`Azure OpenAI`,"azure-ai-foundry":`Azure AI Foundry`,groq:`Groq`,xai:`xAI`,openrouter:`OpenRouter`,local:`your local model`};function XD(e){if(e)return YD[e]??e}const ZD=51200;function QD(e){if(e.length===0)return[];let t=e.split(`
1161
1161
  `);return e.endsWith(`
1162
- `)&&t.pop(),t}function fO(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}function pO(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=dO(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};if(Buffer.byteLength(a[0],`utf-8`)>r)return{content:``,truncated:!0,truncatedBy:`bytes`,totalLines:o,totalBytes:i,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`;for(let e=0;e<a.length&&e<n;e++){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(e>0);if(c+n>r){l=`bytes`;break}s.push(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let u=s.join(`
1163
- `),d=Buffer.byteLength(u,`utf-8`);return{content:u,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:d,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function mO(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=dO(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`,u=!1;for(let e=a.length-1;e>=0&&s.length<n;e--){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(s.length>0);if(c+n>r){if(l=`bytes`,s.length===0){let e=hO(t,r);s.unshift(e),c=Buffer.byteLength(e,`utf-8`),u=!0}break}s.unshift(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let d=s.join(`
1164
- `),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 hO(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 gO=_(`tool:bash`),_O=40960,vO=1048576,yO=`\0slicc-img:`;function bO(e){let t=gn(e).filter(e=>e.kind===`image`);if(t.length===0)return{text:e,markers:new Map};let n=new Set,r=vO;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=`${yO}${r}`;i.set(e,t.marker),a+=e}else a+=`[image dropped: a newer image in this command used up the ${vO/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 xO(e){let t=gn(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 SO(e){return e.replaceAll(RegExp(`${yO}\\d+`,`g`),`[image]`)}function CO(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 wO(e,t,n,r){let{text:i,markers:a}=bO(e),o=mO(i,{maxBytes:_O});if(!o.truncated)return CO(i,a);let s=`showing the last ${fO(o.outputBytes)} of ${fO(o.totalBytes)} (${o.totalLines} lines)`,c=`${n}/bash-output-${r()}.txt`;try{return await t.writeFile(c,SO(i)),CO(`${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 gO.warn(`Failed to persist full bash output`,{error:e instanceof Error?e.message:String(e)}),CO(`${o.content}\n\n[Output truncated: ${s}. Re-run piping through \`head\`/\`tail\`/\`grep\`/\`sed -n\` to narrow the output.]`,a)}}const TO=new Set([`grep`,`egrep`,`fgrep`,`rg`]);function EO(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 DO(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=EO(r.name);if(i!==`command`)return i;let a=r.args[0];return a?EO(a):null}function OO(e,t,n,r){if(n!==1||r.trim())return!1;let i;try{i=DO(e.getBash().transform(t).ast)}catch{return!1}return i!==null&&TO.has(i)}function kO(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return e}function AO(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 ${_O/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 ${vO/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 jO(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 MO(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 NO(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 RO(e,n,r);await e.fs.writeFile(t,i)}).catch(e=>gO.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:(e,t)=>{s=e,c=t,u()},flushPersist:()=>l,killedByTimeout:!1}}function PO(e,t){t===`timeout`&&(e.killedByTimeout=!0),e.job?.kill(),e.controller.abort(),e.job?.exit(null)}function FO(e,t){e.job?.exit(e.job.signal.aborted?null:t)}function IO(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 LO(e,t,n,r={}){let i=0,a=0,o={shell:e,fs:t,tempDir:n,options:r,defaultBackgroundAfter:kO(r.defaultBackgroundAfterSeconds)??600,nextOutputSeq:()=>i+=1,nextJobId:()=>`bg-${a+=1}`};return{name:`bash`,description:AO(o.defaultBackgroundAfter),inputSchema:jO(o.defaultBackgroundAfter),execute:(e,t)=>WO(o,e,t)}}async function RO(e,t,n){let r=e.options.scrubOutput;if(!r||!n)return n;try{return await r(n)}catch(e){return gO.warn(`Background bash output scrub failed; withholding output`,{jobId:t,error:e instanceof Error?e.message:String(e)}),`[output withheld: secret scrub unavailable]`}}function zO(e){return e.ok?e.result.exitCode===124&&/execution aborted/i.test(e.result.stderr):/execution aborted/i.test(e.error)}function BO(e,t){return e===void 0?`--- killed (exit ${t}) ---\n`:`--- killed after ${e}s (exit ${t}) ---\n`}async function VO(e,t,n,r,i,a,s,c){await s.flushPersist();let l=s.killedByTimeout||zO(a),u,d;if(l){let e=s.getTeedOutput();d=124,u=`${e.endsWith(`
1165
- `)||e.length===0?e:`${e}\n`}${BO(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(`
1166
- `)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let f=await RO(e,t,u),p;try{await e.fs.writeFile(i,f),p=i}catch(e){gO.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){gO.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:d});return}let m=mO(xO(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 HO(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=i===void 0?void 0:i-a,u=l===void 0?void 0:setTimeout(()=>PO(t,`timeout`),l*1e3);return t.settled.then(r=>(u!==void 0&&clearTimeout(u),FO(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),VO(e,o,s,n,c,r,t,i))).catch(e=>gO.error(`Background bash delivery failed`,{jobId:o,error:e})),gO.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:l}),IO(o,s,r,c,i)}async function UO(e,t,n){gO.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=o(r,n.pipeStatus),{content:await wO(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!OO(e.shell,t,n.exitCode,n.stderr)}}async function WO(e,t,n){let r=t.command,i=kO(t.timeout),a=kO(t.background_after)??e.defaultBackgroundAfter;gO.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=NO(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?(PO(o,`timeout`),gO.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),MO(c)):t===`elapsed`?HO(e,o,r,c,i,a):(FO(o,t.ok?t.result.exitCode:1),t.ok?await UO(e,r,t.result):(gO.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const GO={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 KO(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function qO(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:KO(e)&&(t.edits=[e])}catch{}else KO(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 JO(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:GO,prepareArguments:qO,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-C2vx7I8W.js`);return i(e,t,n,r)}}}async function YO(e,t,n){if(kr(xn(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 XO=_(`tool:fs`);function ZO(e,t=`/workspace`){return[QO(e),$O(e),JO(e,t)]}function QO(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${uO/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;XO.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
1167
- `),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=pO(c.join(`
1168
- `));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${fO(new TextEncoder().encode(t[o]??``).length)}, exceeds ${fO(uO)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${uO}]`};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} (${fO(uO)} 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 XO.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function $O(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;XO.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await YO(e,n,r);return t?(XO.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 XO.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const ek={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 tk(e,t){return{name:ti,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:ek,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-E9mWyIAl.js`);return r(e,t,n)}}}function nk(){return null}const rk=_(`tool:request-secret`);async function ik(e,t){let n=nk();if(n)return n(e);let r=t.callPanelRpc??await ak();return r?r(e):{stored:!1,reason:`unavailable`}}async function ak(){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 ok(e){try{return e.getProvider?.()||void 0}catch(e){rk.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function sk(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 ck(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(`
1169
- `)}function lk(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 uk(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:sk(t.domains),persist:t.persist===!0,requester:e.requester,provider:ok(e)},a;try{a=await ik(i,e)}catch(e){let t=e instanceof Error?e.message:String(e);return rk.error(`secret request failed`,{name:n,error:t}),{content:`The secret prompt failed: ${t}`,isError:!0}}if(!a.stored)return{content:lk(a),isError:!0};let o=dk(a.name,a.maskedValue,e);return rk.info(`secret stored via request_secret`,{name:a.name,persisted:a.persisted}),{content:ck(a,o)}}}}function dk(e,t,n){if(!n.setEnv||!t||!g(e))return!1;try{return n.setEnv(e,t),!0}catch(t){return rk.warn(`could not inject the masked value into the shell env`,{name:e,error:t instanceof Error?t.message:String(t)}),!1}}const fk=_(`scoop-management-tools`),pk=`cross_cone`;function mk(e){return kn(e.getScoops(),e.scoop.jid)}function hk(e){let t=new Set;for(let n of mk(e))n.jid!==e.scoop.jid&&n.parentJid!==null&&t.add(n.jid);return t}function gk(e){let t=Nn(e.getScoops());return t!==void 0&&t.jid===e.scoop.jid}function _k(e){let t=e.getScoops(),n=hk(e),r=gk(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=Yn(t,e);a.kind!==`cycle`&&i.push({scoop:e,relation:a.kind===`root`?`foreign`:`inherited`})}return i}function vk(e){return t=>t.folder===e||t.name===e}function yk(e,t){let n=_k(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 bk(e,t){let n=[],r=[];for(let i of e){let e=yk(i,t);e?n.push(e):r.push(i)}return{resolved:n,unknown:r}}function xk(e,t){return jn(e.getScoops(),t.scoop)?.folder??`unknown`}function Sk(e,t){return t.relation===`inherited`?`inherited (its owning cone is gone)`:`owned by cone "${xk(e,t)}"`}function Ck(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 ${Sk(r,e)}`).join(`; `)}. Pass ${pk}: true to act on it anyway.`,isError:!0}}function wk(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 Tk=[`command`,`read`,`write`,`secret`];function Ek(e){return`${be(e,{maxLen:50})}-scoop`}function Dk(e){return e===void 0?{ok:!0}:sr(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${cr.join(`, `)}.`,isError:!0}}function Ok(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 kk(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 Ak(e,t){let n=_k(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 jk(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 Mk(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),fk.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function Nk(e){let{kind:t,detail:n,suggested_pattern:r,reason:i}=e;if(!Tk.includes(t))return{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${Tk.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 Pk(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(`
1170
- `)}async function Fk(e,t){let n=Nk(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return fk.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:Pk(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function Ik(e,t){let{scoop_name:n,prompt:r,cross_cone:i}=e;if(vk(n)(t.scoop))return{content:`Cannot feed yourself.`,isError:!0};let a=yk(n,t);if(!a)return Ak([n],t);let o=Ck([a],i,`feed "${n}"`,t);if(o)return o;try{await t.onFeedScoop(a.scoop.jid,r),fk.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 (${pk}: 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 Lk(e,t){return t.relation===`own`?``:t.relation===`inherited`?` [INHERITED]`:` [FOREIGN: ${xk(e,t)}]`}async function Rk(e){let t=new Map(_k(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 jk(n,e.getScoopTabState,r?Lk(e,r):``)}).join(`
1171
- `)}`}}function zk({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}:{},...Bk(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 Bk(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function Vk(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return fk.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 Hk(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=En(s);if(!f.ok)return{content:f.error,isError:!0};let p=Dk(l);if(!p.ok)return{content:p.content,isError:p.isError};let m=Ok(u);if(!m.ok)return{content:m.content,isError:!0};let h=kk(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let ee=Ek(n),g=mk(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=Ln(ee,t.getScoops().map(e=>e.folder));try{let e=zk({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:rr(or(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return fk.info(`Scoop created`,{name:n,folder:te}),i&&t.onFeedScoop?Vk(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 Uk(e,t){let{scoop_name:n,cross_cone:r}=e;if(vk(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=yk(n,t);if(!i)return Ak([n],t);let a=Ck([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),fk.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 Wk(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function Gk(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return Wk();let{resolved:i,unknown:a}=bk(n,t);return i.length===0?Ak(a,t):Ck(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),fk.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 Kk(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 qk(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return Wk();let{resolved:i,unknown:a}=bk(n,t);if(i.length===0)return Ak(a,t);let o=Ck(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);fk.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(...Kk(l,c)),{content:u.join(`
1172
- `)}}function Jk(e,t){return!Array.isArray(e)||e.length===0?Wk():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 Yk(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 Xk(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=Jk(n,r);if(a)return a;let{resolved:o,unknown:s}=bk(n,t);if(o.length===0)return Ak(s,t);let c=Ck(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 fk.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:Yk(f,s,p,r)}}function Zk(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 Qk(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?(fk.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:Zk(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 $k(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?(fk.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 eA(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(`
1173
- `)}`}}async function tA(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),fk.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 nA(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=>Mk(t,e)}}function rA(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:[...Tk],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=>Fk(t,e)}}function iA(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.`},[pk]:wk(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>Ik(t,e)}}function aA(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:()=>Rk(e)}}function oA(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:[...cr],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=>Hk(t,e)}}function sA(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.`},[pk]:wk(`drop`)},required:[`scoop_name`]},execute:t=>Uk(t,e)}}function cA(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"]).`},[pk]:wk(`mute`)},required:[`scoop_names`]},execute:t=>Gk(t,e)}}function lA(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"]).`},[pk]:wk(`unmute`)},required:[`scoop_names`]},execute:t=>qk(t,e)}}function uA(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."},[pk]:wk(`wait on`)},required:[`scoop_names`]},execute:t=>Xk(t,e)}}function dA(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=>Qk(t,e)}}function fA(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=>$k(t,e)}}function pA(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:()=>eA(e)}}function mA(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=>tA(t,e)}}function hA(e){let t=[],n=An(e.scoop);return On(e.scoop)||(t.push(nA(e)),e.onSudoRequest&&t.push(rA(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(oA(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(iA(e)),t.push(aA(e)),e.onDropScoop&&t.push(sA(e)),e.onMuteScoops&&t.push(cA(e)),e.onUnmuteScoops&&t.push(lA(e)),e.onScheduleScoopWait&&t.push(uA(e)),e.onSudoResolve&&(t.push(dA(e)),t.push(fA(e))),e.onListSudoRequests&&t.push(pA(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(mA(e))),t}const gA=_(`scoop-context`);function _A(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-yzMDXmb7.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function vA(e){let{scoop:t,unit:n,callbacks:r}=e,i=hA({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=ZO(e.gatedFs,n.workspace.root),o=tk(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>uw);return t(e.fs)}}),s=[...a,o,LO(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:cn(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){gA.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i,uk({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>lO(kD(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);s.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let c={scrubToolResult:cn()},l=_A(e);return e.processManager?ln(s,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},c,l):ln(s,void 0,c,l)}const yA=_(`scoop-context`);async function bA(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();yA.info(`Filesystem ready`,{folder:t.folder}),await JD(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,skills:l}=await sO({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(o);let u=await vA({getTurnGuestGates:e.getTurnGuestGates,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:d,globalMemory:f}=await ED(r,n,()=>i.getGlobalMemory());if(!OD(t))return yA.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let p=AD(t,n),m=ND(t,n,f,d,l),h=await e.sessions.restore(),{streamWithSessionId:ee,compactFn:g,getCompactionApiKey:te}=await XD(p,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>OD(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let ne=Rn(t);return{kind:`ready`,agent:KD({model:p,tools:u,systemPrompt:m,messages:h,thinkingLevel:FD(ID()??ne.level,p),getApiKey:()=>OD(t)??void 0,transformContext:g,streamFn:ee,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:g,getCompactionApiKey:te,effortOverride:ne.effortOverride,toolCount:u.length}}const xA=_(`scoop-context`);var SA=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 xA.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=HC(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=un(n);return xA.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=>{xA.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){xA.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 CA(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 wA(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function TA(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const EA=_(`scoop-context`);var DA=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;EA.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)&&(EA.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:pD(r)}),!!(t<3&&(await mD(OA(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return fD(e)?(EA.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 Ja(e)?(EA.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Za(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(!pD(e)||t>=3)return!1;let r=OA(t);return EA.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await mD(r,n)&&!this.deps.isDisposed()}fail(e,t){rD(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function OA(e){return 1e3*2**(e-1)}function kA(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){EA.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 AA=_(`scoop-context`);var jA=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;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=tr(e),this.owner={kind:Fn(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 SA({store:r??null,canonical:c?{store:c,identity:wr(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 UD({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new xD({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new CD({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new HD({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 DA({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 rO(this.unit,this.scoop,k(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Qn(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 bA({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`),AA.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);AA.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(MD(this.scoop)),!1)}cleanupPromptState(e,t,n,r){this.runBounds.disarm();let i=this.runBounds.takeExceededNote();i!==null&&this.callbacks.onError(`agent run terminated: ${i}`),(n||r.aborted)&&this.sessions.persistNow(),this.isProcessing=!1,this.turnJournal?.end(this.scoop.jid),!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),wA(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(kA(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;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let a=CA(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:r});this.currentTurnProcess=a,this.runBounds.arm(),this.turnJournal?.begin(this.scoop.jid,this.scoop.folder,t,this.turnGuestGates);let o=null;try{if(o=await this.turnRunner.run(n,i),o&&!this.disposed&&!i.aborted){this.turnRunner.reportExhausted(o);return}!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,a,o,i)}}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(){TA(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0)}idleCompactionEnabled(){return Nx(this.scoop)?!0:this.unit.parentId===null&&Na(`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:dn,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&&!Na(`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-BSndLrLB.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-eLY2VPhg.js`).then(e=>e.r).then(n=>n.scheduleLiveDeltaCuration({vfs:e,cone:t})).catch(e=>{AA.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-BSndLrLB.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){AA.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 jD(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=RD(this.agent,this.scoop))}async reloadSkills(){this.agent&&await BD(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?ID()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,zD(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.turnJournal?.end(this.scoop.jid),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),TA(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 _D(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`&&AA.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||hD(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const Q=_(`scoop-lifecycle-manager`);var MA=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 eD(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))??k(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return jn(t.values(),e)??k(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Q.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof xr))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`)Q.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Q.debug(`Context already exists`,{jid:e});return}}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=tr(t).policy.filesystem;if(a.kind===`restricted`){let e=En(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new xr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:Tn(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 jA(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0,this.deps.getTurnJournal?.()??void 0);if(n.attachContext(l,i),await l.init(),this.units.get(e)!==n||n.context!==l)return;n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{Q.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),Q.info(`Scoop context created`,{jid:e,contextId:i})}async reinitAfterPromote(e){let t=this.units.get(e);if(t?.context){t.disposeContext();try{await this.createTab(e)}catch(n){let r=n instanceof Error?n.message:String(n);Q.warn(`Failed to re-init promoted unit; next prompt will retry`,{jid:e,error:r}),t.disposeContext(),this.markTabError(e,r)}}}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.deps.getScoops().get(e);if(o&&Nx(o)&&(await this.syncGelatiereModel(),!Gn(o)))throw Error(`The gelatiere cannot run until the leading cone has a model`);let s=this.getContext(e);s||=(await this.createTab(e),this.getContext(e));let c=this.units.get(e);if(c?.tab?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}s=this.getContext(e)}if(!s||!c){Q.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),c.tab&&c.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await s.prompt(t,i,a)}async resumeTurn(e,t,n){let r=this.getContext(e),i=this.units.get(e);!r||!i||r.isBusy||(this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),i.tab&&i.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),await r.resumeTurn(t,n))}async register(e){let t=this.deps.getScoops(),n=Nn(t.values())?.jid;if(qn(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=Ln(e.folder,n);r!==e.folder&&(Q.warn(`Scoop folder already taken — registering under a free variant`,{jid:e.jid,requested:e.folder,folder:r}),e.folder=r,e.trigger=`@${r}`,e.assistantLabel=r)}t.set(e.jid,e);try{await this.deps.db.saveScoop(e)}catch(n){throw t.delete(e.jid),n}this.deps.messageRouter.ensureQueue(e.jid),Q.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&NE(`spawn`,e.folder)}catch(n){Q.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){Q.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{Q.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}Nn(t.values())?.jid!==n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the new leading cone after registration`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}inheritModel(e){if(Nx(e)){let t=Nn(this.deps.getScoops().values());In(e,t?Gn(t):void 0);return}if(Pn(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Gn(t):void 0)??CE();n&&In(e,n)}async unregister(e){let t=this.deps.getScoops(),n=Nn(t.values())?.jid===e;for(let n of Xn(t.values(),e))await this.unregister(n.jid);let r=t.get(e);if(r&&r.parentJid===null&&k(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let i=this.deps.getLickManager();if(r&&i){let{webhooks:e,cronTasks:t}=await i.getLicksForScoopFromDb(r.name,r.folder),n=this.deps.buildActiveLicksError(r.folder,e,t);if(n)throw n}this.deps.costTracker.snapshot(e);let a=globalThis.__slicc_wsSubscribers;a&&a.dropForScoop(e).catch(t=>{Q.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),await Promise.all([r?this.deps.getConversationStore()?.delete(Cr(r)):void 0,this.deps.getSessionStore()?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})})]),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let o=this.deps.approvalRouter.failScoop(e);if(o>0&&Q.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:o}),r&&this.deps.getSudoManager()?.forgetScoopPolicies(r.folder),Q.info(`Scoop unregistered`,{jid:e}),r)try{this.deps.callbacks.onScoopUnregistered?.(r)}catch(t){Q.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the replacement leading cone after root removal`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;if(Nx(n))return await this.syncGelatiereModel(),!1;let r=Nn(this.deps.getScoops().values())?.jid===e,i=n.model;In(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return In(n,i),this.getContext(e)?.updateModel(),Q.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return r&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to synchronize gelatiere after leading model change`,{jid:e,error:t instanceof Error?t.message:String(t)})}),!0}syncGelatiereModel(){let e=this.gelatiereModelSync.then(()=>this.applyGelatiereModel());return this.gelatiereModelSync=e.then(()=>void 0,()=>void 0),e}async applyGelatiereModel(){let e=this.deps.getScoops(),t=[...e.values()].find(Nx);if(!t)return!1;let n=Nn(e.values()),r=n?Gn(n):void 0,i=Gn(t),a=r?i?.provider===r.provider&&i.id===r.id:Pn(t)===void 0;if(!a){let e=t.model?{...t.model}:void 0,i=t.config?{...t.config}:void 0;In(t,r);try{await this.deps.db.saveScoop(t)}catch(n){throw t.model=e,t.config=i,n}Q.info(`Gelatiere model synchronized with leading cone`,{jid:t.jid,leadingJid:n?.jid,model:r?`${r.provider}:${r.id}`:void 0})}return r&&this.getContext(t.jid)?.updateModel(),!a}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();Q.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Un(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Q.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=tr(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),NE(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Mn(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:or(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,On(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(On(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(Q.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),NE(`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`),tr(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(i)try{this.deps.callbacks.onError(i.jid,`[@${r.assistantLabel} FAILED]: ${t}`,{endTurn:!1})}catch(e){Q.error(`Failed to record fatal error for scoop owner`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}}};const $=_(`scoop-message-router`);var NA=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if($.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){$.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);NE(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),$.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){$.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){$.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if($.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){$.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{$.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`||t.channel===`scoop-notify`||t.channel===`scoop-idle`||t.channel===`scoop-wait`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);$.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;n.reported||r<3e5||(n.reported=!0,$.warn(`Busy lick queue may be starved`,{jid:e,error:`Lick queue remained deferred while scoop was busy for 300s`}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r}))}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){$.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){$.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){$.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if($.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){$.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){$.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=Cb(Tb(Sb(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){$.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=[],l=s.map(e=>{let t=new Date(e.timestamp),n=t.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}),r=I_(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(`
1174
- `);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>L_(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=Cb(Tb(Sb(a),o));this.lastAgentTimestamp.set(e,f),await this.deps.db.setState(`lastAgentTs_${e}`,f);let p=s.some(e=>e.steer),m=new Set,h=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);m.has(t)||(m.add(t),h.push(e.guestGate))}await this.deps.sendPrompt(e,l,d.senderId,d.senderName,u,{steer:p,...h.length>0?{guestGates:h}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);$.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),t&&await t.clearSession(n).catch(t=>{$.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{$.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),$.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{$.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{$.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),$.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const PA=_(`orchestrator`),FA={decision:`deny`};var IA=class{scoops=new Map;workUnits=new Wy(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new HT({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 ZE({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 YE({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new BE({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 DE({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=>bb(e),saveMessage:e=>vb(e)});lickRegistry=new yE({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 NA({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(),db:{saveMessage:e=>vb(e),deleteMessage:e=>yb(e),clearMessagesForScoop:e=>_b(e),clearAllMessages:()=>gb(),getMessagesSince:(e,t,n)=>Eb(e,t,n),setState:(e,t)=>Mb(e,t)},isExternalLickChannel:Cy});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new MA({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=>pb(e),deleteScoop:e=>hb(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>mE(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 wE(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new Vx({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 Ox(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new SE(e,t),await this.modelPolicyFile.init(),n(),mb()),n,{stagePrefix:`orchestrator-init`})}setOnConversationsReady(e){this.onConversationsReady=e}async openSharedFilesystem(e,t){let n=await wE(e=>br.create({dbName:`slicc-fs`,onRepairProgress:e}),e);this.sharedFs=n,this.sessionStore=new B_,this.conversationStore=new ew;let{TurnJournal:r}=await import(`./turn-journal-DGbDeEVx.js`);this.turnJournal=new r,this.interruptedTurns=await this.turnJournal.readAll();let i=new yr;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 Nb();let{sharedFs:n,fsWatcher:r}=await this.openSharedFilesystem(e,t),i=await this.initPolicyLayerAndLoadRecords(n,r,e),a=Object.values(i).find(e=>Hn(e))?.jid;for(let e of Object.values(i)){await this.backfillParent(e,a),qn(e),this.migrateScoopConfig(e,Object.values(i)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await jb(`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 EE({onTaskRun:async(e,t)=>{PA.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(),PA.info(`Orchestrator initialized`,{scoopCount:this.scoops.size}),e?.(`conversations-ready`),await this.onConversationsReady?.(),await this.restoreScoopContexts(e),Ar(e=>this.getSessionCostsForCommand(e)),jr(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>H_);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 AE(t,4,t=>this.restoreScoopContext(t,e));let r=AE(n,4,t=>this.restoreScoopContext(t,e)).catch(e=>{PA.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);PA.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 dy;try{await LC({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){PA.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(wr(r),t).catch(t=>{PA.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=Hn(e)?null:t??null;try{await pb(e)}catch(t){PA.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=>!Pn(e)&&!Nx(e));if(e.length>0){let t=CE(),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?Gn(n):void 0)??t;if(r){In(e,r);try{await pb(e)}catch(t){PA.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){PA.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=`${nr.root}/`,r=rr(ar(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-DsTXqsDu.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:or,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(PA.warn(`Guest approval before SudoManager init — failing closed`),FA)}})}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 pb(e),e.parentJid===null&&await this.lifecycle.syncGelatiereModel().catch(t=>{PA.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 k(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 Jn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return jn(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 br.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await IT(this.sharedFs).catch(e=>{PA.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new Vx({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 Ox(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new SE(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),PA.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 bb(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-dk4HMys6.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)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await Promise.resolve().then(()=>_S),r=await n(this.sharedFs);return[...t,...r.map(Mr)]}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&&PA.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,PA.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new XC(this.conversationStore):null,t=this.sharedFs;return new eC({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:yC(),snapshotStore:{read:e=>dC(t,e),write:(e,n)=>uC(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.180.0`})}};const LA=_(`workflow-run-manager`),RA=`/shared/workflow-runs`,zA=1e3;function BA(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function VA(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){LA.warn(`observeRun handler threw`,e)}},i=(e,n)=>KA(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=BA(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),WA(t,n);let f=i(a.ctx,c),p=GA(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=>LA.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=`${RA}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(RA,{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);LA.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`?UA(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){LA.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function HA(e){let t=VA(e);return globalThis[f]=t,LA.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function UA(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function WA(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 GA(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 KA(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?qA(n,t,a?.args??[],r):e===`agent`?JA(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function qA(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>zA&&i.logs.splice(0,i.logs.length-zA),r()}return{stdout:``,stderr:``,exitCode:0}}async function JA(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 YA=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function XA(e,t,n){let r=ZA(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=ej(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function ZA(e){let t=new Map;return QA(t,e.discoveryOrigin),QA(t,e.discoveryUrl),[...t.values()]}function QA(e,t){if(t){$A(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);$A(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!YA.has(e)))$A(e,t,1,`substring`)}catch{}}}function $A(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 ej(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=nj(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)tj(a,e)&&(r+=e.weight*o)}return r}function tj(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 nj(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}function rj(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 ij=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=sj(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:oj,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===oj)throw new A(`ENOTDIR`,`not a directory`,e);let n=cj(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);return aj.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new A(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=sj(e);if(t.length===1&&t[0]===oj)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new A(`EISDIR`,`is a directory`,e);let n=cj(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!aj.includes(r))throw new A(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new A(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=sj(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===oj)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=cj(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=cj(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!aj.includes(r))throw new A(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new A(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new A(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new A(`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 A(`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:pj(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:mj(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
1175
- `}renderProcFile(e,t){if(e===1)return hj(t);let n=this.pm.get(e);switch(t){case`status`:return lj(n);case`cmdline`:return uj(n);case`cwd`:return dj(n);case`stat`:return fj(n)}}};const aj=[`status`,`cmdline`,`cwd`,`stat`],oj=`table`;function sj(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function cj(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function lj(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${pj(e.status)} (${e.status})`,`Owner:\t${mj(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(`
1162
+ `)&&t.pop(),t}function $D(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}function eO(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=QD(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};if(Buffer.byteLength(a[0],`utf-8`)>r)return{content:``,truncated:!0,truncatedBy:`bytes`,totalLines:o,totalBytes:i,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`;for(let e=0;e<a.length&&e<n;e++){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(e>0);if(c+n>r){l=`bytes`;break}s.push(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let u=s.join(`
1163
+ `),d=Buffer.byteLength(u,`utf-8`);return{content:u,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:d,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function tO(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=QD(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`,u=!1;for(let e=a.length-1;e>=0&&s.length<n;e--){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(s.length>0);if(c+n>r){if(l=`bytes`,s.length===0){let e=nO(t,r);s.unshift(e),c=Buffer.byteLength(e,`utf-8`),u=!0}break}s.unshift(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let d=s.join(`
1164
+ `),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 nO(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 rO=_(`tool:bash`),iO=40960,aO=1048576,oO=`\0slicc-img:`;function sO(e){let t=yn(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=`${oO}${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 cO(e){let t=yn(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 lO(e){return e.replaceAll(RegExp(`${oO}\\d+`,`g`),`[image]`)}function uO(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 dO(e,t,n,r){let{text:i,markers:a}=sO(e),o=tO(i,{maxBytes:iO});if(!o.truncated)return uO(i,a);let s=`showing the last ${$D(o.outputBytes)} of ${$D(o.totalBytes)} (${o.totalLines} lines)`,c=`${n}/bash-output-${r()}.txt`;try{return await t.writeFile(c,lO(i)),uO(`${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 rO.warn(`Failed to persist full bash output`,{error:e instanceof Error?e.message:String(e)}),uO(`${o.content}\n\n[Output truncated: ${s}. Re-run piping through \`head\`/\`tail\`/\`grep\`/\`sed -n\` to narrow the output.]`,a)}}const fO=new Set([`grep`,`egrep`,`fgrep`,`rg`]);function pO(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 mO(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=pO(r.name);if(i!==`command`)return i;let a=r.args[0];return a?pO(a):null}function hO(e,t,n,r){if(n!==1||r.trim())return!1;let i;try{i=mO(e.getBash().transform(t).ast)}catch{return!1}return i!==null&&fO.has(i)}function gO(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return e}function _O(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 ${iO/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 vO(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 yO(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 bO(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 TO(e,n,r);await e.fs.writeFile(t,i)}).catch(e=>rO.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:(e,t)=>{s=e,c=t,u()},flushPersist:()=>l,killedByTimeout:!1}}function xO(e,t){t===`timeout`&&(e.killedByTimeout=!0),e.job?.kill(),e.controller.abort(),e.job?.exit(null)}function SO(e,t){e.job?.exit(e.job.signal.aborted?null:t)}function CO(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 wO(e,t,n,r={}){let i=0,a=0,o={shell:e,fs:t,tempDir:n,options:r,defaultBackgroundAfter:gO(r.defaultBackgroundAfterSeconds)??600,nextOutputSeq:()=>i+=1,nextJobId:()=>`bg-${a+=1}`};return{name:`bash`,description:_O(o.defaultBackgroundAfter),inputSchema:vO(o.defaultBackgroundAfter),execute:(e,t)=>jO(o,e,t)}}async function TO(e,t,n){let r=e.options.scrubOutput;if(!r||!n)return n;try{return await r(n)}catch(e){return rO.warn(`Background bash output scrub failed; withholding output`,{jobId:t,error:e instanceof Error?e.message:String(e)}),`[output withheld: secret scrub unavailable]`}}function EO(e){return e.ok?e.result.exitCode===124&&/execution aborted/i.test(e.result.stderr):/execution aborted/i.test(e.error)}function DO(e,t){return e===void 0?`--- killed (exit ${t}) ---\n`:`--- killed after ${e}s (exit ${t}) ---\n`}async function OO(e,t,n,r,i,a,s,c){await s.flushPersist();let l=s.killedByTimeout||EO(a),u,d;if(l){let e=s.getTeedOutput();d=124,u=`${e.endsWith(`
1165
+ `)||e.length===0?e:`${e}\n`}${DO(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(`
1166
+ `)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let f=await TO(e,t,u),p;try{await e.fs.writeFile(i,f),p=i}catch(e){rO.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){rO.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:d});return}let m=tO(cO(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 kO(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=i===void 0?void 0:i-a,u=l===void 0?void 0:setTimeout(()=>xO(t,`timeout`),l*1e3);return t.settled.then(r=>(u!==void 0&&clearTimeout(u),SO(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),OO(e,o,s,n,c,r,t,i))).catch(e=>rO.error(`Background bash delivery failed`,{jobId:o,error:e})),rO.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:l}),CO(o,s,r,c,i)}async function AO(e,t,n){rO.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=o(r,n.pipeStatus),{content:await dO(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!hO(e.shell,t,n.exitCode,n.stderr)}}async function jO(e,t,n){let r=t.command,i=gO(t.timeout),a=gO(t.background_after)??e.defaultBackgroundAfter;rO.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=bO(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?(xO(o,`timeout`),rO.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),yO(c)):t===`elapsed`?kO(e,o,r,c,i,a):(SO(o,t.ok?t.result.exitCode:1),t.ok?await AO(e,r,t.result):(rO.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const MO={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 NO(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function PO(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:NO(e)&&(t.edits=[e])}catch{}else NO(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 FO(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:MO,prepareArguments:PO,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-wHbJ4R48.js`);return i(e,t,n,r)}}}async function IO(e,t,n){if(Mr(wn(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 LO=_(`tool:fs`);function RO(e,t=`/workspace`){return[zO(e),BO(e),FO(e,t)]}function zO(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${ZD/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;LO.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
1167
+ `),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=eO(c.join(`
1168
+ `));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${$D(new TextEncoder().encode(t[o]??``).length)}, exceeds ${$D(ZD)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${ZD}]`};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} (${$D(ZD)} 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 LO.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function BO(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;LO.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await IO(e,n,r);return t?(LO.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 LO.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const VO={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 HO(e,t){return{name:ii,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:VO,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-mQfg-aG4.js`);return r(e,t,n)}}}function UO(){return null}const WO=_(`tool:request-secret`);async function GO(e,t){let n=UO();if(n)return n(e);let r=t.callPanelRpc??await KO();return r?r(e):{stored:!1,reason:`unavailable`}}async function KO(){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 qO(e){try{return e.getProvider?.()||void 0}catch(e){WO.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function JO(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 YO(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(`
1169
+ `)}function XO(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 ZO(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:JO(t.domains),persist:t.persist===!0,requester:e.requester,provider:qO(e)},a;try{a=await GO(i,e)}catch(e){let t=e instanceof Error?e.message:String(e);return WO.error(`secret request failed`,{name:n,error:t}),{content:`The secret prompt failed: ${t}`,isError:!0}}if(!a.stored)return{content:XO(a),isError:!0};let o=QO(a.name,a.maskedValue,e);return WO.info(`secret stored via request_secret`,{name:a.name,persisted:a.persisted}),{content:YO(a,o)}}}}function QO(e,t,n){if(!n.setEnv||!t||!g(e))return!1;try{return n.setEnv(e,t),!0}catch(t){return WO.warn(`could not inject the masked value into the shell env`,{name:e,error:t instanceof Error?t.message:String(t)}),!1}}const $O=_(`scoop-management-tools`),ek=`cross_cone`;function tk(e){return Mn(e.getScoops(),e.scoop.jid)}function nk(e){let t=new Set;for(let n of tk(e))n.jid!==e.scoop.jid&&n.parentJid!==null&&t.add(n.jid);return t}function rk(e){let t=In(e.getScoops());return t!==void 0&&t.jid===e.scoop.jid}function ik(e){let t=e.getScoops(),n=nk(e),r=rk(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=Qn(t,e);a.kind!==`cycle`&&i.push({scoop:e,relation:a.kind===`root`?`foreign`:`inherited`})}return i}function ak(e){return t=>t.folder===e||t.name===e}function ok(e,t){let n=ik(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 sk(e,t){let n=[],r=[];for(let i of e){let e=ok(i,t);e?n.push(e):r.push(i)}return{resolved:n,unknown:r}}function ck(e,t){return Pn(e.getScoops(),t.scoop)?.folder??`unknown`}function lk(e,t){return t.relation===`inherited`?`inherited (its owning cone is gone)`:`owned by cone "${ck(e,t)}"`}function uk(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 ${lk(r,e)}`).join(`; `)}. Pass ${ek}: true to act on it anyway.`,isError:!0}}function dk(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 fk=[`command`,`read`,`write`,`secret`];function pk(e){return`${be(e,{maxLen:50})}-scoop`}function mk(e){return e===void 0?{ok:!0}:ur(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${dr.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 gk(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 _k(e,t){let n=ik(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 vk(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 yk(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),$O.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function bk(e){let{kind:t,detail:n,suggested_pattern:r,reason:i}=e;if(!fk.includes(t))return{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${fk.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 xk(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(`
1170
+ `)}async function Sk(e,t){let n=bk(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return $O.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:xk(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function Ck(e,t){let{scoop_name:n,prompt:r,cross_cone:i}=e;if(ak(n)(t.scoop))return{content:`Cannot feed yourself.`,isError:!0};let a=ok(n,t);if(!a)return _k([n],t);let o=uk([a],i,`feed "${n}"`,t);if(o)return o;try{await t.onFeedScoop(a.scoop.jid,r),$O.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 (${ek}: 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 wk(e,t){return t.relation===`own`?``:t.relation===`inherited`?` [INHERITED]`:` [FOREIGN: ${ck(e,t)}]`}async function Tk(e){let t=new Map(ik(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 vk(n,e.getScoopTabState,r?wk(e,r):``)}).join(`
1171
+ `)}`}}function Ek({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}:{},...Dk(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 Dk(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function Ok(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return $O.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 kk(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=kn(s);if(!f.ok)return{content:f.error,isError:!0};let p=mk(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=gk(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let ee=pk(n),g=tk(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=Bn(ee,t.getScoops().map(e=>e.folder));try{let e=Ek({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:or(lr(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return $O.info(`Scoop created`,{name:n,folder:te}),i&&t.onFeedScoop?Ok(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 Ak(e,t){let{scoop_name:n,cross_cone:r}=e;if(ak(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=ok(n,t);if(!i)return _k([n],t);let a=uk([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),$O.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 jk(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function Mk(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return jk();let{resolved:i,unknown:a}=sk(n,t);return i.length===0?_k(a,t):uk(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),$O.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 Nk(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 Pk(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return jk();let{resolved:i,unknown:a}=sk(n,t);if(i.length===0)return _k(a,t);let o=uk(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);$O.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(...Nk(l,c)),{content:u.join(`
1172
+ `)}}function Fk(e,t){return!Array.isArray(e)||e.length===0?jk():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 Ik(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 Lk(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=Fk(n,r);if(a)return a;let{resolved:o,unknown:s}=sk(n,t);if(o.length===0)return _k(s,t);let c=uk(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 $O.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:Ik(f,s,p,r)}}function Rk(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 zk(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?($O.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:Rk(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 Bk(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?($O.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 Vk(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(`
1173
+ `)}`}}async function Hk(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),$O.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 Uk(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=>yk(t,e)}}function Wk(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:[...fk],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=>Sk(t,e)}}function Gk(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.`},[ek]:dk(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>Ck(t,e)}}function Kk(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:()=>Tk(e)}}function qk(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:[...dr],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=>kk(t,e)}}function Jk(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.`},[ek]:dk(`drop`)},required:[`scoop_name`]},execute:t=>Ak(t,e)}}function Yk(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"]).`},[ek]:dk(`mute`)},required:[`scoop_names`]},execute:t=>Mk(t,e)}}function Xk(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"]).`},[ek]:dk(`unmute`)},required:[`scoop_names`]},execute:t=>Pk(t,e)}}function Zk(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."},[ek]:dk(`wait on`)},required:[`scoop_names`]},execute:t=>Lk(t,e)}}function Qk(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=>zk(t,e)}}function $k(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=>Bk(t,e)}}function eA(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:()=>Vk(e)}}function tA(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=>Hk(t,e)}}function nA(e){let t=[],n=Nn(e.scoop);return jn(e.scoop)||(t.push(Uk(e)),e.onSudoRequest&&t.push(Wk(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(qk(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(Gk(e)),t.push(Kk(e)),e.onDropScoop&&t.push(Jk(e)),e.onMuteScoops&&t.push(Yk(e)),e.onUnmuteScoops&&t.push(Xk(e)),e.onScheduleScoopWait&&t.push(Zk(e)),e.onSudoResolve&&(t.push(Qk(e)),t.push($k(e))),e.onListSudoRequests&&t.push(eA(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(tA(e))),t}const rA=_(`scoop-context`);function iA(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-YxkVsl15.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function aA(e){let{scoop:t,unit:n,callbacks:r}=e,i=nA({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=RO(e.gatedFs,n.workspace.root),o=HO(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>ZC);return t(e.fs)}}),s=[...a,o,wO(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:dn(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){rA.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i,ZO({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>XD(gD(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);s.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let c={scrubToolResult:dn()},l=iA(e);return e.processManager?fn(s,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},c,l):fn(s,void 0,c,l)}const oA=_(`scoop-context`);async function sA(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();oA.info(`Filesystem ready`,{folder:t.folder}),await FD(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,skills:l}=await JD({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(o);let u=await aA({getTurnGuestGates:e.getTurnGuestGates,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:d,globalMemory:f}=await pD(r,n,()=>i.getGlobalMemory());if(!hD(t))return oA.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let p=_D(t,n),m=bD(t,n,f,d,l),h=await e.sessions.restore(),{streamWithSessionId:ee,compactFn:g,getCompactionApiKey:te}=await LD(p,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>hD(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let ne=Vn(t);return{kind:`ready`,agent:ND({model:p,tools:u,systemPrompt:m,messages:h,thinkingLevel:SD(CD()??ne.level,p),getApiKey:()=>hD(t)??void 0,transformContext:g,streamFn:ee,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:g,getCompactionApiKey:te,effortOverride:ne.effortOverride,toolCount:u.length}}const cA=_(`scoop-context`);var lA=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 cA.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=AC(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=pn(n);return cA.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=>{cA.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){cA.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 uA(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 dA(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function fA(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const pA=_(`scoop-context`);var mA=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;pA.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)&&(pA.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:eD(r)}),!!(t<3&&(await tD(hA(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return $E(e)?(pA.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 Fa(e)?(pA.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Ra(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(!eD(e)||t>=3)return!1;let r=hA(t);return pA.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await tD(r,n)&&!this.deps.isDisposed()}fail(e,t){WE(`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 gA(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){pA.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 _A=_(`scoop-context`);var vA=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;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=ir(e),this.owner={kind:Rn(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 lA({store:r??null,canonical:c?{store:c,identity:Dr(e)}:null,sessionId:e.jid,folder:e.folder,getMessages:()=>this.agent?.state?.messages,isDisposed:()=>this.disposed,onRestoreError:e=>this.callbacks.onError(e)}),this.runBounds=new AD({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new cD({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new uD({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new kD({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 mA({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 WD(this.unit,this.scoop,k(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return tr(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 sA({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`),_A.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);_A.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(yD(this.scoop)),!1)}cleanupPromptState(e,t,n,r){this.runBounds.disarm();let i=this.runBounds.takeExceededNote();i!==null&&this.callbacks.onError(`agent run terminated: ${i}`),(n||r.aborted)&&this.sessions.persistNow(),this.isProcessing=!1,this.turnJournal?.end(this.scoop.jid),!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),dA(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(gA(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;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let a=uA(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:r});this.currentTurnProcess=a,this.runBounds.arm(),this.turnJournal?.begin(this.scoop.jid,this.scoop.folder,t,this.turnGuestGates);let o=null;try{if(o=await this.turnRunner.run(n,i),o&&!this.disposed&&!i.aborted){this.turnRunner.reportExhausted(o);return}!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,a,o,i)}}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(){fA(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0)}idleCompactionEnabled(){return xx(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:mn,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-D_7T7FHe.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-6O9TA5qM.js`).then(e=>e.r).then(n=>n.scheduleLiveDeltaCuration({vfs:e,cone:t})).catch(e=>{_A.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-D_7T7FHe.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){_A.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 vD(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=TD(this.agent,this.scoop))}async reloadSkills(){this.agent&&await DD(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?CD()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,ED(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.turnJournal?.end(this.scoop.jid),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),fA(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 iD(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`&&_A.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||nD(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const Q=_(`scoop-lifecycle-manager`);var yA=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 VE(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}displayJidFor(e){let t=this.deps.approverFor(e)?.jid;return t&&t!==e?t:void 0}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??k(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Pn(t.values(),e)??k(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Q.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof wr))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`)Q.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Q.debug(`Context already exists`,{jid:e});return}}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=ir(t).policy.filesystem;if(a.kind===`restricted`){let e=kn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new wr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:On(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 vA(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0,this.deps.getTurnJournal?.()??void 0);if(n.attachContext(l,i),await l.init(),this.units.get(e)!==n||n.context!==l)return;n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{Q.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),Q.info(`Scoop context created`,{jid:e,contextId:i})}async reinitAfterPromote(e){let t=this.units.get(e);if(t?.context){t.disposeContext();try{await this.createTab(e)}catch(n){let r=n instanceof Error?n.message:String(n);Q.warn(`Failed to re-init promoted unit; next prompt will retry`,{jid:e,error:r}),t.disposeContext(),this.markTabError(e,r)}}}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.deps.getScoops().get(e);if(o&&xx(o)&&(await this.syncGelatiereModel(),!Jn(o)))throw Error(`The gelatiere cannot run until the leading cone has a model`);let s=this.getContext(e);s||=(await this.createTab(e),this.getContext(e));let c=this.units.get(e);if(c?.tab?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}s=this.getContext(e)}if(!s||!c){Q.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),c.tab&&c.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await s.prompt(t,i,a)}async resumeTurn(e,t,n){let r=this.getContext(e),i=this.units.get(e);!r||!i||r.isBusy||(this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),i.tab&&i.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),await r.resumeTurn(t,n))}async register(e){let t=this.deps.getScoops(),n=In(t.values())?.jid;if(Xn(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=Bn(e.folder,n);r!==e.folder&&(Q.warn(`Scoop folder already taken — registering under a free variant`,{jid:e.jid,requested:e.folder,folder:r}),e.folder=r,e.trigger=`@${r}`,e.assistantLabel=r)}t.set(e.jid,e);try{await this.deps.db.saveScoop(e)}catch(n){throw t.delete(e.jid),n}this.deps.messageRouter.ensureQueue(e.jid),Q.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&bE(`spawn`,e.folder)}catch(n){Q.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){Q.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{Q.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}In(t.values())?.jid!==n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the new leading cone after registration`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}inheritModel(e){if(xx(e)){let t=In(this.deps.getScoops().values());zn(e,t?Jn(t):void 0);return}if(Ln(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Jn(t):void 0)??uE();n&&zn(e,n)}async unregister(e){let t=this.deps.getScoops(),n=In(t.values())?.jid===e;for(let n of $n(t.values(),e))await this.unregister(n.jid);let r=t.get(e);if(r&&r.parentJid===null&&k(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let i=this.deps.getLickManager();if(r&&i){let{webhooks:e,cronTasks:t}=await i.getLicksForScoopFromDb(r.name,r.folder),n=this.deps.buildActiveLicksError(r.folder,e,t);if(n)throw n}this.deps.costTracker.snapshot(e);let a=globalThis.__slicc_wsSubscribers;a&&a.dropForScoop(e).catch(t=>{Q.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),await Promise.all([r?this.deps.getConversationStore()?.delete(Er(r)):void 0,this.deps.getSessionStore()?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})})]),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let o=this.deps.approvalRouter.failScoop(e);if(o>0&&Q.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:o}),r&&this.deps.getSudoManager()?.forgetScoopPolicies(r.folder),Q.info(`Scoop unregistered`,{jid:e}),r)try{this.deps.callbacks.onScoopUnregistered?.(r)}catch(t){Q.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the replacement leading cone after root removal`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;if(xx(n))return await this.syncGelatiereModel(),!1;let r=In(this.deps.getScoops().values())?.jid===e,i=n.model;zn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return zn(n,i),this.getContext(e)?.updateModel(),Q.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return r&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to synchronize gelatiere after leading model change`,{jid:e,error:t instanceof Error?t.message:String(t)})}),!0}syncGelatiereModel(){let e=this.gelatiereModelSync.then(()=>this.applyGelatiereModel());return this.gelatiereModelSync=e.then(()=>void 0,()=>void 0),e}async applyGelatiereModel(){let e=this.deps.getScoops(),t=[...e.values()].find(xx);if(!t)return!1;let n=In(e.values()),r=n?Jn(n):void 0,i=Jn(t),a=r?i?.provider===r.provider&&i.id===r.id:Ln(t)===void 0;if(!a){let e=t.model?{...t.model}:void 0,i=t.config?{...t.config}:void 0;zn(t,r);try{await this.deps.db.saveScoop(t)}catch(n){throw t.model=e,t.config=i,n}Q.info(`Gelatiere model synchronized with leading cone`,{jid:t.jid,leadingJid:n?.jid,model:r?`${r.provider}:${r.id}`:void 0})}return r&&this.getContext(t.jid)?.updateModel(),!a}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();Q.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Kn(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Q.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=ir(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),bE(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Fn(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:lr(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,jn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(jn(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(Q.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),bE(`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`),ir(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(i)try{this.deps.callbacks.onError(i.jid,`[@${r.assistantLabel} FAILED]: ${t}`,{endTurn:!1})}catch(e){Q.error(`Failed to record fatal error for scoop owner`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}}};const $=_(`scoop-message-router`);var bA=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if($.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){$.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);bE(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),$.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){$.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){$.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if($.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){$.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{$.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`||t.channel===`scoop-notify`||t.channel===`scoop-idle`||t.channel===`scoop-wait`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);$.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;n.reported||r<3e5||(n.reported=!0,$.warn(`Busy lick queue may be starved`,{jid:e,error:`Lick queue remained deferred while scoop was busy for 300s`}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r}))}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){$.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){$.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){$.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if($.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){$.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){$.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=db(pb(ub(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){$.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=[],l=s.map(e=>{let t=new Date(e.timestamp),n=t.toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}),r=w_(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(`
1174
+ `);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>T_(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=db(pb(ub(a),o));this.lastAgentTimestamp.set(e,f),await this.deps.db.setState(`lastAgentTs_${e}`,f);let p=s.some(e=>e.steer),m=new Set,h=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);m.has(t)||(m.add(t),h.push(e.guestGate))}await this.deps.sendPrompt(e,l,d.senderId,d.senderName,u,{steer:p,...h.length>0?{guestGates:h}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);$.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),t&&await t.clearSession(n).catch(t=>{$.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{$.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),$.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{$.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{$.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),$.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const xA=_(`orchestrator`),SA={decision:`deny`};var CA=class{scoops=new Map;workUnits=new My(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new kT({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 RE({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 IE({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new DE({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 mE({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=>cb(e),saveMessage:e=>ob(e)});lickRegistry=new oE({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 bA({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(),db:{saveMessage:e=>ob(e),deleteMessage:e=>sb(e),clearMessagesForScoop:e=>ab(e),clearAllMessages:()=>ib(),getMessagesSince:(e,t,n)=>mb(e,t,n),setState:(e,t)=>bb(e,t)},isExternalLickChannel:dy});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new yA({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=>tb(e),deleteScoop:e=>rb(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>tE(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 dE(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new kx({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 gx(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new lE(e,t),await this.modelPolicyFile.init(),n(),nb()),n,{stagePrefix:`orchestrator-init`})}setOnConversationsReady(e){this.onConversationsReady=e}async openSharedFilesystem(e,t){let n=await dE(e=>Cr.create({dbName:`slicc-fs`,onRepairProgress:e}),e);this.sharedFs=n,this.sessionStore=new O_,this.conversationStore=new VC;let{TurnJournal:r}=await import(`./turn-journal-_Hrn3Aoy.js`);this.turnJournal=new r,this.interruptedTurns=await this.turnJournal.readAll();let i=new Sr;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 xb();let{sharedFs:n,fsWatcher:r}=await this.openSharedFilesystem(e,t),i=await this.initPolicyLayerAndLoadRecords(n,r,e),a=Object.values(i).find(e=>Gn(e))?.jid;for(let e of Object.values(i)){await this.backfillParent(e,a),Xn(e),this.migrateScoopConfig(e,Object.values(i)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await yb(`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 pE({onTaskRun:async(e,t)=>{xA.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(),xA.info(`Orchestrator initialized`,{scoopCount:this.scoops.size}),e?.(`conversations-ready`),await this.onConversationsReady?.(),await this.restoreScoopContexts(e),Nr(e=>this.getSessionCostsForCommand(e)),Pr(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>A_);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 _E(t,4,t=>this.restoreScoopContext(t,e));let r=_E(n,4,t=>this.restoreScoopContext(t,e)).catch(e=>{xA.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);xA.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 $v;try{await TC({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){xA.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(Dr(r),t).catch(t=>{xA.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=Gn(e)?null:t??null;try{await tb(e)}catch(t){xA.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=>!Ln(e)&&!xx(e));if(e.length>0){let t=uE(),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?Jn(n):void 0)??t;if(r){zn(e,r);try{await tb(e)}catch(t){xA.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){xA.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=`${ar.root}/`,r=or(cr(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-DvAxEX5J.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:lr,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(xA.warn(`Guest approval before SudoManager init — failing closed`),SA)}})}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 tb(e),e.parentJid===null&&await this.lifecycle.syncGelatiereModel().catch(t=>{xA.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 k(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 Zn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Pn(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 Cr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await CT(this.sharedFs).catch(e=>{xA.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new kx({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 gx(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new lE(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),xA.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 cb(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-BK9ZDM7F.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)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await Promise.resolve().then(()=>aS),r=await n(this.sharedFs);return[...t,...r.map(Fr)]}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&&xA.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,xA.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new RC(this.conversationStore):null,t=this.sharedFs;return new HS({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:sC(),snapshotStore:{read:e=>$S(t,e),write:(e,n)=>QS(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.181.0`})}};const wA=_(`workflow-run-manager`),TA=`/shared/workflow-runs`,EA=1e3;function DA(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function OA(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){wA.warn(`observeRun handler threw`,e)}},i=(e,n)=>NA(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=DA(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),jA(t,n);let f=i(a.ctx,c),p=MA(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=>wA.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=`${TA}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(TA,{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);wA.error(`failed to write run result file`,{runId:n,resultPath:c,error:t}),o=`result file write failed: ${t}`,i===`done`&&(i=`error`)}s.status=i,s.error=o,s.finishedAt=u,s.preview=i===`done`?AA(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:new Date().toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){wA.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function kA(e){let t=OA(e);return globalThis[f]=t,wA.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function AA(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function jA(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 MA(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 NA(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?PA(n,t,a?.args??[],r):e===`agent`?FA(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function PA(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>EA&&i.logs.splice(0,i.logs.length-EA),r()}return{stdout:``,stderr:``,exitCode:0}}async function FA(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 IA=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function LA(e,t,n){let r=RA(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=VA(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function RA(e){let t=new Map;return zA(t,e.discoveryOrigin),zA(t,e.discoveryUrl),[...t.values()]}function zA(e,t){if(t){BA(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);BA(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!IA.has(e)))BA(e,t,1,`substring`)}catch{}}}function BA(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 VA(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=UA(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)HA(a,e)&&(r+=e.weight*o)}return r}function HA(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 UA(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}function WA(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 GA=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=JA(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:qA,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===qA)throw new A(`ENOTDIR`,`not a directory`,e);let n=YA(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);return KA.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new A(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=JA(e);if(t.length===1&&t[0]===qA)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new A(`EISDIR`,`is a directory`,e);let n=YA(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!KA.includes(r))throw new A(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new A(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=JA(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===qA)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=YA(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=YA(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!KA.includes(r))throw new A(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new A(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new A(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new A(`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 A(`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:tj(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
1175
+ `}renderProcFile(e,t){if(e===1)return nj(t);let n=this.pm.get(e);switch(t){case`status`:return XA(n);case`cmdline`:return ZA(n);case`cwd`:return QA(n);case`stat`:return $A(n)}}};const KA=[`status`,`cmdline`,`cwd`,`stat`],qA=`table`;function JA(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function YA(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function XA(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${ej(e.status)} (${e.status})`,`Owner:\t${tj(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(`
1176
1176
  `)+`
1177
- `}function uj(e){return e.argv.join(`\0`)+`\0`}function dj(e){return e.cwd+`
1178
- `}function fj(e){return[e.pid,`(${e.kind})`,pj(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
1179
- `}function pj(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function mj(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.kind===`jshd`?`jshd`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function hj(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
1177
+ `}function ZA(e){return e.argv.join(`\0`)+`\0`}function QA(e){return e.cwd+`
1178
+ `}function $A(e){return[e.pid,`(${e.kind})`,ej(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
1179
+ `}function ej(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function tj(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.kind===`jshd`?`jshd`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function nj(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
1180
1180
  `)+`
1181
1181
  `;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
1182
1182
  `;case`stat`:return`1 (kernel-host) R 0 - 0 -
1183
- `}}const gj=Math.max(_i,pi)+5e3;function _j(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(yi(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(!di(n.token))return;let a=i.get(n.id);if(a){r({type:mi,id:n.id}),a.result&&r({type:hi,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:mi,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),gj),r({type:hi,id:n.id,...e})};(gi(n)?vi(n):fi(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 vj(){return globalThis}function yj(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 Ey(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 bj(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 xj(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Sj(e,t)}async function Sj(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=k(r),a=e.type===`discovery`&&!e.targetScoop?XA(e,i.filter(Tx),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?io(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Tx(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-Dwqx8mXn.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=By(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=yj(e),l=bj(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 Cj(e,t,n,r,i){let a=new oi,o=new IA(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=sn(),l=i.capabilityBroker??c(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(l),mr(l),vj().__slicc_pm=a,si(li()),vj().__slicc_browser=t,await n.bind(o,t);let u=Er(()=>n.emitTrayRuntimeStatus()),d=we(()=>n.emitTrayRuntimeStatus());rj(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-B7KPVgHq.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 wj(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-DZQVtgRS.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await Promise.resolve().then(()=>H_);r(()=>a());let{getLickManager:o}=await Promise.resolve().then(()=>sE),s=o();await s.init(),e.setLickManager(s);let c=t.lickEventHandler??xj,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function Tj(e){let t=e.getScoops();k(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 Ej(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:a}=e;HA({sharedFs:a,getStartingRoot:e=>{let n=k(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)=>ui(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>u().slice(10,22),splitResult:(e,t)=>i(e,t)})}async function Dj(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))+`
1184
- `,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 Oj(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-CVcgQWV0.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-CMj5JyW-.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 kj(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 gx(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})},{...Aj(t),isOwnTab:mx(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Aj(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:()=>_x()}}async function jj(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 Mj(e,t,n,r,i,a){e&&(await Pj(e,n,r),i(`mounts-restored`),await Nj(e,t,n,r,a),i(`jshd-restored`))}async function Nj(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-B5L76uAO.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 Pj(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(()=>my),{applyConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-B7KPVgHq.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 Fj(){Or(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-B0UzxzJj.js`);return e()})}function Ij(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-B0UzxzJj.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 Lj(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DBtF-C4h.js`),{ScriptCatalog:r}=await import(`./script-catalog-DZtOMxvi.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 Rj(e){return e===`node-rest`}function zj(e,t,n,r){import(`./gelatiere-unit-BguezRYn.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!Na(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-6PnudWGB.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function Bj(e,t){if(!e)return()=>{};import(`./memory-curation-seam-CmUEG05f.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return Na(`memory-v2`)&&import(`./memory-health-DVwJNc8y.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 Vj(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}Zv(e,t,e.getSessionStore())}async function Hj(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Fj();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Cj(t,n,r,i,e);if(s(`orchestrator-ready`),Vj(l,f,o),f)try{await f.mountInternal(`/proc`,new ij(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await wj(l,e,o);s(`lick-manager-ready`),f&&Ej({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),vj().__slicc_lickManager=m,zj(l,m,f,o);let h=Bj(f,o),{wsBridge:ee,wsRegistry:g}=await Dj({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});vj().__slicc_wsSubscribers=g;let te=Rj(p.adapter)?await Oj(m,o,e.localLickWsUrl??null,f):null,ne=kj(n,m,o,e.appPageUrl);await Mj(f,c,m,o,s,l),a||await Tj(l),s(`cone-bootstrapped`),jj(l,m,o),f&&Ij(m,o);let re=null,_=null;f&&({bshWatchdogStop:re,scriptCatalogDispose:_}=await Lj(f,n,o));let ie=null;f&&e.syncFsChannelNonce&&(ie=_j({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 Uj({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 Uj(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)}Wj({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Wj(e){let t=vj();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,si(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 Gj=`x-bypass-llm-proxy`;function Kj(e,t,n){return t?(r,i)=>{if(!qj(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(Gj)||a.set(Gj,`1`),e(r,{...i,headers:a})}:e}function qj(e,t,n){if(Yj(e,t))return!0;let r=n?.()??null;return r?Jj(e,r,t):!1}function Jj(e,t,n){let r=Xj(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 Yj(e,t){let n=Xj(e);try{return new URL(n,t).origin===t}catch{return!0}}function Xj(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Zj(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 Qj=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(!$j(e)||e.source!==`panel`)return;let t=e.payload;tM(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=bi(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?eM(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,eM(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 $j(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function eM(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function tM(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 nM=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)}}};function rM(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new Qj({transport:t,processManager:i,createShell:(a,o)=>new nM(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Dr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function iM(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return sM(e);if(typeof e==`object`)return cM(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function aM(e){if(typeof e==`object`&&e&&!(e instanceof Error))return uM(e)??dM(e);let t=iM(e);if(t!==void 0)return oM(t)}function oM(e){let t=e.trim();if(!t)return e;let n=lM(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=lM(t.slice(r,i+1));if(e)return e}return e}function sM(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function cM(e){let t=uM(e),n=dM(e);return n&&t?`${n}: ${t}`:t??n}function lM(e){if(e.startsWith(`{`))try{return uM(JSON.parse(e))}catch{return}}function uM(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 dM(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 fM=null,pM=!1;function mM(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function hM(e){return mM()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function gM(e={}){if(!pM&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){m(_M),ME(yM),nD(vM);try{let t=hM(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(fM=(await import(`./rum-worker-CwmNSpjO.js`)).default,SM(self)):t===`extension`?(fM=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&SM(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),kM(),wM(),fM=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),pM=!0,fM&&fM(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function _M(e){fM?.(`fill`,{source:e})}function vM(e,t){let n=xM(t);n!==null&&fM?.(`error`,{source:e,target:n})}function yM(e,t,n){if(e===`error`){let e=xM(n);if(e===null)return;fM?.(`error`,{source:`scoop:${t}`,target:e});return}fM?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function bM(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function xM(e){let t=iM(e);if(t===void 0)return e==null?void 0:null;if(uD(t))return null;let n=aM(e)??oM(t);return uD(n)?null:TM(n)}function SM(e){e.addEventListener(`error`,e=>{let t=e;vM(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{vM(`js`,e.reason)})}function CM(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function wM(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;CM(t)&&(vM(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;CM(t)&&(vM(`js`,t),e.stopImmediatePropagation())},!0))}function TM(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
1185
- `).filter(e=>!bM(e)).join(`
1186
- `).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 EM=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function DM(e){let t=typeof e==`string`?e:aM(e)??iM(e);if(typeof t!=`string`)return{kind:`absent`};let n=oM(t);if(n===`[object Object]`)return{kind:`noise`};let r=TM(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function OM(e){let t=DM(e.source),n=DM(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 kM(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[EM])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=OM(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[EM]=!0,navigator.sendBeacon=n}function AM(e){let t=new jM(e);return t.start(),{stop:()=>t.dispose()}}var jM=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(!MM(e)||e.source!==`panel`)return;let t=e.payload;if(NM(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(PM(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(FM(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 A(`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 A(`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 A(`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(IM(e.type),e.requestId,new A(`EACCES`,`vfs-rpc-host has no writable backend wired`),LM(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 A(`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 A(`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 A(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=RM(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=RM(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function MM(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function NM(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 PM(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 FM(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function IM(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 LM(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function RM(e,t){return e instanceof A?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function zM(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Kj(e.bind(globalThis),t,BM)}function BM(){let e=Ne();if(!e)return null;try{return new URL(e).origin}catch{return null}}function VM(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 HM=null,UM=null,WM=null,GM=null,KM=null,qM=null;const JM=Zj(e=>ZM(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&JM.handle(e.data)});function YM(e){let t=$a(e.pageBuildId,`6.180.0-mue1tk8m`);return()=>{t&&vM(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.180.0-mue1tk8m`)}}function XM(e){zM(),Me(e.localApiBaseUrl??null),je(e.bridgeToken??null),ci(e.syncFsBridgeEnabled??!1),t(e.pageLoadedAt??null),Ie(e.extensionDelegateId??null),VM(e.localStorageSeed??{}),e.flagFloat&&Ba(e.flagFloat)}async function ZM(e){Xa(e.instanceId);let t=YM(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{XM(e),gM().then(t).catch(()=>{}),await ke(),n(`providers-registered`);let r=no(e.kernelPort),i=new nx(r),a=nx.createCallbacks(i),o=new ro(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new fa(o);HM=await Hj({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=HM.sharedFs?.getWatcher();if(u){let e=null,t=new Set;for(let n of Si)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);qM=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=qM,s.setTrayTargetProvider(xa(Oe));let f=await $M({host:HM,transport:r,browser:s,instanceId:e.instanceId});f&&(UM=f.stopTerminalHost,WM=f.stopVfsRpcHost,GM=f.stopSpeechAssetsResponder,KM=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){QM(e.kernelPort,t)}}function QM(e,t){Qa(t);try{let n=t instanceof Error?t.message:String(t),r=t?.code;e.postMessage({type:`kernel-worker-boot-error`,message:n,...typeof r==`string`?{code:r}:{},...t instanceof Error&&t.stack?{stack:t.stack}:{}})}catch{}throw t}async function $M(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=()=>e.host.capabilityBroker.adapter===`node-rest`,r=rM({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=AM({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await eN(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 eN(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-0UZlYzUX.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CNe6icTW.js`).then(e=>e.i),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(UM?.(),UM=null,WM?.(),WM=null,GM?.(),GM=null,KM?.(),KM=null,qM?.dispose(),qM=null,HM?.dispose())});export{sv as _,xS as a,Na as b,jx as c,Nx as d,jb as f,Hv as g,kv as h,yS as i,Mx as l,Vy as m,xT as n,bS as o,Mb as p,vS as r,kx as s,YO as t,Ax as u,J_ as v,P_ as y};
1183
+ `}}const rj=Math.max(bi,gi)+5e3;function ij(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(Si(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(!mi(n.token))return;let a=i.get(n.id);if(a){r({type:_i,id:n.id}),a.result&&r({type:vi,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:_i,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),rj),r({type:vi,id:n.id,...e})};(yi(n)?xi(n):hi(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 aj(){return globalThis}function oj(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 my(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 sj(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 cj(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}lj(e,t)}async function lj(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=k(r),a=e.type===`discovery`&&!e.targetScoop?LA(e,i.filter(px),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?Ga(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!px(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-D1vFOKgN.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=Oy(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=oj(e),l=sj(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 uj(e,t,n,r,i){let a=new li,o=new CA(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=un(),l=i.capabilityBroker??c(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(l),_r(l),aj().__slicc_pm=a,ui(fi()),aj().__slicc_browser=t,await n.bind(o,t);let u=kr(()=>n.emitTrayRuntimeStatus()),d=we(()=>n.emitTrayRuntimeStatus());WA(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-B7KPVgHq.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 dj(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-DZQVtgRS.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await Promise.resolve().then(()=>A_);r(()=>a());let{getLickManager:o}=await Promise.resolve().then(()=>JT),s=o();await s.init(),e.setLickManager(s);let c=t.lickEventHandler??cj,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function fj(e){let t=e.getScoops();k(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 pj(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:a}=e;kA({sharedFs:a,getStartingRoot:e=>{let n=k(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)=>pi(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>u().slice(10,22),splitResult:(e,t)=>i(e,t)})}async function mj(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))+`
1184
+ `,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 hj(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-DdgwrW91.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-CMj5JyW-.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 gj(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 ix(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})},{..._j(t),isOwnTab:nx(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function _j(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:()=>ax()}}async function vj(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 yj(e,t,n,r,i,a){e&&(await xj(e,n,r),i(`mounts-restored`),await bj(e,t,n,r,a),i(`jshd-restored`))}async function bj(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-DVP0SPlY.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 xj(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(()=>ny),{applyConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-B7KPVgHq.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 Sj(){jr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-jhAzOLSL.js`);return e()})}function Cj(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-jhAzOLSL.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 wj(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DBtF-C4h.js`),{ScriptCatalog:r}=await import(`./script-catalog-DZtOMxvi.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 Tj(e){return e===`node-rest`}function Ej(e,t,n,r){import(`./gelatiere-unit-DxFUh33e.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-ChogqkEu.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function Dj(e,t){if(!e)return()=>{};import(`./memory-curation-seam-CNOuxuz4.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-BSo0HKQx.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 Oj(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}zv(e,t,e.getSessionStore())}async function kj(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Sj();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await uj(t,n,r,i,e);if(s(`orchestrator-ready`),Oj(l,f,o),f)try{await f.mountInternal(`/proc`,new GA(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await dj(l,e,o);s(`lick-manager-ready`),f&&pj({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),aj().__slicc_lickManager=m,Ej(l,m,f,o);let h=Dj(f,o),{wsBridge:ee,wsRegistry:g}=await mj({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});aj().__slicc_wsSubscribers=g;let te=Tj(p.adapter)?await hj(m,o,e.localLickWsUrl??null,f):null,ne=gj(n,m,o,e.appPageUrl);await yj(f,c,m,o,s,l),a||await fj(l),s(`cone-bootstrapped`),vj(l,m,o),f&&Cj(m,o);let re=null,_=null;f&&({bshWatchdogStop:re,scriptCatalogDispose:_}=await wj(f,n,o));let ie=null;f&&e.syncFsChannelNonce&&(ie=ij({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 Aj({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 Aj(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)}jj({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function jj(e){let t=aj();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,ui(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 Mj=`x-bypass-llm-proxy`;function Nj(e,t,n){return t?(r,i)=>{if(!Pj(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(Mj)||a.set(Mj,`1`),e(r,{...i,headers:a})}:e}function Pj(e,t,n){if(Ij(e,t))return!0;let r=n?.()??null;return r?Fj(e,r,t):!1}function Fj(e,t,n){let r=Lj(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 Ij(e,t){let n=Lj(e);try{return new URL(n,t).origin===t}catch{return!0}}function Lj(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Rj(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 zj=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(!Bj(e)||e.source!==`panel`)return;let t=e.payload;Hj(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=``;if(e.stdin)try{i=Ci(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?Vj(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,Vj(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 Bj(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Vj(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function Hj(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var Uj=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)}}};function Wj(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new zj({transport:t,processManager:i,createShell:(a,o)=>new Uj(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Ar},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Gj(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return Jj(e);if(typeof e==`object`)return Yj(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function Kj(e){if(typeof e==`object`&&e&&!(e instanceof Error))return Zj(e)??Qj(e);let t=Gj(e);if(t!==void 0)return qj(t)}function qj(e){let t=e.trim();if(!t)return e;let n=Xj(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=Xj(t.slice(r,i+1));if(e)return e}return e}function Jj(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function Yj(e){let t=Zj(e),n=Qj(e);return n&&t?`${n}: ${t}`:t??n}function Xj(e){if(e.startsWith(`{`))try{return Zj(JSON.parse(e))}catch{return}}function Zj(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 Qj(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 $j=null,eM=!1;function tM(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function nM(e){return tM()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function rM(e={}){if(!eM&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){m(iM),yE(oM),UE(aM);try{let t=nM(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?($j=(await import(`./rum-worker-CwmNSpjO.js`)).default,lM(self)):t===`extension`?($j=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&lM(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),gM(),dM(),$j=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),eM=!0,$j&&$j(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function iM(e){$j?.(`fill`,{source:e})}function aM(e,t){let n=cM(t);n!==null&&$j?.(`error`,{source:e,target:n})}function oM(e,t,n){if(e===`error`){let e=cM(n);if(e===null)return;$j?.(`error`,{source:`scoop:${t}`,target:e});return}$j?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function sM(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function cM(e){let t=Gj(e);if(t===void 0)return e==null?void 0:null;if(ZE(t))return null;let n=Kj(e)??qj(t);return ZE(n)?null:fM(n)}function lM(e){e.addEventListener(`error`,e=>{let t=e;aM(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{aM(`js`,e.reason)})}function uM(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function dM(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;uM(t)&&(aM(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;uM(t)&&(aM(`js`,t),e.stopImmediatePropagation())},!0))}function fM(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
1185
+ `).filter(e=>!sM(e)).join(`
1186
+ `).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 pM=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function mM(e){let t=typeof e==`string`?e:Kj(e)??Gj(e);if(typeof t!=`string`)return{kind:`absent`};let n=qj(t);if(n===`[object Object]`)return{kind:`noise`};let r=fM(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function hM(e){let t=mM(e.source),n=mM(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 gM(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[pM])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[pM]=!0,navigator.sendBeacon=n}function _M(e){let t=new vM(e);return t.start(),{stop:()=>t.dispose()}}var vM=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(!yM(e)||e.source!==`panel`)return;let t=e.payload;if(bM(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(xM(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(SM(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 A(`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 A(`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 A(`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(CM(e.type),e.requestId,new A(`EACCES`,`vfs-rpc-host has no writable backend wired`),wM(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 A(`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 A(`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 A(`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=TM(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=TM(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 yM(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function bM(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 xM(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 SM(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function CM(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 wM(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function TM(e,t){return e instanceof A?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function EM(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Nj(e.bind(globalThis),t,DM)}function DM(){let e=Ie();if(!e)return null;try{return new URL(e).origin}catch{return null}}function OM(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let kM=null,AM=null,jM=null,MM=null,NM=null,PM=null;const FM=Rj(e=>RM(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&FM.handle(e.data)});function IM(e){let t=Ba(e.pageBuildId,`6.181.0-mue9qgmb`);return()=>{t&&aM(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.181.0-mue9qgmb`)}}function LM(e){EM(),Fe(e.localApiBaseUrl??null),Pe(e.bridgeToken??null),di(e.syncFsBridgeEnabled??!1),t(e.pageLoadedAt??null),ze(e.extensionDelegateId??null),OM(e.localStorageSeed??{}),e.flagFloat&&Da(e.flagFloat)}async function RM(e){La(e.instanceId);let t=IM(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{LM(e),rM().then(t).catch(()=>{}),await Me(),n(`providers-registered`);let r=Ua(e.kernelPort),i=new Wb(r),a=Wb.createCallbacks(i),o=new Wa(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new ha(o);kM=await kj({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=kM.sharedFs?.getWatcher();if(u){let e=null,t=new Set;for(let n of Ti)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);PM=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=PM,s.setTrayTargetProvider(wa(Oe));let f=await BM({host:kM,transport:r,browser:s,instanceId:e.instanceId});f&&(AM=f.stopTerminalHost,jM=f.stopVfsRpcHost,MM=f.stopSpeechAssetsResponder,NM=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){zM(e.kernelPort,t)}}function zM(e,t){za(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 BM(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=Wj({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=_M({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await VM(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 VM(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CQ05z2Xw.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CNe6icTW.js`).then(e=>e.i),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(AM?.(),AM=null,jM?.(),jM=null,MM?.(),MM=null,NM?.(),NM=null,PM?.dispose(),PM=null,kM?.dispose())});export{Y_ as _,lS as a,yx as c,xx as d,yb as f,Av as g,_v as h,sS as i,bx as l,ky as m,cT as n,cS as o,bb as p,oS as r,_x as s,IO as t,vx as u,I_ as v,S_ as y};