sliccy 6.256.0 → 6.256.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/node-server/cloud-status.d.ts +8 -0
  2. package/dist/node-server/cloud-status.js +38 -0
  3. package/dist/ui/.vite/manifest.json +183 -183
  4. package/dist/ui/assets/{account-store-QxWo48Y1.js → account-store-CYXcTNmf.js} +1 -1
  5. package/dist/ui/assets/{account-store-DRK_jfiB.js → account-store-DLG3Av-u.js} +1 -1
  6. package/dist/ui/assets/{adobe-BwSa2oAU.js → adobe-DcrhMctx.js} +1 -1
  7. package/dist/ui/assets/{adobe-XnlO8IOa.js → adobe-OKBElK5I.js} +1 -1
  8. package/dist/ui/assets/{agent-panels-DLsxOOjW.js → agent-panels-ZG3ebUSL.js} +1 -1
  9. package/dist/ui/assets/{almost-bash-shell-headless-YXVG1DPI.js → almost-bash-shell-headless-RU8iANoA.js} +15 -15
  10. package/dist/ui/assets/{apply-layout-BtzT4Jrn.js → apply-layout-qj_IZphr.js} +1 -1
  11. package/dist/ui/assets/{azure-openai-BiTykqg3.js → azure-openai-DK0alNtF.js} +1 -1
  12. package/dist/ui/assets/{azure-openai-BH03ks5Y.js → azure-openai-DPYo4Wln.js} +1 -1
  13. package/dist/ui/assets/{bunny-probe-Bq1N-AVN.js → bunny-probe-DKhPxZeZ.js} +1 -1
  14. package/dist/ui/assets/{bunny-run-DyJVGqsu.js → bunny-run-DwKL9l6t.js} +1 -1
  15. package/dist/ui/assets/{cdp-Dm3JXxCN.js → cdp-DSFJzViN.js} +1 -1
  16. package/dist/ui/assets/{cerebras-Cj-dhgCb.js → cerebras-B9mbkTZf.js} +1 -1
  17. package/dist/ui/assets/{cerebras-B5dFzZuU.js → cerebras-Cm_8OStE.js} +1 -1
  18. package/dist/ui/assets/{composer-speech-0uRgiL71.js → composer-speech-CoFdC6Ue.js} +1 -1
  19. package/dist/ui/assets/{connect-surface-BQgwhG8d.js → connect-surface-BBRi7lly.js} +1 -1
  20. package/dist/ui/assets/{directed-approval-BxWIFFqA.js → directed-approval-DgdRwugK.js} +1 -1
  21. package/dist/ui/assets/{emscripten-vfs-hook-C73xuKfz.js → emscripten-vfs-hook-BGmnPBF-.js} +1 -1
  22. package/dist/ui/assets/{fast-path-hqxZk1HF.js → fast-path-D86NfZfu.js} +1 -1
  23. package/dist/ui/assets/{frozen-archive-writer-Cr1_j3pp.js → frozen-archive-writer-Dk602Q9A.js} +1 -1
  24. package/dist/ui/assets/{frozen-session-delete-CpcHR1XS.js → frozen-session-delete-D41KLb1Q.js} +1 -1
  25. package/dist/ui/assets/{frozen-session-identity-dpueujl9.js → frozen-session-identity-Wawl3rz4.js} +1 -1
  26. package/dist/ui/assets/{gelatiere-unit-PHQc3WNq.js → gelatiere-unit-NbtPiF37.js} +1 -1
  27. package/dist/ui/assets/{github-Bj8suNGU.js → github-C_k9XNGJ.js} +1 -1
  28. package/dist/ui/assets/{github-Dvjydy3P.js → github-D2A7mZDF.js} +1 -1
  29. package/dist/ui/assets/{github-copilot-CpJKXWfn.js → github-copilot-20yc0eqx.js} +1 -1
  30. package/dist/ui/assets/{github-copilot-D8DdUlya.js → github-copilot-D-lJD9JM.js} +1 -1
  31. package/dist/ui/assets/{hear-DDr5S4Od.js → hear-CS8KuGJo.js} +1 -1
  32. package/dist/ui/assets/{js-realm-worker-CXD4SmqZ.js → js-realm-worker-CvBctwsA.js} +2 -2
  33. package/dist/ui/assets/{jsh-executor-BFwK2t97.js → jsh-executor-B54XDkz2.js} +3 -3
  34. package/dist/ui/assets/{kernel-worker-DadD3ayk.js → kernel-worker-DS575H__.js} +9 -9
  35. package/dist/ui/assets/{lick-ws-bridge-Bq9kUe4V.js → lick-ws-bridge-BBZpW-Dg.js} +1 -1
  36. package/dist/ui/assets/{lick-ws-bridge-DMNf8klz.js → lick-ws-bridge-DMRxA0GE.js} +1 -1
  37. package/dist/ui/assets/{live-session-curation-CSJCW_xQ.js → live-session-curation-ChoGCSOH.js} +1 -1
  38. package/dist/ui/assets/{live-session-curation-CNk-iYCa.js → live-session-curation-nSX_c9Jb.js} +1 -1
  39. package/dist/ui/assets/{live-session-snapshot-BedjttIR.js → live-session-snapshot-BQcFx9d7.js} +1 -1
  40. package/dist/ui/assets/{local-llm-NE-qI2cb.js → local-llm-BdhJYy6M.js} +1 -1
  41. package/dist/ui/assets/{local-llm-qPIX8NMO.js → local-llm-cy-hboD7.js} +1 -1
  42. package/dist/ui/assets/{main-DVD6CfWm.js → main-BvTNS5M1.js} +3 -3
  43. package/dist/ui/assets/{main-cherry-ByF5f6AT.js → main-cherry-CLPxNUOm.js} +1 -1
  44. package/dist/ui/assets/{mcp-command-n1wIw393.js → mcp-command-Bshk9-8r.js} +10 -10
  45. package/dist/ui/assets/{memory-curation-seam-CjYHWDBt.js → memory-curation-seam-NFHXE0W5.js} +1 -1
  46. package/dist/ui/assets/{memory-health-DnbzPxqU.js → memory-health-DpXsg2PB.js} +1 -1
  47. package/dist/ui/assets/{memory-write-execute-BQg4KGxO.js → memory-write-execute-D4wz6znH.js} +1 -1
  48. package/dist/ui/assets/{merge-folded-cost-into-frozen-DA0swiNk.js → merge-folded-cost-into-frozen-Ce6e9pCy.js} +1 -1
  49. package/dist/ui/assets/{new-session-BHvzb7bp.js → new-session-DX7Em69X.js} +2 -2
  50. package/dist/ui/assets/{oauth-bootstrap-CqivQ7HA.js → oauth-bootstrap-BIoESN8s.js} +2 -2
  51. package/dist/ui/assets/{onboarding-orchestrator-C6UC6cTM.js → onboarding-orchestrator-DgsmYqKs.js} +1 -1
  52. package/dist/ui/assets/{openai-codex-B7A6dTqN.js → openai-codex-2LN44-VU.js} +1 -1
  53. package/dist/ui/assets/{openai-codex-xtvQmRuH.js → openai-codex-BNDOGlHP.js} +1 -1
  54. package/dist/ui/assets/{openrouter-CQeyGGEy.js → openrouter-B-qvuFIC.js} +1 -1
  55. package/dist/ui/assets/{openrouter-_6zsj8-6.js → openrouter-Cbloo6-N.js} +1 -1
  56. package/dist/ui/assets/{openrouter-free-BM772ovL.js → openrouter-free-CPMEIAmD.js} +1 -1
  57. package/dist/ui/assets/{openrouter-free-Du1No0Z_.js → openrouter-free-YgWGIS-T.js} +1 -1
  58. package/dist/ui/assets/{openrouter-oauth-BSSNY_G1.js → openrouter-oauth-DspK3V7c.js} +1 -1
  59. package/dist/ui/assets/{openrouter-oauth-D9dklyIn.js → openrouter-oauth-d_WhF-i_.js} +1 -1
  60. package/dist/ui/assets/{panel-rpc-handlers-rMOPHOSf.js → panel-rpc-handlers-CiVSlbYh.js} +2 -2
  61. package/dist/ui/assets/{panelize-shell-DLm7AfDp.js → panelize-shell-CszEdwrr.js} +1 -1
  62. package/dist/ui/assets/{pi-edit-execution-dq5caQ-R.js → pi-edit-execution-BOt2UG1t.js} +1 -1
  63. package/dist/ui/assets/{provider-4M0-Za9p.js → provider-Da_Xha6T.js} +1 -1
  64. package/dist/ui/assets/{provider-C6V5bKb2.js → provider-ic7srMSZ.js} +1 -1
  65. package/dist/ui/assets/{provider-settings-C46VEmp7.js → provider-settings-DXTVzWZr.js} +1 -1
  66. package/dist/ui/assets/provider-store-access-C1OIs0Sn.js +1 -0
  67. package/dist/ui/assets/provider-store-access-C94YO93f.js +1 -0
  68. package/dist/ui/assets/{providers-B5VMaUWX.js → providers-BwKmSpLH.js} +2 -2
  69. package/dist/ui/assets/{providers-Bw0birsa.js → providers-DinkpGvr.js} +1 -1
  70. package/dist/ui/assets/{quick-llm-D5hmdHQQ.js → quick-llm-4ddeV6ZI.js} +1 -1
  71. package/dist/ui/assets/{realm-inprocess-DsBZtVOH.js → realm-inprocess-gfLwWl-i.js} +2 -2
  72. package/dist/ui/assets/{realm-unhandled-rejections-BDHLlsLp.js → realm-unhandled-rejections-CkX1BGEd.js} +1 -1
  73. package/dist/ui/assets/{realm-unhandled-rejections-BDnl84l4.js → realm-unhandled-rejections-iuOFsoIO.js} +1 -1
  74. package/dist/ui/assets/{remote-terminal-view-DYm18AE3.js → remote-terminal-view-DM_rdDTN.js} +2 -2
  75. package/dist/ui/assets/{restore-CKcu1P_Z.js → restore-ku3NI9gU.js} +1 -1
  76. package/dist/ui/assets/{run-Ds-D_Vog.js → run-B9uXGQYv.js} +2 -2
  77. package/dist/ui/assets/{run-DS9gNHJH.js → run-BHLpn7EO.js} +2 -2
  78. package/dist/ui/assets/{run-BV4IO7_J.js → run-C9mlrs_A.js} +1 -1
  79. package/dist/ui/assets/{run-C4x_nui1.js → run-DbR82j2G.js} +2 -2
  80. package/dist/ui/assets/{run-C1jQodOF.js → run-YyW5Bd1z.js} +1 -1
  81. package/dist/ui/assets/{run-DYDjMUGP.js → run-kDywGyI_.js} +2 -2
  82. package/dist/ui/assets/{run-CRGyQPIr.js → run-oiQnjELg.js} +1 -1
  83. package/dist/ui/assets/{serve-command-Dxu0zqDl.js → serve-command-CYP3K9ID.js} +2 -2
  84. package/dist/ui/assets/{serve-runtime-CEmOBSkh.js → serve-runtime-CwPc5Ipg.js} +1 -1
  85. package/dist/ui/assets/{session-command-memory-CZZ78BU8.js → session-command-memory-Bjbktm7f.js} +2 -2
  86. package/dist/ui/assets/{session-jsonl-kHYH-7Ib.js → session-jsonl-DvM9G2Ke.js} +1 -1
  87. package/dist/ui/assets/{session-search-index-eJnlwzC6.js → session-search-index-DtkT95V1.js} +1 -1
  88. package/dist/ui/assets/{setup-feature-flags-remote-Ci3nvXGY.js → setup-feature-flags-remote-DVDOwgnm.js} +1 -1
  89. package/dist/ui/assets/{setup-model-catalog-DWI-pcXH.js → setup-model-catalog-D_3w06PR.js} +1 -1
  90. package/dist/ui/assets/{silent-renew-backoff-2lMvXpiU.js → silent-renew-backoff-CAjvUu0c.js} +1 -1
  91. package/dist/ui/assets/slicc-version-CJuEM6d6.js +1 -0
  92. package/dist/ui/assets/{soundscape-DK8vzDpK.js → soundscape-BBfqPI7l.js} +1 -1
  93. package/dist/ui/assets/{speak-D_AKrPu0.js → speak-BZjF8HVW.js} +1 -1
  94. package/dist/ui/assets/{sprinkle-manager-CJGReRLz.js → sprinkle-manager-CZEpPXOO.js} +1 -1
  95. package/dist/ui/assets/{sprinkle-renderer-CcWhSBfB.js → sprinkle-renderer-BkwlbHXw.js} +1 -1
  96. package/dist/ui/assets/{src-DWA1MizA.js → src-BQREyqyX.js} +63 -63
  97. package/dist/ui/assets/{ssh-CAQr291h.js → ssh-COAG0Prl.js} +1 -1
  98. package/dist/ui/assets/{sudo-CSzJTCd9.js → sudo-wabmuIKV.js} +1 -1
  99. package/dist/ui/assets/{supervisor-DBofbxjT.js → supervisor-B2nXofh7.js} +1 -1
  100. package/dist/ui/assets/{sync-dialog-FwBEmm7W.js → sync-dialog-CHmuJIFU.js} +1 -1
  101. package/dist/ui/assets/{transformers-env-DfuTpXXR.js → transformers-env-CHgjo8-d.js} +1 -1
  102. package/dist/ui/assets/tray-leader-DG6Rmdd2.js +1 -0
  103. package/dist/ui/assets/{tray-leave-runtime-BoVSKaCt.js → tray-leave-runtime-CHqFireQ.js} +1 -1
  104. package/dist/ui/assets/{tray-sidecar-CYuPitKs.js → tray-sidecar-DM4mHGds.js} +1 -1
  105. package/dist/ui/assets/{upgrade-detection-B8TZhKUa.js → upgrade-detection-XwHj-EZO.js} +1 -1
  106. package/dist/ui/assets/{upgrade-to-seven-B2H6KnlF.js → upgrade-to-seven-DnMOrCDQ.js} +1 -1
  107. package/dist/ui/assets/{voice-reply-BKaB8Asb.js → voice-reply-DJEUbUbb.js} +1 -1
  108. package/dist/ui/assets/{wc-attach-CoR9zN1R.js → wc-attach-Blm4ssVC.js} +2 -2
  109. package/dist/ui/assets/{wc-browser-D2k3tkR-.js → wc-browser-DzD5njrA.js} +1 -1
  110. package/dist/ui/assets/{wc-computers-CPX2x6Th.js → wc-computers-BDapcAz_.js} +1 -1
  111. package/dist/ui/assets/{wc-detached-BHiC5h-Y.js → wc-detached-6AHVMP_P.js} +1 -1
  112. package/dist/ui/assets/{wc-extension-DnJc8F1P.js → wc-extension-Hao4ySoS.js} +2 -2
  113. package/dist/ui/assets/{wc-follower-CpqjednQ.js → wc-follower-CwMgvm3U.js} +3 -3
  114. package/dist/ui/assets/{wc-follower-oauth-CjMFLgHd.js → wc-follower-oauth-DDwNrB05.js} +1 -1
  115. package/dist/ui/assets/{wc-gelatiere-B1UhGGlW.js → wc-gelatiere-BAPOL7Z1.js} +1 -1
  116. package/dist/ui/assets/{wc-live-MMV5wx1F.js → wc-live-Cw6xVOGo.js} +5 -5
  117. package/dist/ui/assets/{wc-nav-BLmah4u4.js → wc-nav-CMY9ERM1.js} +2 -2
  118. package/dist/ui/assets/{wc-onboarding-BLjMaifw.js → wc-onboarding-bNg06Z62.js} +2 -2
  119. package/dist/ui/assets/{wc-permissions-BH_pyjzt.js → wc-permissions-D0w94vXH.js} +2 -2
  120. package/dist/ui/assets/{wc-placeholder-B5m9keHf.js → wc-placeholder-Ch7fQFM1.js} +2 -2
  121. package/dist/ui/assets/{wc-profile-export-CUSnMx4l.js → wc-profile-export-BFF90Vk2.js} +3 -3
  122. package/dist/ui/assets/{wc-secret-request-COrsGNVO.js → wc-secret-request-pXJeMHeS.js} +1 -1
  123. package/dist/ui/assets/{wc-settings-DbOCHvQA.js → wc-settings-KGpHvHOO.js} +3 -3
  124. package/dist/ui/assets/{wc-shell-Xrw2Q_l-.js → wc-shell-B5uhQoSH.js} +3 -3
  125. package/dist/ui/assets/{wc-shortcut-config-BQBPwMA2.js → wc-shortcut-config-DCatL4tb.js} +1 -1
  126. package/dist/ui/assets/{wc-sprinkles-D752QtPV.js → wc-sprinkles-BQyYYsOa.js} +2 -2
  127. package/dist/ui/assets/{wc-transcript-export-DvAF0rPF.js → wc-transcript-export-DyqvXeuU.js} +2 -2
  128. package/dist/ui/assets/wc-tray-CjYFNQr2.js +5 -0
  129. package/dist/ui/assets/welcome-detection-t1oPE25e.js +1 -0
  130. package/dist/ui/assets/{whisper-session-CExf0vBt.js → whisper-session-6A5TUCSd.js} +2 -2
  131. package/dist/ui/assets/{xai-grok-iOYIBxH8.js → xai-grok-5TMXFoso.js} +1 -1
  132. package/dist/ui/assets/{xai-grok-Cfob0nrx.js → xai-grok-CFvK8Gfg.js} +1 -1
  133. package/dist/ui/index.html +3 -3
  134. package/dist/ui/packages/webapp/index.html +3 -3
  135. package/dist/ui/packages/webapp/upgrade-to-seven.html +1 -1
  136. package/dist/ui/upgrade-to-seven.html +1 -1
  137. package/package.json +1 -1
  138. package/dist/ui/assets/provider-store-access-CgaKC7rB.js +0 -1
  139. package/dist/ui/assets/provider-store-access-DgrYdKML.js +0 -1
  140. package/dist/ui/assets/slicc-version-ComMn6Xo.js +0 -1
  141. package/dist/ui/assets/tray-leader-1ntSUEXa.js +0 -1
  142. package/dist/ui/assets/wc-tray-QWpxQYLb.js +0 -5
  143. package/dist/ui/assets/welcome-detection-Ny04c6Rd.js +0 -1
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DBVvNlSN.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,o as d,p as f,r as p,t as m,u as ee,v as te,y as ne}from"./almost-bash-shell-headless-YXVG1DPI.js";import{t as h}from"./logger-Cx6Y120U.js";import{r as re,t as ie}from"./base64-BPBW1Gzr.js";import{i as ae,r as oe}from"./handoff-link-B3It6xQY.js";import{C as se,a as ce,b as le,f as ue,g as de,h as fe,i as pe,m as me,p as he,v as ge,x as _e,y as ve}from"./account-store-QxWo48Y1.js";import{n as ye}from"./proxied-fetch-1DfC_94U.js";import{t as be}from"./sha256-DynDhwRL.js";import{t as xe}from"./slugify-BYJ6QVAt.js";import{i as Se,n as Ce,t as we}from"./archive-redaction-Bi6veJCs.js";import{a as Te,o as Ee}from"./host-command-CkJyrXy3.js";import{h as De}from"./snapshot-BqARfI1v.js";import{t as Oe}from"./panel-rpc-accessor-B4BfPLSo.js";import{n as ke}from"./panel-rpc-BJU93e51.js";import{i as Ae,l as je,o as Me,r as Ne}from"./feature-flags-CoR3q8DD.js";import{a as Pe,t as Fe}from"./providers-Bw0birsa.js";import{c as Ie,d as Le,o as Re,s as ze,t as Be,u as Ve}from"./api-endpoint-D8lUKmPu.js";import{_ as He,a as Ue,c as We,l as Ge,m as Ke,p as qe,s as Je,u as Ye}from"./models-7tbZ9MB5.js";import{o as Xe,t as Ze}from"./compat-CuWVDYYO.js";import{i as Qe,n as $e,r as et,t as tt}from"./context-compaction-BvTawIjc.js";import{t as nt}from"./utf16-clip-Dcxt-q1C.js";import{r as rt,t as it}from"./core-TaEErdII.js";import{n as at}from"./float-topology-87nCRxRw.js";import{t as ot}from"./secrets-bridge-client-DlJPW3h4.js";import{n as st,t as ct}from"./image-markers-B82WnSyf.js";import{i as lt}from"./tool-ui-blvQ8qgI.js";import{l as ut,t as dt}from"./claude-model-version-BlyDyuTC.js";import{a as ft,n as pt,t as mt}from"./path-utils-DNJG-zQf.js";import{t as ht}from"./merge-file-core-YFxa1Gy8.js";import{i as gt,n as _t,r as vt,t as yt}from"./workspace-mode-CIL8WpBe.js";import{C as bt,D as xt,E as St,O as Ct,S as wt,T as Tt,_ as Et,a as Dt,c as Ot,d as kt,f as At,g as jt,h as Mt,l as Nt,m as Pt,n as Ft,o as It,p as Lt,r as Rt,s as zt,t as Bt,u as Vt,v as Ht,w as Ut,y as Wt}from"./record-DTUQtot0.js";import{a as Gt,c as Kt,d as qt,i as Jt,l as Yt,n as Xt,o as Zt,r as Qt,s as $t,u as en}from"./descriptor-3sZ9zo81.js";import{n as tn,t as nn}from"./thinking-level-5x0UAu9N.js";import{t as g}from"./types-D8gIX-W-.js";import{i as rn,n as an}from"./mount-index-LvDi_MEB.js";import{a as on,i as sn,n as cn,r as ln,s as un,t as dn}from"./signed-fetch-B4_syuGv.js";import{n as fn}from"./mount-table-store-xM3U8UHg.js";import{t as pn}from"./remote-cache-MMXYpOmA.js";import{i as mn,n as hn,r as gn}from"./fs-DNsJRW_E.js";import{i as _n,n as vn,t as yn}from"./key-D3gIEgUz.js";import{n as bn,r as xn,t as Sn}from"./tray-leader-status-BPM2zVsj.js";import"./tray-runtime-config-BvQtvIxB.js";import{r as Cn}from"./slicc-version-ComMn6Xo.js";import{r as wn}from"./virtual-device-paths-C4gV0QwB.js";import{a as Tn}from"./gelatiere-constants-BYJlhm8R.js";import{a as En,i as Dn,r as On}from"./cost-command-CG3mKA1r.js";import{_ as kn,a as An,c as jn,d as Mn,f as Nn,g as Pn,h as Fn,l as In,m as Ln,n as Rn,p as zn,r as Bn,s as Vn,t as Hn,u as Un,v as Wn}from"./sudoers-2C-BpgXh.js";import{n as Gn,r as Kn,t as qn}from"./sudo-fs-Ou8-0Q4u.js";import{t as Jn}from"./llm-session-id-BkEQhxBR.js";import{t as Yn}from"./src-SFACrjnb.js";import{a as Xn,i as Zn,n as Qn,o as $n,s as er}from"./memory-budget-CFfevxz_.js";import{i as tr,n as nr,r as rr,t as ir}from"./frontmatter-DRCezvro.js";import{i as ar}from"./browser-DKcnER7J.js";import{c as or,r as sr,s as cr}from"./pipe-status-BBrT3VeG.js";import{n as lr}from"./just-bash-compat-DWUHpp9U.js";import{t as ur}from"./jsh-discovery-D7D5iKYT.js";import{t as dr}from"./process-manager-Dy17Kify.js";import{a as fr,i as pr,s as mr,t as hr}from"./jsh-executor-BFwK2t97.js";import{C as gr,_ as _r,b as vr,f as yr,h as br,l as xr,n as Sr,r as Cr,x as wr}from"./sync-exec-dispatch-Cy_hRFJu.js";import{t as Tr}from"./lick-target-env-8JxfVcIV.js";const Er=[`/workspace`,`/shared`,`/scoops`,`/home`];var Dr=class{pending=/* @__PURE__ */ new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function Or(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 kr=h(`cdp`);function Ar(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 jr=class{ws=null;nextId=1;_superseded=!1;pending=new Dr;listeners=/* @__PURE__ */ new Map;_state=`disconnected`;stateListeners=/* @__PURE__ */ new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(/* @__PURE__ */ Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,kr.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(kr.error(`Connection failed`,{url:t}),this.cleanup(),i(/* @__PURE__ */ Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),kr.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),kr.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}on(e,t){let n=this.listeners.get(e);n||(n=/* @__PURE__ */ new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return Or(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;kr.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(kr.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,/* @__PURE__ */ Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;kr.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,kr.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?kr.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):kr.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Ar(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 Mr({attempt:e,baseMs:t,capMs:n,jitter:r=0,maxShift:i,random:a=Math.random}){let o=Math.max(0,e);i!==void 0&&(o=Math.min(o,i));let s=t*2**o,c=n===void 0?s:Math.min(n,s);if(r<=0)return c;let l=c+Math.round(c*r*a());return n===void 0?l:Math.min(n,l)}function Nr(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Pr(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Fr=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Ir(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Fr.map(e=>Lr(i,e,t,r)))).filter(e=>e!==null)}async function Lr(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(/* @__PURE__ */ Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal,redirect:`manual`,credentials:`omit`});return e.status!==200||!Rr(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Rr(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}var zr=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`}},Br=class extends Error{constructor(){super(`CDP reconnect is backing off`),this.name=`CdpReconnectBackoffError`}};function Vr(e,t=Math.random){return Mr({attempt:e,baseMs:250,capMs:3e4,jitter:.2,maxShift:16,random:t})}function Hr(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var Ur=class{lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;reconnectAttempt=0;reconnectNotBefore=0;bridgeRejection=null;bridgeRejectedHandler=null;bridgeRejectedNotified=!1;classifyConnectFailure=async()=>`transient`;primeConnectOptions(e){this.lastConnectOptions=e?{...e}:{}}setSupersededHandler(e){this.supersededHandler=e}setBridgeRejectedHandler(e){this.bridgeRejectedHandler=e}setConnectFailureClassifier(e){this.classifyConnectFailure=e}async connect(e,t){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new zr(this.bridgeRejection);this.lastConnectOptions=t?{...t}:{};try{await e.connect({url:t?.url??Hr(),timeout:t?.timeout,...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t),this.bridgeRejection?new zr(this.bridgeRejection):e}this.noteReconnectSuccess()}async ensureLocalConnected(e){if(e.superseded===!0){this.notifySuperseded();return}if(e.state===`disconnected`){this.throwIfReconnectPaused();let t=this.lastConnectOptions;try{await e.connect({url:t?.url??Hr(),...t?.timeout===void 0?{}:{timeout:t.timeout},...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t??void 0),this.bridgeRejection?new zr(this.bridgeRejection):e}this.noteReconnectSuccess()}}async ensureConnected(e){if(e.client.superseded===!0){this.notifySuperseded();return}if(e.client.state===`disconnected`){this.throwIfReconnectPaused();let t=e.client;e.restoreLocalAfterRemoteDrop(),e.clearSessionsForTransport(t),e.getClient().state===`disconnected`&&await this.connect(e.getClient(),this.lastConnectOptions??void 0)}}throwIfReconnectPaused(){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new zr(this.bridgeRejection);if(Date.now()<this.reconnectNotBefore)throw new Br}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 zr().message,this.notifyBridgeRejected();return}let t=Vr(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{}}}},Wr=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 Gr(e,t){if(e?.aborted)throw new Wr(t)}function Kr(e,t){return e?{signal:e,error:()=>new Wr(t)}:void 0}function qr(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new Wr(n));return}let a=()=>{clearTimeout(o),i(new Wr(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Jr(e,t,n){return t?t.aborted?Promise.reject(new Wr(n)):new Promise((r,i)=>{let a=()=>i(new Wr(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var Yr=class{contexts=/* @__PURE__ */ new Map;for(e,t){let n=`${t}:${e}`,r=this.contexts.get(n);return r||(r=/* @__PURE__ */ new Map,this.contexts.set(n,r)),r}peek(e,t){return this.contexts.get(`${t}:${e}`)}drop(e){this.contexts.delete(`main:${e}`),this.contexts.delete(`isolated:${e}`)}get size(){return this.contexts.size}};const Xr=h(`har-recorder`);var Zr=class{recordings=/* @__PURE__ */ new Map;client;fs;eventCleanup=/* @__PURE__ */ new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Gr(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Gr(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Gr(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:/* @__PURE__ */ new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),Xr.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=>{Xr.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=>{Xr.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 Qr(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Xr.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 Xr.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),Xr.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 Xr.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 Qr(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){Xr.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Xr.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var $r=class{maxSessions;onEvict;sessions=/* @__PURE__ */ new Map;pinnedTargets=/* @__PURE__ */ new Map;appliedSends=/* @__PURE__ */ new Map;constructor(e=32,t){this.maxSessions=e,this.onEvict=t}get size(){return this.sessions.size}get(e){return this.sessions.get(e)}has(e){return this.sessions.has(e)}values(){return this.sessions.values()}entries(){return this.sessions.entries()}snapshot(){return[...this.sessions]}remember(e,t){this.pruneAppliedSends(),this.sessions.set(e,t),this.enforceCap(e)}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}take(e){let t=this.sessions.get(e);return t&&this.sessions.delete(e),t}delete(e){this.sessions.delete(e)}clear(){this.sessions.clear()}pin(e){this.pinnedTargets.set(e,(this.pinnedTargets.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(this.pinnedTargets.get(e)??1)-1;n>0?this.pinnedTargets.set(e,n):this.pinnedTargets.delete(e),this.enforceCap()}}isPinned(e){return this.pinnedTargets.has(e)}enforceCap(e){for(;this.sessions.size>this.maxSessions;){let t;for(let n of this.sessions.keys())if(!(n===e||this.pinnedTargets.has(n))){t=n;break}if(t===void 0)return;let n=this.sessions.get(t);this.sessions.delete(t),n&&this.onEvict?.(t,n)}}noteApplied(e){this.appliedSends.set(e,(this.appliedSends.get(e)??0)+1)}appliedCount(e){return this.appliedSends.get(e)??0}pruneAppliedSends(){if(this.appliedSends.size<=this.maxSessions*4)return;let e=new Set([...this.sessions.values()].map(e=>e.sessionId));for(let t of[...this.appliedSends.keys()])e.has(t)||this.appliedSends.delete(t)}findBySessionId(e){for(let[t,n]of this.sessions)if(n.sessionId===e)return[t,n]}findByTargetOrLocalId(e){let t=[];for(let[n,r]of this.sessions)(n===e||r.remote?.localTargetId===e)&&t.push([n,r]);return t}anyOnTransport(e){for(let t of this.sessions.values())if(t.transport===e)return!0;return!1}anyMatchingRemote(e,t){for(let n of this.sessions.values())if(n.remote?.runtimeId===e&&n.remote.localTargetId===t)return!0;return!1}};const ei=`slicc.ariaRefs`,ti=[`textbox`,`button`,`link`,`checkbox`,`radio`,`iframe`];function ni(e=0){return`(${ai})(${Number.isSafeInteger(e)&&e>0?e:0})`}function ri(e){return`(function(ref) {
1
+ import{n as e}from"./rolldown-runtime-DBVvNlSN.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,o as d,p as f,r as p,t as m,u as ee,v as te,y as ne}from"./almost-bash-shell-headless-RU8iANoA.js";import{t as h}from"./logger-Cx6Y120U.js";import{r as re,t as ie}from"./base64-BPBW1Gzr.js";import{i as ae,r as oe}from"./handoff-link-B3It6xQY.js";import{C as se,a as ce,b as le,f as ue,g as de,h as fe,i as pe,m as me,p as he,v as ge,x as _e,y as ve}from"./account-store-CYXcTNmf.js";import{n as ye}from"./proxied-fetch-1DfC_94U.js";import{t as be}from"./sha256-DynDhwRL.js";import{t as xe}from"./slugify-BYJ6QVAt.js";import{i as Se,n as Ce,t as we}from"./archive-redaction-Bi6veJCs.js";import{a as Te,o as Ee}from"./host-command-CkJyrXy3.js";import{h as De}from"./snapshot-BqARfI1v.js";import{t as Oe}from"./panel-rpc-accessor-B4BfPLSo.js";import{n as ke}from"./panel-rpc-BJU93e51.js";import{i as Ae,l as je,o as Me,r as Ne}from"./feature-flags-CoR3q8DD.js";import{a as Pe,t as Fe}from"./providers-DinkpGvr.js";import{c as Ie,d as Le,o as Re,s as ze,t as Be,u as Ve}from"./api-endpoint-D8lUKmPu.js";import{_ as He,a as Ue,c as We,l as Ge,m as Ke,p as qe,s as Je,u as Ye}from"./models-7tbZ9MB5.js";import{o as Xe,t as Ze}from"./compat-CuWVDYYO.js";import{i as Qe,n as $e,r as et,t as tt}from"./context-compaction-BvTawIjc.js";import{t as nt}from"./utf16-clip-Dcxt-q1C.js";import{r as rt,t as it}from"./core-TaEErdII.js";import{n as at}from"./float-topology-87nCRxRw.js";import{t as ot}from"./secrets-bridge-client-DlJPW3h4.js";import{n as st,t as ct}from"./image-markers-B82WnSyf.js";import{i as lt}from"./tool-ui-blvQ8qgI.js";import{l as ut,t as dt}from"./claude-model-version-BlyDyuTC.js";import{a as ft,n as pt,t as mt}from"./path-utils-DNJG-zQf.js";import{t as ht}from"./merge-file-core-YFxa1Gy8.js";import{i as gt,n as _t,r as vt,t as yt}from"./workspace-mode-CIL8WpBe.js";import{C as bt,D as xt,E as St,O as Ct,S as wt,T as Tt,_ as Et,a as Dt,c as Ot,d as kt,f as At,g as jt,h as Mt,l as Nt,m as Pt,n as Ft,o as It,p as Lt,r as Rt,s as zt,t as Bt,u as Vt,v as Ht,w as Ut,y as Wt}from"./record-DTUQtot0.js";import{a as Gt,c as Kt,d as qt,i as Jt,l as Yt,n as Xt,o as Zt,r as Qt,s as $t,u as en}from"./descriptor-3sZ9zo81.js";import{n as tn,t as nn}from"./thinking-level-5x0UAu9N.js";import{t as g}from"./types-D8gIX-W-.js";import{i as rn,n as an}from"./mount-index-LvDi_MEB.js";import{a as on,i as sn,n as cn,r as ln,s as un,t as dn}from"./signed-fetch-B4_syuGv.js";import{n as fn}from"./mount-table-store-xM3U8UHg.js";import{t as pn}from"./remote-cache-MMXYpOmA.js";import{i as mn,n as hn,r as gn}from"./fs-DNsJRW_E.js";import{i as _n,n as vn,t as yn}from"./key-D3gIEgUz.js";import{n as bn,r as xn,t as Sn}from"./tray-leader-status-BPM2zVsj.js";import"./tray-runtime-config-BvQtvIxB.js";import{r as Cn}from"./slicc-version-CJuEM6d6.js";import{r as wn}from"./virtual-device-paths-C4gV0QwB.js";import{a as Tn}from"./gelatiere-constants-BYJlhm8R.js";import{a as En,i as Dn,r as On}from"./cost-command-CG3mKA1r.js";import{_ as kn,a as An,c as jn,d as Mn,f as Nn,g as Pn,h as Fn,l as In,m as Ln,n as Rn,p as zn,r as Bn,s as Vn,t as Hn,u as Un,v as Wn}from"./sudoers-2C-BpgXh.js";import{n as Gn,r as Kn,t as qn}from"./sudo-fs-Ou8-0Q4u.js";import{t as Jn}from"./llm-session-id-BkEQhxBR.js";import{t as Yn}from"./src-SFACrjnb.js";import{a as Xn,i as Zn,n as Qn,o as $n,s as er}from"./memory-budget-CFfevxz_.js";import{i as tr,n as nr,r as rr,t as ir}from"./frontmatter-DRCezvro.js";import{i as ar}from"./browser-DKcnER7J.js";import{c as or,r as sr,s as cr}from"./pipe-status-BBrT3VeG.js";import{n as lr}from"./just-bash-compat-DWUHpp9U.js";import{t as ur}from"./jsh-discovery-D7D5iKYT.js";import{t as dr}from"./process-manager-Dy17Kify.js";import{a as fr,i as pr,s as mr,t as hr}from"./jsh-executor-B54XDkz2.js";import{C as gr,_ as _r,b as vr,f as yr,h as br,l as xr,n as Sr,r as Cr,x as wr}from"./sync-exec-dispatch-Cy_hRFJu.js";import{t as Tr}from"./lick-target-env-8JxfVcIV.js";const Er=[`/workspace`,`/shared`,`/scoops`,`/home`];var Dr=class{pending=/* @__PURE__ */ new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function Or(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 kr=h(`cdp`);function Ar(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 jr=class{ws=null;nextId=1;_superseded=!1;pending=new Dr;listeners=/* @__PURE__ */ new Map;_state=`disconnected`;stateListeners=/* @__PURE__ */ new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(/* @__PURE__ */ Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,kr.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(kr.error(`Connection failed`,{url:t}),this.cleanup(),i(/* @__PURE__ */ Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),kr.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),kr.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}on(e,t){let n=this.listeners.get(e);n||(n=/* @__PURE__ */ new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return Or(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;kr.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(kr.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,/* @__PURE__ */ Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;kr.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,kr.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?kr.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):kr.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(Ar(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 Mr({attempt:e,baseMs:t,capMs:n,jitter:r=0,maxShift:i,random:a=Math.random}){let o=Math.max(0,e);i!==void 0&&(o=Math.min(o,i));let s=t*2**o,c=n===void 0?s:Math.min(n,s);if(r<=0)return c;let l=c+Math.round(c*r*a());return n===void 0?l:Math.min(n,l)}function Nr(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}function Pr(e){return[e.origin??``,e.kind??``,e.url??``].join(`\0`)}const Fr=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Ir(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Fr.map(e=>Lr(i,e,t,r)))).filter(e=>e!==null)}async function Lr(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(/* @__PURE__ */ Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal,redirect:`manual`,credentials:`omit`});return e.status!==200||!Rr(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function Rr(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}var zr=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`}},Br=class extends Error{constructor(){super(`CDP reconnect is backing off`),this.name=`CdpReconnectBackoffError`}};function Vr(e,t=Math.random){return Mr({attempt:e,baseMs:250,capMs:3e4,jitter:.2,maxShift:16,random:t})}function Hr(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var Ur=class{lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;reconnectAttempt=0;reconnectNotBefore=0;bridgeRejection=null;bridgeRejectedHandler=null;bridgeRejectedNotified=!1;classifyConnectFailure=async()=>`transient`;primeConnectOptions(e){this.lastConnectOptions=e?{...e}:{}}setSupersededHandler(e){this.supersededHandler=e}setBridgeRejectedHandler(e){this.bridgeRejectedHandler=e}setConnectFailureClassifier(e){this.classifyConnectFailure=e}async connect(e,t){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new zr(this.bridgeRejection);this.lastConnectOptions=t?{...t}:{};try{await e.connect({url:t?.url??Hr(),timeout:t?.timeout,...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t),this.bridgeRejection?new zr(this.bridgeRejection):e}this.noteReconnectSuccess()}async ensureLocalConnected(e){if(e.superseded===!0){this.notifySuperseded();return}if(e.state===`disconnected`){this.throwIfReconnectPaused();let t=this.lastConnectOptions;try{await e.connect({url:t?.url??Hr(),...t?.timeout===void 0?{}:{timeout:t.timeout},...t?.protocols===void 0?{}:{protocols:t.protocols}})}catch(e){throw await this.noteReconnectFailure(t??void 0),this.bridgeRejection?new zr(this.bridgeRejection):e}this.noteReconnectSuccess()}}async ensureConnected(e){if(e.client.superseded===!0){this.notifySuperseded();return}if(e.client.state===`disconnected`){this.throwIfReconnectPaused();let t=e.client;e.restoreLocalAfterRemoteDrop(),e.clearSessionsForTransport(t),e.getClient().state===`disconnected`&&await this.connect(e.getClient(),this.lastConnectOptions??void 0)}}throwIfReconnectPaused(){if(this.bridgeRejection)throw this.notifyBridgeRejected(),new zr(this.bridgeRejection);if(Date.now()<this.reconnectNotBefore)throw new Br}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 zr().message,this.notifyBridgeRejected();return}let t=Vr(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{}}}},Wr=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 Gr(e,t){if(e?.aborted)throw new Wr(t)}function Kr(e,t){return e?{signal:e,error:()=>new Wr(t)}:void 0}function qr(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new Wr(n));return}let a=()=>{clearTimeout(o),i(new Wr(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function Jr(e,t,n){return t?t.aborted?Promise.reject(new Wr(n)):new Promise((r,i)=>{let a=()=>i(new Wr(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var Yr=class{contexts=/* @__PURE__ */ new Map;for(e,t){let n=`${t}:${e}`,r=this.contexts.get(n);return r||(r=/* @__PURE__ */ new Map,this.contexts.set(n,r)),r}peek(e,t){return this.contexts.get(`${t}:${e}`)}drop(e){this.contexts.delete(`main:${e}`),this.contexts.delete(`isolated:${e}`)}get size(){return this.contexts.size}};const Xr=h(`har-recorder`);var Zr=class{recordings=/* @__PURE__ */ new Map;client;fs;eventCleanup=/* @__PURE__ */ new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Gr(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Gr(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Gr(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:/* @__PURE__ */ new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),Xr.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=>{Xr.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=>{Xr.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 Qr(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Xr.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 Xr.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),Xr.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 Xr.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 Qr(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){Xr.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Xr.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var $r=class{maxSessions;onEvict;sessions=/* @__PURE__ */ new Map;pinnedTargets=/* @__PURE__ */ new Map;appliedSends=/* @__PURE__ */ new Map;constructor(e=32,t){this.maxSessions=e,this.onEvict=t}get size(){return this.sessions.size}get(e){return this.sessions.get(e)}has(e){return this.sessions.has(e)}values(){return this.sessions.values()}entries(){return this.sessions.entries()}snapshot(){return[...this.sessions]}remember(e,t){this.pruneAppliedSends(),this.sessions.set(e,t),this.enforceCap(e)}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}take(e){let t=this.sessions.get(e);return t&&this.sessions.delete(e),t}delete(e){this.sessions.delete(e)}clear(){this.sessions.clear()}pin(e){this.pinnedTargets.set(e,(this.pinnedTargets.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(this.pinnedTargets.get(e)??1)-1;n>0?this.pinnedTargets.set(e,n):this.pinnedTargets.delete(e),this.enforceCap()}}isPinned(e){return this.pinnedTargets.has(e)}enforceCap(e){for(;this.sessions.size>this.maxSessions;){let t;for(let n of this.sessions.keys())if(!(n===e||this.pinnedTargets.has(n))){t=n;break}if(t===void 0)return;let n=this.sessions.get(t);this.sessions.delete(t),n&&this.onEvict?.(t,n)}}noteApplied(e){this.appliedSends.set(e,(this.appliedSends.get(e)??0)+1)}appliedCount(e){return this.appliedSends.get(e)??0}pruneAppliedSends(){if(this.appliedSends.size<=this.maxSessions*4)return;let e=new Set([...this.sessions.values()].map(e=>e.sessionId));for(let t of[...this.appliedSends.keys()])e.has(t)||this.appliedSends.delete(t)}findBySessionId(e){for(let[t,n]of this.sessions)if(n.sessionId===e)return[t,n]}findByTargetOrLocalId(e){let t=[];for(let[n,r]of this.sessions)(n===e||r.remote?.localTargetId===e)&&t.push([n,r]);return t}anyOnTransport(e){for(let t of this.sessions.values())if(t.transport===e)return!0;return!1}anyMatchingRemote(e,t){for(let n of this.sessions.values())if(n.remote?.runtimeId===e&&n.remote.localTargetId===t)return!0;return!1}};const ei=`slicc.ariaRefs`,ti=[`textbox`,`button`,`link`,`checkbox`,`radio`,`iframe`];function ni(e=0){return`(${ai})(${Number.isSafeInteger(e)&&e>0?e:0})`}function ri(e){return`(function(ref) {
2
2
  var store = window[Symbol.for(${JSON.stringify(ei)})];
3
3
  var held = store && store.byRef.get(ref);
4
4
  var el = held && (typeof held.deref === 'function' ? held.deref() : held);
@@ -967,7 +967,7 @@ import{n as e}from"./rolldown-runtime-DBVvNlSN.js";import{_ as t,a as n,c as r,d
967
967
 
968
968
  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 rN(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 iN(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function aN(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 oN(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 sN(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 cN(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(`
969
969
  `)}}function lN(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.`:`
970
- This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function uN(e,t){let n=QM(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 dN(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return uN(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 fN(e,t){let n=uN(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 pN(e){let t=ZM[e.type];return e.type===`session-reload`?tN(e,t):e.type===`upgrade`?nN(e,t):e.type===`cherry`?rN(e,t):e.type===`preview`?iN(e,t):e.type===`workflow`?aN(e,t):e.type===`bash`?sN(e,t):e.type===`jshd`?oN(e,t):e.type===`sudo-request`?cN(e,t):e.type===`navigate`?fN(e,t):e.type===`webhook`?dN(e,t):e.type===`discovery`?lN(e,t):uN(e,t)}function mN(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i=n?e.config:hN(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 hN(e,t){let n=gt(e.workspace?.mode??e.config?.workspaceMode),r=e.workspace?.from??`/workspace`,i=Gt(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 gN(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:en(n).root}}:e}var _N=class{host;constructor(e){this.host=e}async create(e){e.parentId===null&&e.workspace?.mode!==void 0&&gt(e.workspace.mode);let t=mN(gN(e,this.host));if(SN(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}`);Et(t,n)}return await this.host.registerScoop(t),this.get(t.jid).descriptor}async createMany(e){if(e.length===0)return[];CN(e,e=>this.host.getScoop(e),()=>this.host.getScoops());let t=xN(e);for(let e of t)e.id&&SN(e.id,e=>this.host.getScoop(e));let n=TN(t),r=[],i=/* @__PURE__ */ 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 Wt(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return St(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=/* @__PURE__ */ 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=vn(t),r=yN(t,t.parentJid);t.parentJid=null,Vt(t);try{await this.host.persistScoop(t)}catch(e){throw bN(t,r),e}return await this.host.rekeyConversation?.(n,{key:vn(t),workUnitId:t.jid,workspaceId:_n(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:Ft(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)vN(e,t)===`detach`?await this.promote(e.descriptor.id):await this.close(e.descriptor.id,t);await n.close()}};function vN(e,t){return t?.descendants??e.descriptor.onParentClose}function yN(e,t){return{parentJid:t,trigger:e.trigger,requiresTrigger:e.requiresTrigger,approvesGuestRequests:e.approvesGuestRequests,onParentClose:e.onParentClose}}function bN(e,t){e.parentJid=t.parentJid,e.trigger=t.trigger,e.requiresTrigger=t.requiresTrigger,e.approvesGuestRequests=t.approvesGuestRequests,e.onParentClose=t.onParentClose}function xN(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 SN(e,t){if(t(e))throw Error(`Work unit already exists: ${e}`)}function CN(e,t,n){let r=/* @__PURE__ */ 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}`);SN(n.id,t),r.add(n.id)}wN(e,n);let i=[],a=/* @__PURE__ */ 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 wN(e,t){let n=new Set(t().map(e=>e.folder)),r=/* @__PURE__ */ 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 TN(e){let t=e.length;if(t<=1)return e.slice();let n=/* @__PURE__ */ 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 EN=h(`kernel-agent-event-stream`);var DN=class{listeners=/* @__PURE__ */ new Set;messageIds=/* @__PURE__ */ 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){EN.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}-${ON()}`,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 ON(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var kN=class{statuses=/* @__PURE__ */ 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=AN(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=St(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function AN(e){let t=Ot(e),n=Nt(e),{level:r,effortOverride:i}=Mt(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 Y={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let jN=null;function MN(e){if(!e.objectStoreNames.contains(Y.MESSAGES)){let t=e.createObjectStore(Y.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(Y.SESSIONS)||e.createObjectStore(Y.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(Y.TASKS)||e.createObjectStore(Y.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(Y.STATE)||e.createObjectStore(Y.STATE,{keyPath:`key`})}function NN(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 PN(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(Y.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);let i=e.find(e=>e.isMain)?.jid;for(let t of e)r.put(NN(t,i))};return}t.objectStoreNames.contains(Y.SCOOPS)||t.createObjectStore(Y.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function FN(e){e.objectStoreNames.contains(Y.WEBHOOKS)||e.createObjectStore(Y.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(Y.CRONTASKS)||e.createObjectStore(Y.CRONTASKS,{keyPath:`id`})}function IN(e){let t=e.target.result,n=e.oldVersion;n<1&&MN(t),n<2&&PN(e,t),n<3&&FN(t)}function LN(){if(!jN)return null;let e=Object.values(Y).every(e=>jN.objectStoreNames.contains(e));return jN.version===3&&e?jN:(jN.close(),jN=null,null)}function RN(e){e.onversionchange=()=>{e.close(),jN===e&&(jN=null)},e.onclose=()=>{jN===e&&(jN=null)}}async function zN(){return LN()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=IN,n.onsuccess=()=>{let t=n.result;RN(t),jN=t,e(t)},n.onerror=()=>t(n.error)})}async function BN(e,t=`readonly`){return(await zN()).transaction(e,t).objectStore(e)}async function VN(e){let t=await BN(Y.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function HN(){let e=await BN(Y.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 UN(e){let t=await BN(Y.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function WN(){let e=await BN(Y.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function GN(e){let t=(await BN(Y.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 KN(e){let t=await BN(Y.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function qN(e){let t=await BN(Y.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function JN(e){let t=(await BN(Y.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 YN=`wm1:`;function XN(e){if(!e)return{ts:``,ids:/* @__PURE__ */ new Set};if(e.startsWith(YN))try{let t=JSON.parse(e.slice(4));return{ts:t.ts,ids:new Set(t.ids)}}catch{}return{ts:e,ids:null}}function ZN(e){let t=e.ids?Array.from(e.ids):[];return`${YN}${JSON.stringify({ts:e.ts,ids:t})}`}function QN(e,t){return e.timestamp>t.ts?!0:e.timestamp<t.ts||t.ids===null?!1:!t.ids.has(e.id)}function $N(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=/* @__PURE__ */ 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 eP(e,t,n){let r=(await BN(Y.MESSAGES)).index(`chatJid_timestamp`),i=XN(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=>QN(e,i));n&&(t=t.filter(e=>e.senderName!==n)),e(t)},o.onerror=()=>t(o.error)})}async function tP(e){let t=await BN(Y.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function nP(e){let t=await BN(Y.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function rP(){let e=await BN(Y.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function iP(e){let t=await BN(Y.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function aP(e){let t=await BN(Y.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 oP(e,t){let n=await BN(Y.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 sP(){await zN()}async function cP(e){let t=await BN(Y.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function lP(e){let t=await BN(Y.WEBHOOKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function uP(){try{let e=await BN(Y.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function dP(e){let t=await BN(Y.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function fP(e){let t=await BN(Y.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function pP(e){let t=await BN(Y.CRONTASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function mP(){try{let e=await BN(Y.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function hP(e){let t=await BN(Y.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}h(`tray-leader`);function gP(){return _P(bn(),Te())}function _P(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 vP=`__slicc_binary__`;function yP(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[vP]===`b64`&&typeof t.data==`string`}function bP(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function xP(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)&&!yP(e)}function SP(e){if(e instanceof Uint8Array)return{[vP]:`b64`,data:re(e)};if(Array.isArray(e))return e.map(SP);if(bP(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=SP(r);return t}return e}function CP(e){if(yP(e))return ie(e.data);if(Array.isArray(e))return e.map(CP);if(xP(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=CP(r);return t}return e}const wP=h(`panel-transport`);function TP(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function EP(){return{onMessage:e=>{let t=(t,n,r)=>(TP(t)&&e(CP(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=SP(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)||wP.error(`Offscreen → panel transport send failed`,{error:t})})}}}const DP=h(`kernel-bridge`);function OP(){return globalThis}function kP(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 AP=class{orchestrator=null;agentSpawnAborts=/* @__PURE__ */ new Map;browserAPI=null;messageBuffers=/* @__PURE__ */ new Map;conesBeingCreated=/* @__PURE__ */ new Map;currentMessageId=/* @__PURE__ */ new Map;compactionRows=new BM(e=>`compaction-${e}-${jP()}`);pendingMarkers=/* @__PURE__ */ new Map;scoopPresentation=new kN;transcriptsPublished=!1;agentEventStream=new DN;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=EP(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new RM;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-${jP()}`;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)=>{uj.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{uj.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=pj(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??jP(),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=mj(n),e.isError=r)}}this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:hj(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(Ft(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()??[],gP())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...gP()};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=kP(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=u(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=ia(a,e.value),l)break;c.push(e)}if(l||=this.originRootOf(a,r?.unitJid)??St(a)[0],c.length>0&&DP.warn(`Sprinkle lick target could not be resolved; using fallback`,{sprinkleName:e,unresolvedTargets:c,fallbackJid:l?.jid}),!l)return;let d=`sprinkle-${e}-${Date.now()}`,f=pN({type:`sprinkle`,sprinkleName:e,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:t,originLabel:r?.label})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,p=c.map(({source:e,value:t})=>`${e} ${JSON.stringify(t)}`).join(` and `),m=f+(p?`\n\n> Delivery note: ${p} could not be resolved; delivered to fallback ${JSON.stringify(l.folder)}.`:``),ee={id:d,chatJid:l.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:m,timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(l.jid).push({id:d,role:`user`,content:m,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),await this.orchestrator.handleMessage(ee)}originRootOf(e,t){if(t)return Tt(e,e.find(e=>e.jid===t))}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=St(this.orchestrator.getScoops())[0];if(!t)return;let n=NP(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?St(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:(/* @__PURE__ */ 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-D3gIEgUz.js`).then(e=>e.r),r=await t.load(n(e));if(!r)return null;let{toChatMessages:i}=await Promise.resolve().then(()=>_L),a=await i(r,{source:Pt(e)});return a.length===0?null:this.overlayPersistedLickDecisionsOn(e,NP(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 RP(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=Rt(e,i),o=a===Bt,s=St(i)[0],c=r??(s?zt(s):void 0),l=t?.trim(),u={...mN({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`,reason:`unavailable`},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([GA().catch(()=>null),new Promise(e=>setTimeout(()=>e(null),2500))])??void 0):(GA().catch(()=>null),WA()??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:MP(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:Pt(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:MP(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-D3gIEgUz.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-D3gIEgUz.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){DP.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):DP.warn(`Conversation marker retry deferred`,{scoopJid:e,folder:r.folder,markerId:a.id,kind:a.kind})}}async recordErrorCard(e,t){let n=jP(),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){DP.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-D3gIEgUz.js`).then(e=>e.r),c=s(o),l=!1;try{l=await a.putMarker(c.key,i,{createWith:c})}catch(t){DP.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):DP.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}-${jP()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?Pt(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)),Ri(e.key);break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key)),Ri(e.key);break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear()),Ri()}}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=OP()[Fj];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,n=null;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null,n=this.orchestrator.streamThinking?.(e.scoopJid)??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,...n?{resolvedLevel:n.level,...n.effortOverride?{resolvedEffortOverride:n.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){try{e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments),this.emitUserMessageAck(e,!0)}catch(t){this.emitUserMessageAck(e,!1,t)}return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!1,channel:`web`,...e.guestGate?{guestGate:e.guestGate}:{},...e.steer?{steer:!0}:{}};try{if(!this.orchestrator)throw Error(`kernel not ready`);if(!e.requestId){await this.orchestrator.handleMessage(t),await this.orchestrator.createScoopTab(e.scoopJid);return}let n={outcome:`pending`},r=this.orchestrator.handleMessage(t);if(r.then(()=>{n.outcome=`ok`},e=>{n.outcome=`fail`,n.err=e}),await Promise.resolve(),n.outcome===`fail`){this.emitUserMessageAck(e,!1,n.err);return}this.emitUserMessageAck(e,!0),r.then(()=>this.orchestrator?.createScoopTab(e.scoopJid)).catch(t=>{console.error(`[kernel-bridge] user-message failed after handoff:`,t),this.emit({type:`error`,scoopJid:e.scoopJid,error:t instanceof Error?t.message:String(t)})})}catch(t){if(this.emitUserMessageAck(e,!1,t),!e.requestId)throw t}}emitUserMessageAck(e,t,n){e.requestId&&this.emit({type:`user-message-ack`,requestId:e.requestId,messageId:e.messageId,scoopJid:e.scoopJid,ok:t,...t?{}:{error:n instanceof Error?n.message:n==null?void 0:String(n)}})}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&bt(n)){if(St(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=Ft({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)??St(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(Ft({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=OP().__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=OP().__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`){lt.markMounted(t);return}try{await lt.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}),lt.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 jP(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function MP(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
970
+ This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function uN(e,t){let n=QM(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 dN(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return uN(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 fN(e,t){let n=uN(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 pN(e){let t=ZM[e.type];return e.type===`session-reload`?tN(e,t):e.type===`upgrade`?nN(e,t):e.type===`cherry`?rN(e,t):e.type===`preview`?iN(e,t):e.type===`workflow`?aN(e,t):e.type===`bash`?sN(e,t):e.type===`jshd`?oN(e,t):e.type===`sudo-request`?cN(e,t):e.type===`navigate`?fN(e,t):e.type===`webhook`?dN(e,t):e.type===`discovery`?lN(e,t):uN(e,t)}function mN(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i=n?e.config:hN(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 hN(e,t){let n=gt(e.workspace?.mode??e.config?.workspaceMode),r=e.workspace?.from??`/workspace`,i=Gt(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 gN(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:en(n).root}}:e}var _N=class{host;constructor(e){this.host=e}async create(e){e.parentId===null&&e.workspace?.mode!==void 0&&gt(e.workspace.mode);let t=mN(gN(e,this.host));if(SN(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}`);Et(t,n)}return await this.host.registerScoop(t),this.get(t.jid).descriptor}async createMany(e){if(e.length===0)return[];CN(e,e=>this.host.getScoop(e),()=>this.host.getScoops());let t=xN(e);for(let e of t)e.id&&SN(e.id,e=>this.host.getScoop(e));let n=TN(t),r=[],i=/* @__PURE__ */ 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 Wt(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return St(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=/* @__PURE__ */ 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=vn(t),r=yN(t,t.parentJid);t.parentJid=null,Vt(t);try{await this.host.persistScoop(t)}catch(e){throw bN(t,r),e}return await this.host.rekeyConversation?.(n,{key:vn(t),workUnitId:t.jid,workspaceId:_n(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:Ft(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)vN(e,t)===`detach`?await this.promote(e.descriptor.id):await this.close(e.descriptor.id,t);await n.close()}};function vN(e,t){return t?.descendants??e.descriptor.onParentClose}function yN(e,t){return{parentJid:t,trigger:e.trigger,requiresTrigger:e.requiresTrigger,approvesGuestRequests:e.approvesGuestRequests,onParentClose:e.onParentClose}}function bN(e,t){e.parentJid=t.parentJid,e.trigger=t.trigger,e.requiresTrigger=t.requiresTrigger,e.approvesGuestRequests=t.approvesGuestRequests,e.onParentClose=t.onParentClose}function xN(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 SN(e,t){if(t(e))throw Error(`Work unit already exists: ${e}`)}function CN(e,t,n){let r=/* @__PURE__ */ 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}`);SN(n.id,t),r.add(n.id)}wN(e,n);let i=[],a=/* @__PURE__ */ 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 wN(e,t){let n=new Set(t().map(e=>e.folder)),r=/* @__PURE__ */ 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 TN(e){let t=e.length;if(t<=1)return e.slice();let n=/* @__PURE__ */ 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 EN=h(`kernel-agent-event-stream`);var DN=class{listeners=/* @__PURE__ */ new Set;messageIds=/* @__PURE__ */ 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){EN.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}-${ON()}`,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 ON(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var kN=class{statuses=/* @__PURE__ */ 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=AN(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=St(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function AN(e){let t=Ot(e),n=Nt(e),{level:r,effortOverride:i}=Mt(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 Y={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let jN=null;function MN(e){if(!e.objectStoreNames.contains(Y.MESSAGES)){let t=e.createObjectStore(Y.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(Y.SESSIONS)||e.createObjectStore(Y.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(Y.TASKS)||e.createObjectStore(Y.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(Y.STATE)||e.createObjectStore(Y.STATE,{keyPath:`key`})}function NN(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 PN(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(Y.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);let i=e.find(e=>e.isMain)?.jid;for(let t of e)r.put(NN(t,i))};return}t.objectStoreNames.contains(Y.SCOOPS)||t.createObjectStore(Y.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function FN(e){e.objectStoreNames.contains(Y.WEBHOOKS)||e.createObjectStore(Y.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(Y.CRONTASKS)||e.createObjectStore(Y.CRONTASKS,{keyPath:`id`})}function IN(e){let t=e.target.result,n=e.oldVersion;n<1&&MN(t),n<2&&PN(e,t),n<3&&FN(t)}function LN(){if(!jN)return null;let e=Object.values(Y).every(e=>jN.objectStoreNames.contains(e));return jN.version===3&&e?jN:(jN.close(),jN=null,null)}function RN(e){e.onversionchange=()=>{e.close(),jN===e&&(jN=null)},e.onclose=()=>{jN===e&&(jN=null)}}async function zN(){return LN()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=IN,n.onsuccess=()=>{let t=n.result;RN(t),jN=t,e(t)},n.onerror=()=>t(n.error)})}async function BN(e,t=`readonly`){return(await zN()).transaction(e,t).objectStore(e)}async function VN(e){let t=await BN(Y.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function HN(){let e=await BN(Y.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 UN(e){let t=await BN(Y.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function WN(){let e=await BN(Y.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function GN(e){let t=(await BN(Y.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 KN(e){let t=await BN(Y.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function qN(e){let t=await BN(Y.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function JN(e){let t=(await BN(Y.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 YN=`wm1:`;function XN(e){if(!e)return{ts:``,ids:/* @__PURE__ */ new Set};if(e.startsWith(YN))try{let t=JSON.parse(e.slice(4));return{ts:t.ts,ids:new Set(t.ids)}}catch{}return{ts:e,ids:null}}function ZN(e){let t=e.ids?Array.from(e.ids):[];return`${YN}${JSON.stringify({ts:e.ts,ids:t})}`}function QN(e,t){return e.timestamp>t.ts?!0:e.timestamp<t.ts||t.ids===null?!1:!t.ids.has(e.id)}function $N(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=/* @__PURE__ */ 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 eP(e,t,n){let r=(await BN(Y.MESSAGES)).index(`chatJid_timestamp`),i=XN(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=>QN(e,i));n&&(t=t.filter(e=>e.senderName!==n)),e(t)},o.onerror=()=>t(o.error)})}async function tP(e){let t=await BN(Y.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function nP(e){let t=await BN(Y.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function rP(){let e=await BN(Y.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function iP(e){let t=await BN(Y.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function aP(e){let t=await BN(Y.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 oP(e,t){let n=await BN(Y.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 sP(){await zN()}async function cP(e){let t=await BN(Y.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function lP(e){let t=await BN(Y.WEBHOOKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function uP(){try{let e=await BN(Y.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function dP(e){let t=await BN(Y.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function fP(e){let t=await BN(Y.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function pP(e){let t=await BN(Y.CRONTASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function mP(){try{let e=await BN(Y.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function hP(e){let t=await BN(Y.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}h(`tray-leader`),h(`tray-leader`);function gP(){return _P(bn(),Te())}function _P(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 vP=`__slicc_binary__`;function yP(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[vP]===`b64`&&typeof t.data==`string`}function bP(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function xP(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)&&!yP(e)}function SP(e){if(e instanceof Uint8Array)return{[vP]:`b64`,data:re(e)};if(Array.isArray(e))return e.map(SP);if(bP(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=SP(r);return t}return e}function CP(e){if(yP(e))return ie(e.data);if(Array.isArray(e))return e.map(CP);if(xP(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=CP(r);return t}return e}const wP=h(`panel-transport`);function TP(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function EP(){return{onMessage:e=>{let t=(t,n,r)=>(TP(t)&&e(CP(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=SP(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)||wP.error(`Offscreen → panel transport send failed`,{error:t})})}}}const DP=h(`kernel-bridge`);function OP(){return globalThis}function kP(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 AP=class{orchestrator=null;agentSpawnAborts=/* @__PURE__ */ new Map;browserAPI=null;messageBuffers=/* @__PURE__ */ new Map;conesBeingCreated=/* @__PURE__ */ new Map;currentMessageId=/* @__PURE__ */ new Map;compactionRows=new BM(e=>`compaction-${e}-${jP()}`);pendingMarkers=/* @__PURE__ */ new Map;scoopPresentation=new kN;transcriptsPublished=!1;agentEventStream=new DN;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=EP(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new RM;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-${jP()}`;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)=>{uj.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{uj.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=pj(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??jP(),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=mj(n),e.isError=r)}}this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:hj(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(Ft(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()??[],gP())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...gP()};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=kP(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=u(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=ia(a,e.value),l)break;c.push(e)}if(l||=this.originRootOf(a,r?.unitJid)??St(a)[0],c.length>0&&DP.warn(`Sprinkle lick target could not be resolved; using fallback`,{sprinkleName:e,unresolvedTargets:c,fallbackJid:l?.jid}),!l)return;let d=`sprinkle-${e}-${Date.now()}`,f=pN({type:`sprinkle`,sprinkleName:e,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:t,originLabel:r?.label})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,p=c.map(({source:e,value:t})=>`${e} ${JSON.stringify(t)}`).join(` and `),m=f+(p?`\n\n> Delivery note: ${p} could not be resolved; delivered to fallback ${JSON.stringify(l.folder)}.`:``),ee={id:d,chatJid:l.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:m,timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(l.jid).push({id:d,role:`user`,content:m,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),await this.orchestrator.handleMessage(ee)}originRootOf(e,t){if(t)return Tt(e,e.find(e=>e.jid===t))}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=St(this.orchestrator.getScoops())[0];if(!t)return;let n=NP(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?St(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:(/* @__PURE__ */ 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-D3gIEgUz.js`).then(e=>e.r),r=await t.load(n(e));if(!r)return null;let{toChatMessages:i}=await Promise.resolve().then(()=>_L),a=await i(r,{source:Pt(e)});return a.length===0?null:this.overlayPersistedLickDecisionsOn(e,NP(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 RP(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=Rt(e,i),o=a===Bt,s=St(i)[0],c=r??(s?zt(s):void 0),l=t?.trim(),u={...mN({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`,reason:`unavailable`},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([GA().catch(()=>null),new Promise(e=>setTimeout(()=>e(null),2500))])??void 0):(GA().catch(()=>null),WA()??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:MP(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:Pt(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:MP(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-D3gIEgUz.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-D3gIEgUz.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){DP.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):DP.warn(`Conversation marker retry deferred`,{scoopJid:e,folder:r.folder,markerId:a.id,kind:a.kind})}}async recordErrorCard(e,t){let n=jP(),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){DP.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-D3gIEgUz.js`).then(e=>e.r),c=s(o),l=!1;try{l=await a.putMarker(c.key,i,{createWith:c})}catch(t){DP.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):DP.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}-${jP()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?Pt(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)),Ri(e.key);break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key)),Ri(e.key);break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear()),Ri()}}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=OP()[Fj];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,n=null;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null,n=this.orchestrator.streamThinking?.(e.scoopJid)??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,...n?{resolvedLevel:n.level,...n.effortOverride?{resolvedEffortOverride:n.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){try{e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments),this.emitUserMessageAck(e,!0)}catch(t){this.emitUserMessageAck(e,!1,t)}return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!1,channel:`web`,...e.guestGate?{guestGate:e.guestGate}:{},...e.steer?{steer:!0}:{}};try{if(!this.orchestrator)throw Error(`kernel not ready`);if(!e.requestId){await this.orchestrator.handleMessage(t),await this.orchestrator.createScoopTab(e.scoopJid);return}let n={outcome:`pending`},r=this.orchestrator.handleMessage(t);if(r.then(()=>{n.outcome=`ok`},e=>{n.outcome=`fail`,n.err=e}),await Promise.resolve(),n.outcome===`fail`){this.emitUserMessageAck(e,!1,n.err);return}this.emitUserMessageAck(e,!0),r.then(()=>this.orchestrator?.createScoopTab(e.scoopJid)).catch(t=>{console.error(`[kernel-bridge] user-message failed after handoff:`,t),this.emit({type:`error`,scoopJid:e.scoopJid,error:t instanceof Error?t.message:String(t)})})}catch(t){if(this.emitUserMessageAck(e,!1,t),!e.requestId)throw t}}emitUserMessageAck(e,t,n){e.requestId&&this.emit({type:`user-message-ack`,requestId:e.requestId,messageId:e.messageId,scoopJid:e.scoopJid,ok:t,...t?{}:{error:n instanceof Error?n.message:n==null?void 0:String(n)}})}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&bt(n)){if(St(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=Ft({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)??St(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(Ft({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=OP().__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=OP().__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`){lt.markMounted(t);return}try{await lt.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}),lt.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 jP(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function MP(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
971
971
  `)}function NP(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 PP(e){return e===`confirmed`||e===`dismissed`}function FP(e){return e.channel===`sudo-request`||!!e.lickId||!!e.lickState||e.id.startsWith(`sudo-request-`)}function IP(e){return e.lickId?e.lickId:FP(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 LP(e,t,n){let r=e.get(t);(!r||PP(n.lickState)&&!PP(r.lickState))&&e.set(t,n)}function RP(e,t){if(!t||t.length===0)return e;let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let e of t){if(!FP(e))continue;let t=IP(e);t&&LP(n,t,e),LP(r,e.id,e),LP(i,e.content,e)}return e.map(e=>{if(!FP(e))return e;let t=IP(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??IP(a),s=PP(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 zP=h(`navigation-watcher`);function BP(e){if(!e)return null;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:null}catch{return null}}function VP(e){return e.replace(/\/+$/,``)||`/`}function HP(e){return t=>{let n=BP(e()??void 0);if(!n)return!1;let r=BP(t.url);return r?n.origin===r.origin&&VP(n.pathname)===VP(r.pathname):!1}}function UP(e,t){return oe(e,t)}var WP=class{transport;onEvent;sessions=/* @__PURE__ */ new Map;started=!1;unsubscribeState=null;rearming=!1;rearmQueued=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;isOwnTab;probedOrigins=/* @__PURE__ */ new Set;pendingAttachTargetIds=/* @__PURE__ */ new Set;ownSessionIds=/* @__PURE__ */ 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}=UP(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=Nr(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 Ir(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){zP.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 zP.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){zP.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){zP.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,zP.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 zP.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),zP.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&&zP.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){zP.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}};function GP(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var KP=`# /etc/llmstxtignore — llms.txt discovery suppression
972
972
  #
973
973
  # One advertising hostname or glob per line. Matching is case-insensitive.
@@ -1061,7 +1061,7 @@ Write /etc/models
1061
1061
  `)}\n`}var uF=class{fs;watcher;broker;onPolicyReload;policy=jn();unwatch=null;reloadChain=Promise.resolve();scoopPolicies=/* @__PURE__ */ new Map;scoopConfigPolicies=/* @__PURE__ */ new Map;scoopReloadChains=/* @__PURE__ */ new Map;constructor(e){this.fs=e.fs,this.watcher=e.watcher??null,this.broker=e.broker??l(e.capabilityBroker??null),this.onPolicyReload=e.onPolicyReload??(()=>{})}async init(){await this.ensureDefaults(),await this.reload(),this.startWatching()}getBroker(){return this.broker}async approve(e){if(e.kind===`export`&&Nn(this.policy,e.detail)===`nopasswd-allow`)return iF.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 iF.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(Vn(e.kind),n)}catch(n){return iF.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=[An(),this.policy];return n&&r.push(n),t&&r.push(t),Ln(...r)}getConfiguredPolicyForScoop(e){let t=this.scoopConfigPolicies.get(e);return t?Ln(An(),t):An()}registerScoopConfig(e,t){this.scoopConfigPolicies.set(e,Fn(lF(t??void 0))),this.onPolicyReload(e)}async initScoopPolicy(e,t){this.registerScoopConfig(e,t);let n=Un(e);if(await this.fs.exists(n).catch(()=>!1)){let{migrateLegacyScoopSudoers:t}=await import(`./migrate-scoop-sudoers-CiGKeg93.js`);await t(e,{fs:this.fs})}await this.reloadScoopPolicy(e)}async appendScoopRule(e,t,n){let r=Pn(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=Wn(e);if(!a)return iF.warn(`Unspellable scoop folder; not persisting`,{folder:e}),null;let o=await this.readTextOrEmpty(a),s=`NOPASSWD ${i} ${r}`;if(o.split(`
1062
1062
  `).some(e=>e.trim()===s))return iF.info(`Per-scoop grant already present; skipping duplicate append`,{folder:e,kind:t,pattern:r}),r;try{await this.fs.mkdir(Rn,{recursive:!0})}catch{}let c=o?o.endsWith(`
1063
1063
  `)?o:`${o}\n`:cF;return await this.fs.writeFile(a,`${c}${s}\n`),await this.reloadScoopPolicy(e),iF.info(`Appended per-scoop grant`,{folder:e,path:a,kind:t,pattern:r}),r}async readTextOrEmpty(e){try{if(!await this.fs.exists(e))return``;let t=await this.fs.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:new TextDecoder().decode(t)}catch(e){if(e instanceof g&&e.code===`ENOENT`)return``;throw e}}getShellConfig(e={}){return{getPolicy:()=>this.policy,broker:this.broker,persistCommandGrant:e=>this.persistCommandGrant(e),transparentGating:e.transparentGating??!0}}reload(){return this.reloadChain=this.reloadChain.then(()=>this.doReload()),this.reloadChain}forgetScoopPolicies(e){this.scoopConfigPolicies.delete(e),this.scoopPolicies.delete(e),this.scoopReloadChains.delete(e),this.onPolicyReload(e)}reloadScoopPolicyByFolder(e){return this.reloadScoopPolicy(e)}dispose(){this.unwatch?.(),this.unwatch=null}reloadScoopPolicy(e){let t=(this.scoopReloadChains.get(e)??Promise.resolve()).then(()=>this.doReloadScoopPolicy(e));return this.scoopReloadChains.set(e,t),t}async doReloadScoopPolicy(e){let t=Wn(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(Bn)];try{let t=(await this.fs.readDir(Rn)).filter(e=>e.type===`file`).filter(e=>kn(e.name)===null).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${Rn}/${n}`))}catch{}this.policy=Ln(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return jn();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return Fn(n)}catch(t){return iF.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),jn()}}async ensureDefaults(){try{await this.fs.mkdir(Rn,{recursive:!0})}catch{}await this.seedWhenAbsent(Bn,()=>rF),await this.seedWhenAbsent(Hn,async()=>(await import(`./approver-agent-Dd-dJT-g.js`)).DEFAULT_APPROVALS_MD)}async seedWhenAbsent(e,t){try{if(await this.fs.exists(e))return;await this.fs.writeFile(e,await t()),iF.info(`Seeded bundled policy default`,{path:e})}catch(t){iF.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=Pn(t);if(!n)return;let r=``;try{if(await this.fs.exists(qn)){let e=await this.fs.readFile(qn,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof g&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(Rn,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
1064
- `)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(qn,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,aF,e=>{let t=/* @__PURE__ */ new Set,n=!1,r=!1;for(let i of e){if(i.path===`/etc/sudoers.d`){r=!0;continue}let e=oF(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 dF(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function fF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pF(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++)pF(e[r],`${t}/${r}`,n);return}if(fF(e))for(let[r,i]of Object.entries(e))pF(i,`${t}/${dF(r)}`,n)}function mF(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=mF(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(fF(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=mF(o,`${t}/${dF(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function hF(e,t,n){if(fF(e))return mF(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=hF(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function gF(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function _F(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new o(`redaction-unavailable`);let a=0,s=i;for(;s<e.length;){let t=e[s].length;if(s>i&&a+t>1048576)break;a+=t,s++}let c=e.slice(i,s),l;try{l=await t.redact(c,n)}catch{throw new o(`redaction-unavailable`)}if(l.length!==c.length)throw new o(`redaction-unavailable`);r.push(...l),i=s}return r}function vF(e,t,n,r){let i=[],a=gF(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=gF(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=Se(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function yF(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 bF(e,n,r,i){if(i?.aborted)throw new o(`redaction-unavailable`);let{privacy:a,...s}=e,c=[];pF(s,``,c);let l=c.filter(e=>!t(e.pointer)),u=[...n.entries()],d=await _F([...l.map(e=>e.value),...u.map(([,e])=>e)],r,i),f=[],p={},m=1,ee=/* @__PURE__ */ new Map,te=[];for(let e=0;e<l.length;e++){let t=l[e],n=vF(t.value,d[e],{kind:`json`,pointer:t.pointer},m);m=n.nextId,n.finalText!==t.value&&ee.set(t.pointer,n.finalText),te.push(n)}yF(te,f,p);let ne=/* @__PURE__ */ new Map,h=l.length,re=[];for(let e=0;e<u.length;e++){let[t,n]=u[e],r=vF(n,d[h+e],{kind:`attachment`,attachmentId:t},m);m=r.nextId,ne.set(t,r.finalText),re.push(r)}yF(re,f,p);let ie=hF(e,``,ee);return{document:{...ie,privacy:{...ie.privacy,redactionCounts:p,redactions:f}},textAttachments:ne}}function xF(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}const SF={"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 CF(e,t){return SF[e]??(t===`text-redacted`?`.txt`:`.bin`)}function wF(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${CF(t,n)}`}function TF(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 EF(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 DF(e,t,n,r,i){let a=xF(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(TF(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=TF(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 OF(e,t,n,r){let i=[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:TF(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(DF(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function kF(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 AF(e,t,n,r,i,a,o){let s=kF(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(DF(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function jF(e,t,n,r,i){let a=/* @__PURE__ */ new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=AF(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,/* @__PURE__ */ new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function MF(e,t){let n=/* @__PURE__ */ new Map,r=0,i=/* @__PURE__ */ new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,wF(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 NF(e,t,n,r,i){let{rawAttachments:a,textMap:s}=MF(e,n),c,l;try{let e=await bF({...t,attachments:a},s,r,i);c=e.document,l=e.textAttachments}catch(e){throw e instanceof o?e:new o(`attachment-unreadable`)}let u=/* @__PURE__ */ new Map;for(let t of e){if(u.has(t.attachmentId))throw new o(`schema-invalid`);u.set(t.attachmentId,t)}let d=/* @__PURE__ */ new Map,f=await Promise.all(c.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=u.get(e.id);if(t===void 0)throw new o(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(l.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await be(n);return d.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...c,attachments:f},bundleFiles:d}}async function PF(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??/* @__PURE__ */ new Map,o=e.vfsReader,s=/* @__PURE__ */ new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=OF(EF(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}=jF(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),ee=[...d,...m],te=t;f.size>0&&(te={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:ne,bundleFiles:h}=await NF(ee,te,s,r,i),re=[...ne.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{...ne,session:{...ne.session,completeness:{status:re.length>0?`partial`:ne.session.completeness.status,missing:re}}},bundleFiles:h}}function FF(e){return Ft(e)}function IF(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 LF(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let e of t)i.set(e.id,e);let a=/* @__PURE__ */ new Map;for(let e of n)a.set(e.id,e);let o=[],s=/* @__PURE__ */ new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:bt(t)?`cone`:`scoop`,name:t.name,...t.folder&&!bt(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=FF(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function RF(e,t,n={}){let r=e=>n.rootJid===void 0?e:Ct(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new o(`transfer-aborted`);let i=IF(n,e),[a,s]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new o(`transfer-aborted`);let c=r(e.listScoops());if(i===IF(c,e))return LF(c,a,s,e)}}var zF=/* @__PURE__ */ e({SESSIONS_DIR:()=>BF,SESSIONS_INDEX_PATH:()=>VF,carryCurationLedger:()=>HF,parseFrozenArchive:()=>WF,readSessionsIndex:()=>UF});const BF=`/sessions`,VF=`/sessions/index.json`;function HF(e,t={}){return e?{...e.curatedThrough?{curatedThrough:e.curatedThrough}:{},...e.memoryCuratedAt?{memoryCuratedAt:e.memoryCuratedAt}:{},...e.memoryFailed&&!t.dropFailure?{memoryFailed:e.memoryFailed}:{},...e.memorySkipped?{memorySkipped:!0}:{}}:{}}async function UF(e){try{let t=await e.readFile(VF,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function WF(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,GF(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=KF(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:JF(t),...r})}function GF(e){let t={},n=qF(e,`cost`),r=qF(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=KF(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(/^sessionId:\s*(\S+)\s*$/m)?.[1];u&&(t.sessionId=u);let d=e.match(/^attachmentsKey:\s*(\S+)\s*$/m)?.[1];d&&(t.attachmentsKey=d);let f=e.match(/^sidecar:\s*(\S+)\s*$/m)?.[1];return f&&(t.sidecar=f),t}function KF(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 qF(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function JF(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 YF(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function XF(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function ZF(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(XF(t,r++));return n}function QF(e,t){let n=[],r=/* @__PURE__ */ new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=XF(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 $F(e,t){let n=[],r=/* @__PURE__ */ new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=XF(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 eI(e,t,n){let r=YF(t,n),i=ZF(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:/* @__PURE__ */ new Map}}function tI(e,t,n){let r=YF(t,n),{blocks:i,excluded:a,images:o}=QF(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 nI(e,t,n){let r=YF(t,n),{blocks:i,images:a}=$F(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 rI(e,t,n){return e.role===`user`?eI(e,t,n):e.role===`assistant`?tI(e,t,n):e.role===`toolResult`?nI(e,t,n):{message:null,excludedReasoningBlocks:0,images:/* @__PURE__ */ new Map}}function iI(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 aI(e){let t=0,n=/* @__PURE__ */ new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=rI(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:iI(e),excludedReasoningBlocks:t,canonicalImages:n}}const oI=(()=>{let e=/* @__PURE__ */ new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function sI(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^oI[(t^e[n])&255];return~t>>>0}const cI=new TextEncoder;function lI(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function uI(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 dI(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,lI(r,4,20),lI(r,6,2048),lI(r,8,0),lI(r,10,0),lI(r,12,0),uI(r,14,n),uI(r,18,t),uI(r,22,t),lI(r,26,e.length),lI(r,28,0),r.set(e,30),r}function fI(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,lI(i,4,20),lI(i,6,20),lI(i,8,2048),lI(i,10,0),lI(i,12,0),lI(i,14,0),uI(i,16,n),uI(i,20,t),uI(i,24,t),lI(i,28,e.length),lI(i,30,0),lI(i,32,0),lI(i,34,0),lI(i,36,0),uI(i,38,0),uI(i,42,r),i.set(e,46),i}function pI(e,t,n){let r=/* @__PURE__ */ new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,lI(r,4,0),lI(r,6,0),lI(r,8,e),lI(r,10,e),uI(r,12,t),uI(r,16,n),lI(r,20,0),r}function mI(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 hI(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${xe(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*gI(e,t,n,r){if(t?.aborted)throw r(new o(`transfer-aborted`)),new o(`transfer-aborted`);let i=()=>r(new o(`transfer-aborted`));t?.addEventListener(`abort`,i,{once:!0});let a=Yn.create(),s=0,c=0,l=[],u=!1;function*d(e){a.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{for(let n of e){if(t?.aborted)throw new o(`transfer-aborted`);let e=await n.load();if(t?.aborted)throw new o(`transfer-aborted`);if(e.byteLength>_I)throw new o(`schema-invalid`);let r=cI.encode(n.path),i=sI(e),a=dI(r,e.length,i);if(c+a.length+e.length>_I)throw new o(`schema-invalid`,`archive exceeds ZIP32 offsets`);if(l.push({nameBytes:r,size:e.length,crc:i,localOffset:c}),yield*d(a),t?.aborted)throw new o(`transfer-aborted`);yield*d(e)}if(l.length>vI)throw new o(`schema-invalid`);let r=c;for(let e of l){if(t?.aborted)throw new o(`transfer-aborted`);yield*d(fI(e.nameBytes,e.size,e.crc,e.localOffset))}if(t?.aborted)throw new o(`transfer-aborted`);yield*d(pI(l.length,c-r,r)),u=!0,n({byteLength:s,sha256:a.hex()})}catch(e){throw u=!0,r(e),e}finally{t?.removeEventListener(`abort`,i),u||(u=!0,r(new o(`transfer-aborted`)))}}const _I=4294967295,vI=65535;function yI(e,t){let n=/* @__PURE__ */ new Set;for(let{path:t}of e){if(!mI(t)||n.has(t))throw new o(`schema-invalid`);n.add(t)}if(e.length>vI)throw new o(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return a.catch(()=>void 0),{chunks:gI(e,t,r,i),completion:a}}function bI(e,t,n){for(let e of t.keys())if(!mI(e))throw new o(`schema-invalid`);if(t.size+1>vI)throw new o(`schema-invalid`);for(let e of t.values())if(e.byteLength>_I)throw new o(`schema-invalid`);let r=[{path:`transcript.json`,load:()=>new TextEncoder().encode(JSON.stringify(e,null,2))},...[...t].map(([e,t])=>({path:e,load:()=>t}))];return{filename:hI(e),...yI(r,n)}}function xI(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:(/* @__PURE__ */ new Date()).toISOString(),producer:{application:`slicc`,version:i},format:s},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function SI(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 CI(e){let t=te(e);if(!t.ok)throw new o(`schema-invalid`,t.error)}function wI(e,t,n){let r=/* @__PURE__ */ new Map;for(let i of e)if(i.present&&i.path){if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}}return r}async function TI(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);return n?{...e,byteLength:n.length,sha256:await be(n)}:e}))}function EI(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 DI=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),CI(i.document),r?.({phase:`packaging`}),bI(i.document,i.bundleFiles,n)}async snapshotCone(e,t){let n=await RF(this.deps.collection,t,{rootJid:e.jid}),r=aI(n.sources),i=await PF({document:xI(e.jid,e.name,`active`,r,this.deps.version),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});return CI(i.document),i}async snapshotFrozen(e,t){let n=await this.buildFrozenSnapshot(e,t);return CI(n.document),n}async captureFrozen(e,t){let n=await RF(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=aI(n.sources),{document:i,bundleFiles:a}=await PF({document:xI(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});if(CI(i),t?.aborted)throw new o(`transfer-aborted`);try{await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a},t)}finally{this.deps.snapshotStore.discardIfUnindexed?.(e.sessionId)?.catch(()=>void 0)}}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await RF(this.deps.collection,e),r=aI(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=xI(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),PF({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r;try{r=await this.deps.snapshotStore.read(e)}catch(e){if(!(e instanceof o)||e.code!==`session-not-found`)throw e;r=null}return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=/* @__PURE__ */ new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await bF(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new o(`redaction-unavailable`)}let a=wI(r.attachments,i,e.attachments),s=await TI(r.attachments,a);return{document:{...r,attachments:s},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await UF(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new o(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new o(`session-not-found`)}let{loadFrozenArchive:a}=await import(`./session-jsonl-kHYH-7Ib.js`),{title:c,messages:l}=await a(this.deps.vfs,i,r.filename),u=`legacy-cone`,d=SI(l,u),f=EI(i),p={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:(/* @__PURE__ */ new Date()).toISOString(),producer:{application:`slicc`,version:this.deps.version},format:s},session:{id:e,title:c,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...f,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:u,kind:`cone`,name:c,messages:d}],delegations:[],attachments:[]},m=/* @__PURE__ */ new Map([[u,l]]);return n?.({phase:`redacting`}),PF({document:p,chatMessagesByConversation:m,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new o(`attachment-unreadable`);return t}};const OI=`/sessions/data`,kI=`document.json`,AI=`.publishing`;function jI(e){if(e?.aborted)throw new o(`transfer-aborted`)}function MI(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new o(`session-not-found`)}function NI(e){return`${OI}/${e}`}function PI(e){return`${OI}/.tmp-${e}`}async function FI(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function II(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 II(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function LI(e,t){let n=await e.readDir(t);for(let r of n){if(r.name===AI)continue;let n=`${t}/${r.name}`;r.type===`directory`?await II(e,n):await e.rm(n)}}async function RI(e,t,n,r){jI(r),await FI(e,n);let i=await e.readDir(t);for(let a of i){jI(r);let i=`${t}/${a.name}`,o=`${n}/${a.name}`;if(a.type===`directory`)await RI(e,i,o,r);else{let t=await e.readFile(i,{encoding:`binary`});await e.writeFile(o,t)}}}async function zI(e,t,n,r){MI(t);let i=PI(t),a=NI(t),s=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!s.has(e))throw new o(`schema-invalid`);jI(r),await FI(e,i);let c=!1;try{let t=[...n.document.attachments];for(let[e,i]of n.attachments){jI(r);let n=await be(i),a=s.get(e);if(a!==void 0){let e=t.indexOf(a);e!==-1&&(t[e]={...a,sha256:n,byteLength:i.length})}}let o={...n.document,attachments:t},l=JSON.stringify(o,null,2);if(await e.writeFile(`${i}/${kI}`,l),n.attachments.size>0)for(let[t,r]of n.attachments){let n=`${i}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await FI(e,`${i}/${t.slice(0,a)}`),await e.writeFile(n,r)}await e.flush(),jI(r),await FI(e,a),c=!0,await e.writeFile(`${a}/${AI}`,`in-progress`),await LI(e,a),jI(r),await RI(e,i,a,r),await e.flush(),jI(r),await e.rm(`${a}/${AI}`)}catch(t){if(c)try{await LI(e,a)}catch{}throw await II(e,i),t}await II(e,i)}async function BI(e,t){MI(t);for(let n of[NI(t),PI(t)])try{await e.rm(n,{recursive:!0})}catch(e){if(e?.code!==`ENOENT`)throw e}}async function VI(e,t){let[{serializeIndexWrite:n},{readIndexForPresence:r}]=await Promise.all([import(`./frozen-archive-writer-Cr1_j3pp.js`).then(e=>e.i),import(`./frozen-session-identity-dpueujl9.js`)]);return n(async()=>{let n=await r(e);return n===null||n.some(e=>e.sessionId===t)?!1:(await BI(e,t),!0)})}async function HI(e,t){MI(t);let n=NI(t),r=`${n}/${kI}`;try{throw await e.stat(`${n}/${AI}`),new o(`session-not-found`)}catch(e){if(e instanceof o||e.code!==`ENOENT`)throw e}let i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new o(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new o(`schema-invalid`)}if(!te(a).ok)throw new o(`schema-invalid`);let s=/* @__PURE__ */ new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new o(`transfer-corrupt`)}if(await be(i)!==t.sha256)throw new o(`transfer-corrupt`);s.set(t.path,i)}return{document:a,attachments:s}}function UI(e){return`error`in e}function WI(){throw new o(`redaction-unavailable`)}function GI(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&WI(),e.texts}function KI(){return{async redact(e){let t;try{t=await fetch(ze(`/api/secrets/redact-export`),{method:`POST`,headers:Be({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{WI()}t.ok||WI();let n;try{n=await t.json()}catch{WI()}return GI(n,e.length)}}}function qI(){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{WI()}return typeof t==`object`&&t&&UI(t)&&WI(),GI(t,e.length)}}}function JI(){return{async redact(e){let t;try{t=await ot(`secrets.redact-export`,{texts:e})}catch{WI()}return t??WI(),typeof t==`object`&&t&&UI(t)&&WI(),GI(t,e.length)}}}function YI(){return{async redact(e){WI()}}}function XI(){let e=at();return e===`connect`?YI():e===`extension-direct`?qI():e===`extension-delegate`?JI():KI()}const ZI=/* @__PURE__ */ new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function QI(e){return`e${e}`}function $I(e){let t=[];for(let n of e){let e=nL(n),r=iL(n);if(e===`assistant`){let e=t.length,i=QI(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:sL(n),message:n,model:oL(n)});for(let e of cL(n)){let n=t.length;t.push({id:QI(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:QI(i),seq:i,kind:`tool-result`,timestamp:r,text:sL(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=sL(n),a=e===`user`?tL(i):null,o=t.length,s=QI(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):ZI.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 eL(e){let t=[];for(let n of e){let e=t.length,r=QI(e),i=aL(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:QI(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&ij(n.channel)?n.channel:tL(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):ZI.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 tL(e){for(let t of oj(e)){let e=(t.sender?sj(t.sender):null)??cj(t.body);if(e)return e}return null}function nL(e){return e.role??``}function rL(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 iL(e){return rL(e.timestamp)}function aL(e){return rL(e.timestamp)}function oL(e){let t=e.model;return typeof t==`string`?t:void 0}function sL(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 cL(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 lL(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function uL(e){return e!==null&&e.version<=2}const dL=h(`work-unit-conversation`);var fL=class extends Error{};const pL=`conversations`;async function mL(e){let t=e.now??(()=>Date.now()),n=await gL(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=vn(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await hL(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}],dL.warn(`Skipping a unit whose conversation could not be migrated`,{key:c,folder:s.folder,error:o}),i instanceof fL){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),dL.info(`Canonical conversation migration complete`,{...r}),r}async function hL(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return dL.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw new fL(`canonical record unreadable: ${i.reason}`);let a=yn(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:$I(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:eL(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function gL(e,t){let n=await e.getMigrationState(pL);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:pL,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var _L=/* @__PURE__ */ e({applyAttachmentOverlays:()=>xL,interleaveMarkers:()=>SL,toAgentMessages:()=>yL,toChatMessages:()=>bL});const vL=/* @__PURE__ */ new Set([`summarized`,`fallback`]);function yL(e){if(!uL(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 bL(e,t={}){if(!uL(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 SL(t,e.markers)}let n=e.projectionPrefix??[],r=yL(e);if(r.length===0)return SL([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>_j),a=xL(i(r,t),e.attachments);return SL([...n,...a],e.markers)}function xL(e,t){if(!t?.length)return e;let n=[...t].sort((e,t)=>e.timestamp-t.timestamp),r=/* @__PURE__ */ new Set;return e.map(e=>{if(e.role!==`user`||e.attachments?.length)return e;let t=e.content.trim(),i=n.findIndex((e,n)=>!r.has(n)&&e.body.trim()===t);return i<0?e:(r.add(i),{...e,attachments:n[i].attachments})})}function SL(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||vL.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=CL(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(wL(r[a++]));i.push(t)}for(;a<r.length;)i.push(wL(r[a++]));return i}function CL(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 wL(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 TL(e){return{id:e.legacyKeys.chatSessionId,messages:await bL(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function EL(e){return{id:e.workUnitId,messages:yL(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var DL=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(EL)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(TL))}async latestPerUnit(){let e=/* @__PURE__ */ new Map;for(let t of await this.store.loadAll()){let n=e.get(t.workUnitId);(!n||t.updatedAt>n.updatedAt)&&e.set(t.workUnitId,t)}return[...e.values()]}async loadRootChatSession(e){let t=await this.store.loadLatestInWorkspace(en({parentJid:null,folder:e}).root);return t?TL(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const OL=h(`work-unit-conversation`),kL=`conversations`,AL=`migrations`;var jL=class{dbPromise=null;dbName;writeChains=/* @__PURE__ */ new Map;constructor(e={}){this.dbName=e.dbName??`slicc-work-units`}async load(e){let t=await this.read(e);return t.status===`ok`?t.record:null}async read(e){try{let t=await RL((await this.getDb()).transaction(kL,`readonly`).objectStore(kL).get(e));return t?uL(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(OL.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(OL.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return OL.warn(`Conversation record read failed`,{key:e,error:BL(t)}),{status:`error`,reason:BL(t)}}}async save(e){let t=e.version>2?e.version:lL(e),n={...e,version:t},r=(await this.getDb()).transaction(kL,`readwrite`);return r.objectStore(kL).put(n),await zL(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(kL,`readwrite`);t.objectStore(kL).delete(e),await zL(t)}catch(t){OL.warn(`Conversation record delete failed`,{key:e,error:BL(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`){OL.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){OL.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:BL(n)})}}async loadAll(){try{return(await RL((await this.getDb()).transaction(kL,`readonly`).objectStore(kL).getAll())).filter(e=>uL(e)&&Array.isArray(e.entries))}catch(e){return OL.warn(`Conversation record listing failed`,{error:BL(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await RL((await this.getDb()).transaction(kL,`readonly`).objectStore(kL).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)uL(e)&&Array.isArray(e.entries)&&(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return OL.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:BL(t)}),null}}async listKeys(){try{return(await RL((await this.getDb()).transaction(kL,`readonly`).objectStore(kL).getAllKeys())).map(String)}catch(e){return OL.warn(`Conversation key listing failed`,{error:BL(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=$I(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=ML(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return OL.warn(`Conversation record write failed`,{key:e.key,error:BL(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?NL(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 OL.warn(`Conversation marker write failed`,{key:e,error:BL(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 RL((await this.getDb()).transaction(AL,`readonly`).objectStore(AL).get(e))??null}catch(t){return OL.warn(`Migration state read failed`,{id:e,error:BL(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(AL,`readwrite`);t.objectStore(AL).put(e),await zL(t)}catch(t){OL.warn(`Migration state write failed`,{id:e.id,error:BL(t)})}}async clearAll(){let e=(await this.getDb()).transaction([kL,AL],`readwrite`);e.objectStore(kL).clear(),e.objectStore(AL).clear(),await zL(e)}getDb(){return this.dbPromise||(this.dbPromise=LL(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 ML(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??[],...PL(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&FL(a,t))return null;let o=t.length>a.length&&FL(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 NL(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 PL(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function FL(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!IL(e[n],t[n]))return!1;return!0}function IL(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 LL(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(kL)||e.createObjectStore(kL,{keyPath:`key`}),e.objectStoreNames.contains(AL)||e.createObjectStore(AL,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function RL(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function zL(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function BL(e){return e instanceof Error?e.message:String(e)}var VL=/* @__PURE__ */ e({CONE_MEMORY_PATH:()=>WL,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>UL,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>GL,applyConeMemoryBudget:()=>XL,readSessionCount:()=>JL,restructureConeMemory:()=>YL,splitConeMemory:()=>qL});const HL=h(`cone-memory-budget`),UL=1.25,WL=Xt.memoryPath,GL=`/sessions/index.json`,KL=/^## Auto-extracted/m;function qL(e){let t=KL.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function JL(e){try{let t=await e.readFile(GL,{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 YL(e){let{header:t,autoExtracted:n}=qL(e.currentContent);if(!n.trim())return e.currentContent;let r=nt(`You are a memory consolidation assistant. You are given a markdown file's "auto-extracted" section — a list of memory bullets accumulated across sessions of an AI coding assistant. Your job is to rewrite that section as a tighter, deduplicated set of durable memories that fits well within ${e.budget} characters.
1064
+ `)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(qn,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,aF,e=>{let t=/* @__PURE__ */ new Set,n=!1,r=!1;for(let i of e){if(i.path===`/etc/sudoers.d`){r=!0;continue}let e=oF(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 dF(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function fF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pF(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++)pF(e[r],`${t}/${r}`,n);return}if(fF(e))for(let[r,i]of Object.entries(e))pF(i,`${t}/${dF(r)}`,n)}function mF(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=mF(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(fF(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=mF(o,`${t}/${dF(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function hF(e,t,n){if(fF(e))return mF(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=hF(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function gF(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function _F(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new o(`redaction-unavailable`);let a=0,s=i;for(;s<e.length;){let t=e[s].length;if(s>i&&a+t>1048576)break;a+=t,s++}let c=e.slice(i,s),l;try{l=await t.redact(c,n)}catch{throw new o(`redaction-unavailable`)}if(l.length!==c.length)throw new o(`redaction-unavailable`);r.push(...l),i=s}return r}function vF(e,t,n,r){let i=[],a=gF(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=gF(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=Se(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function yF(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 bF(e,n,r,i){if(i?.aborted)throw new o(`redaction-unavailable`);let{privacy:a,...s}=e,c=[];pF(s,``,c);let l=c.filter(e=>!t(e.pointer)),u=[...n.entries()],d=await _F([...l.map(e=>e.value),...u.map(([,e])=>e)],r,i),f=[],p={},m=1,ee=/* @__PURE__ */ new Map,te=[];for(let e=0;e<l.length;e++){let t=l[e],n=vF(t.value,d[e],{kind:`json`,pointer:t.pointer},m);m=n.nextId,n.finalText!==t.value&&ee.set(t.pointer,n.finalText),te.push(n)}yF(te,f,p);let ne=/* @__PURE__ */ new Map,h=l.length,re=[];for(let e=0;e<u.length;e++){let[t,n]=u[e],r=vF(n,d[h+e],{kind:`attachment`,attachmentId:t},m);m=r.nextId,ne.set(t,r.finalText),re.push(r)}yF(re,f,p);let ie=hF(e,``,ee);return{document:{...ie,privacy:{...ie.privacy,redactionCounts:p,redactions:f}},textAttachments:ne}}function xF(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}const SF={"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 CF(e,t){return SF[e]??(t===`text-redacted`?`.txt`:`.bin`)}function wF(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${CF(t,n)}`}function TF(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 EF(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 DF(e,t,n,r,i){let a=xF(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(TF(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=TF(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 OF(e,t,n,r){let i=[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:TF(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(DF(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function kF(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 AF(e,t,n,r,i,a,o){let s=kF(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(DF(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function jF(e,t,n,r,i){let a=/* @__PURE__ */ new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=AF(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,/* @__PURE__ */ new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function MF(e,t){let n=/* @__PURE__ */ new Map,r=0,i=/* @__PURE__ */ new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,wF(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 NF(e,t,n,r,i){let{rawAttachments:a,textMap:s}=MF(e,n),c,l;try{let e=await bF({...t,attachments:a},s,r,i);c=e.document,l=e.textAttachments}catch(e){throw e instanceof o?e:new o(`attachment-unreadable`)}let u=/* @__PURE__ */ new Map;for(let t of e){if(u.has(t.attachmentId))throw new o(`schema-invalid`);u.set(t.attachmentId,t)}let d=/* @__PURE__ */ new Map,f=await Promise.all(c.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=u.get(e.id);if(t===void 0)throw new o(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(l.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await be(n);return d.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...c,attachments:f},bundleFiles:d}}async function PF(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??/* @__PURE__ */ new Map,o=e.vfsReader,s=/* @__PURE__ */ new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=OF(EF(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}=jF(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),ee=[...d,...m],te=t;f.size>0&&(te={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:ne,bundleFiles:h}=await NF(ee,te,s,r,i),re=[...ne.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{...ne,session:{...ne.session,completeness:{status:re.length>0?`partial`:ne.session.completeness.status,missing:re}}},bundleFiles:h}}function FF(e){return Ft(e)}function IF(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 LF(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let e of t)i.set(e.id,e);let a=/* @__PURE__ */ new Map;for(let e of n)a.set(e.id,e);let o=[],s=/* @__PURE__ */ new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:bt(t)?`cone`:`scoop`,name:t.name,...t.folder&&!bt(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=FF(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function RF(e,t,n={}){let r=e=>n.rootJid===void 0?e:Ct(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new o(`transfer-aborted`);let i=IF(n,e),[a,s]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new o(`transfer-aborted`);let c=r(e.listScoops());if(i===IF(c,e))return LF(c,a,s,e)}}var zF=/* @__PURE__ */ e({SESSIONS_DIR:()=>BF,SESSIONS_INDEX_PATH:()=>VF,carryCurationLedger:()=>HF,parseFrozenArchive:()=>WF,readSessionsIndex:()=>UF});const BF=`/sessions`,VF=`/sessions/index.json`;function HF(e,t={}){return e?{...e.curatedThrough?{curatedThrough:e.curatedThrough}:{},...e.memoryCuratedAt?{memoryCuratedAt:e.memoryCuratedAt}:{},...e.memoryFailed&&!t.dropFailure?{memoryFailed:e.memoryFailed}:{},...e.memorySkipped?{memorySkipped:!0}:{}}:{}}async function UF(e){try{let t=await e.readFile(VF,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function WF(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,GF(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=KF(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:JF(t),...r})}function GF(e){let t={},n=qF(e,`cost`),r=qF(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=KF(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(/^sessionId:\s*(\S+)\s*$/m)?.[1];u&&(t.sessionId=u);let d=e.match(/^attachmentsKey:\s*(\S+)\s*$/m)?.[1];d&&(t.attachmentsKey=d);let f=e.match(/^sidecar:\s*(\S+)\s*$/m)?.[1];return f&&(t.sidecar=f),t}function KF(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 qF(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function JF(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 YF(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function XF(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function ZF(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(XF(t,r++));return n}function QF(e,t){let n=[],r=/* @__PURE__ */ new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=XF(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 $F(e,t){let n=[],r=/* @__PURE__ */ new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=XF(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 eI(e,t,n){let r=YF(t,n),i=ZF(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:/* @__PURE__ */ new Map}}function tI(e,t,n){let r=YF(t,n),{blocks:i,excluded:a,images:o}=QF(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 nI(e,t,n){let r=YF(t,n),{blocks:i,images:a}=$F(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 rI(e,t,n){return e.role===`user`?eI(e,t,n):e.role===`assistant`?tI(e,t,n):e.role===`toolResult`?nI(e,t,n):{message:null,excludedReasoningBlocks:0,images:/* @__PURE__ */ new Map}}function iI(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 aI(e){let t=0,n=/* @__PURE__ */ new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=rI(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:iI(e),excludedReasoningBlocks:t,canonicalImages:n}}const oI=(()=>{let e=/* @__PURE__ */ new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function sI(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^oI[(t^e[n])&255];return~t>>>0}const cI=new TextEncoder;function lI(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function uI(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 dI(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,lI(r,4,20),lI(r,6,2048),lI(r,8,0),lI(r,10,0),lI(r,12,0),uI(r,14,n),uI(r,18,t),uI(r,22,t),lI(r,26,e.length),lI(r,28,0),r.set(e,30),r}function fI(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,lI(i,4,20),lI(i,6,20),lI(i,8,2048),lI(i,10,0),lI(i,12,0),lI(i,14,0),uI(i,16,n),uI(i,20,t),uI(i,24,t),lI(i,28,e.length),lI(i,30,0),lI(i,32,0),lI(i,34,0),lI(i,36,0),uI(i,38,0),uI(i,42,r),i.set(e,46),i}function pI(e,t,n){let r=/* @__PURE__ */ new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,lI(r,4,0),lI(r,6,0),lI(r,8,e),lI(r,10,e),uI(r,12,t),uI(r,16,n),lI(r,20,0),r}function mI(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 hI(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${xe(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*gI(e,t,n,r){if(t?.aborted)throw r(new o(`transfer-aborted`)),new o(`transfer-aborted`);let i=()=>r(new o(`transfer-aborted`));t?.addEventListener(`abort`,i,{once:!0});let a=Yn.create(),s=0,c=0,l=[],u=!1;function*d(e){a.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{for(let n of e){if(t?.aborted)throw new o(`transfer-aborted`);let e=await n.load();if(t?.aborted)throw new o(`transfer-aborted`);if(e.byteLength>_I)throw new o(`schema-invalid`);let r=cI.encode(n.path),i=sI(e),a=dI(r,e.length,i);if(c+a.length+e.length>_I)throw new o(`schema-invalid`,`archive exceeds ZIP32 offsets`);if(l.push({nameBytes:r,size:e.length,crc:i,localOffset:c}),yield*d(a),t?.aborted)throw new o(`transfer-aborted`);yield*d(e)}if(l.length>vI)throw new o(`schema-invalid`);let r=c;for(let e of l){if(t?.aborted)throw new o(`transfer-aborted`);yield*d(fI(e.nameBytes,e.size,e.crc,e.localOffset))}if(t?.aborted)throw new o(`transfer-aborted`);yield*d(pI(l.length,c-r,r)),u=!0,n({byteLength:s,sha256:a.hex()})}catch(e){throw u=!0,r(e),e}finally{t?.removeEventListener(`abort`,i),u||(u=!0,r(new o(`transfer-aborted`)))}}const _I=4294967295,vI=65535;function yI(e,t){let n=/* @__PURE__ */ new Set;for(let{path:t}of e){if(!mI(t)||n.has(t))throw new o(`schema-invalid`);n.add(t)}if(e.length>vI)throw new o(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return a.catch(()=>void 0),{chunks:gI(e,t,r,i),completion:a}}function bI(e,t,n){for(let e of t.keys())if(!mI(e))throw new o(`schema-invalid`);if(t.size+1>vI)throw new o(`schema-invalid`);for(let e of t.values())if(e.byteLength>_I)throw new o(`schema-invalid`);let r=[{path:`transcript.json`,load:()=>new TextEncoder().encode(JSON.stringify(e,null,2))},...[...t].map(([e,t])=>({path:e,load:()=>t}))];return{filename:hI(e),...yI(r,n)}}function xI(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:(/* @__PURE__ */ new Date()).toISOString(),producer:{application:`slicc`,version:i},format:s},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function SI(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 CI(e){let t=te(e);if(!t.ok)throw new o(`schema-invalid`,t.error)}function wI(e,t,n){let r=/* @__PURE__ */ new Map;for(let i of e)if(i.present&&i.path){if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}}return r}async function TI(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);return n?{...e,byteLength:n.length,sha256:await be(n)}:e}))}function EI(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 DI=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),CI(i.document),r?.({phase:`packaging`}),bI(i.document,i.bundleFiles,n)}async snapshotCone(e,t){let n=await RF(this.deps.collection,t,{rootJid:e.jid}),r=aI(n.sources),i=await PF({document:xI(e.jid,e.name,`active`,r,this.deps.version),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});return CI(i.document),i}async snapshotFrozen(e,t){let n=await this.buildFrozenSnapshot(e,t);return CI(n.document),n}async captureFrozen(e,t){let n=await RF(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=aI(n.sources),{document:i,bundleFiles:a}=await PF({document:xI(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});if(CI(i),t?.aborted)throw new o(`transfer-aborted`);try{await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a},t)}finally{this.deps.snapshotStore.discardIfUnindexed?.(e.sessionId)?.catch(()=>void 0)}}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await RF(this.deps.collection,e),r=aI(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=xI(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),PF({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r;try{r=await this.deps.snapshotStore.read(e)}catch(e){if(!(e instanceof o)||e.code!==`session-not-found`)throw e;r=null}return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=/* @__PURE__ */ new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await bF(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new o(`redaction-unavailable`)}let a=wI(r.attachments,i,e.attachments),s=await TI(r.attachments,a);return{document:{...r,attachments:s},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await UF(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new o(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new o(`session-not-found`)}let{loadFrozenArchive:a}=await import(`./session-jsonl-DvM9G2Ke.js`),{title:c,messages:l}=await a(this.deps.vfs,i,r.filename),u=`legacy-cone`,d=SI(l,u),f=EI(i),p={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:(/* @__PURE__ */ new Date()).toISOString(),producer:{application:`slicc`,version:this.deps.version},format:s},session:{id:e,title:c,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...f,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:u,kind:`cone`,name:c,messages:d}],delegations:[],attachments:[]},m=/* @__PURE__ */ new Map([[u,l]]);return n?.({phase:`redacting`}),PF({document:p,chatMessagesByConversation:m,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new o(`attachment-unreadable`);return t}};const OI=`/sessions/data`,kI=`document.json`,AI=`.publishing`;function jI(e){if(e?.aborted)throw new o(`transfer-aborted`)}function MI(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new o(`session-not-found`)}function NI(e){return`${OI}/${e}`}function PI(e){return`${OI}/.tmp-${e}`}async function FI(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function II(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 II(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function LI(e,t){let n=await e.readDir(t);for(let r of n){if(r.name===AI)continue;let n=`${t}/${r.name}`;r.type===`directory`?await II(e,n):await e.rm(n)}}async function RI(e,t,n,r){jI(r),await FI(e,n);let i=await e.readDir(t);for(let a of i){jI(r);let i=`${t}/${a.name}`,o=`${n}/${a.name}`;if(a.type===`directory`)await RI(e,i,o,r);else{let t=await e.readFile(i,{encoding:`binary`});await e.writeFile(o,t)}}}async function zI(e,t,n,r){MI(t);let i=PI(t),a=NI(t),s=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!s.has(e))throw new o(`schema-invalid`);jI(r),await FI(e,i);let c=!1;try{let t=[...n.document.attachments];for(let[e,i]of n.attachments){jI(r);let n=await be(i),a=s.get(e);if(a!==void 0){let e=t.indexOf(a);e!==-1&&(t[e]={...a,sha256:n,byteLength:i.length})}}let o={...n.document,attachments:t},l=JSON.stringify(o,null,2);if(await e.writeFile(`${i}/${kI}`,l),n.attachments.size>0)for(let[t,r]of n.attachments){let n=`${i}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await FI(e,`${i}/${t.slice(0,a)}`),await e.writeFile(n,r)}await e.flush(),jI(r),await FI(e,a),c=!0,await e.writeFile(`${a}/${AI}`,`in-progress`),await LI(e,a),jI(r),await RI(e,i,a,r),await e.flush(),jI(r),await e.rm(`${a}/${AI}`)}catch(t){if(c)try{await LI(e,a)}catch{}throw await II(e,i),t}await II(e,i)}async function BI(e,t){MI(t);for(let n of[NI(t),PI(t)])try{await e.rm(n,{recursive:!0})}catch(e){if(e?.code!==`ENOENT`)throw e}}async function VI(e,t){let[{serializeIndexWrite:n},{readIndexForPresence:r}]=await Promise.all([import(`./frozen-archive-writer-Dk602Q9A.js`).then(e=>e.i),import(`./frozen-session-identity-Wawl3rz4.js`)]);return n(async()=>{let n=await r(e);return n===null||n.some(e=>e.sessionId===t)?!1:(await BI(e,t),!0)})}async function HI(e,t){MI(t);let n=NI(t),r=`${n}/${kI}`;try{throw await e.stat(`${n}/${AI}`),new o(`session-not-found`)}catch(e){if(e instanceof o||e.code!==`ENOENT`)throw e}let i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new o(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new o(`schema-invalid`)}if(!te(a).ok)throw new o(`schema-invalid`);let s=/* @__PURE__ */ new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new o(`transfer-corrupt`)}if(await be(i)!==t.sha256)throw new o(`transfer-corrupt`);s.set(t.path,i)}return{document:a,attachments:s}}function UI(e){return`error`in e}function WI(){throw new o(`redaction-unavailable`)}function GI(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&WI(),e.texts}function KI(){return{async redact(e){let t;try{t=await fetch(ze(`/api/secrets/redact-export`),{method:`POST`,headers:Be({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{WI()}t.ok||WI();let n;try{n=await t.json()}catch{WI()}return GI(n,e.length)}}}function qI(){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{WI()}return typeof t==`object`&&t&&UI(t)&&WI(),GI(t,e.length)}}}function JI(){return{async redact(e){let t;try{t=await ot(`secrets.redact-export`,{texts:e})}catch{WI()}return t??WI(),typeof t==`object`&&t&&UI(t)&&WI(),GI(t,e.length)}}}function YI(){return{async redact(e){WI()}}}function XI(){let e=at();return e===`connect`?YI():e===`extension-direct`?qI():e===`extension-delegate`?JI():KI()}const ZI=/* @__PURE__ */ new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function QI(e){return`e${e}`}function $I(e){let t=[];for(let n of e){let e=nL(n),r=iL(n);if(e===`assistant`){let e=t.length,i=QI(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:sL(n),message:n,model:oL(n)});for(let e of cL(n)){let n=t.length;t.push({id:QI(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:QI(i),seq:i,kind:`tool-result`,timestamp:r,text:sL(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=sL(n),a=e===`user`?tL(i):null,o=t.length,s=QI(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):ZI.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 eL(e){let t=[];for(let n of e){let e=t.length,r=QI(e),i=aL(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:QI(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&ij(n.channel)?n.channel:tL(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):ZI.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 tL(e){for(let t of oj(e)){let e=(t.sender?sj(t.sender):null)??cj(t.body);if(e)return e}return null}function nL(e){return e.role??``}function rL(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 iL(e){return rL(e.timestamp)}function aL(e){return rL(e.timestamp)}function oL(e){let t=e.model;return typeof t==`string`?t:void 0}function sL(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 cL(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 lL(e){let t=e.markers?.some(e=>e.kind===`error`)??!1,n=(e.projectionPrefix?.length??0)>0;return t||n?2:1}function uL(e){return e!==null&&e.version<=2}const dL=h(`work-unit-conversation`);var fL=class extends Error{};const pL=`conversations`;async function mL(e){let t=e.now??(()=>Date.now()),n=await gL(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=vn(s);if(i.has(c)){r.alreadyDone++;continue}try{let n=await hL(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}],dL.warn(`Skipping a unit whose conversation could not be migrated`,{key:c,folder:s.folder,error:o}),i instanceof fL){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),dL.info(`Canonical conversation migration complete`,{...r}),r}async function hL(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return dL.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw new fL(`canonical record unreadable: ${i.reason}`);let a=yn(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:$I(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:eL(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function gL(e,t){let n=await e.getMigrationState(pL);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:pL,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}var _L=/* @__PURE__ */ e({applyAttachmentOverlays:()=>xL,interleaveMarkers:()=>SL,toAgentMessages:()=>yL,toChatMessages:()=>bL});const vL=/* @__PURE__ */ new Set([`summarized`,`fallback`]);function yL(e){if(!uL(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 bL(e,t={}){if(!uL(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 SL(t,e.markers)}let n=e.projectionPrefix??[],r=yL(e);if(r.length===0)return SL([...n],e.markers);let{agentMessagesToChatMessages:i}=await Promise.resolve().then(()=>_j),a=xL(i(r,t),e.attachments);return SL([...n,...a],e.markers)}function xL(e,t){if(!t?.length)return e;let n=[...t].sort((e,t)=>e.timestamp-t.timestamp),r=/* @__PURE__ */ new Set;return e.map(e=>{if(e.role!==`user`||e.attachments?.length)return e;let t=e.content.trim(),i=n.findIndex((e,n)=>!r.has(n)&&e.body.trim()===t);return i<0?e:(r.add(i),{...e,attachments:n[i].attachments})})}function SL(e,t){let n=(t??[]).filter(e=>e.kind!==`compaction`||vL.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=CL(t);for(;a<r.length&&r[a].timestamp<=e;)i.push(wL(r[a++]));i.push(t)}for(;a<r.length;)i.push(wL(r[a++]));return i}function CL(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 wL(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 TL(e){return{id:e.legacyKeys.chatSessionId,messages:await bL(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function EL(e){return{id:e.workUnitId,messages:yL(e),config:{},createdAt:e.createdAt,updatedAt:e.updatedAt}}var DL=class{store;constructor(e){this.store=e}async loadAgentSessions(){return(await this.latestPerUnit()).map(EL)}async loadChatSessions(){return Promise.all((await this.latestPerUnit()).map(TL))}async latestPerUnit(){let e=/* @__PURE__ */ new Map;for(let t of await this.store.loadAll()){let n=e.get(t.workUnitId);(!n||t.updatedAt>n.updatedAt)&&e.set(t.workUnitId,t)}return[...e.values()]}async loadRootChatSession(e){let t=await this.store.loadLatestInWorkspace(en({parentJid:null,folder:e}).root);return t?TL(t):null}async load(e){return e.startsWith(`session-`)?this.loadRootChatSession(e.slice(8)):null}};const OL=h(`work-unit-conversation`),kL=`conversations`,AL=`migrations`;var jL=class{dbPromise=null;dbName;writeChains=/* @__PURE__ */ new Map;constructor(e={}){this.dbName=e.dbName??`slicc-work-units`}async load(e){let t=await this.read(e);return t.status===`ok`?t.record:null}async read(e){try{let t=await RL((await this.getDb()).transaction(kL,`readonly`).objectStore(kL).get(e));return t?uL(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(OL.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(OL.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return OL.warn(`Conversation record read failed`,{key:e,error:BL(t)}),{status:`error`,reason:BL(t)}}}async save(e){let t=e.version>2?e.version:lL(e),n={...e,version:t},r=(await this.getDb()).transaction(kL,`readwrite`);return r.objectStore(kL).put(n),await zL(r),n}delete(e){return this.serialize(e,async()=>{try{let t=(await this.getDb()).transaction(kL,`readwrite`);t.objectStore(kL).delete(e),await zL(t)}catch(t){OL.warn(`Conversation record delete failed`,{key:e,error:BL(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`){OL.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){OL.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:BL(n)})}}async loadAll(){try{return(await RL((await this.getDb()).transaction(kL,`readonly`).objectStore(kL).getAll())).filter(e=>uL(e)&&Array.isArray(e.entries))}catch(e){return OL.warn(`Conversation record listing failed`,{error:BL(e)}),[]}}async loadLatestInWorkspace(e){try{let t=`${e}::`,n=await RL((await this.getDb()).transaction(kL,`readonly`).objectStore(kL).getAll(IDBKeyRange.bound(t,`${t}\uffff`))),r=null;for(let e of n)uL(e)&&Array.isArray(e.entries)&&(!r||e.updatedAt>r.updatedAt)&&(r=e);return r}catch(t){return OL.warn(`Conversation workspace lookup failed`,{workspaceId:e,error:BL(t)}),null}}async listKeys(){try{return(await RL((await this.getDb()).transaction(kL,`readonly`).objectStore(kL).getAllKeys())).map(String)}catch(e){return OL.warn(`Conversation key listing failed`,{error:BL(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=$I(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=ML(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?await this.save(o):a}catch(t){return OL.warn(`Conversation record write failed`,{key:e.key,error:BL(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?NL(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 OL.warn(`Conversation marker write failed`,{key:e,error:BL(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 RL((await this.getDb()).transaction(AL,`readonly`).objectStore(AL).get(e))??null}catch(t){return OL.warn(`Migration state read failed`,{id:e,error:BL(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(AL,`readwrite`);t.objectStore(AL).put(e),await zL(t)}catch(t){OL.warn(`Migration state write failed`,{id:e.id,error:BL(t)})}}async clearAll(){let e=(await this.getDb()).transaction([kL,AL],`readwrite`);e.objectStore(kL).clear(),e.objectStore(AL).clear(),await zL(e)}getDb(){return this.dbPromise||(this.dbPromise=LL(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 ML(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??[],...PL(e)],updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&FL(a,t))return null;let o=t.length>a.length&&FL(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 NL(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 PL(e){let t=[];for(let n of e.entries)n.kind!==`tool-call`&&n.chat&&t.push(n.chat);return t}function FL(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!IL(e[n],t[n]))return!1;return!0}function IL(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 LL(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(kL)||e.createObjectStore(kL,{keyPath:`key`}),e.objectStoreNames.contains(AL)||e.createObjectStore(AL,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function RL(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function zL(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function BL(e){return e instanceof Error?e.message:String(e)}var VL=/* @__PURE__ */ e({CONE_MEMORY_PATH:()=>WL,MEMORY_BASE_CHARS:()=>MEMORY_BASE_CHARS,MEMORY_OVERSHOOT_RATIO:()=>UL,MEMORY_PER_LOG_CHARS:()=>MEMORY_PER_LOG_CHARS,SESSIONS_INDEX_PATH:()=>GL,applyConeMemoryBudget:()=>XL,readSessionCount:()=>JL,restructureConeMemory:()=>YL,splitConeMemory:()=>qL});const HL=h(`cone-memory-budget`),UL=1.25,WL=Xt.memoryPath,GL=`/sessions/index.json`,KL=/^## Auto-extracted/m;function qL(e){let t=KL.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function JL(e){try{let t=await e.readFile(GL,{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 YL(e){let{header:t,autoExtracted:n}=qL(e.currentContent);if(!n.trim())return e.currentContent;let r=nt(`You are a memory consolidation assistant. You are given a markdown file's "auto-extracted" section — a list of memory bullets accumulated across sessions of an AI coding assistant. Your job is to rewrite that section as a tighter, deduplicated set of durable memories that fits well within ${e.budget} characters.
1065
1065
 
1066
1066
  <auto-extracted>
1067
1067
  ${n}
@@ -1239,15 +1239,15 @@ Created: ${(/* @__PURE__ */ new Date()).toISOString()}
1239
1239
  `),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 mH(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 hH=h(`tool:bash`),gH=40960,_H=1048576,vH=`\0slicc-img:`;function yH(e){let t=ct(e).filter(e=>e.kind===`image`);if(t.length===0)return{text:e,markers:/* @__PURE__ */ new Map};let n=/* @__PURE__ */ new Set,r=_H;for(let e=t.length-1;e>=0;e--){let i=t[e].marker.length;if(i>r&&n.size>0)break;r-=i,n.add(e)}let i=/* @__PURE__ */ new Map,a=``,o=0;return t.forEach((t,r)=>{if(a+=e.slice(o,t.index),n.has(r)){let e=`${vH}${r}`;i.set(e,t.marker),a+=e}else a+=`[image dropped: a newer image in this command used up the ${_H/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 bH(e){let t=ct(e).filter(e=>e.kind===`image`);if(t.length===0)return e;let n=``,r=0;for(let i of t)n+=`${e.slice(r,i.index)}[image]`,r=i.index+i.marker.length;return n+e.slice(r)}function xH(e){return e.replaceAll(RegExp(`${vH}\\d+`,`g`),`[image]`)}function SH(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 CH(e,t,n,r){let{text:i,markers:a}=yH(e),o=pH(i,{maxBytes:gH});if(!o.truncated)return SH(i,a);let s=`showing the last ${dH(o.outputBytes)} of ${dH(o.totalBytes)} (${o.totalLines} lines)`,c=`${n}/bash-output-${r()}.txt`;try{return await t.writeFile(c,xH(i)),SH(`${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 hH.warn(`Failed to persist full bash output`,{error:e instanceof Error?e.message:String(e)}),SH(`${o.content}\n\n[Output truncated: ${s}. Re-run piping through \`head\`/\`tail\`/\`grep\`/\`sed -n\` to narrow the output.]`,a)}}const wH=/* @__PURE__ */ new Set([`grep`,`egrep`,`fgrep`,`rg`]);function TH(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 EH(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=TH(r.name);if(i!==`command`)return i;let a=r.args[0];return a?TH(a):null}function DH(e,t,n,r){if(n!==1||r.trim())return!1;let i;try{i=EH(e.getBash().transform(t).ast)}catch{return!1}return i!==null&&wH.has(i)}function OH(e,t){let n=e.options.annotateResult?.();return n?`${t.endsWith(`
1240
1240
  `)||t.length===0?t:`${t}\n`}${n}\n`:t}function kH(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return e}function AH(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 ${gH/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 ${_H/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 jH(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 MH(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 NH(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 zH(e,n,r);await e.fs.writeFile(t,i)}).catch(e=>hH.warn(`Failed to tee background bash output`,{jobId:n,outputPath:t,error:e instanceof Error?e.message:String(e)}))};return{job:i,controller:r,settled:e.shell.executeCommand(t,r.signal,i?.pid,void 0,{capturePipeStatus:!0,onOutput:e=>{o.push(e),u()}}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e instanceof Error?e.message:String(e)})),releaseTurnSignal:()=>n?.removeEventListener(`abort`,a),getTeedOutput:()=>o.join(``),startPersisting:(t,n)=>{s=t,c=n,l=l.then(()=>e.swept).then(()=>void 0),u()},flushPersist:()=>l,killedByTimeout:!1}}function PH(e,t){t===`timeout`&&(e.killedByTimeout=!0),e.job?.kill(),e.controller.abort(),e.job?.exit(null)}function FH(e,t){e.job?.exit(e.job.signal.aborted?null:t)}function IH(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 LH(e,t,n,r={}){let i=0,a=0,o=import(`./bash-job-journal-DEe5YuRn.js`),s=o.then(({createBashJobJournal:e})=>e(t,n,void 0,(e,t)=>hH.warn(e,{tempDir:n,error:t instanceof Error?t.message:String(t)}))),c={shell:e,fs:t,tempDir:n,options:r,defaultBackgroundAfter:kH(r.defaultBackgroundAfterSeconds)??600,nextOutputSeq:()=>i+=1,nextJobId:()=>`bg-${a+=1}`,journal:s,swept:Promise.resolve()};return c.swept=Promise.all([o,s]).then(([{KERNEL_RESTART_EXIT_CODE:e},t])=>t.sweep((t,n)=>RH(c,t,n,e))).catch(e=>hH.warn(`Could not sweep orphaned bash jobs`,{tempDir:n,error:e})),{name:`bash`,description:AH(c.defaultBackgroundAfter),inputSchema:jH(c.defaultBackgroundAfter),execute:(e,t)=>GH(c,e,t)}}function RH(e,t,n,r){let i={type:`bash`,bashJobId:t.jobId,bashCommand:t.command,bashExitCode:r,...t.pid===void 0?{}:{bashJobPid:t.pid},resultPath:t.outputPath,preview:n,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{jobId:t.jobId,pid:t.pid??null,command:t.command,exitCode:r,resultPath:t.outputPath,killedByKernelRestart:!0}};hH.warn(`Background bash job was killed by a kernel restart`,{jobId:t.jobId,command:t.command,startedAt:t.startedAt});let a=n=>{if(e.options.fireLick?.(i)===!1){if(n<=1){hH.warn(`No lick sink for a kernel-restart job report; output file still has it`,{jobId:t.jobId,outputPath:t.outputPath});return}setTimeout(()=>a(n-1),2e3)}};a(30)}async function zH(e,t,n){let r=e.options.scrubOutput;if(!r||!n)return n;try{return await r(n)}catch(e){return hH.warn(`Background bash output scrub failed; withholding output`,{jobId:t,error:e instanceof Error?e.message:String(e)}),`[output withheld: secret scrub unavailable]`}}function BH(e){return e.ok?e.result.exitCode===124&&/execution aborted/i.test(e.result.stderr):/execution aborted/i.test(e.error)}function VH(e,t){return e===void 0?`--- killed (exit ${t}) ---\n`:`--- killed after ${e}s (exit ${t}) ---\n`}async function HH(e,t,n,r,i,a,o,s){await o.flushPersist();let c=o.killedByTimeout||BH(a),l,u;if(c){let e=o.getTeedOutput();u=124,l=`${e.endsWith(`
1241
1241
  `)||e.length===0?e:`${e}\n`}${VH(s,u)}`}else if(a.ok)l=sr([a.result.stdout,a.result.stderr].filter(Boolean).join(``)||`(exit code: ${a.result.exitCode})`,a.result.pipeStatus),u=a.result.exitCode;else{let e=o.getTeedOutput();u=1,l=e?`${e.endsWith(`
1242
- `)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await zH(e,t,OH(e,l)),f;try{await e.fs.writeFile(i,d),f=i}catch(e){hH.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){hH.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=pH(bH(d),{maxBytes:2048});e.options.fireLick({type:`bash`,bashJobId:t,bashCommand:r,bashExitCode:u,...n===void 0?{}:{bashJobPid:n},resultPath:f,preview:p.content,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:u,resultPath:f??null}})}function UH(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=Promise.all([e.journal,e.swept]).then(([e])=>e.record({jobId:o,pid:s,command:n,outputPath:c,startedAt:(/* @__PURE__ */ new Date()).toISOString()})),u=()=>l.then(()=>e.journal).then(e=>e.clear(o)).catch(e=>hH.warn(`Could not journal a detached bash job`,{jobId:o,error:e})),d=i===void 0?void 0:i-a,f=d===void 0?void 0:setTimeout(()=>PH(t,`timeout`),d*1e3);return t.settled.then(r=>(f!==void 0&&clearTimeout(f),FH(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),HH(e,o,s,n,c,r,t,i))).catch(e=>hH.error(`Background bash delivery failed`,{jobId:o,error:e})).then(u),hH.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:d}),IH(o,s,r,c,i)}async function WH(e,t,n){hH.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=OH(e,sr(r,n.pipeStatus)),{content:await CH(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!DH(e.shell,t,n.exitCode,n.stderr)}}async function GH(e,t,n){let r=t.command,i=kH(t.timeout),a=kH(t.background_after)??e.defaultBackgroundAfter;hH.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=NH(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?(PH(o,`timeout`),hH.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),MH(c)):t===`elapsed`?UH(e,o,r,c,i,a):(FH(o,t.ok?t.result.exitCode:1),t.ok?await WH(e,r,t.result):(hH.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const KH={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 qH(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function JH(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:qH(e)&&(t.edits=[e])}catch{}else qH(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 YH(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:KH,prepareArguments:JH,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-dq5caQ-R.js`);return i(e,t,n,r)}}}async function XH(e,t,n){if(wn(pt(t)))return null;try{let r=await e.readTextFile(t);if(n.length<=262144)return r===n?null:`Write did not land: ${t} content mismatch (expected ${n.length} chars, got ${r.length})`;if(r.length!==n.length)return`Write did not land: ${t} content mismatch (expected ${n.length} chars, got ${r.length})`;let i=4096;return r.slice(0,i)!==n.slice(0,i)||r.slice(-4096)!==n.slice(-4096)?`Write did not land: ${t} content mismatch (head/tail sample)`:null}catch(e){return`Write did not land: ${t} is not readable (${e instanceof Error?e.message:String(e)})`}}const ZH=h(`tool:fs`);function QH(e,t=`/workspace`){return[$H(e),eU(e),YH(e,t)]}function $H(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${lH/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;ZH.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
1242
+ `)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await zH(e,t,OH(e,l)),f;try{await e.fs.writeFile(i,d),f=i}catch(e){hH.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){hH.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=pH(bH(d),{maxBytes:2048});e.options.fireLick({type:`bash`,bashJobId:t,bashCommand:r,bashExitCode:u,...n===void 0?{}:{bashJobPid:n},resultPath:f,preview:p.content,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:u,resultPath:f??null}})}function UH(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=Promise.all([e.journal,e.swept]).then(([e])=>e.record({jobId:o,pid:s,command:n,outputPath:c,startedAt:(/* @__PURE__ */ new Date()).toISOString()})),u=()=>l.then(()=>e.journal).then(e=>e.clear(o)).catch(e=>hH.warn(`Could not journal a detached bash job`,{jobId:o,error:e})),d=i===void 0?void 0:i-a,f=d===void 0?void 0:setTimeout(()=>PH(t,`timeout`),d*1e3);return t.settled.then(r=>(f!==void 0&&clearTimeout(f),FH(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),HH(e,o,s,n,c,r,t,i))).catch(e=>hH.error(`Background bash delivery failed`,{jobId:o,error:e})).then(u),hH.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:d}),IH(o,s,r,c,i)}async function WH(e,t,n){hH.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=OH(e,sr(r,n.pipeStatus)),{content:await CH(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!DH(e.shell,t,n.exitCode,n.stderr)}}async function GH(e,t,n){let r=t.command,i=kH(t.timeout),a=kH(t.background_after)??e.defaultBackgroundAfter;hH.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=NH(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?(PH(o,`timeout`),hH.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),MH(c)):t===`elapsed`?UH(e,o,r,c,i,a):(FH(o,t.ok?t.result.exitCode:1),t.ok?await WH(e,r,t.result):(hH.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const KH={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 qH(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function JH(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:qH(e)&&(t.edits=[e])}catch{}else qH(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 YH(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:KH,prepareArguments:JH,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-BOt2UG1t.js`);return i(e,t,n,r)}}}async function XH(e,t,n){if(wn(pt(t)))return null;try{let r=await e.readTextFile(t);if(n.length<=262144)return r===n?null:`Write did not land: ${t} content mismatch (expected ${n.length} chars, got ${r.length})`;if(r.length!==n.length)return`Write did not land: ${t} content mismatch (expected ${n.length} chars, got ${r.length})`;let i=4096;return r.slice(0,i)!==n.slice(0,i)||r.slice(-4096)!==n.slice(-4096)?`Write did not land: ${t} content mismatch (head/tail sample)`:null}catch(e){return`Write did not land: ${t} is not readable (${e instanceof Error?e.message:String(e)})`}}const ZH=h(`tool:fs`);function QH(e,t=`/workspace`){return[$H(e),eU(e),YH(e,t)]}function $H(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${lH/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;ZH.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
1243
1243
  `),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=fH(c.join(`
1244
- `));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${dH(new TextEncoder().encode(t[o]??``).length)}, exceeds ${dH(lH)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${lH}]`};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} (${dH(lH)} 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 ZH.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function eU(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;ZH.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await XH(e,n,r);return t?(ZH.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 ZH.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const tU={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 nU(e,t){return{name:Zn,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:tU,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-BQg4KGxO.js`);return r(e,t,n)}}}function rU(){return null}const iU=h(`tool:request-secret`);async function aU(e,t){let n=rU();if(n)return n(e);let r=t.callPanelRpc??await oU();return r?r(e):{stored:!1,reason:`unavailable`}}async function oU(){let{getPanelRpcClient:e}=await import(`./panel-rpc-BJU93e51.js`).then(e=>e.r),t=e();return t?e=>t.call(`secret-request`,e,{timeoutMs:3e5}):null}function sU(e){try{return e.getProvider?.()||void 0}catch(e){iU.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function cU(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 lU(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(`
1244
+ `));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${dH(new TextEncoder().encode(t[o]??``).length)}, exceeds ${dH(lH)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${lH}]`};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} (${dH(lH)} 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 ZH.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function eU(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;ZH.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await XH(e,n,r);return t?(ZH.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 ZH.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const tU={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 nU(e,t){return{name:Zn,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:tU,async execute(n){let{executeMemoryWrite:r}=await import(`./memory-write-execute-D4wz6znH.js`);return r(e,t,n)}}}function rU(){return null}const iU=h(`tool:request-secret`);async function aU(e,t){let n=rU();if(n)return n(e);let r=t.callPanelRpc??await oU();return r?r(e):{stored:!1,reason:`unavailable`}}async function oU(){let{getPanelRpcClient:e}=await import(`./panel-rpc-BJU93e51.js`).then(e=>e.r),t=e();return t?e=>t.call(`secret-request`,e,{timeoutMs:3e5}):null}function sU(e){try{return e.getProvider?.()||void 0}catch(e){iU.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function cU(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 lU(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(`
1245
1245
  `)}function uU(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 dU(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:cU(t.domains),persist:t.persist===!0,requester:e.requester,provider:sU(e)},a;try{a=await aU(i,e)}catch(e){let t=e instanceof Error?e.message:String(e);return iU.error(`secret request failed`,{name:n,error:t}),{content:`The secret prompt failed: ${t}`,isError:!0}}if(!a.stored)return{content:uU(a),isError:!0};let o=fU(a.name,a.maskedValue,e);return iU.info(`secret stored via request_secret`,{name:a.name,persisted:a.persisted}),{content:lU(a,o)}}}}function fU(e,t,n){if(!n.setEnv||!t||!or(e))return!1;try{return n.setEnv(e,t),!0}catch(t){return iU.warn(`could not inject the masked value into the shell env`,{name:e,error:t instanceof Error?t.message:String(t)}),!1}}const pU=/* @__PURE__ */ new Set([`true`,`false`,`:`]);function mU(e){return!e||e.length===0||e.some(e=>e.trim()===`*`)?!1:e.every(e=>pU.has(e.trim()))}function hU(e){let t=e?.toolSurface??`full`;return t===`full`?`full`:t===`output`||mU(e?.allowedCommands)?e?.structuredOutputSchema?`output`:`none`:`full`}const gU=h(`scoop-management-tools`),_U=`cross_cone`;function vU(e){return Ct(e.getScoops(),e.scoop.jid)}function yU(e){let t=/* @__PURE__ */ new Set;for(let n of vU(e))n.jid!==e.scoop.jid&&n.parentJid!==null&&t.add(n.jid);return t}function bU(e){let t=Dt(e.getScoops());return t!==void 0&&t.jid===e.scoop.jid}function xU(e){let t=e.getScoops(),n=yU(e),r=bU(e),i=[];for(let e of t){if(e.parentJid===null)continue;if(n.has(e.jid)){i.push({scoop:e,relation:`own`});continue}if(!r)continue;let a=Ut(t,e);a.kind!==`cycle`&&i.push({scoop:e,relation:a.kind===`root`?`foreign`:`inherited`})}return i}function SU(e){return t=>t.folder===e||t.name===e}function CU(e,t){let n=xU(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 wU(e,t){let n=[],r=[];for(let i of e){let e=CU(i,t);e?n.push(e):r.push(i)}return{resolved:n,unknown:r}}function TU(e,t){return Tt(e.getScoops(),t.scoop)?.folder??`unknown`}function EU(e,t){return t.relation===`inherited`?`inherited (its owning cone is gone)`:`owned by cone "${TU(e,t)}"`}function DU(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 ${EU(r,e)}`).join(`; `)}. Pass ${_U}: true to act on it anyway.`,isError:!0}}function OU(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 kU=[`command`,`read`,`write`,`secret`];function AU(e){return`${xe(e,{maxLen:50})}-scoop`}function jU(e){return e===void 0?{ok:!0}:tn(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${nn.join(`, `)}.`,isError:!0}}function MU(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 NU(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 PU(e,t){let n=xU(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 FU(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 IU(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),gU.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function LU(e){let{kind:t,detail:n,suggested_pattern:r,reason:i}=e;if(!kU.includes(t))return{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${kU.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`?cr(i):``;return{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{},...a?{reason:a}:{}}}}function RU(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(`
1246
1246
  `)}async function zU(e,t){let n=LU(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return gU.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:RU(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function BU(e,t){let{scoop_name:n,prompt:r,cross_cone:i}=e;if(SU(n)(t.scoop))return{content:`Cannot feed yourself.`,isError:!0};let a=CU(n,t);if(!a)return PU([n],t);let o=DU([a],i,`feed "${n}"`,t);if(o)return o;try{await t.onFeedScoop(a.scoop.jid,r),gU.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 (${_U}: 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 VU(e,t){return t.relation===`own`?``:t.relation===`inherited`?` [INHERITED]`:` [FOREIGN: ${TU(e,t)}]`}async function HU(e){let t=new Map(xU(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 FU(n,e.getScoopTabState,r?VU(e,r):``)}).join(`
1247
1247
  `)}`}}function UU({name:e,folder:t,model:n,modelProviderId:r,visiblePaths:i,writablePaths:a,workspaceMode:o,allowedCommands:s,thinkingLevel:c,backgroundAfterSeconds:l,parentJid:u,defaultVisibleRoots:d,canCreateChildren:f}){return{name:e,folder:t,trigger:`@${t}`,requiresTrigger:!0,assistantLabel:t,addedAt:(/* @__PURE__ */ new Date()).toISOString(),config:{...n?{modelId:n}:{},...n&&r?{modelProviderId:r}:{},...WU(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 WU(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function GU(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return gU.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 KU(e,t){let n=t.getTurnSignal?.();if(n?.aborted)return{content:`The parent turn was stopped.`,isError:!0};let{name:r,model:i,prompt:a,visiblePaths:o,writablePaths:s,workspaceMode:c,allowedCommands:l,thinking:u,background_after:d,canCreateChildren:f}=e,p=vt(c);if(!p.ok)return{content:p.error,isError:!0};let m=jU(u);if(!m.ok)return{content:m.content,isError:m.isError};let ee=MU(d);if(!ee.ok)return{content:ee.content,isError:!0};let te=NU(i,t.resolveModelSelection);if(!te.ok)return{content:te.content,isError:te.isError};let ne=AU(r),h=vU(t).find(e=>e.jid!==t.scoop.jid&&e.parentJid!==null&&(e.name===r||e.folder===ne));if(h)return{content:`A scoop named "${h.name}" (${h.folder}) already exists in your scoops. Use feed_scoop to give it another task, or drop_scoop first.`,isError:!0};let re=jt(ne,t.getScoops().map(e=>e.folder));try{let e=UU({name:r,folder:re,model:te.modelId,modelProviderId:te.providerId,visiblePaths:o,writablePaths:s,workspaceMode:p.mode,allowedCommands:l,thinkingLevel:m.level,backgroundAfterSeconds:ee.seconds,parentJid:t.scoop.jid,defaultVisibleRoots:Zt(en(t.scoop)),canCreateChildren:f===!0}),i=await t.onScoopScoop(e);if(n?.aborted)return await t.onDropScoop?.(i.jid),{content:`The parent turn was stopped before the scoop could start.`,isError:!0};if(gU.info(`Scoop created`,{name:r,folder:re}),a&&t.onFeedScoop){let e=await GU(i,a,r,re,t.onFeedScoop);return n?.aborted?(await t.onDropScoop?.(i.jid),{content:`The parent turn was stopped while starting the scoop.`,isError:!0}):e}return{content:`Scoop "${r}" created as "${re}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function qU(e,t){let{scoop_name:n,cross_cone:r}=e;if(SU(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=CU(n,t);if(!i)return PU([n],t);let a=DU([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),gU.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 JU(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function YU(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return JU();let{resolved:i,unknown:a}=wU(n,t);return i.length===0?PU(a,t):DU(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),gU.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 XU(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 ZU(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return JU();let{resolved:i,unknown:a}=wU(n,t);if(i.length===0)return PU(a,t);let o=DU(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);gU.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(...XU(l,c)),{content:u.join(`
1248
1248
  `)}}function QU(e,t){return!Array.isArray(e)||e.length===0?JU():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 $U(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 eW(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=QU(n,r);if(a)return a;let{resolved:o,unknown:s}=wU(n,t);if(o.length===0)return PU(s,t);let c=DU(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 gU.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:$U(f,s,p,r)}}function tW(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 nW(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`?cr(a):``,s={...r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`},...o?{note:o}:{}};try{let e=await t.onSudoResolve(n,s);return e.settled?(gU.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:tW(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 rW(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`?cr(r):``;try{let e=await t.onSudoResolve(n,{decision:`deny`,...i?{note:i}:{}});return e.settled?(gU.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 iW(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(`
1249
- `)}`}}async function aW(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),gU.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 oW(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=>IU(t,e)}}function sW(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:[...kU],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=>zU(t,e)}}function cW(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.`},[_U]:OU(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>BU(t,e)}}function lW(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:()=>HU(e)}}function uW(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:[...nn],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=>KU(t,e)}}function dW(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.`},[_U]:OU(`drop`)},required:[`scoop_name`]},execute:t=>qU(t,e)}}function fW(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"]).`},[_U]:OU(`mute`)},required:[`scoop_names`]},execute:t=>YU(t,e)}}function pW(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"]).`},[_U]:OU(`unmute`)},required:[`scoop_names`]},execute:t=>ZU(t,e)}}function mW(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."},[_U]:OU(`wait on`)},required:[`scoop_names`]},execute:t=>eW(t,e)}}function hW(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=>nW(t,e)}}function gW(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=>rW(t,e)}}function _W(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:()=>iW(e)}}function vW(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=>aW(t,e)}}function yW(e){let t=[],n=wt(e.scoop);return bt(e.scoop)||(t.push(oW(e)),e.onSudoRequest&&t.push(sW(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(uW(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(cW(e)),t.push(lW(e)),e.onDropScoop&&t.push(dW(e)),e.onMuteScoops&&t.push(fW(e)),e.onUnmuteScoops&&t.push(pW(e)),e.onScheduleScoopWait&&t.push(mW(e)),e.onSudoResolve&&(t.push(hW(e)),t.push(gW(e))),e.onListSudoRequests&&t.push(_W(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(vW(e))),t}var bW=/* @__PURE__ */ e({buildScoopTools:()=>TW,getOrCreateConnectionManager:()=>NW});const xW=h(`scoop-context`);function SW(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-BHK4U4e6.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function CW(e){let t=e.scoop.config?.structuredOutputSchema;if(hU(e.scoop.config)!==`output`||!t)return wW(e,[]);let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BrnZ-LJ8.js`);return wW(e,[n(t,e.onStructuredOutput)])}function wW(e,t){let n={scrubToolResult:rt()},r=SW(e);return e.processManager?it(t,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},n,r):it(t,void 0,n,r)}async function TW(e){if(hU(e.scoop.config)!==`full`)return CW(e);let{scoop:t,unit:n,callbacks:r}=e,i=yW({scoop:t,getTurnSignal:e.getTurnSignal,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:de,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:e.onSudoRequest??r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=QH(e.gatedFs,n.workspace.root),o=e.blindReads??null,s=nU(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>VL);return t(e.fs)},...o?{blindPaths:()=>o.outsidePaths()}:{}}),c=[...a,s,LH(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:rt(),...o?{annotateResult:()=>o.takeNote()}:{},fireLick:e=>{let n=globalThis.__slicc_lick_handler;return n?(n(e),!0):(xW.warn(`No lick handler for background bash completion`,{folder:t.folder}),!1)}}),...i,dU({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>se(pV(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BrnZ-LJ8.js`);c.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let l={scrubToolResult:rt()},u=SW(e),d=e.processManager?it(c,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},l,u):it(c,void 0,l,u),f=AW(await EW(e.fs,t),u,l);return[...d,...f]}async function EW(e,t){try{if(t.parentJid!==null)return[];let{listServers:n}=await import(`./store-DU7IkRE0.js`).then(e=>e.r),r=await n(e),i=Object.entries(r);if(i.length===0)return[];let a=i.filter(([,e])=>{let t=e.exposure??`codemode`;return t===`direct`||t===`codemode`||t===`codemode-deferred`||jW(e)});if(a.length===0)return[];let{toAgentTools:o}=await import(`./agent-tools-ENaFAaxk.js`),s=await NW(),c=[];for(let[t,n]of a)try{let{connection:r,transport:i}=await s.connect(t,n);i!==n.transport&&(n.transport=i,import(`./store-DU7IkRE0.js`).then(e=>e.r).then(({setServer:r})=>r(t,n,e)).catch(()=>{}));let a=n.tools??await r.listTools()??[],l=o({serverName:t,tools:a,connection:r,exposure:n.exposure,toolExposure:n.toolExposure,writeOverflow:async(t,n)=>{try{await e.mkdir(`/tmp/mcp`,{recursive:!0}),await e.writeFile(`/tmp/mcp/${t}.txt`,n)}catch{}}});c.push(...l);let u=await DW(t,a,r,n);u&&c.push(u)}catch(e){xW.warn(`failed to load MCP tools for agent`,{server:t,error:e instanceof Error?e.message:String(e)})}return c}catch(e){return xW.debug(`MCP agent tools unavailable`,{error:e instanceof Error?e.message:String(e)}),[]}}async function DW(e,t,n,r){try{let{createCodemodeAgentTool:i}=await import(`./codemode-tool-Bjubrh1X.js`);return i({serverName:e,tools:t,connection:n,exposure:r.exposure,toolExposure:r.toolExposure})}catch(t){return xW.debug(`codemode tool unavailable for server`,{server:e,error:t instanceof Error?t.message:String(t)}),null}}async function OW(e,t,n,r){let i=n.currentGate();if(!i)return null;if(r?.aborted)return{content:[{type:`text`,text:`${e}: not approved (guest-caused turn).`}],details:void 0};let a;try{a=await i.approve(e,t)}catch{a=!1}return!a||r?.aborted?{content:[{type:`text`,text:`${e}: not approved (guest-caused turn).`}],details:void 0}:null}async function kW(e,t){if(t)for(let n=0;n<e.content.length;n++){let r=e.content[n];if(r.type===`text`&&`text`in r&&typeof r.text==`string`)try{let i=await t(r.text);i!==r.text&&(e.content[n]={type:`text`,text:i})}catch{}}}function AW(e,t,n){return e.map(e=>({...e,async execute(r,i,a,o){let s=await OW(e.name,i,t,a);if(s)return s;let c=await e.execute(r,i,a,o);return await kW(c,n.scrubToolResult),c}}))}function jW(e){return e.toolExposure?Object.values(e.toolExposure).some(e=>e===`direct`||e===`codemode`||e===`codemode-deferred`):!1}let MW=null;async function NW(){if(MW)return MW;let{McpConnectionManager:e}=await import(`./connection-manager-Dj5JSkDt.js`);return MW=new e({getAuthHeader:async e=>{try{let{getOAuthAccountInfo:t}=await import(`./account-store-QxWo48Y1.js`).then(e=>e.t),n=t(`mcp:${e}`);return n?`Bearer ${n.token}`:null}catch{return null}}}),MW}const PW=h(`scoop-context`);async function FW(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();PW.info(`Filesystem ready`,{folder:t.folder}),await FV(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,blindReads:l,sudoBroker:u,skills:d}=await cH({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,...e.escalations?{escalations:e.escalations}:{},processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),mcpConnectionManager:e.mcpConnectionManager});e.onShellReady(o);let f=await TW({getTurnGuestGates:e.getTurnGuestGates,getTurnSignal:e.getTurnSignal,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,blindReads:l,...i.onSudoRequest&&u?{onSudoRequest:e=>u.requestApproval(e)}:{},processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:p,globalMemory:m}=await uV(r,n,()=>i.getGlobalMemory());if(!fV(t))return PW.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let ee=mV(t,n),te=yV(t,n,m,p,d),ne=await e.sessions.restore(),{streamWithSessionId:h,compactFn:re,getCompactionApiKey:ie}=await LV(ee,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>fV(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let ae=Mt(t);return{kind:`ready`,agent:MV({model:ee,tools:f,systemPrompt:te,messages:ne,thinkingLevel:xV(SV()??ae.level,ee),getApiKey:()=>fV(t)??void 0,transformContext:re,streamFn:h,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:re,getCompactionApiKey:ie,effortOverride:ae.effortOverride,toolCount:f.length}}const IW=h(`scoop-context`);var LW=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 IW.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=yL(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=Qe(n);return IW.info(`Restored conversation from the canonical work-unit record`,{folder:this.deps.folder,messageCount:r.length,droppedOrphans:n.length-r.length}),r}persistNow(e){this.flush(e)}flush(e){return this.flushChecked(e).then(()=>void 0)}flushChecked(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return Promise.resolve(!0);let n=this.deps.canonical;return n?(this.createdAt||=Date.now(),n.store.syncAgentMessages(n.identity,t,{createdAt:this.createdAt}).then(e=>e!==null,e=>(IW.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),!1))):Promise.resolve(!0)}async clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.createdAt=0;let e=this.deps.canonical;e&&await e.store.delete(e.identity.key);try{await this.deps.store?.delete(this.deps.sessionId)}catch(e){IW.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 RW(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 zW(e,t,n){t&&e&&(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function BW(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const VW=h(`scoop-context`);var HW=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;VW.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)&&(VW.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:ZB(r)}),!!(t<3&&(await QB(UW(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return XB(e)?(VW.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 Gi(e)?(VW.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Ji(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(!ZB(e)||t>=3)return!1;let r=UW(t);return VW.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await QB(r,n)&&!this.deps.isDisposed()}fail(e,t){VB(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function UW(e){return Mr({attempt:e-1,baseMs:1e3})}function WW(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){VW.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 GW=h(`scoop-context`);var KW=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;escalations={asked:0,allowed:0,denied:0};promptAbortController=null;forceReleaseTimer=null;turnEpoch=0;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;mcpConnectionManager;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;turnJournal;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>(this.callbacks.onToolStart?.(e,t,n),this.makeToolCallDurable(e,t,n)),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:e=>this.checkpoint(e),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s,c,l,u){this.scoop=e,this.unit=Yt(e),this.owner={kind:kt(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.capabilityBroker=l??null,this.turnJournal=u??null,this.sessions=new LW({store:r??null,canonical:c?{store:c,identity:yn(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 kV({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new aV({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new sV({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new OV({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 HW({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 eH(this.unit,this.scoop,St(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Kt(this.callbacks.getScoops(),this.scoop)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}resetStructuredOutput(){this.structuredOutputCaptured=!1,this.structuredOutputValue=void 0}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);if(!this.mcpConnectionManager){let{getOrCreateConnectionManager:e}=await Promise.resolve().then(()=>bW);this.mcpConnectionManager=await e()}let e=await FW({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,escalations:this.escalations,capabilityBroker:this.capabilityBroker,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getTurnGuestGates:()=>this.turnGuestGates,getTurnSignal:()=>this.promptAbortController?.signal,getLickTarget:()=>this.ownLickTarget(),getTmpDir:()=>this.ownTmpDir(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputCaptured||=(this.structuredOutputValue=e,!0)},mcpConnectionManager:this.mcpConnectionManager,spawnBashJob:e=>this.bashJobs.spawn(e),onBeforeCompaction:(e,t)=>this.maybeSnapshotBeforeCompaction(e,t)});if(e.kind===`abandoned`)return;if(e.kind===`deferred`){this.setStatus(`ready`);return}this.compactFn=e.compactFn,this.getCompactionApiKey=e.getCompactionApiKey,this.activeEffortOverride=e.effortOverride,this.agent=e.agent,this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),GW.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);GW.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(gV(this.scoop)),!1)}cleanupPromptState(e,t,n,r,i){if(i!==void 0&&i!==this.turnEpoch){this.currentTurnProcess!==t&&zW(this.processManager,t,{lastError:n,aborted:!0});return}this.runBounds.disarm();let a=this.runBounds.takeExceededNote();a!==null&&this.callbacks.onError(`agent run terminated: ${a}`),(n||r.aborted)&&this.sessions.persistNow(),this.disarmForceRelease(),this.isProcessing=!1,this.turnJournal?.end(this.scoop.jid),!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),zW(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(WW(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder})){for(let e of r)this.addTurnGuestGate(e);return}this.turnGuestGates=[...r];let i=this.agent;await this.runTurn(e,0,()=>i.prompt(e,t))}async resumeTurn(e,t=[]){if(!await this.ensureAgentReady()||this.isBusy)return;this.turnGuestGates=[...t];let n=this.agent;await this.runTurn(`(resumed after reload)`,e,()=>{let e=n.state.messages,t=e[e.length-1];return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)&&(n.state.messages=e.slice(0,-1)),n.continue()})}settleInterruptedToolCalls(e){let t=this.agent;if(!t||e.length===0)return;let n=Date.now(),r=e.map(e=>({role:`toolResult`,toolCallId:e.toolCallId,toolName:e.toolName,content:[{type:`text`,text:e.text}],isError:!0,timestamp:n}));t.state.messages=[...t.state.messages,...r],this.sessions.persistNow();for(let t of e)this.callbacks.onToolEnd?.(t.toolName,t.text,!0,t.toolCallId)}reportError(e){this.callbacks.onError(e)}hasAgent(){return this.agent!==null}async runTurn(e,t,n){this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal,a=++this.turnEpoch;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let o=RW(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:r});this.currentTurnProcess=o,this.runBounds.arm(),this.turnJournal?.begin(this.scoop.jid,this.scoop.folder,t,this.turnGuestGates);let s=null;try{if(s=await this.turnRunner.run(n,i),s&&!this.disposed&&!i.aborted){this.turnRunner.reportExhausted(s);return}a===this.turnEpoch&&!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,o,s,i,a)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||(this.turnGuestGates.push(e),this.turnJournal?.setGuestGates(this.scoop.jid,this.turnGuestGates))}stop(){BW(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.armForceRelease()}disarmForceRelease(){this.forceReleaseTimer!==null&&(clearTimeout(this.forceReleaseTimer),this.forceReleaseTimer=null)}armForceRelease(){this.disarmForceRelease();let e=this.turnEpoch,t=this.currentTurnProcess;this.forceReleaseTimer=setTimeout(()=>{this.forceReleaseTimer=null,!this.disposed&&this.turnEpoch===e&&this.isProcessing&&(t&&this.processManager&&(this.processManager.signal(t.pid,`SIGKILL`),this.processManager.exit(t.pid,null)),this.bashJobs.reapAll(),this.shell?.cancelActiveCommand(),this.agent?.abort?.(),this.turnEpoch===e&&this.isProcessing&&(this.isProcessing=!1,this.status===`processing`&&this.setStatus(`ready`)))},2e3)}clearMessages(){if(this.agent){let e=We(this.agent.state.messages);this.agent.state.messages=e?[e]:[]}}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0);try{await this.reloadSkills()}catch(e){GW.warn(`clearSession: could not rebuild system prompt from memory`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})}}idleCompactionEnabled(){return Tn(this.scoop)?!0:this.unit.parentId===null&&Ae(`compact-on-idle`)}armIdleCompaction(){if(!this.idleCompactionEnabled()){this.idleCompaction?.disarm();return}if(this.idleCompaction){this.idleCompaction.arm();return}this.idleCompactionLoading??=this.loadIdleCompaction(),this.idleCompactionLoading.then(e=>{!this.disposed&&this.status===`ready`&&e.arm()})}async loadIdleCompaction(){let[{IdleCompaction:e},{readIdleCompactionSettings:t}]=await Promise.all([import(`./idle-compaction-CkyuBvDI.js`),import(`./idle-compaction-settings-1yyApSsQ.js`)]),n=new e({isEnabled:()=>this.idleCompactionEnabled(),getSettings:t,getAgent:()=>this.agent,isDisposed:()=>this.disposed,isBusy:()=>this.isBusy,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),estimateTokens:$e,onCompacted:()=>this.sessions.persistNow(),onDiscarded:e=>this.callbacks.onCompactionStateChange?.(`cancelled`,{trigger:`idle`,roundId:e}),folder:this.scoop.folder});return this.idleCompaction=n,n}async maybeSnapshotBeforeCompaction(e,t){if(this.unit.parentId===null||Ae(`memory-v2`))return this.snapshotBeforeCompaction(e,t)}async snapshotBeforeCompaction(e,t){if(!this.fs||this.disposed)return;let n=this.sessionGeneration,{scoopSessionsDir:r,snapshotLiveSession:i}=await import(`./live-session-snapshot-BedjttIR.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-CNk-iYCa.js`).then(n=>n.scheduleLiveDeltaCuration({vfs:e,cone:t})).catch(e=>{GW.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-BedjttIR.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){GW.warn(`Live snapshot settle failed (archive stays live)`,{folder:this.scoop.folder,discard:e,error:t instanceof Error?t.message:String(t)})}}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getEscalations(){return{...this.escalations}}getContextFill(){return hV(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=wV(this.agent,this.scoop))}async reloadSkills(){this.agent&&await EV(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){if(!this.agent)return GW.info(`Thinking level stored for a deferred agent`,{requested:e}),`off`;if(SV())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=TV(this.agent,e);return GW.info(`Thinking level applied`,{requested:e,resolved:n,model:this.agent.state.model?.id,provider:this.agent.state.model?.provider,reasoning:this.agent.state.model?.reasoning===!0}),n}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}streamThinking(){if(!this.agent)return null;let e=this.agent.state.thinkingLevel;return{level:e,...e!==`off`&&this.activeEffortOverride===`max`?{effortOverride:`max`}:{}}}flushConversation(){return this.sessions.flushChecked()}dispose(){this.sessions.persistNow(),this.turnJournal?.end(this.scoop.jid),this.disposed=!0,this.disarmForceRelease(),this.idleCompaction?.cancel(),this.runBounds.disarm(),BW(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 tV(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`&&GW.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||$B(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const Q=h(`scoop-lifecycle-manager`);var qW=class{deps;units=/* @__PURE__ */ new Map;tabCreates=/* @__PURE__ */ new Map;gelatiereModelSync=Promise.resolve();constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new RB(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}displayJidFor(e){let t=this.deps.approverFor(e)?.jid;return t&&t!==e?t:void 0}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??St(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Tt(t.values(),e)??St(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Q.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof gn))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}createTab(e){let t=this.tabCreates.get(e);if(t!=null)return t;let n;return n=this.openTab(e).finally(()=>{this.tabCreates.get(e)===n&&this.tabCreates.delete(e)}),this.tabCreates.set(e,n),n}async openTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Q.debug(`Context already exists`,{jid:e});return}}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Yt(t).policy.filesystem;if(a.kind===`restricted`){let e=vt(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new gn(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:_t(a.mode)});a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new KW(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0,this.deps.getTurnJournal?.()??void 0);if(n.attachContext(l,i),await l.init(),this.units.get(e)!==n||n.context!==l)return;n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{Q.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),Q.info(`Scoop context created`,{jid:e,contextId:i})}async reinitAfterPromote(e){let t=this.units.get(e);if(t?.context){t.disposeContext();try{await this.createTab(e)}catch(n){let r=n instanceof Error?n.message:String(n);Q.warn(`Failed to re-init promoted unit; next prompt will retry`,{jid:e,error:r}),t.disposeContext(),this.markTabError(e,r)}}}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.deps.getScoops().get(e);if(o&&Tn(o)&&(await this.syncGelatiereModel(),!zt(o)))throw Error(`The gelatiere cannot run until the leading cone has a model`);let s=this.getContext(e);s||=(await this.createTab(e),this.getContext(e));let c=this.units.get(e);if(c?.tab?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}s=this.getContext(e)}if(!s||!c){Q.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),c.tab&&c.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await s.prompt(t,i,a)}async resumeTurn(e,t,n){let r=this.getContext(e),i=this.units.get(e);r&&i&&!r.isBusy&&(this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),i.tab&&i.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),await r.resumeTurn(t,n))}async register(e){let t=this.deps.getScoops(),n=Dt(t.values())?.jid;if(Vt(e),this.inheritModel(e),e.parentJid!==null){let n=[];for(let r of t.values())r.jid!==e.jid&&n.push(r.folder);let r=jt(e.folder,n);r!==e.folder&&(Q.warn(`Scoop folder already taken — registering under a free variant`,{jid:e.jid,requested:e.folder,folder:r}),e.folder=r,e.trigger=`@${r}`,e.assistantLabel=r)}t.set(e.jid,e);try{await this.deps.db.saveScoop(e)}catch(n){throw t.delete(e.jid),n}this.deps.messageRouter.ensureQueue(e.jid),Q.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&fB(`spawn`,e.folder)}catch(n){Q.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){Q.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{Q.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}Dt(t.values())?.jid!==n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the new leading cone after registration`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}inheritModel(e){if(Tn(e)){let t=Dt(this.deps.getScoops().values());At(e,t?zt(t):void 0);return}if(Ot(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?zt(t):void 0)??tB();n&&At(e,n)}async unregister(e){let t=this.deps.getScoops(),n=Dt(t.values())?.jid===e;for(let n of Wt(t.values(),e))await this.unregister(n.jid);let r=t.get(e);if(r&&r.parentJid===null&&St(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let i=this.deps.getLickManager();if(r&&i){let{webhooks:e,cronTasks:t}=await i.getLicksForScoopFromDb(r.name,r.folder),n=this.deps.buildActiveLicksError(r.folder,e,t);if(n)throw n}this.deps.costTracker.snapshot(e);let a=globalThis.__slicc_wsSubscribers;a&&a.dropForScoop(e).catch(t=>{Q.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),await Promise.all([r?this.deps.getConversationStore()?.delete(vn(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(Tn(n))return await this.syncGelatiereModel(),!1;let r=Dt(this.deps.getScoops().values())?.jid===e,i=n.model;At(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return At(n,i),this.getContext(e)?.updateModel(),Q.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return r&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to synchronize gelatiere after leading model change`,{jid:e,error:t instanceof Error?t.message:String(t)})}),!0}syncGelatiereModel(){let e=this.gelatiereModelSync.then(()=>this.applyGelatiereModel());return this.gelatiereModelSync=e.then(()=>void 0,()=>void 0),e}async applyGelatiereModel(){let e=this.deps.getScoops(),t=[...e.values()].find(Tn);if(!t)return!1;let n=Dt(e.values()),r=n?zt(n):void 0,i=zt(t),a=r?i?.provider===r.provider&&i.id===r.id:Ot(t)===void 0;if(!a){let e=t.model?{...t.model}:void 0,i=t.config?{...t.config}:void 0;At(t,r);try{await this.deps.db.saveScoop(t)}catch(n){throw t.model=e,t.config=i,n}Q.info(`Gelatiere model synchronized with leading cone`,{jid:t.jid,leadingJid:n?.jid,model:r?`${r.provider}:${r.id}`:void 0})}return r&&this.getContext(t.jid)?.updateModel(),!a}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();Q.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Lt(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Q.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}streamThinking(e){return this.getContext(e)?.streamThinking()??null}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Yt(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:n=>this.handleScoopTurnError(e,t,n),onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Et(n,t),await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(t,n)=>i.scheduleScoopWait(t,n,e):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:en(t).memoryPath}):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),approveGuestToolCall:e=>i.approveDirectedOrUser(e),onSudoResolve:o.canResolveApprovals?(n,r)=>i.resolveActionableLick(n,r,bt(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(bt(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleScoopTurnError(e,t,n){this.deps.getScoops().has(e)&&(this.deps.completionService.recordFailure(e,n),this.units.get(e)?.transition(`error`,{error:n}),fB(`error`,t.folder,n),this.deps.callbacks.onError(e,n),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,n),this.dispatch(e,`onStatusChange`,`error`))}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(Q.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),fB(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Yt(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(i)try{this.deps.callbacks.onError(i.jid,`[@${r.assistantLabel} FAILED]: ${t}`,{endTurn:!1})}catch(e){Q.error(`Failed to record fatal error for scoop owner`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}}};const $=h(`scoop-message-router`);var JW=class{deps;messageQueues=/* @__PURE__ */ new Map;lastAgentTimestamp=/* @__PURE__ */ new Map;pollInterval=null;debounceStates=/* @__PURE__ */ new Map;processing=/* @__PURE__ */ new Map;busyDeferrals=/* @__PURE__ */ new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if($.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){$.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);fB(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),$.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){$.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){$.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if($.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){$.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{$.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`||t.channel===`scoop-notify`||t.channel===`scoop-idle`||t.channel===`scoop-wait`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);$.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;n.reported||r<3e5||(n.reported=!0,$.warn(`Busy lick queue may be starved`,{jid:e,error:`Lick queue remained deferred while scoop was busy for 300s`}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r}))}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){$.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){$.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){$.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if($.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){$.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){$.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=ZN($N(XN(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=PA(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(`
1250
- `);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>FA(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=ZN($N(XN(a),o));this.lastAgentTimestamp.set(e,f),await this.deps.db.setState(`lastAgentTs_${e}`,f);let p=s.some(e=>e.steer),m=/* @__PURE__ */ new Set,ee=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);m.has(t)||(m.add(t),ee.push(e.guestGate))}await this.deps.sendPrompt(e,l,d.senderId,d.senderName,u,{steer:p,...ee.length>0?{guestGates:ee}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);$.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),await this.deps.settleFoldedCost?.(e),t&&await t.clearSession(n).catch(t=>{$.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{$.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),$.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{$.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{$.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),$.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const YW=h(`orchestrator`),XW={decision:`deny`};var ZW=class{scoops=/* @__PURE__ */ new Map;workUnits=new _N(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new yz({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 FB({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 NB({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts(),mergeFoldedIntoFrozen:(e,t)=>this.mergeFoldedCostIntoFrozen(e,t)});completionService=new yB({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 oB({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=>JN(e),saveMessage:e=>KN(e)});lickRegistry=new Zz({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 JW({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),recordSentAttachments:(e,t)=>this.recordSentAttachments(e,t),onError:(e,t,n)=>this.callbacks.onError(e,t,n),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),settleFoldedCost:e=>this.costTracker.settleFolded(e),db:{saveMessage:e=>KN(e),deleteMessage:e=>qN(e),clearMessagesForScoop:e=>GN(e),clearAllMessages:()=>WN(),getMessagesSince:(e,t,n)=>eP(e,t,n),setState:(e,t)=>oP(e,t)},isExternalLickChannel:XM});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new qW({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=>VN(e),deleteScoop:e=>UN(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Kz(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 nB(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new uF({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 nF(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new eB(e,t),await this.modelPolicyFile.init(),n(),HN()),n,{stagePrefix:`orchestrator-init`})}setOnConversationsReady(e){this.onConversationsReady=e}async openSharedFilesystem(e,t){let n=await nB(e=>hn.create({dbName:`slicc-fs`,onRepairProgress:e}),e);this.sharedFs=n,this.sessionStore=new RA,this.conversationStore=new jL;let{TurnJournal:r}=await import(`./turn-journal-B8tRUgnH.js`);this.turnJournal=new r,this.interruptedTurns=await this.turnJournal.readAll();let i=new mn;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 sP();let{sharedFs:n,fsWatcher:i}=await this.openSharedFilesystem(e,t),a=await this.initPolicyLayerAndLoadRecords(n,i,e),o=Object.values(a).find(e=>It(e))?.jid;for(let e of Object.values(a)){await this.backfillParent(e,o),Vt(e),this.migrateScoopConfig(e,Object.values(a)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await aP(`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 iB({onTaskRun:async(e,t)=>{YW.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(),YW.info(`Orchestrator initialized`,{scoopCount:this.scoops.size}),e?.(`conversations-ready`),await this.onConversationsReady?.(),await this.restoreScoopContexts(e),En(e=>this.getSessionCostsForCommand(e)),Dn(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>BA);return e()}),this.unregisterExportService=r(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}whenBootRestoresSettled(){return this.bootRestoreTail}async restoreScoopContexts(e){let t=[],n=[];for(let e of this.scoops.values())e.parentJid===null?t.push(e):n.push(e);await lB(t,4,t=>this.restoreScoopContext(t,e));let r=lB(n,4,t=>this.restoreScoopContext(t,e)).catch(e=>{YW.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);YW.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 RM;try{await mL({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){YW.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(yn(r),t).catch(t=>{YW.warn(`Failed to record sent attachments`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=It(e)?null:t??null;try{await VN(e)}catch(t){YW.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!Ot(e)&&!Tn(e));if(e.length>0){let t=tB(),n=[...e].sort((e,t)=>Number(e.parentJid!==null)-Number(t.parentJid!==null));for(let e of n){let n=e.parentJid?this.scoops.get(e.parentJid):void 0,r=(n?zt(n):void 0)??t;if(r){At(e,r);try{await VN(e)}catch(t){YW.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){YW.warn(`Failed to repair gelatiere model on boot; will retry next boot`,{error:e instanceof Error?e.message:String(e)})}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Xt.root}/`,r=Zt($t(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:(/* @__PURE__ */ new Date()).toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}notifyScoopOutcome(e,t){return this.completionService.notifyWithOutcome(e,t)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-BxWIFFqA.js`);return t(e,{scoops:this.scoops,ownerRootOf:e=>this.ownerRootOrDefault(e),enqueue:(e,t,n)=>this.approvalRouter.enqueueSudoRequest(e,t,n),getSharedFs:()=>this.sharedFs,workspaceFor:en,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(YW.warn(`Guest approval before SudoManager init — failing closed`),XW)}})}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 VN(e),e.parentJid===null&&await this.lifecycle.syncGelatiereModel().catch(t=>{YW.warn(`Failed to follow a persisted root leadership change`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}reinitLiveUnit(e){return this.lifecycle.reinitAfterPromote(e)}async rekeyConversation(e,t){await this.conversationStore?.rekey(e,t)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return St(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}capableApproverOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return Ht(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Tt(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){await this.bootRestoreTail,this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await hn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await fz(this.sharedFs).catch(e=>{YW.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new uF({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 nF(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new eB(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),YW.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 JN(e)}async recoverInterruptedWork(e){await this.bootRestoreTail;let t=this.interruptedTurns;this.interruptedTurns=null;let n=this.turnJournal;if(!t||t.length===0||!n)return[];let{recoverInterruptedWork:r}=await import(`./interrupted-work-recovery-BolgIHkM.js`);return r(t,{journal:n,getScoop:e=>this.scoops.get(e),getUnit:e=>this.lifecycle.getContext(e),resumeTurn:(e,t,n)=>this.lifecycle.resumeTurn(e,t,n),emitLick:e})}sendPrompt(e,t,n,r,i=[],a){return this.completionService.allowCompletion(e),this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}syncGelatiereModel(){return this.lifecycle.syncGelatiereModel()}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}streamThinking(e){return this.lifecycle.streamThinking(e)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){for(let t of xt(this.scoops.values(),e))this.completionService.cancelScheduledWaits(t),this.completionService.suppressCompletionUntilNextPrompt(t),this.lifecycle.getContext(t)?.stop(),this.clearQueuedMessages(t).catch(e=>{YW.warn(`Failed to clear queued messages on stop`,{jid:t,error:e instanceof Error?e.message:String(e)})})}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async mergeFoldedCostIntoFrozen(e,t){let n=this.scoops.get(e);if(!n||!this.sharedFs)return!1;try{let{mergeFoldedCostIntoLatestFrozen:e}=await import(`./merge-folded-cost-into-frozen-DA0swiNk.js`);return await e(this.sharedFs,n,t)}catch(t){return YW.warn(`Failed to merge folded agent spend into frozen session`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await Promise.resolve().then(()=>zF),r=await n(this.sharedFs);return[...t,...r.map(On)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async flushConversations(){let e=[...this.lifecycle.getContexts().values()];return(await Promise.allSettled(e.map(e=>e.flushConversation()))).every(e=>e.status===`fulfilled`&&e.value===!0)}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&YW.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,YW.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new DL(this.conversationStore):null,t=this.sharedFs;return new DI({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:XI(),snapshotStore:{read:e=>HI(t,e),write:(e,n,r)=>zI(t,e,n,r),discardIfUnindexed:e=>VI(t,e)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.256.0`})}};const QW=h(`workflow-run-manager`),$W=`/shared/workflow-runs`,eG=1e3;function tG(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function nG(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){QW.warn(`observeRun handler threw`,e)}},i=(e,n)=>sG(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=tG(e,a.parentJid),d={id:c,name:a.name,source:a.source,origin:u.origin,lickTarget:u.lickTarget,status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:(/* @__PURE__ */ new Date()).toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(c,d),aG(t,n);let f=i(a.ctx,c),p=oG(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=>QW.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=`${$W}/${n}.json`,u=(/* @__PURE__ */ new Date()).toISOString();try{await e.sharedFs.mkdir($W,{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);QW.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`?iG(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=/* @__PURE__ */ new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){QW.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function rG(e){let t=nG(e);return globalThis[d]=t,QW.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function iG(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function aG(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 oG(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 sG(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?cG(n,t,a?.args??[],r):e===`agent`?lG(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function cG(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>eG&&i.logs.splice(0,i.logs.length-eG),r()}return{stdout:``,stderr:``,exitCode:0}}async function lG(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 uG=/* @__PURE__ */ new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function dG(e,t,n){let r=fG(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=hG(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function fG(e){let t=/* @__PURE__ */ new Map;return pG(t,e.discoveryOrigin),pG(t,e.discoveryUrl),[...t.values()]}function pG(e,t){if(t){mG(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);mG(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!uG.has(e)))mG(e,t,1,`substring`)}catch{}}}function mG(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 hG(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=_G(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)gG(a,e)&&(r+=e.weight*o)}return r}function gG(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 _G(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}function vG(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 yG=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=SG(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:xG,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===xG)throw new g(`ENOTDIR`,`not a directory`,e);let n=CG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);return bG.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new g(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=SG(e);if(t.length===1&&t[0]===xG)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new g(`EISDIR`,`is a directory`,e);let n=CG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!bG.includes(r))throw new g(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new g(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=SG(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===xG)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=CG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=CG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!bG.includes(r))throw new g(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new g(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new g(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new g(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new g(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderTable(){let e={stats:this.pm.stats(),processes:this.pm.list().map(e=>({pid:e.pid,ppid:e.ppid,kind:e.kind,state:OG(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:kG(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
1249
+ `)}`}}async function aW(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),gU.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 oW(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=>IU(t,e)}}function sW(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:[...kU],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=>zU(t,e)}}function cW(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.`},[_U]:OU(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>BU(t,e)}}function lW(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:()=>HU(e)}}function uW(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:[...nn],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=>KU(t,e)}}function dW(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.`},[_U]:OU(`drop`)},required:[`scoop_name`]},execute:t=>qU(t,e)}}function fW(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"]).`},[_U]:OU(`mute`)},required:[`scoop_names`]},execute:t=>YU(t,e)}}function pW(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"]).`},[_U]:OU(`unmute`)},required:[`scoop_names`]},execute:t=>ZU(t,e)}}function mW(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."},[_U]:OU(`wait on`)},required:[`scoop_names`]},execute:t=>eW(t,e)}}function hW(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=>nW(t,e)}}function gW(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=>rW(t,e)}}function _W(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:()=>iW(e)}}function vW(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=>aW(t,e)}}function yW(e){let t=[],n=wt(e.scoop);return bt(e.scoop)||(t.push(oW(e)),e.onSudoRequest&&t.push(sW(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(uW(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(cW(e)),t.push(lW(e)),e.onDropScoop&&t.push(dW(e)),e.onMuteScoops&&t.push(fW(e)),e.onUnmuteScoops&&t.push(pW(e)),e.onScheduleScoopWait&&t.push(mW(e)),e.onSudoResolve&&(t.push(hW(e)),t.push(gW(e))),e.onListSudoRequests&&t.push(_W(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(vW(e))),t}var bW=/* @__PURE__ */ e({buildScoopTools:()=>TW,getOrCreateConnectionManager:()=>NW});const xW=h(`scoop-context`);function SW(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-BHK4U4e6.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function CW(e){let t=e.scoop.config?.structuredOutputSchema;if(hU(e.scoop.config)!==`output`||!t)return wW(e,[]);let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BrnZ-LJ8.js`);return wW(e,[n(t,e.onStructuredOutput)])}function wW(e,t){let n={scrubToolResult:rt()},r=SW(e);return e.processManager?it(t,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},n,r):it(t,void 0,n,r)}async function TW(e){if(hU(e.scoop.config)!==`full`)return CW(e);let{scoop:t,unit:n,callbacks:r}=e,i=yW({scoop:t,getTurnSignal:e.getTurnSignal,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:de,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:e.onSudoRequest??r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=QH(e.gatedFs,n.workspace.root),o=e.blindReads??null,s=nU(e.memoryFs,{readSessionCount:async()=>{let{readSessionCount:t}=await Promise.resolve().then(()=>VL);return t(e.fs)},...o?{blindPaths:()=>o.outsidePaths()}:{}}),c=[...a,s,LH(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:rt(),...o?{annotateResult:()=>o.takeNote()}:{},fireLick:e=>{let n=globalThis.__slicc_lick_handler;return n?(n(e),!0):(xW.warn(`No lick handler for background bash completion`,{folder:t.folder}),!1)}}),...i,dU({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>se(pV(t).provider)})];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BrnZ-LJ8.js`);c.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let l={scrubToolResult:rt()},u=SW(e),d=e.processManager?it(c,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},l,u):it(c,void 0,l,u),f=AW(await EW(e.fs,t),u,l);return[...d,...f]}async function EW(e,t){try{if(t.parentJid!==null)return[];let{listServers:n}=await import(`./store-DU7IkRE0.js`).then(e=>e.r),r=await n(e),i=Object.entries(r);if(i.length===0)return[];let a=i.filter(([,e])=>{let t=e.exposure??`codemode`;return t===`direct`||t===`codemode`||t===`codemode-deferred`||jW(e)});if(a.length===0)return[];let{toAgentTools:o}=await import(`./agent-tools-ENaFAaxk.js`),s=await NW(),c=[];for(let[t,n]of a)try{let{connection:r,transport:i}=await s.connect(t,n);i!==n.transport&&(n.transport=i,import(`./store-DU7IkRE0.js`).then(e=>e.r).then(({setServer:r})=>r(t,n,e)).catch(()=>{}));let a=n.tools??await r.listTools()??[],l=o({serverName:t,tools:a,connection:r,exposure:n.exposure,toolExposure:n.toolExposure,writeOverflow:async(t,n)=>{try{await e.mkdir(`/tmp/mcp`,{recursive:!0}),await e.writeFile(`/tmp/mcp/${t}.txt`,n)}catch{}}});c.push(...l);let u=await DW(t,a,r,n);u&&c.push(u)}catch(e){xW.warn(`failed to load MCP tools for agent`,{server:t,error:e instanceof Error?e.message:String(e)})}return c}catch(e){return xW.debug(`MCP agent tools unavailable`,{error:e instanceof Error?e.message:String(e)}),[]}}async function DW(e,t,n,r){try{let{createCodemodeAgentTool:i}=await import(`./codemode-tool-Bjubrh1X.js`);return i({serverName:e,tools:t,connection:n,exposure:r.exposure,toolExposure:r.toolExposure})}catch(t){return xW.debug(`codemode tool unavailable for server`,{server:e,error:t instanceof Error?t.message:String(t)}),null}}async function OW(e,t,n,r){let i=n.currentGate();if(!i)return null;if(r?.aborted)return{content:[{type:`text`,text:`${e}: not approved (guest-caused turn).`}],details:void 0};let a;try{a=await i.approve(e,t)}catch{a=!1}return!a||r?.aborted?{content:[{type:`text`,text:`${e}: not approved (guest-caused turn).`}],details:void 0}:null}async function kW(e,t){if(t)for(let n=0;n<e.content.length;n++){let r=e.content[n];if(r.type===`text`&&`text`in r&&typeof r.text==`string`)try{let i=await t(r.text);i!==r.text&&(e.content[n]={type:`text`,text:i})}catch{}}}function AW(e,t,n){return e.map(e=>({...e,async execute(r,i,a,o){let s=await OW(e.name,i,t,a);if(s)return s;let c=await e.execute(r,i,a,o);return await kW(c,n.scrubToolResult),c}}))}function jW(e){return e.toolExposure?Object.values(e.toolExposure).some(e=>e===`direct`||e===`codemode`||e===`codemode-deferred`):!1}let MW=null;async function NW(){if(MW)return MW;let{McpConnectionManager:e}=await import(`./connection-manager-Dj5JSkDt.js`);return MW=new e({getAuthHeader:async e=>{try{let{getOAuthAccountInfo:t}=await import(`./account-store-CYXcTNmf.js`).then(e=>e.t),n=t(`mcp:${e}`);return n?`Bearer ${n.token}`:null}catch{return null}}}),MW}const PW=h(`scoop-context`);async function FW(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();PW.info(`Filesystem ready`,{folder:t.folder}),await FV(r,t,n,a);let{shell:o,gatedFs:s,memoryFs:c,blindReads:l,sudoBroker:u,skills:d}=await cH({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,capabilityBroker:e.capabilityBroker,onSudoRequest:i.onSudoRequest,...e.escalations?{escalations:e.escalations}:{},processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),mcpConnectionManager:e.mcpConnectionManager});e.onShellReady(o);let f=await TW({getTurnGuestGates:e.getTurnGuestGates,getTurnSignal:e.getTurnSignal,scoop:t,unit:n,callbacks:i,shell:o,fs:r,gatedFs:s,memoryFs:c,blindReads:l,...i.onSudoRequest&&u?{onSudoRequest:e=>u.requestApproval(e)}:{},processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:p,globalMemory:m}=await uV(r,n,()=>i.getGlobalMemory());if(!fV(t))return PW.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let ee=mV(t,n),te=yV(t,n,m,p,d),ne=await e.sessions.restore(),{streamWithSessionId:h,compactFn:re,getCompactionApiKey:ie}=await LV(ee,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>fV(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:(e,t)=>i.onCompactionStateChange?.(e,t),onBeforeCompaction:e.onBeforeCompaction});if(e.isDisposed())return{kind:`abandoned`};let ae=Mt(t);return{kind:`ready`,agent:MV({model:ee,tools:f,systemPrompt:te,messages:ne,thinkingLevel:xV(SV()??ae.level,ee),getApiKey:()=>fV(t)??void 0,transformContext:re,streamFn:h,onContextCompacted:()=>e.sessions.persistNow(),captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:re,getCompactionApiKey:ie,effortOverride:ae.effortOverride,toolCount:f.length}}const IW=h(`scoop-context`);var LW=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 IW.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=yL(t);if(t&&(this.createdAt=t.createdAt),n.length===0)return[];let r=Qe(n);return IW.info(`Restored conversation from the canonical work-unit record`,{folder:this.deps.folder,messageCount:r.length,droppedOrphans:n.length-r.length}),r}persistNow(e){this.flush(e)}flush(e){return this.flushChecked(e).then(()=>void 0)}flushChecked(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return Promise.resolve(!0);let n=this.deps.canonical;return n?(this.createdAt||=Date.now(),n.store.syncAgentMessages(n.identity,t,{createdAt:this.createdAt}).then(e=>e!==null,e=>(IW.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),!1))):Promise.resolve(!0)}async clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.createdAt=0;let e=this.deps.canonical;e&&await e.store.delete(e.identity.key);try{await this.deps.store?.delete(this.deps.sessionId)}catch(e){IW.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 RW(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 zW(e,t,n){t&&e&&(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function BW(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const VW=h(`scoop-context`);var HW=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;VW.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)&&(VW.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:ZB(r)}),!!(t<3&&(await QB(UW(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return XB(e)?(VW.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 Gi(e)?(VW.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Ji(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(!ZB(e)||t>=3)return!1;let r=UW(t);return VW.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await QB(r,n)&&!this.deps.isDisposed()}fail(e,t){VB(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function UW(e){return Mr({attempt:e-1,baseMs:1e3})}function WW(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){VW.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 GW=h(`scoop-context`);var KW=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;escalations={asked:0,allowed:0,denied:0};promptAbortController=null;forceReleaseTimer=null;turnEpoch=0;processManager=null;currentTurnProcess=null;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;capabilityBroker=null;mcpConnectionManager;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;idleCompaction=null;idleCompactionLoading=null;sessionGeneration=0;turnRunner;turnJournal;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>(this.callbacks.onToolStart?.(e,t,n),this.makeToolCallDurable(e,t,n)),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:e=>this.checkpoint(e),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s,c,l,u){this.scoop=e,this.unit=Yt(e),this.owner={kind:kt(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.capabilityBroker=l??null,this.turnJournal=u??null,this.sessions=new LW({store:r??null,canonical:c?{store:c,identity:yn(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 kV({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new aV({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new sV({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new OV({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 HW({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 eH(this.unit,this.scoop,St(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Kt(this.callbacks.getScoops(),this.scoop)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}resetStructuredOutput(){this.structuredOutputCaptured=!1,this.structuredOutputValue=void 0}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);if(!this.mcpConnectionManager){let{getOrCreateConnectionManager:e}=await Promise.resolve().then(()=>bW);this.mcpConnectionManager=await e()}let e=await FW({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,escalations:this.escalations,capabilityBroker:this.capabilityBroker,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getTurnGuestGates:()=>this.turnGuestGates,getTurnSignal:()=>this.promptAbortController?.signal,getLickTarget:()=>this.ownLickTarget(),getTmpDir:()=>this.ownTmpDir(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputCaptured||=(this.structuredOutputValue=e,!0)},mcpConnectionManager:this.mcpConnectionManager,spawnBashJob:e=>this.bashJobs.spawn(e),onBeforeCompaction:(e,t)=>this.maybeSnapshotBeforeCompaction(e,t)});if(e.kind===`abandoned`)return;if(e.kind===`deferred`){this.setStatus(`ready`);return}this.compactFn=e.compactFn,this.getCompactionApiKey=e.getCompactionApiKey,this.activeEffortOverride=e.effortOverride,this.agent=e.agent,this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),GW.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);GW.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(gV(this.scoop)),!1)}cleanupPromptState(e,t,n,r,i){if(i!==void 0&&i!==this.turnEpoch){this.currentTurnProcess!==t&&zW(this.processManager,t,{lastError:n,aborted:!0});return}this.runBounds.disarm();let a=this.runBounds.takeExceededNote();a!==null&&this.callbacks.onError(`agent run terminated: ${a}`),(n||r.aborted)&&this.sessions.persistNow(),this.disarmForceRelease(),this.isProcessing=!1,this.turnJournal?.end(this.scoop.jid),!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),zW(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(WW(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder})){for(let e of r)this.addTurnGuestGate(e);return}this.turnGuestGates=[...r];let i=this.agent;await this.runTurn(e,0,()=>i.prompt(e,t))}async resumeTurn(e,t=[]){if(!await this.ensureAgentReady()||this.isBusy)return;this.turnGuestGates=[...t];let n=this.agent;await this.runTurn(`(resumed after reload)`,e,()=>{let e=n.state.messages,t=e[e.length-1];return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)&&(n.state.messages=e.slice(0,-1)),n.continue()})}settleInterruptedToolCalls(e){let t=this.agent;if(!t||e.length===0)return;let n=Date.now(),r=e.map(e=>({role:`toolResult`,toolCallId:e.toolCallId,toolName:e.toolName,content:[{type:`text`,text:e.text}],isError:!0,timestamp:n}));t.state.messages=[...t.state.messages,...r],this.sessions.persistNow();for(let t of e)this.callbacks.onToolEnd?.(t.toolName,t.text,!0,t.toolCallId)}reportError(e){this.callbacks.onError(e)}hasAgent(){return this.agent!==null}async runTurn(e,t,n){this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal,a=++this.turnEpoch;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let o=RW(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:r});this.currentTurnProcess=o,this.runBounds.arm(),this.turnJournal?.begin(this.scoop.jid,this.scoop.folder,t,this.turnGuestGates);let s=null;try{if(s=await this.turnRunner.run(n,i),s&&!this.disposed&&!i.aborted){this.turnRunner.reportExhausted(s);return}a===this.turnEpoch&&!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,o,s,i,a)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||(this.turnGuestGates.push(e),this.turnJournal?.setGuestGates(this.scoop.jid,this.turnGuestGates))}stop(){BW(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.armForceRelease()}disarmForceRelease(){this.forceReleaseTimer!==null&&(clearTimeout(this.forceReleaseTimer),this.forceReleaseTimer=null)}armForceRelease(){this.disarmForceRelease();let e=this.turnEpoch,t=this.currentTurnProcess;this.forceReleaseTimer=setTimeout(()=>{this.forceReleaseTimer=null,!this.disposed&&this.turnEpoch===e&&this.isProcessing&&(t&&this.processManager&&(this.processManager.signal(t.pid,`SIGKILL`),this.processManager.exit(t.pid,null)),this.bashJobs.reapAll(),this.shell?.cancelActiveCommand(),this.agent?.abort?.(),this.turnEpoch===e&&this.isProcessing&&(this.isProcessing=!1,this.status===`processing`&&this.setStatus(`ready`)))},2e3)}clearMessages(){if(this.agent){let e=We(this.agent.state.messages);this.agent.state.messages=e?[e]:[]}}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0);try{await this.reloadSkills()}catch(e){GW.warn(`clearSession: could not rebuild system prompt from memory`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})}}idleCompactionEnabled(){return Tn(this.scoop)?!0:this.unit.parentId===null&&Ae(`compact-on-idle`)}armIdleCompaction(){if(!this.idleCompactionEnabled()){this.idleCompaction?.disarm();return}if(this.idleCompaction){this.idleCompaction.arm();return}this.idleCompactionLoading??=this.loadIdleCompaction(),this.idleCompactionLoading.then(e=>{!this.disposed&&this.status===`ready`&&e.arm()})}async loadIdleCompaction(){let[{IdleCompaction:e},{readIdleCompactionSettings:t}]=await Promise.all([import(`./idle-compaction-CkyuBvDI.js`),import(`./idle-compaction-settings-1yyApSsQ.js`)]),n=new e({isEnabled:()=>this.idleCompactionEnabled(),getSettings:t,getAgent:()=>this.agent,isDisposed:()=>this.disposed,isBusy:()=>this.isBusy,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),estimateTokens:$e,onCompacted:()=>this.sessions.persistNow(),onDiscarded:e=>this.callbacks.onCompactionStateChange?.(`cancelled`,{trigger:`idle`,roundId:e}),folder:this.scoop.folder});return this.idleCompaction=n,n}async maybeSnapshotBeforeCompaction(e,t){if(this.unit.parentId===null||Ae(`memory-v2`))return this.snapshotBeforeCompaction(e,t)}async snapshotBeforeCompaction(e,t){if(!this.fs||this.disposed)return;let n=this.sessionGeneration,{scoopSessionsDir:r,snapshotLiveSession:i}=await import(`./live-session-snapshot-BQcFx9d7.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-nSX_c9Jb.js`).then(n=>n.scheduleLiveDeltaCuration({vfs:e,cone:t})).catch(e=>{GW.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-BQcFx9d7.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){GW.warn(`Live snapshot settle failed (archive stays live)`,{folder:this.scoop.folder,discard:e,error:t instanceof Error?t.message:String(t)})}}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getEscalations(){return{...this.escalations}}getContextFill(){return hV(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=wV(this.agent,this.scoop))}async reloadSkills(){this.agent&&await EV(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){if(!this.agent)return GW.info(`Thinking level stored for a deferred agent`,{requested:e}),`off`;if(SV())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=TV(this.agent,e);return GW.info(`Thinking level applied`,{requested:e,resolved:n,model:this.agent.state.model?.id,provider:this.agent.state.model?.provider,reasoning:this.agent.state.model?.reasoning===!0}),n}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}streamThinking(){if(!this.agent)return null;let e=this.agent.state.thinkingLevel;return{level:e,...e!==`off`&&this.activeEffortOverride===`max`?{effortOverride:`max`}:{}}}flushConversation(){return this.sessions.flushChecked()}dispose(){this.sessions.persistNow(),this.turnJournal?.end(this.scoop.jid),this.disposed=!0,this.disarmForceRelease(),this.idleCompaction?.cancel(),this.runBounds.disarm(),BW(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 tV(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`&&GW.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||$B(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const Q=h(`scoop-lifecycle-manager`);var qW=class{deps;units=/* @__PURE__ */ new Map;tabCreates=/* @__PURE__ */ new Map;gelatiereModelSync=Promise.resolve();constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new RB(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}displayJidFor(e){let t=this.deps.approverFor(e)?.jid;return t&&t!==e?t:void 0}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??St(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Tt(t.values(),e)??St(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Q.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof gn))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}createTab(e){let t=this.tabCreates.get(e);if(t!=null)return t;let n;return n=this.openTab(e).finally(()=>{this.tabCreates.get(e)===n&&this.tabCreates.delete(e)}),this.tabCreates.set(e,n),n}async openTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Q.debug(`Context already exists`,{jid:e});return}}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Yt(t).policy.filesystem;if(a.kind===`restricted`){let e=vt(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new gn(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:_t(a.mode)});a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new KW(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0,this.deps.getTurnJournal?.()??void 0);if(n.attachContext(l,i),await l.init(),this.units.get(e)!==n||n.context!==l)return;n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{Q.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),Q.info(`Scoop context created`,{jid:e,contextId:i})}async reinitAfterPromote(e){let t=this.units.get(e);if(t?.context){t.disposeContext();try{await this.createTab(e)}catch(n){let r=n instanceof Error?n.message:String(n);Q.warn(`Failed to re-init promoted unit; next prompt will retry`,{jid:e,error:r}),t.disposeContext(),this.markTabError(e,r)}}}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.deps.getScoops().get(e);if(o&&Tn(o)&&(await this.syncGelatiereModel(),!zt(o)))throw Error(`The gelatiere cannot run until the leading cone has a model`);let s=this.getContext(e);s||=(await this.createTab(e),this.getContext(e));let c=this.units.get(e);if(c?.tab?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}s=this.getContext(e)}if(!s||!c){Q.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),c.tab&&c.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await s.prompt(t,i,a)}async resumeTurn(e,t,n){let r=this.getContext(e),i=this.units.get(e);r&&i&&!r.isBusy&&(this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),i.tab&&i.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),await r.resumeTurn(t,n))}async register(e){let t=this.deps.getScoops(),n=Dt(t.values())?.jid;if(Vt(e),this.inheritModel(e),e.parentJid!==null){let n=[];for(let r of t.values())r.jid!==e.jid&&n.push(r.folder);let r=jt(e.folder,n);r!==e.folder&&(Q.warn(`Scoop folder already taken — registering under a free variant`,{jid:e.jid,requested:e.folder,folder:r}),e.folder=r,e.trigger=`@${r}`,e.assistantLabel=r)}t.set(e.jid,e);try{await this.deps.db.saveScoop(e)}catch(n){throw t.delete(e.jid),n}this.deps.messageRouter.ensureQueue(e.jid),Q.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&fB(`spawn`,e.folder)}catch(n){Q.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){Q.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{Q.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}Dt(t.values())?.jid!==n&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to follow the new leading cone after registration`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}inheritModel(e){if(Tn(e)){let t=Dt(this.deps.getScoops().values());At(e,t?zt(t):void 0);return}if(Ot(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?zt(t):void 0)??tB();n&&At(e,n)}async unregister(e){let t=this.deps.getScoops(),n=Dt(t.values())?.jid===e;for(let n of Wt(t.values(),e))await this.unregister(n.jid);let r=t.get(e);if(r&&r.parentJid===null&&St(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let i=this.deps.getLickManager();if(r&&i){let{webhooks:e,cronTasks:t}=await i.getLicksForScoopFromDb(r.name,r.folder),n=this.deps.buildActiveLicksError(r.folder,e,t);if(n)throw n}this.deps.costTracker.snapshot(e);let a=globalThis.__slicc_wsSubscribers;a&&a.dropForScoop(e).catch(t=>{Q.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),await Promise.all([r?this.deps.getConversationStore()?.delete(vn(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(Tn(n))return await this.syncGelatiereModel(),!1;let r=Dt(this.deps.getScoops().values())?.jid===e,i=n.model;At(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return At(n,i),this.getContext(e)?.updateModel(),Q.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return r&&await this.syncGelatiereModel().catch(t=>{Q.warn(`Failed to synchronize gelatiere after leading model change`,{jid:e,error:t instanceof Error?t.message:String(t)})}),!0}syncGelatiereModel(){let e=this.gelatiereModelSync.then(()=>this.applyGelatiereModel());return this.gelatiereModelSync=e.then(()=>void 0,()=>void 0),e}async applyGelatiereModel(){let e=this.deps.getScoops(),t=[...e.values()].find(Tn);if(!t)return!1;let n=Dt(e.values()),r=n?zt(n):void 0,i=zt(t),a=r?i?.provider===r.provider&&i.id===r.id:Ot(t)===void 0;if(!a){let e=t.model?{...t.model}:void 0,i=t.config?{...t.config}:void 0;At(t,r);try{await this.deps.db.saveScoop(t)}catch(n){throw t.model=e,t.config=i,n}Q.info(`Gelatiere model synchronized with leading cone`,{jid:t.jid,leadingJid:n?.jid,model:r?`${r.provider}:${r.id}`:void 0})}return r&&this.getContext(t.jid)?.updateModel(),!a}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();Q.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Lt(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Q.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}streamThinking(e){return this.getContext(e)?.streamThinking()??null}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Yt(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:n=>this.handleScoopTurnError(e,t,n),onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return Et(n,t),await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(t,n)=>i.scheduleScoopWait(t,n,e):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:en(t).memoryPath}):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),approveGuestToolCall:e=>i.approveDirectedOrUser(e),onSudoResolve:o.canResolveApprovals?(n,r)=>i.resolveActionableLick(n,r,bt(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(bt(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleScoopTurnError(e,t,n){this.deps.getScoops().has(e)&&(this.deps.completionService.recordFailure(e,n),this.units.get(e)?.transition(`error`,{error:n}),fB(`error`,t.folder,n),this.deps.callbacks.onError(e,n),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,n),this.dispatch(e,`onStatusChange`,`error`))}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(Q.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),fB(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Yt(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(i)try{this.deps.callbacks.onError(i.jid,`[@${r.assistantLabel} FAILED]: ${t}`,{endTurn:!1})}catch(e){Q.error(`Failed to record fatal error for scoop owner`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}}};const $=h(`scoop-message-router`);var JW=class{deps;messageQueues=/* @__PURE__ */ new Map;lastAgentTimestamp=/* @__PURE__ */ new Map;pollInterval=null;debounceStates=/* @__PURE__ */ new Map;processing=/* @__PURE__ */ new Map;busyDeferrals=/* @__PURE__ */ new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if($.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){$.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);fB(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),$.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){$.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){$.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if($.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){$.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{$.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`||t.channel===`scoop-notify`||t.channel===`scoop-idle`||t.channel===`scoop-wait`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);$.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);$.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;n.reported||r<3e5||(n.reported=!0,$.warn(`Busy lick queue may be starved`,{jid:e,error:`Lick queue remained deferred while scoop was busy for 300s`}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r}))}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){$.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){$.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){$.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if($.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){$.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){$.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=ZN($N(XN(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=PA(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(`
1250
+ `);c.length>0&&this.deps.recordSentAttachments?.(e,c);let u=s.flatMap(e=>FA(e.attachments));this.messageQueues.set(e,[]);let d=s[s.length-1],f=ZN($N(XN(a),o));this.lastAgentTimestamp.set(e,f),await this.deps.db.setState(`lastAgentTs_${e}`,f);let p=s.some(e=>e.steer),m=/* @__PURE__ */ new Set,ee=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);m.has(t)||(m.add(t),ee.push(e.guestGate))}await this.deps.sendPrompt(e,l,d.senderId,d.senderName,u,{steer:p,...ee.length>0?{guestGates:ee}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);$.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),await this.deps.settleFoldedCost?.(e),t&&await t.clearSession(n).catch(t=>{$.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{$.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),$.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{$.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{$.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),$.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const YW=h(`orchestrator`),XW={decision:`deny`};var ZW=class{scoops=/* @__PURE__ */ new Map;workUnits=new _N(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new yz({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 FB({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 NB({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts(),mergeFoldedIntoFrozen:(e,t)=>this.mergeFoldedCostIntoFrozen(e,t)});completionService=new yB({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 oB({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=>JN(e),saveMessage:e=>KN(e)});lickRegistry=new Zz({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 JW({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),recordSentAttachments:(e,t)=>this.recordSentAttachments(e,t),onError:(e,t,n)=>this.callbacks.onError(e,t,n),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),settleFoldedCost:e=>this.costTracker.settleFolded(e),db:{saveMessage:e=>KN(e),deleteMessage:e=>qN(e),clearMessagesForScoop:e=>GN(e),clearAllMessages:()=>WN(),getMessagesSince:(e,t,n)=>eP(e,t,n),setState:(e,t)=>oP(e,t)},isExternalLickChannel:XM});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new qW({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=>VN(e),deleteScoop:e=>UN(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Kz(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 nB(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new uF({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 nF(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new eB(e,t),await this.modelPolicyFile.init(),n(),HN()),n,{stagePrefix:`orchestrator-init`})}setOnConversationsReady(e){this.onConversationsReady=e}async openSharedFilesystem(e,t){let n=await nB(e=>hn.create({dbName:`slicc-fs`,onRepairProgress:e}),e);this.sharedFs=n,this.sessionStore=new RA,this.conversationStore=new jL;let{TurnJournal:r}=await import(`./turn-journal-B8tRUgnH.js`);this.turnJournal=new r,this.interruptedTurns=await this.turnJournal.readAll();let i=new mn;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 sP();let{sharedFs:n,fsWatcher:i}=await this.openSharedFilesystem(e,t),a=await this.initPolicyLayerAndLoadRecords(n,i,e),o=Object.values(a).find(e=>It(e))?.jid;for(let e of Object.values(a)){await this.backfillParent(e,o),Vt(e),this.migrateScoopConfig(e,Object.values(a)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await aP(`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 iB({onTaskRun:async(e,t)=>{YW.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(),YW.info(`Orchestrator initialized`,{scoopCount:this.scoops.size}),e?.(`conversations-ready`),await this.onConversationsReady?.(),await this.restoreScoopContexts(e),En(e=>this.getSessionCostsForCommand(e)),Dn(async()=>{let{refreshBudgetWindow:e}=await Promise.resolve().then(()=>BA);return e()}),this.unregisterExportService=r(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}whenBootRestoresSettled(){return this.bootRestoreTail}async restoreScoopContexts(e){let t=[],n=[];for(let e of this.scoops.values())e.parentJid===null?t.push(e):n.push(e);await lB(t,4,t=>this.restoreScoopContext(t,e));let r=lB(n,4,t=>this.restoreScoopContext(t,e)).catch(e=>{YW.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);YW.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 RM;try{await mL({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){YW.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(yn(r),t).catch(t=>{YW.warn(`Failed to record sent attachments`,{jid:e,error:t instanceof Error?t.message:String(t)})})}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=It(e)?null:t??null;try{await VN(e)}catch(t){YW.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!Ot(e)&&!Tn(e));if(e.length>0){let t=tB(),n=[...e].sort((e,t)=>Number(e.parentJid!==null)-Number(t.parentJid!==null));for(let e of n){let n=e.parentJid?this.scoops.get(e.parentJid):void 0,r=(n?zt(n):void 0)??t;if(r){At(e,r);try{await VN(e)}catch(t){YW.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){YW.warn(`Failed to repair gelatiere model on boot; will retry next boot`,{error:e instanceof Error?e.message:String(e)})}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Xt.root}/`,r=Zt($t(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:(/* @__PURE__ */ new Date()).toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}notifyScoopOutcome(e,t){return this.completionService.notifyWithOutcome(e,t)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-DgdRwugK.js`);return t(e,{scoops:this.scoops,ownerRootOf:e=>this.ownerRootOrDefault(e),enqueue:(e,t,n)=>this.approvalRouter.enqueueSudoRequest(e,t,n),getSharedFs:()=>this.sharedFs,workspaceFor:en,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(YW.warn(`Guest approval before SudoManager init — failing closed`),XW)}})}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 VN(e),e.parentJid===null&&await this.lifecycle.syncGelatiereModel().catch(t=>{YW.warn(`Failed to follow a persisted root leadership change`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})})}reinitLiveUnit(e){return this.lifecycle.reinitAfterPromote(e)}async rekeyConversation(e,t){await this.conversationStore?.rekey(e,t)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return St(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}capableApproverOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return Ht(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Tt(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){await this.bootRestoreTail,this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await hn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await fz(this.sharedFs).catch(e=>{YW.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new uF({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 nF(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new eB(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),YW.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 JN(e)}async recoverInterruptedWork(e){await this.bootRestoreTail;let t=this.interruptedTurns;this.interruptedTurns=null;let n=this.turnJournal;if(!t||t.length===0||!n)return[];let{recoverInterruptedWork:r}=await import(`./interrupted-work-recovery-BolgIHkM.js`);return r(t,{journal:n,getScoop:e=>this.scoops.get(e),getUnit:e=>this.lifecycle.getContext(e),resumeTurn:(e,t,n)=>this.lifecycle.resumeTurn(e,t,n),emitLick:e})}sendPrompt(e,t,n,r,i=[],a){return this.completionService.allowCompletion(e),this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}syncGelatiereModel(){return this.lifecycle.syncGelatiereModel()}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}streamThinking(e){return this.lifecycle.streamThinking(e)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){for(let t of xt(this.scoops.values(),e))this.completionService.cancelScheduledWaits(t),this.completionService.suppressCompletionUntilNextPrompt(t),this.lifecycle.getContext(t)?.stop(),this.clearQueuedMessages(t).catch(e=>{YW.warn(`Failed to clear queued messages on stop`,{jid:t,error:e instanceof Error?e.message:String(e)})})}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async mergeFoldedCostIntoFrozen(e,t){let n=this.scoops.get(e);if(!n||!this.sharedFs)return!1;try{let{mergeFoldedCostIntoLatestFrozen:e}=await import(`./merge-folded-cost-into-frozen-Ce6e9pCy.js`);return await e(this.sharedFs,n,t)}catch(t){return YW.warn(`Failed to merge folded agent spend into frozen session`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await Promise.resolve().then(()=>zF),r=await n(this.sharedFs);return[...t,...r.map(On)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async flushConversations(){let e=[...this.lifecycle.getContexts().values()];return(await Promise.allSettled(e.map(e=>e.flushConversation()))).every(e=>e.status===`fulfilled`&&e.value===!0)}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&YW.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,YW.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=this.conversationStore?new DL(this.conversationStore):null,t=this.sharedFs;return new DI({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:XI(),snapshotStore:{read:e=>HI(t,e),write:(e,n,r)=>zI(t,e,n,r),discardIfUnindexed:e=>VI(t,e)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.256.2`})}};const QW=h(`workflow-run-manager`),$W=`/shared/workflow-runs`,eG=1e3;function tG(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function nG(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){QW.warn(`observeRun handler threw`,e)}},i=(e,n)=>sG(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=tG(e,a.parentJid),d={id:c,name:a.name,source:a.source,origin:u.origin,lickTarget:u.lickTarget,status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:(/* @__PURE__ */ new Date()).toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(c,d),aG(t,n);let f=i(a.ctx,c),p=oG(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=>QW.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=`${$W}/${n}.json`,u=(/* @__PURE__ */ new Date()).toISOString();try{await e.sharedFs.mkdir($W,{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);QW.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`?iG(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=/* @__PURE__ */ new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){QW.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function rG(e){let t=nG(e);return globalThis[d]=t,QW.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function iG(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function aG(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 oG(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 sG(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?cG(n,t,a?.args??[],r):e===`agent`?lG(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function cG(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>eG&&i.logs.splice(0,i.logs.length-eG),r()}return{stdout:``,stderr:``,exitCode:0}}async function lG(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 uG=/* @__PURE__ */ new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function dG(e,t,n){let r=fG(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=hG(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function fG(e){let t=/* @__PURE__ */ new Map;return pG(t,e.discoveryOrigin),pG(t,e.discoveryUrl),[...t.values()]}function pG(e,t){if(t){mG(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);mG(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!uG.has(e)))mG(e,t,1,`substring`)}catch{}}}function mG(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 hG(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=_G(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)gG(a,e)&&(r+=e.weight*o)}return r}function gG(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 _G(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}function vG(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 yG=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=SG(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:xG,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===xG)throw new g(`ENOTDIR`,`not a directory`,e);let n=CG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);return bG.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new g(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=SG(e);if(t.length===1&&t[0]===xG)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new g(`EISDIR`,`is a directory`,e);let n=CG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!bG.includes(r))throw new g(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new g(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=SG(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===xG)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=CG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=CG(t[0]);if(n===null||!this.pidExists(n))throw new g(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!bG.includes(r))throw new g(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new g(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new g(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new g(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new g(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderTable(){let e={stats:this.pm.stats(),processes:this.pm.list().map(e=>({pid:e.pid,ppid:e.ppid,kind:e.kind,state:OG(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:kG(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
1251
1251
  `}renderProcFile(e,t){if(e===1)return AG(t);let n=this.pm.get(e);switch(t){case`status`:return wG(n);case`cmdline`:return TG(n);case`cwd`:return EG(n);case`stat`:return DG(n)}}};const bG=[`status`,`cmdline`,`cwd`,`stat`],xG=`table`;function SG(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function CG(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function wG(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${OG(e.status)} (${e.status})`,`Owner:\t${kG(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(`
1252
1252
  `)+`
1253
1253
  `}function TG(e){return e.argv.join(`\0`)+`\0`}function EG(e){return e.cwd+`
@@ -1257,6 +1257,6 @@ Created: ${(/* @__PURE__ */ new Date()).toISOString()}
1257
1257
  `;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
1258
1258
  `;case`stat`:return`1 (kernel-host) R 0 - 0 -
1259
1259
  `}}const jG=Math.max(br,xr)+5e3;function MG(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(vr(e.nonce)),r=e=>n.postMessage(e),i=/* @__PURE__ */ new Map,a=e=>{let t=e.data;if(t?.type!==`sync-fs-req`||typeof t.id!=`string`)return;let n=t;if(!gr(n.token))return;let a=i.get(n.id);if(a){r({type:yr,id:n.id}),a.result&&r({type:_r,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:yr,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),jG),r({type:_r,id:n.id,...e})};(Cr(n)?Sr(n):wr(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 NG(){return globalThis}function PG(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 $M(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 FG(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 IG(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}LG(e,t)}async function LG(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=St(r),a=e.type===`discovery`&&!e.targetScoop?dG(e,i.filter($P),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?ia(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!$P(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-BEU0uoa6.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=pN(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=PG(e),l=FG(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 RG(e,t,n,r,i){let o=new dr,s=new ZW(e,{...r,getBrowserAPI:()=>t});s.setProcessManager(o);let c=at(),l=i.capabilityBroker??a(c,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});s.setCapabilityBroker(l),ln(l),NG().__slicc_pm=o,fr(pr()),NG().__slicc_browser=t,await n.bind(s,t);let u=xn(()=>n.emitTrayRuntimeStatus()),d=Ee(()=>n.emitTrayRuntimeStatus());vG(s,n);let f=i.logger??console;return await s.init(i.onBootProgress,{onSharedFsReady:async e=>{try{let{applyConfiguredHostMounts:t}=await import(`./auto-mount-table-B2A2zm7m.js`);await t(e,f)}catch(e){f.warn(`Configured host mounts failed`,e)}i.onBootProgress?.(`host-mounts-applied`)}}),await n.hydrateBuffersFromRecords(),n.publishHydratedTranscripts(),{processManager:o,orchestrator:s,unsubLeader:u,unsubFollower:d,sharedFs:s.getSharedFS(),capabilityBroker:l}}async function zG(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-CG3mKA1r.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await Promise.resolve().then(()=>BA);r(()=>a());let{getLickManager:o}=await Promise.resolve().then(()=>zz),s=o();await s.init(),e.setLickManager(s);let c=t.lickEventHandler??IG,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function BG(e){let t=e.getScoops();St(t).length>0||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,parentJid:null,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:(/* @__PURE__ */ new Date()).toISOString()})}function VG(e){let{orchestrator:t,processManager:r,lickManager:i,sharedFs:a}=e;rG({sharedFs:a,getStartingRoot:e=>{let n=St(t.getScoops()),r=n.find(t=>t.jid===e);return r?{jid:r.jid,lickTarget:r.jid===n[0]?.jid?void 0:r.folder}:null},fireLick:e=>i.emitEvent(e),processManager:r,runRealm:(e,t,n)=>hr(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>c().slice(10,22),splitResult:(e,t)=>n(e,t)})}async function HG(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-C1F4CP6u.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-wLGrnjph.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:(/* @__PURE__ */ new Date()).toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
1260
- `,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 UG(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-DMNf8klz.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-DQHez2UB.js`);return i(e,{locationHref:self.location.href,lickWsUrl:n??null,onHostfsInvalidate:e=>{if(!r)return;let n=r.getMountBackend(e.mount);if(!(n instanceof a)){t.debug?.(`hostfs_invalidate for unknown/non-hostfs mount`,{mount:e.mount});return}n.applyHostInvalidation(e.paths).catch(n=>{t.warn(`hostfs_invalidate apply failed`,{mount:e.mount,error:n instanceof Error?n.message:String(n)})})}}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function WG(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 WP(i,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:n})},{...GG(t),isOwnTab:HP(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function GG(e){let t=ye();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(/* @__PURE__ */ Error(`aborted`));return}i.addEventListener(`abort`,()=>t(/* @__PURE__ */ Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>GP()}}async function KG(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 qG(e,t,n,r,i,a){e&&(await ZG(e,n,r),i(`mounts-restored`),await JG(e,t,n,r,a),i(`jshd-restored`),await YG(e,r))}async function JG(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-CKcu1P_Z.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 YG(e,t){try{let{restoreMcpServe:t}=await import(`./serve-runtime-CEmOBSkh.js`),{executeJshFile:n}=await import(`./jsh-executor-BFwK2t97.js`).then(e=>e.r),{textAsStdin:r}=await import(`./just-bash-compat-DWUHpp9U.js`).then(e=>e.r),{createCommandContext:i}=await import(`./browser-4sjVvKih.js`).then(e=>e.n),{DEFAULT_HOME_DIR:a}=await import(`./home-dir-DAXEFyny.js`).then(e=>e.n),{DEFAULT_SHELL_PATH:o}=await import(`./jsh-discovery-D7D5iKYT.js`).then(e=>e.o),s=/* @__PURE__ */ new Map([[`HOME`,a],[`PATH`,o],[`PWD`,`/workspace`]]);await t(XG(e),async(t,a,o)=>{let c=i({fs:e,cwd:`/workspace`,env:s,stdin:r(o??``)}),l=await n(t,a,c);return{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode}})}catch(e){t.warn(`mcp serve restore failed`,e)}}function XG(e){return{readFile:async t=>{let n=await e.readFile(t);return typeof n==`string`?n:new TextDecoder().decode(n)},writeFile:async(t,n)=>{await e.writeFile(t,n)},exists:t=>e.exists(t),mkdir:async t=>{await e.exists(t)||await e.mkdir(t,{recursive:!0})}}}async function ZG(e,t,n){try{let{getAllMountEntries:r}=await import(`./mount-table-store-xM3U8UHg.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>VM),{applyConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-B2A2zm7m.js`),s=await a(e,n),c=o(await r(),s);if(c.length===0)return;let{needsRecovery:l}=await i(c,e,n);if(l.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{reason:`mount-recovery`,mounts:l}})}catch(e){n.warn(`mount recovery failed`,e)}}function QG(){Cn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-B8TZhKUa.js`);return e()})}function $G(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-B8TZhKUa.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function eK(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DOwTR0vR.js`),{ScriptCatalog:r}=await import(`./script-catalog-DDeMaTU_.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function tK(e){return e===`node-rest`}function nK(e,t,n,r){import(`./gelatiere-unit-PHQc3WNq.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!Ae(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-GVNdni5w.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function rK(e,t){if(!e)return()=>{};import(`./memory-curation-seam-CjYHWDBt.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return Ae(`memory-v2`)&&import(`./memory-health-DnbzPxqU.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 iK(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}CM(e,t,e.getSessionStore())}async function aK(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);QG();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await RG(t,n,r,i,e);if(s(`orchestrator-ready`),iK(l,f,o),f)try{await f.mountInternal(`/proc`,new yG(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await zG(l,e,o);s(`lick-manager-ready`),f&&VG({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),NG().__slicc_lickManager=m,nK(l,m,f,o);let ee=rK(f,o),{wsBridge:te,wsRegistry:ne}=await HG({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});NG().__slicc_wsSubscribers=ne;let h=tK(p.adapter)?await UG(m,o,e.localLickWsUrl??null,f):null,re=WG(n,m,o,e.appPageUrl);await qG(f,c,m,o,s,l),a||await BG(l),s(`cone-bootstrapped`),KG(l,m,o),f&&$G(m,o);let ie=null,ae=null;f&&({bshWatchdogStop:ie,scriptCatalogDispose:ae}=await eK(f,n,o));let oe=null;f&&e.syncFsChannelNonce&&(oe=MG({nonce:e.syncFsChannelNonce}).dispose);let se=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){se||(se=!0,await oK({unsubLeader:u,unsubFollower:d,bshWatchdogStop:ie,memoryHealthStop:ee,scriptCatalogDispose:ae,lickWsBridgeStop:h,navigationWatcherStop:re,syncFsResponderDispose:oe,sharedFs:f,wsRegistry:ne,wsBridge:te,processManager:c,lickManager:m,browser:n,log:o}))}}}async function oK(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)}sK({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function sK(e){let t=NG();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,fr(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[d]}const cK=`x-bypass-llm-proxy`;function lK(e,t,n){return t?(r,i)=>{if(!uK(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(cK)||a.set(cK,`1`),e(r,{...i,headers:a})}:e}function uK(e,t,n){if(fK(e,t))return!0;let r=n?.()??null;return r?dK(e,r,t):!1}function dK(e,t,n){let r=pK(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 fK(e,t){let n=pK(e);try{return new URL(n,t).origin===t}catch{return!0}}function pK(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function mK(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}const hK=new TextEncoder;var gK=class{screen;cols=80;rows=24;held=null;constructor(e){this.screen=e}lease(){if(this.held)return null;let e={input:[],resize:[]};this.held=e,this.screen.mode(`pty`);let t=new TextDecoder,n=this,r=!1;return{get cols(){return n.cols},get rows(){return n.rows},write:e=>{r||this.screen.output(t.decode(e,{stream:!0}))},onInput:t=>void e.input.push(t),onResize:t=>void e.resize.push(t),release:()=>{if(r)return;r=!0;let n=t.decode();n&&this.screen.output(n),this.held===e&&(this.held=null),this.screen.mode(`line`)}}}input(e){let t=hK.encode(e);for(let e of this.held?.input??[])e(t)}resize(e,t){if(!(e<=0||t<=0)){this.cols=e,this.rows=t;for(let n of this.held?.resize??[])n(e,t)}}},_K=class{transport;createShell;log;pm;defaultOwner;sessions=/* @__PURE__ */ new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!vK(e)||e.source!==`panel`)return;let t=e.payload;bK(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:this.sessions.get(e.sid)?.terminal.input(e.data);return;case`terminal-resize`:this.sessions.get(e.sid)?.terminal.resize(e.cols,e.rows);return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t={currentExec:null,currentProcess:null};t.currentExecMsg=null;let n=new gK({output:e=>{let n=t.currentExecMsg;n&&this.emitStream(n,`stdout`,e)},mode:t=>this.emit({type:`terminal-mode`,sid:e.sid,mode:t})});e.cols&&e.rows&&n.resize(e.cols,e.rows),t.terminal=n,t.shell=this.createShell(e.sid,{cwd:e.cwd,env:e.env,terminal:n}),this.sessions.set(e.sid,t),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n,t.currentExecMsg=e,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=``;if(e.stdin)try{i=lr(ie(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null,t.currentExecMsg=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?yK(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,yK(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 vK(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function yK(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function bK(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 xK=class extends m{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};const SK={maxExecutionTimeMs:1/0,maxCommandCount:1/0,maxLoopIterations:1/0,maxParserTokens:1/0,maxParseIterations:1/0};function CK(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new _K({transport:t,processManager:i,createShell:(a,o)=>new xK(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Sn},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},terminal:o.terminal,sudo:s,executionLimits:SK}),logger:o});return{host:c,stop:c.start()}}function wK(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return DK(e);if(typeof e==`object`)return OK(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function TK(e){if(typeof e==`object`&&e&&!(e instanceof Error))return AK(e)??jK(e);let t=wK(e);if(t!==void 0)return EK(t)}function EK(e){let t=e.trim();if(!t)return e;let n=kK(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=kK(t.slice(r,i+1));if(e)return e}return e}function DK(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function OK(e){let t=AK(e),n=jK(e);return n&&t?`${n}: ${t}`:t??n}function kK(e){if(e.startsWith(`{`))try{return AK(JSON.parse(e))}catch{return}}function AK(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 jK(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 MK=null,NK=!1;function PK(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function FK(e){return PK()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function IK(e={}){if(!NK&&(typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`telemetry-disabled`)!==`true`)){p(LK),dB(zK),BB(RK);try{let t=FK(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(MK=(await import(`./rum-worker-CwmNSpjO.js`)).default,HK(self)):t===`extension`?($K({filterViteNoise:!1}),MK=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&HK(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),$K({filterViteNoise:!0}),WK(),MK=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),NK=!0,MK&&MK(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function LK(e){MK?.(`fill`,{source:e})}function RK(e,t){let n=VK(t);n!==null&&MK?.(`error`,{source:e,target:n})}function zK(e,t,n){if(e===`error`){let e=VK(n);if(e===null)return;MK?.(`error`,{source:`scoop:${t}`,target:e});return}MK?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function BK(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function VK(e){let t=wK(e);if(t===void 0)return e==null?void 0:null;if(JB(t))return null;let n=TK(e)??EK(t);return JB(n)?null:GK(n)}function HK(e){e.addEventListener(`error`,e=>{let t=e;RK(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{RK(`js`,e.reason)})}function UK(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function WK(){typeof window<`u`&&(window.addEventListener(`error`,e=>{let t=e.error;UK(t)&&(RK(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;UK(t)&&(RK(`js`,t),e.stopImmediatePropagation())},!0))}function GK(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
1260
+ `,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 UG(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-DMRxA0GE.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-DQHez2UB.js`);return i(e,{locationHref:self.location.href,lickWsUrl:n??null,onHostfsInvalidate:e=>{if(!r)return;let n=r.getMountBackend(e.mount);if(!(n instanceof a)){t.debug?.(`hostfs_invalidate for unknown/non-hostfs mount`,{mount:e.mount});return}n.applyHostInvalidation(e.paths).catch(n=>{t.warn(`hostfs_invalidate apply failed`,{mount:e.mount,error:n instanceof Error?n.message:String(n)})})}}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function WG(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 WP(i,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:n})},{...GG(t),isOwnTab:HP(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function GG(e){let t=ye();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(/* @__PURE__ */ Error(`aborted`));return}i.addEventListener(`abort`,()=>t(/* @__PURE__ */ Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>GP()}}async function KG(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 qG(e,t,n,r,i,a){e&&(await ZG(e,n,r),i(`mounts-restored`),await JG(e,t,n,r,a),i(`jshd-restored`),await YG(e,r))}async function JG(e,t,n,r,i){try{let{restoreEnabledJshdUnits:r}=await import(`./restore-ku3NI9gU.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 YG(e,t){try{let{restoreMcpServe:t}=await import(`./serve-runtime-CwPc5Ipg.js`),{executeJshFile:n}=await import(`./jsh-executor-B54XDkz2.js`).then(e=>e.r),{textAsStdin:r}=await import(`./just-bash-compat-DWUHpp9U.js`).then(e=>e.r),{createCommandContext:i}=await import(`./browser-4sjVvKih.js`).then(e=>e.n),{DEFAULT_HOME_DIR:a}=await import(`./home-dir-DAXEFyny.js`).then(e=>e.n),{DEFAULT_SHELL_PATH:o}=await import(`./jsh-discovery-D7D5iKYT.js`).then(e=>e.o),s=/* @__PURE__ */ new Map([[`HOME`,a],[`PATH`,o],[`PWD`,`/workspace`]]);await t(XG(e),async(t,a,o)=>{let c=i({fs:e,cwd:`/workspace`,env:s,stdin:r(o??``)}),l=await n(t,a,c);return{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode}})}catch(e){t.warn(`mcp serve restore failed`,e)}}function XG(e){return{readFile:async t=>{let n=await e.readFile(t);return typeof n==`string`?n:new TextDecoder().decode(n)},writeFile:async(t,n)=>{await e.writeFile(t,n)},exists:t=>e.exists(t),mkdir:async t=>{await e.exists(t)||await e.mkdir(t,{recursive:!0})}}}async function ZG(e,t,n){try{let{getAllMountEntries:r}=await import(`./mount-table-store-xM3U8UHg.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>VM),{applyConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-B2A2zm7m.js`),s=await a(e,n),c=o(await r(),s);if(c.length===0)return;let{needsRecovery:l}=await i(c,e,n);if(l.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:{reason:`mount-recovery`,mounts:l}})}catch(e){n.warn(`mount recovery failed`,e)}}function QG(){Cn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-XwHj-EZO.js`);return e()})}function $G(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-XwHj-EZO.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:(/* @__PURE__ */ new Date()).toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function eK(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DOwTR0vR.js`),{ScriptCatalog:r}=await import(`./script-catalog-DDeMaTU_.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function tK(e){return e===`node-rest`}function nK(e,t,n,r){import(`./gelatiere-unit-NbtPiF37.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!Ae(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-GVNdni5w.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function rK(e,t){if(!e)return()=>{};import(`./memory-curation-seam-NFHXE0W5.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return Ae(`memory-v2`)&&import(`./memory-health-DpXsg2PB.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 iK(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}CM(e,t,e.getSessionStore())}async function aK(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);QG();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await RG(t,n,r,i,e);if(s(`orchestrator-ready`),iK(l,f,o),f)try{await f.mountInternal(`/proc`,new yG(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await zG(l,e,o);s(`lick-manager-ready`),f&&VG({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),NG().__slicc_lickManager=m,nK(l,m,f,o);let ee=rK(f,o),{wsBridge:te,wsRegistry:ne}=await HG({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});NG().__slicc_wsSubscribers=ne;let h=tK(p.adapter)?await UG(m,o,e.localLickWsUrl??null,f):null,re=WG(n,m,o,e.appPageUrl);await qG(f,c,m,o,s,l),a||await BG(l),s(`cone-bootstrapped`),KG(l,m,o),f&&$G(m,o);let ie=null,ae=null;f&&({bshWatchdogStop:ie,scriptCatalogDispose:ae}=await eK(f,n,o));let oe=null;f&&e.syncFsChannelNonce&&(oe=MG({nonce:e.syncFsChannelNonce}).dispose);let se=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){se||(se=!0,await oK({unsubLeader:u,unsubFollower:d,bshWatchdogStop:ie,memoryHealthStop:ee,scriptCatalogDispose:ae,lickWsBridgeStop:h,navigationWatcherStop:re,syncFsResponderDispose:oe,sharedFs:f,wsRegistry:ne,wsBridge:te,processManager:c,lickManager:m,browser:n,log:o}))}}}async function oK(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)}sK({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function sK(e){let t=NG();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,fr(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[d]}const cK=`x-bypass-llm-proxy`;function lK(e,t,n){return t?(r,i)=>{if(!uK(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(cK)||a.set(cK,`1`),e(r,{...i,headers:a})}:e}function uK(e,t,n){if(fK(e,t))return!0;let r=n?.()??null;return r?dK(e,r,t):!1}function dK(e,t,n){let r=pK(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 fK(e,t){let n=pK(e);try{return new URL(n,t).origin===t}catch{return!0}}function pK(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function mK(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}const hK=new TextEncoder;var gK=class{screen;cols=80;rows=24;held=null;constructor(e){this.screen=e}lease(){if(this.held)return null;let e={input:[],resize:[]};this.held=e,this.screen.mode(`pty`);let t=new TextDecoder,n=this,r=!1;return{get cols(){return n.cols},get rows(){return n.rows},write:e=>{r||this.screen.output(t.decode(e,{stream:!0}))},onInput:t=>void e.input.push(t),onResize:t=>void e.resize.push(t),release:()=>{if(r)return;r=!0;let n=t.decode();n&&this.screen.output(n),this.held===e&&(this.held=null),this.screen.mode(`line`)}}}input(e){let t=hK.encode(e);for(let e of this.held?.input??[])e(t)}resize(e,t){if(!(e<=0||t<=0)){this.cols=e,this.rows=t;for(let n of this.held?.resize??[])n(e,t)}}},_K=class{transport;createShell;log;pm;defaultOwner;sessions=/* @__PURE__ */ new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!vK(e)||e.source!==`panel`)return;let t=e.payload;bK(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:this.sessions.get(e.sid)?.terminal.input(e.data);return;case`terminal-resize`:this.sessions.get(e.sid)?.terminal.resize(e.cols,e.rows);return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t={currentExec:null,currentProcess:null};t.currentExecMsg=null;let n=new gK({output:e=>{let n=t.currentExecMsg;n&&this.emitStream(n,`stdout`,e)},mode:t=>this.emit({type:`terminal-mode`,sid:e.sid,mode:t})});e.cols&&e.rows&&n.resize(e.cols,e.rows),t.terminal=n,t.shell=this.createShell(e.sid,{cwd:e.cwd,env:e.env,terminal:n}),this.sessions.set(e.sid,t),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n,t.currentExecMsg=e,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=``;if(e.stdin)try{i=lr(ie(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null,t.currentExecMsg=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?yK(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,yK(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 vK(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function yK(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function bK(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 xK=class extends m{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};const SK={maxExecutionTimeMs:1/0,maxCommandCount:1/0,maxLoopIterations:1/0,maxParserTokens:1/0,maxParseIterations:1/0};function CK(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new _K({transport:t,processManager:i,createShell:(a,o)=>new xK(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Sn},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},terminal:o.terminal,sudo:s,executionLimits:SK}),logger:o});return{host:c,stop:c.start()}}function wK(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return DK(e);if(typeof e==`object`)return OK(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function TK(e){if(typeof e==`object`&&e&&!(e instanceof Error))return AK(e)??jK(e);let t=wK(e);if(t!==void 0)return EK(t)}function EK(e){let t=e.trim();if(!t)return e;let n=kK(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=kK(t.slice(r,i+1));if(e)return e}return e}function DK(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function OK(e){let t=AK(e),n=jK(e);return n&&t?`${n}: ${t}`:t??n}function kK(e){if(e.startsWith(`{`))try{return AK(JSON.parse(e))}catch{return}}function AK(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 jK(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 MK=null,NK=!1;function PK(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function FK(e){return PK()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function IK(e={}){if(!NK&&(typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`telemetry-disabled`)!==`true`)){p(LK),dB(zK),BB(RK);try{let t=FK(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(MK=(await import(`./rum-worker-CwmNSpjO.js`)).default,HK(self)):t===`extension`?($K({filterViteNoise:!1}),MK=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&HK(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),$K({filterViteNoise:!0}),WK(),MK=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),NK=!0,MK&&MK(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function LK(e){MK?.(`fill`,{source:e})}function RK(e,t){let n=VK(t);n!==null&&MK?.(`error`,{source:e,target:n})}function zK(e,t,n){if(e===`error`){let e=VK(n);if(e===null)return;MK?.(`error`,{source:`scoop:${t}`,target:e});return}MK?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function BK(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function VK(e){let t=wK(e);if(t===void 0)return e==null?void 0:null;if(JB(t))return null;let n=TK(e)??EK(t);return JB(n)?null:GK(n)}function HK(e){e.addEventListener(`error`,e=>{let t=e;RK(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{RK(`js`,e.reason)})}function UK(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function WK(){typeof window<`u`&&(window.addEventListener(`error`,e=>{let t=e.error;UK(t)&&(RK(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;UK(t)&&(RK(`js`,t),e.stopImmediatePropagation())},!0))}function GK(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
1261
1261
  `).filter(e=>!BK(e)).join(`
1262
- `).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 KK=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`),qK=[[/(\/|%2F)(join|controller)(\/|%2F)[^/?#&"\s\\]+/gi,`$1$2$3redacted`],[/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[0-9a-f]{16,}/gi,`redacted`],[/\b[0-9a-f]{32}--[0-9a-f]{16,}\b/gi,`redacted`]];function JK(e){let t=e;for(let[e,n]of qK)t=t.replace(e,n);return t}function YK(e){let t=typeof e==`string`?e:TK(e)??wK(e);if(typeof t!=`string`)return{kind:`absent`};let n=EK(t);if(n===`[object Object]`)return{kind:`noise`};let r=GK(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function XK(e){let t=YK(e.source),n=YK(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 ZK(e){try{if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(e)}catch{}return null}function QK(e){if(e.charCodeAt(0)!==123)return null;try{let t=JSON.parse(e);return t?.checkpoint===`error`?XK(t):null}catch{return null}}function $K(e){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let t=navigator.sendBeacon;if(t[KK])return;let n=t.bind(navigator),r=((t,r)=>{let i=ZK(r);if(i===null)return n(t,r);let a=JK(i);if(e.filterViteNoise){let e=QK(a);if(e===!0)return!0;if(e!==null)return n(t,e)}return n(t,a===i?r:a)});r[KK]=!0,navigator.sendBeacon=r}function eq(e){let t=new tq(e);return t.start(),{stop:()=>t.dispose()}}var tq=class{transport;client;writableClient;getWatcher;log;unsubscribe=null;watches=/* @__PURE__ */ new Map;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.getWatcher=e.getWatcher??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!nq(e)||e.source!==`panel`)return;let t=e.payload;if(rq(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(iq(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(aq(t)){this.handleWatchControl(t);return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.watches)for(let t of e)t();this.watches.clear()}handleWatchControl(e){e.type===`vfs-watch`?this.handleWatch(e):this.handleUnwatch(e)}handleWatch(e){this.dropWatch(e.subscriptionId);let t=this.getWatcher?.()??null;if(!t){this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!1,error:{code:`ENOSYS`,message:`vfs-rpc-host has no watcher wired`}});return}let n=e.basePaths.map(n=>t.watch(n,()=>!0,t=>{if(!this.watches.has(e.subscriptionId))return;let n={type:`vfs-watch-event`,subscriptionId:e.subscriptionId,events:t.map(e=>({type:e.type,path:e.path,...e.entryType?{entryType:e.entryType}:{}}))};this.transport.send(n)}));this.watches.set(e.subscriptionId,n),this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!0})}handleUnwatch(e){this.dropWatch(e.subscriptionId)}dropWatch(e){let t=this.watches.get(e);if(t){this.watches.delete(e);for(let e of t)e()}}sendWatchAck(e){this.transport.send(e)}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=e.includeStats===!0?await this.client.readDir(e.path,{includeStats:!0}):await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{if(t===`binary`&&Number.isInteger(e.start)){let t=await this.readFileWindow(e.path,e.start,e.end);this.sendBinaryReadResult(e.requestId,e.path,t);return}let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`)this.sendBinaryReadResult(e.requestId,e.path,n);else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new g(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async readFileWindow(e,t,n){let r=n??(await this.client.stat(e)).size;if(this.client.readFileRange)return this.client.readFileRange(e,t,r);let i=await this.client.readFile(e,{encoding:`binary`});if(!(i instanceof Uint8Array))throw new g(`EIO`,`readFile(binary) did not return Uint8Array`,e);return new Uint8Array(i.subarray(t,Math.min(r,i.byteLength)))}sendBinaryReadResult(e,t,n){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e,new g(`EIO`,`readFile(binary) did not return Uint8Array`),t);return}let r={type:`vfs-read-file-result`,requestId:e,ok:!0,encoding:`binary`,data:n},i=n.buffer,a=typeof ArrayBuffer<`u`&&i instanceof ArrayBuffer?[i]:void 0;this.transport.send(r,a)}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(oq(e.type),e.requestId,new g(`EACCES`,`vfs-rpc-host has no writable backend wired`),sq(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new g(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new g(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new g(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=cq(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=cq(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 nq(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function rq(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 iq(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 aq(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function oq(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 sq(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function cq(e,t){return e instanceof g?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function lq(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=lK(e.bind(globalThis),t,uq)}function uq(){let e=Re();if(!e)return null;try{return new URL(e).origin}catch{return null}}function dq(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 fq=null,pq=null,mq=null,hq=null,gq=null,_q=null;const vq=mK(e=>xq(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&vq.handle(e.data)});function yq(e){let t=Xi(e.pageBuildId,`6.256.0-mvkz9cj8`);return()=>{t&&RK(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.256.0-mvkz9cj8`)}}function bq(e){lq(),Le(e.localApiBaseUrl??null),Ie(e.bridgeToken??null),mr(e.syncFsBridgeEnabled??!1),ne(e.pageLoadedAt??null),Ve(e.extensionDelegateId??null),dq(e.localStorageSeed??{}),e.flagFloat&&Li(e.flagFloat)}async function xq(e){qi(e.instanceId),Qi(e.instanceId);let t=yq(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{bq(e),IK().then(t).catch(()=>{}),await Pe(),n(`providers-registered`);let r=na(e.kernelPort),i=new AP(r),a=AP.createCallbacks(i),o=new ra(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new Ti(o);fq=await aK({container:{},browser:s,bridge:i,callbacks:a,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,appPageUrl:e.appPageUrl??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-DfDodb7e.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=fq.sharedFs?.getWatcher();if(u){let e=null,t=/* @__PURE__ */ new Set;for(let n of Er)u.watch(n,e=>e.endsWith(`.shtml`),n=>{for(let e of n){let n=e.path.split(`/`).pop()?.replace(/\.shtml$/,``);n&&t.add(n)}e||=setTimeout(()=>{e=null;for(let e of t)l.reload(e).catch(()=>{});t.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-BJU93e51.js`).then(e=>e.r);_q=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=_q,s.setTrayTargetProvider(Pi(Oe));let f=await Cq({host:fq,transport:r,browser:s,instanceId:e.instanceId});f&&(pq=f.stopTerminalHost,mq=f.stopVfsRpcHost,hq=f.stopSpeechAssetsResponder,gq=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){Sq(e.kernelPort,t)}}function Sq(e,t){Yi(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 Cq(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=CK({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=eq({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await wq(t,e.instanceId),{startComputersHost:o}=await import(`./host-CJm3lA1s.js`),s=o({transport:e.transport,processManager:e.host.processManager});return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a,stopComputersHost:s.stop}}async function wq(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DiGbVO32.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-C0sTcSO2.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-1DfC_94U.js`).then(e=>e.o),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{if(e.data?.type!==`kernel-worker-drain`)return;let t=e.ports[0];(fq?fq.orchestrator.flushConversations():Promise.resolve(!1)).catch(()=>!1).then(e=>t?.postMessage({type:`kernel-worker-drained`,ok:e}))}),self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(pq?.(),pq=null,mq?.(),mq=null,hq?.(),hq=null,gq?.(),gq=null,_q?.dispose(),_q=null,fq?.dispose())});export{$i as _,VF as a,UF as c,mN as d,Fj as f,MA as g,KA as h,BF as i,aP as l,vj as m,UV as n,HF as o,Qj as p,ZR as r,WF as s,XH as t,oP as u,Mr as v};
1262
+ `).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 KK=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`),qK=[[/(\/|%2F)(join|controller)(\/|%2F)[^/?#&"\s\\]+/gi,`$1$2$3redacted`],[/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[0-9a-f]{16,}/gi,`redacted`],[/\b[0-9a-f]{32}--[0-9a-f]{16,}\b/gi,`redacted`]];function JK(e){let t=e;for(let[e,n]of qK)t=t.replace(e,n);return t}function YK(e){let t=typeof e==`string`?e:TK(e)??wK(e);if(typeof t!=`string`)return{kind:`absent`};let n=EK(t);if(n===`[object Object]`)return{kind:`noise`};let r=GK(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function XK(e){let t=YK(e.source),n=YK(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 ZK(e){try{if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(e)}catch{}return null}function QK(e){if(e.charCodeAt(0)!==123)return null;try{let t=JSON.parse(e);return t?.checkpoint===`error`?XK(t):null}catch{return null}}function $K(e){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let t=navigator.sendBeacon;if(t[KK])return;let n=t.bind(navigator),r=((t,r)=>{let i=ZK(r);if(i===null)return n(t,r);let a=JK(i);if(e.filterViteNoise){let e=QK(a);if(e===!0)return!0;if(e!==null)return n(t,e)}return n(t,a===i?r:a)});r[KK]=!0,navigator.sendBeacon=r}function eq(e){let t=new tq(e);return t.start(),{stop:()=>t.dispose()}}var tq=class{transport;client;writableClient;getWatcher;log;unsubscribe=null;watches=/* @__PURE__ */ new Map;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.getWatcher=e.getWatcher??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!nq(e)||e.source!==`panel`)return;let t=e.payload;if(rq(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(iq(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(aq(t)){this.handleWatchControl(t);return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.watches)for(let t of e)t();this.watches.clear()}handleWatchControl(e){e.type===`vfs-watch`?this.handleWatch(e):this.handleUnwatch(e)}handleWatch(e){this.dropWatch(e.subscriptionId);let t=this.getWatcher?.()??null;if(!t){this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!1,error:{code:`ENOSYS`,message:`vfs-rpc-host has no watcher wired`}});return}let n=e.basePaths.map(n=>t.watch(n,()=>!0,t=>{if(!this.watches.has(e.subscriptionId))return;let n={type:`vfs-watch-event`,subscriptionId:e.subscriptionId,events:t.map(e=>({type:e.type,path:e.path,...e.entryType?{entryType:e.entryType}:{}}))};this.transport.send(n)}));this.watches.set(e.subscriptionId,n),this.sendWatchAck({type:`vfs-watch-result`,subscriptionId:e.subscriptionId,ok:!0})}handleUnwatch(e){this.dropWatch(e.subscriptionId)}dropWatch(e){let t=this.watches.get(e);if(t){this.watches.delete(e);for(let e of t)e()}}sendWatchAck(e){this.transport.send(e)}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=e.includeStats===!0?await this.client.readDir(e.path,{includeStats:!0}):await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{if(t===`binary`&&Number.isInteger(e.start)){let t=await this.readFileWindow(e.path,e.start,e.end);this.sendBinaryReadResult(e.requestId,e.path,t);return}let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`)this.sendBinaryReadResult(e.requestId,e.path,n);else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new g(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async readFileWindow(e,t,n){let r=n??(await this.client.stat(e)).size;if(this.client.readFileRange)return this.client.readFileRange(e,t,r);let i=await this.client.readFile(e,{encoding:`binary`});if(!(i instanceof Uint8Array))throw new g(`EIO`,`readFile(binary) did not return Uint8Array`,e);return new Uint8Array(i.subarray(t,Math.min(r,i.byteLength)))}sendBinaryReadResult(e,t,n){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e,new g(`EIO`,`readFile(binary) did not return Uint8Array`),t);return}let r={type:`vfs-read-file-result`,requestId:e,ok:!0,encoding:`binary`,data:n},i=n.buffer,a=typeof ArrayBuffer<`u`&&i instanceof ArrayBuffer?[i]:void 0;this.transport.send(r,a)}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(oq(e.type),e.requestId,new g(`EACCES`,`vfs-rpc-host has no writable backend wired`),sq(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new g(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new g(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new g(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=cq(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=cq(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 nq(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function rq(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 iq(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 aq(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function oq(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 sq(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function cq(e,t){return e instanceof g?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function lq(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=lK(e.bind(globalThis),t,uq)}function uq(){let e=Re();if(!e)return null;try{return new URL(e).origin}catch{return null}}function dq(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 fq=null,pq=null,mq=null,hq=null,gq=null,_q=null;const vq=mK(e=>xq(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&vq.handle(e.data)});function yq(e){let t=Xi(e.pageBuildId,`6.256.2-mvljf6kg`);return()=>{t&&RK(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.256.2-mvljf6kg`)}}function bq(e){lq(),Le(e.localApiBaseUrl??null),Ie(e.bridgeToken??null),mr(e.syncFsBridgeEnabled??!1),ne(e.pageLoadedAt??null),Ve(e.extensionDelegateId??null),dq(e.localStorageSeed??{}),e.flagFloat&&Li(e.flagFloat)}async function xq(e){qi(e.instanceId),Qi(e.instanceId);let t=yq(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{bq(e),IK().then(t).catch(()=>{}),await Pe(),n(`providers-registered`);let r=na(e.kernelPort),i=new AP(r),a=AP.createCallbacks(i),o=new ra(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new Ti(o);fq=await aK({container:{},browser:s,bridge:i,callbacks:a,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,appPageUrl:e.appPageUrl??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-DfDodb7e.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=fq.sharedFs?.getWatcher();if(u){let e=null,t=/* @__PURE__ */ new Set;for(let n of Er)u.watch(n,e=>e.endsWith(`.shtml`),n=>{for(let e of n){let n=e.path.split(`/`).pop()?.replace(/\.shtml$/,``);n&&t.add(n)}e||=setTimeout(()=>{e=null;for(let e of t)l.reload(e).catch(()=>{});t.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-BJU93e51.js`).then(e=>e.r);_q=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=_q,s.setTrayTargetProvider(Pi(Oe));let f=await Cq({host:fq,transport:r,browser:s,instanceId:e.instanceId});f&&(pq=f.stopTerminalHost,mq=f.stopVfsRpcHost,hq=f.stopSpeechAssetsResponder,gq=f.stopComputersHost),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){Sq(e.kernelPort,t)}}function Sq(e,t){Yi(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 Cq(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=CK({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=eq({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await wq(t,e.instanceId),{startComputersHost:o}=await import(`./host-CJm3lA1s.js`),s=o({transport:e.transport,processManager:e.host.processManager});return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a,stopComputersHost:s.stop}}async function wq(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DiGbVO32.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-C0sTcSO2.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-1DfC_94U.js`).then(e=>e.o),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{if(e.data?.type!==`kernel-worker-drain`)return;let t=e.ports[0];(fq?fq.orchestrator.flushConversations():Promise.resolve(!1)).catch(()=>!1).then(e=>t?.postMessage({type:`kernel-worker-drained`,ok:e}))}),self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(pq?.(),pq=null,mq?.(),mq=null,hq?.(),hq=null,gq?.(),gq=null,_q?.dispose(),_q=null,fq?.dispose())});export{$i as _,VF as a,UF as c,mN as d,Fj as f,MA as g,KA as h,BF as i,aP as l,vj as m,UV as n,HF as o,Qj as p,ZR as r,WF as s,XH as t,oP as u,Mr as v};