sliccy 5.9.0 → 5.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/ui/assets/{account-store-CTQei3k8.js → account-store-BwyITiA-.js} +2 -2
  2. package/dist/ui/assets/{account-store-bTUrDwqh.js → account-store-FpbxpH9l.js} +2 -2
  3. package/dist/ui/assets/adobe-DVP_PpVZ.js +2 -0
  4. package/dist/ui/assets/adobe-Ia0Tw858.js +1 -0
  5. package/dist/ui/assets/{adobe-oauth-state-BMYsTc1P.js → adobe-oauth-state-C5CvRw3D.js} +1 -1
  6. package/dist/ui/assets/{agent-message-to-chat-BTPWICt_.js → agent-message-to-chat-C2HxC1av.js} +1 -1
  7. package/dist/ui/assets/{apps-DFoUcI2B.js → apps-BC_uzGPk.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-BsT_Qew1.js → azure-openai-CeyHnOWV.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-mSMLWQpY.js → azure-openai-DhWqRuHj.js} +1 -1
  10. package/dist/ui/assets/composer-speech-BVc9a9eb.js +1 -0
  11. package/dist/ui/assets/{connect-surface-N1gdAl_T.js → connect-surface-i04RiVzm.js} +1 -1
  12. package/dist/ui/assets/dip-DafTK_vn.js +1 -0
  13. package/dist/ui/assets/{dist-C_7XyZ2l.js → dist-BLEzW5r9.js} +1 -1
  14. package/dist/ui/assets/{dist-DOBBAZ8B.js → dist-BitLfk9F.js} +1 -1
  15. package/dist/ui/assets/{ensure-speech-assets-CvjxCMP-.js → ensure-speech-assets-BUpIrjiI.js} +1 -1
  16. package/dist/ui/assets/esp8266-CbbvJJBN.js +1 -0
  17. package/dist/ui/assets/{esptool-operations-BDGwK7S3.js → esptool-operations-7rkaEUJC.js} +2 -2
  18. package/dist/ui/assets/{fs-BLiBE0Sh.js → fs--t-CTZ8z.js} +2 -2
  19. package/dist/ui/assets/{fs-BOToGWsE.js → fs-DBM0MxFX.js} +1 -1
  20. package/dist/ui/assets/{github-D1LTcb_u.js → github-DDrcHPbM.js} +1 -1
  21. package/dist/ui/assets/{github-exUwjLID.js → github-IFQwPHJe.js} +2 -2
  22. package/dist/ui/assets/{github-copilot-DoS1KN0q.js → github-copilot-Cyt04Yrm.js} +1 -1
  23. package/dist/ui/assets/{github-copilot-Cccu4Amw.js → github-copilot-DISy7HPn.js} +1 -1
  24. package/dist/ui/assets/{hear-ga9gc9VC.js → hear-BEB1nGGC.js} +1 -1
  25. package/dist/ui/assets/{hear-C3VIZSct.js → hear-BxIJ679h.js} +1 -1
  26. package/dist/ui/assets/{kernel-worker-WZ2iz72O.js → kernel-worker-BFkhrRz8.js} +99 -97
  27. package/dist/ui/assets/kokoro-engine-Ck12MVoU.js +2 -0
  28. package/dist/ui/assets/{lick-ws-bridge-CmIPZwU6.js → lick-ws-bridge-CH66z40P.js} +1 -1
  29. package/dist/ui/assets/{lick-ws-bridge-C9Grc0G_.js → lick-ws-bridge-DCvSQxqb.js} +1 -1
  30. package/dist/ui/assets/{local-llm-D4PJe-fA.js → local-llm-CMh8kjVF.js} +1 -1
  31. package/dist/ui/assets/{main-A8L0rM6J.js → main-D8DiFd3K.js} +4 -4
  32. package/dist/ui/assets/{mount-ByGPP7Ad.js → mount-BVGQ0h1F.js} +2 -2
  33. package/dist/ui/assets/{mount-ZketO2Vo.js → mount-Cli7dQgX.js} +1 -1
  34. package/dist/ui/assets/{new-session-hLVMB1VM.js → new-session-BeETIJD6.js} +2 -2
  35. package/dist/ui/assets/{oauth-bootstrap-BIuNcx7O.js → oauth-bootstrap-DAZnzRGo.js} +2 -2
  36. package/dist/ui/assets/{openai-codex-Ck1oyuTZ.js → openai-codex-ByB5C8WH.js} +1 -1
  37. package/dist/ui/assets/{openai-codex-BA8gK7EM.js → openai-codex-CZmdY-O0.js} +1 -1
  38. package/dist/ui/assets/{page-follower-tray-DsXFQjOn.js → page-follower-tray-a0R3hcUF.js} +1 -1
  39. package/dist/ui/assets/panel-rpc-handlers-muBAii9k.js +2 -0
  40. package/dist/ui/assets/{provider-bddnu4fF.js → provider-BcaFySUk.js} +1 -1
  41. package/dist/ui/assets/{provider-Cy3Frzsq.js → provider-DYETVGJi.js} +2 -2
  42. package/dist/ui/assets/provider-store-access-DUD-E6-t.js +1 -0
  43. package/dist/ui/assets/provider-store-access-X7UiGCJx.js +1 -0
  44. package/dist/ui/assets/{providers-BcBKUoGy.js → providers-Cfi3--kj.js} +1 -1
  45. package/dist/ui/assets/{quick-llm-BalhxXNL.js → quick-llm-DVcyufyG.js} +1 -1
  46. package/dist/ui/assets/session-freezer-Dumn28Jf.js +1 -0
  47. package/dist/ui/assets/speak-BhvC2qYp.js +1 -0
  48. package/dist/ui/assets/speak-BsaTiJJa.js +3 -0
  49. package/dist/ui/assets/{sprinkle-manager-Dsklo6YH.js → sprinkle-manager-BB7m7Qov.js} +1 -1
  50. package/dist/ui/assets/{store-D7gdAWiV.js → store-CfsRJWtN.js} +1 -1
  51. package/dist/ui/assets/{sudo-FJDtgrNd.js → sudo-CYG1BGX3.js} +1 -1
  52. package/dist/ui/assets/transformers-env-CXsaPfh5.js +1 -0
  53. package/dist/ui/assets/transformers-env-kQIH3cLT.js +1 -0
  54. package/dist/ui/assets/{tray-leader-C2kx1AEP.js → tray-leader-C3KIAdU7.js} +1 -1
  55. package/dist/ui/assets/{tray-leave-runtime-DfViVR3m.js → tray-leave-runtime-pnaCUWfN.js} +1 -1
  56. package/dist/ui/assets/upgrade-detection-CWYyBGAq.js +1 -0
  57. package/dist/ui/assets/{voice-reply-DrCn5oWL.js → voice-reply-CrSNABF9.js} +1 -1
  58. package/dist/ui/assets/{wc-attach-CM6e3_ZV.js → wc-attach-B2_AM4gP.js} +2 -2
  59. package/dist/ui/assets/{wc-detached-s0-UA_La.js → wc-detached-DU0RLPTf.js} +1 -1
  60. package/dist/ui/assets/{wc-extension-Ch7lj5d_.js → wc-extension-DEyrI6Ix.js} +2 -2
  61. package/dist/ui/assets/{wc-follower-7FQ6uy2J.js → wc-follower-DS3p2bj2.js} +2 -2
  62. package/dist/ui/assets/{wc-live-DLyguj5u.js → wc-live-Bp6DKmco.js} +5 -5
  63. package/dist/ui/assets/{wc-nav-qys31F37.js → wc-nav-DqS1Hc_h.js} +2 -2
  64. package/dist/ui/assets/{wc-onboarding-n7mSm_El.js → wc-onboarding-OxBvGa7X.js} +2 -2
  65. package/dist/ui/assets/{wc-placeholder-CahuQLxT.js → wc-placeholder-BpWcadri.js} +3 -3
  66. package/dist/ui/assets/{wc-settings-B140tTQ4.js → wc-settings-DH22_hzK.js} +2 -2
  67. package/dist/ui/assets/{wc-shell-Cfr_EWbg.js → wc-shell-Dd7nFJy9.js} +3 -3
  68. package/dist/ui/assets/{wc-sprinkles-BvLFr2be.js → wc-sprinkles-BdiX5uLy.js} +2 -2
  69. package/dist/ui/assets/{wc-tray-BfJlH2oM.js → wc-tray-D-uZFss3.js} +2 -2
  70. package/dist/ui/assets/whisper-engine-C4duA1kw.js +1 -0
  71. package/dist/ui/assets/whisper-session-3Uq6Hk8f.js +2 -0
  72. package/dist/ui/assets/{xai-grok-DQAaGin5.js → xai-grok-ByaWtL3e.js} +1 -1
  73. package/dist/ui/assets/{xai-grok-aOHNDioz.js → xai-grok-DBY6Y3JN.js} +1 -1
  74. package/dist/ui/index.html +2 -2
  75. package/dist/ui/packages/webapp/index.html +2 -2
  76. package/package.json +1 -1
  77. package/dist/ui/assets/adobe-BuaKKv6B.js +0 -1
  78. package/dist/ui/assets/adobe-DbcWZe3u.js +0 -2
  79. package/dist/ui/assets/composer-speech-B8gzpoLm.js +0 -1
  80. package/dist/ui/assets/dip-DVyX7KVH.js +0 -1
  81. package/dist/ui/assets/esp8266-b3mqvv0m.js +0 -1
  82. package/dist/ui/assets/kokoro-engine-De3HVaKA.js +0 -2
  83. package/dist/ui/assets/panel-rpc-handlers-CFpYuD14.js +0 -2
  84. package/dist/ui/assets/provider-store-access-8oGqp9Q2.js +0 -1
  85. package/dist/ui/assets/provider-store-access-BFKipbhe.js +0 -1
  86. package/dist/ui/assets/session-freezer-HWMUR9_b.js +0 -1
  87. package/dist/ui/assets/speak-BGc6bNZS.js +0 -1
  88. package/dist/ui/assets/speak-DqTkMukv.js +0 -3
  89. package/dist/ui/assets/transformers-env-BLIAM-E9.js +0 -1
  90. package/dist/ui/assets/transformers-env-D1pjZd13.js +0 -1
  91. package/dist/ui/assets/upgrade-detection-D6VrdGgM.js +0 -1
  92. package/dist/ui/assets/whisper-engine-CzMFsimz.js +0 -1
  93. package/dist/ui/assets/whisper-session-CR621W5w.js +0 -2
@@ -1,8 +1,8 @@
1
- import{i as e,n as t,r as n,t as r}from"./chunk-aKtaBQYM.js";import{t as i}from"./logger-LESFN7Hj.js";import{_ as a,c as o,d as s,f as c,g as l,i as u,l as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v}from"./proxied-fetch-I4cndszg.js";import{n as y,o as b,s as x}from"./tool-ui-t6ocn6AG.js";import{a as S,i as C,n as w,o as T,r as E,t as D}from"./backend-local-mrUgrni5.js";import{t as O}from"./types-idfTVsM8.js";import{n as ee,t as te}from"./mime-types-BqLkKWa7.js";import{a as ne,i as k,n as A,r as re}from"./mount-ZketO2Vo.js";import{t as ie}from"./mount-id-nJcx05eu.js";import{n as ae,r as oe,t as se}from"./fetch-body-DDu_AU5I.js";import{t as ce}from"./remote-cache-BL6NRenp.js";import{n as le}from"./mount-table-store-ggb440m4.js";import{n as ue,r as de,t as j}from"./panel-rpc-D0J5pskz.js";import{a as fe}from"./providers-BcBKUoGy.js";import{i as pe,n as me,t as he}from"./path-utils-DU6QhF_k.js";import{b as ge,d as _e,l as ve,u as ye}from"./bedrock-camp-C1lmRgcD.js";import{t as be}from"./__vite-browser-external-C7iut881.js";import{f as M,o as xe}from"./transform-messages-BjP6vDPY.js";import{A as Se,B as Ce,C as we,D as Te,E as N,F as Ee,I as P,L as F,M as De,N as Oe,O as ke,P as Ae,R as je,S as Me,T as Ne,_ as Pe,a as Fe,b as Ie,c as Le,d as Re,f as ze,g as Be,h as Ve,i as He,j as Ue,k as We,l as Ge,m as Ke,o as qe,p as Je,r as Ye,s as Xe,t as Ze,u as Qe,v as $e,w as et,x as tt,y as nt,z as rt}from"./account-store-bTUrDwqh.js";import{i as it,n as at,r as ot}from"./fs-BOToGWsE.js";import{n as st,r as ct}from"./openai-completions-YNL_qr9N.js";const lt=`__slicc_binary__`;function ut(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[lt]===`b64`&&typeof t.data==`string`}function dt(e){if(e instanceof Uint8Array)return{[lt]:`b64`,data:a(e)};if(Array.isArray(e))return e.map(dt);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=dt(r);return t}return e}function I(e){if(ut(e))return l(e.data);if(Array.isArray(e))return e.map(I);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=I(r);return t}return e}const ft=i(`panel-transport`);function pt(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function mt(){return{onMessage:e=>{let t=(t,n,r)=>(pt(t)&&e(I(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=dt(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)||ft.error(`Offscreen → panel transport send failed`,{error:t})})}}}const ht=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]);var gt=t({formatMountRecoveryPrompt:()=>bt,mdInlineCode:()=>yt,recoverMounts:()=>_t,shellQuote:()=>vt});async function _t(e,t,n){let r=[],i=[];for(let a of e){let{targetPath:e,descriptor:o}=a;if(o.kind===`local`){let a=await le(o.idbHandleKey),s=typeof a?.name==`string`?a.name:``;if(!a||!(`queryPermission`in a)){i.push({kind:`local`,path:e,dirName:s});continue}let c;try{c=await a.queryPermission({mode:`readwrite`})}catch(t){n?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),i.push({kind:`local`,path:e,dirName:s});continue}if(c!==`granted`){i.push({kind:`local`,path:e,dirName:s});continue}try{let i=D.fromHandle(a,{mountId:o.mountId});await t.mount(e,i),n?.info?.(`Restored mount from previous session`,{path:e,name:s}),r.push({kind:`local`,path:e,dirName:s})}catch(t){n?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),i.push({kind:`local`,path:e,dirName:s})}continue}if(o.kind===`s3`){try{let i=new ce({mountId:o.mountId,ttlMs:3e4}),a=new k({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:re(o.profile)});await t.mount(e,a),n?.info?.(`Restored S3 mount from previous session`,{path:e,source:o.source}),r.push({kind:`s3`,path:e,source:o.source,profile:o.profile,reason:``})}catch(t){let r=t instanceof Error?t.message:String(t);n?.warn?.(`Failed to restore S3 mount`,{path:e,error:r}),i.push({kind:`s3`,path:e,source:o.source,profile:o.profile,reason:r})}continue}if(o.kind===`da`)try{let i=new ce({mountId:o.mountId,ttlMs:3e4}),a=new ne({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:A()});await t.mount(e,a),n?.info?.(`Restored DA mount from previous session`,{path:e,source:o.source}),r.push({kind:`da`,path:e,source:o.source,profile:o.profile,reason:``})}catch(t){let r=t instanceof Error?t.message:String(t);n?.warn?.(`Failed to restore DA mount`,{path:e,error:r}),i.push({kind:`da`,path:e,source:o.source,profile:o.profile,reason:r})}}return{restored:r,needsRecovery:i}}function vt(e){return`'${e.replace(/'/g,`'\\''`)}'`}function yt(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function bt(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${yt(t)})`:``;return`- ${yt(e)}${n}`}),i=r.map(({path:e})=>` mount ${vt(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${vt(n)}`,a=`mount --source ${vt(t)}${i} ${vt(e)}`;return`- ${yt(e)} (${yt(t)}, profile ${yt(n)}) — ${r}\n Retry: ${yt(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
1
+ import{i as e,n as t,r as n,t as r}from"./chunk-aKtaBQYM.js";import{t as i}from"./logger-LESFN7Hj.js";import{_ as a,c as o,d as s,f as c,g as l,i as u,l as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v}from"./proxied-fetch-I4cndszg.js";import{n as y,o as b,s as x}from"./tool-ui-t6ocn6AG.js";import{a as S,i as C,n as w,o as T,r as E,t as D}from"./backend-local-mrUgrni5.js";import{t as O}from"./types-idfTVsM8.js";import{n as ee,t as te}from"./mime-types-BqLkKWa7.js";import{a as ne,i as k,n as A,r as re}from"./mount-Cli7dQgX.js";import{t as ie}from"./mount-id-nJcx05eu.js";import{n as ae,r as oe,t as se}from"./fetch-body-DDu_AU5I.js";import{t as ce}from"./remote-cache-BL6NRenp.js";import{n as le}from"./mount-table-store-ggb440m4.js";import{n as ue,r as de,t as j}from"./panel-rpc-D0J5pskz.js";import{a as fe}from"./providers-Cfi3--kj.js";import{i as pe,n as me,t as he}from"./path-utils-DU6QhF_k.js";import{b as ge,d as _e,l as ve,u as ye}from"./bedrock-camp-C1lmRgcD.js";import{t as be}from"./__vite-browser-external-C7iut881.js";import{f as M,o as xe}from"./transform-messages-BjP6vDPY.js";import{A as Se,B as Ce,C as we,D as Te,E as N,F as Ee,I as P,L as F,M as De,N as Oe,O as ke,P as Ae,R as je,S as Me,T as Ne,_ as Pe,a as Fe,b as Ie,c as Le,d as Re,f as ze,g as Be,h as Ve,i as He,j as Ue,k as We,l as Ge,m as Ke,o as qe,p as Je,r as Ye,s as Xe,t as Ze,u as Qe,v as $e,w as et,x as tt,y as nt,z as rt}from"./account-store-FpbxpH9l.js";import{i as it,n as at,r as ot}from"./fs-DBM0MxFX.js";import{n as st,r as ct}from"./openai-completions-YNL_qr9N.js";const lt=`__slicc_binary__`;function ut(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[lt]===`b64`&&typeof t.data==`string`}function dt(e){if(e instanceof Uint8Array)return{[lt]:`b64`,data:a(e)};if(Array.isArray(e))return e.map(dt);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=dt(r);return t}return e}function I(e){if(ut(e))return l(e.data);if(Array.isArray(e))return e.map(I);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=I(r);return t}return e}const ft=i(`panel-transport`);function pt(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function mt(){return{onMessage:e=>{let t=(t,n,r)=>(pt(t)&&e(I(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=dt(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)||ft.error(`Offscreen → panel transport send failed`,{error:t})})}}}const ht=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]);var gt=t({formatMountRecoveryPrompt:()=>bt,mdInlineCode:()=>yt,recoverMounts:()=>_t,shellQuote:()=>vt});async function _t(e,t,n){let r=[],i=[];for(let a of e){let{targetPath:e,descriptor:o}=a;if(o.kind===`local`){let a=await le(o.idbHandleKey),s=typeof a?.name==`string`?a.name:``;if(!a||!(`queryPermission`in a)){i.push({kind:`local`,path:e,dirName:s});continue}let c;try{c=await a.queryPermission({mode:`readwrite`})}catch(t){n?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),i.push({kind:`local`,path:e,dirName:s});continue}if(c!==`granted`){i.push({kind:`local`,path:e,dirName:s});continue}try{let i=D.fromHandle(a,{mountId:o.mountId});await t.mount(e,i),n?.info?.(`Restored mount from previous session`,{path:e,name:s}),r.push({kind:`local`,path:e,dirName:s})}catch(t){n?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),i.push({kind:`local`,path:e,dirName:s})}continue}if(o.kind===`s3`){try{let i=new ce({mountId:o.mountId,ttlMs:3e4}),a=new k({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:re(o.profile)});await t.mount(e,a),n?.info?.(`Restored S3 mount from previous session`,{path:e,source:o.source}),r.push({kind:`s3`,path:e,source:o.source,profile:o.profile,reason:``})}catch(t){let r=t instanceof Error?t.message:String(t);n?.warn?.(`Failed to restore S3 mount`,{path:e,error:r}),i.push({kind:`s3`,path:e,source:o.source,profile:o.profile,reason:r})}continue}if(o.kind===`da`)try{let i=new ce({mountId:o.mountId,ttlMs:3e4}),a=new ne({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:A()});await t.mount(e,a),n?.info?.(`Restored DA mount from previous session`,{path:e,source:o.source}),r.push({kind:`da`,path:e,source:o.source,profile:o.profile,reason:``})}catch(t){let r=t instanceof Error?t.message:String(t);n?.warn?.(`Failed to restore DA mount`,{path:e,error:r}),i.push({kind:`da`,path:e,source:o.source,profile:o.profile,reason:r})}}return{restored:r,needsRecovery:i}}function vt(e){return`'${e.replace(/'/g,`'\\''`)}'`}function yt(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function bt(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${yt(t)})`:``;return`- ${yt(e)}${n}`}),i=r.map(({path:e})=>` mount ${vt(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${vt(n)}`,a=`mount --source ${vt(t)}${i} ${vt(e)}`;return`- ${yt(e)} (${yt(t)}, profile ${yt(n)}) — ${r}\n Retry: ${yt(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
2
2
  `)}const xt=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`sudo-request`]);function St(e){return e!=null&&xt.has(e)}const Ct={webhook:`Webhook Event`,sprinkle:`Sprinkle Event`,fswatch:`File Watch Event`,"session-reload":`Session Reload`,navigate:`Navigate Event`,upgrade:`Upgrade Event`,cherry:`Cherry Event`,workflow:`Workflow Event`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`};function wt(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`session-reload`:return`mount-recovery`;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`cherry`:return e.cherryName;case`workflow`:return e.workflowName;case`sudo-request`:return e.sudoScoopName;default:return e.cronName}}function Tt(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=bt(n.mounts??[]);return e===null?null:{label:t,content:`${e}${r?`\n\nLick ID: ${r}\nThis card is actionable: call \`lick_confirm\` with this lick id to re-run the listed \`mount …\` command(s) so the user can re-authorize, or \`lick_dismiss\` to leave them unmounted. The card flips to ✓ on confirm / muted ✗ on dismiss.`:``}`}}let i=At(e,t);if(!r)return i;let a=`\n\nLick ID: ${r}\nThis card is informational — there is NO confirm action. Call \`lick_dismiss\` with this lick id to acknowledge and clear it. The card flips to muted ✗ on dismiss.`;return{label:i.label,content:`${i.content}${a}`}}function Et(e,t){let n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`,i=e.body?.releasedAt??null,a=i?`\nReleased: ${i}`:``,o=e.lickId;return{label:t,content:`[${t}: ${n}→${r}]\n\nSLICC was upgraded from \`${n}\` to \`${r}\`.${a}${o?`\n\nLick ID: ${o}\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`). The card is a binary action: call \`lick_confirm\` with this lick id to **Update workspace files** (it runs the three-way merge of bundled vfs-root content into the user's VFS), or \`lick_dismiss\` to clear it. The card flips to ✓ on confirm / muted ✗ on dismiss. Reviewing the changelog is a separate step you can run first — it is NOT a card action.`:`
3
3
 
4
4
  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 Dt(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 Ot(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 kt(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.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}" to deny.`),{label:t,content:o.join(`
5
- `)}}function At(e,t){let n=wt(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 jt(e,t){let n=At(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\` with any branch/path scope from the body); 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 Mt(e){let t=Ct[e.type];return e.type===`session-reload`?Tt(e,t):e.type===`upgrade`?Et(e,t):e.type===`cherry`?Dt(e,t):e.type===`workflow`?Ot(e,t):e.type===`sudo-request`?kt(e,t):e.type===`navigate`?jt(e,t):At(e,t)}const Nt=64*1024;function Pt(e,t=Nt){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${zt(t)} of ${zt(e.length)} — the agent received the full output]`}function Ft(e,t=Nt,n=4){if(typeof e==`string`)return Pt(e,t);if(typeof e!=`object`||!e||n<=0)return e;if(Array.isArray(e)){let r=null;for(let i=0;i<e.length;i++){let a=Ft(e[i],t,n-1);a!==e[i]&&(r??=[...e],r[i]=a)}return r??e}let r=null;for(let[i,a]of Object.entries(e)){let o=Ft(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}const It=()=>/<img:data:image\/[^>]+>/g;function Lt(e,t=Nt){if(!e)return e;if(!It().test(e))return Pt(e,t);let n=Pt(e.replace(It(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function Rt(e,t=Nt){if(e.length<=t)return e;if(!It().test(e))return Pt(e,t);let n=[],r=0;for(let i of e.matchAll(It()))n.push(Pt(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(Pt(e.slice(r),t)),n.join(``)}function zt(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}let Bt={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Vt(){return{...Bt}}const Ht=new Set;function Ut(e){return Ht.add(e),()=>{Ht.delete(e)}}const Wt={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Gt=null;function Kt(e){if(!e.objectStoreNames.contains(Wt.MESSAGES)){let t=e.createObjectStore(Wt.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(Wt.SESSIONS)||e.createObjectStore(Wt.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(Wt.TASKS)||e.createObjectStore(Wt.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(Wt.STATE)||e.createObjectStore(Wt.STATE,{keyPath:`key`})}function qt(e){let t=e.isMain??!1;return{jid:e.jid,name:e.name,folder:e.folder,trigger:t?void 0:e.trigger||`@${e.folder}`,requiresTrigger:!t&&(e.requiresTrigger??!0),isCone:t,type:t?`cone`:`scoop`,assistantLabel:t?`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 Jt(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(Wt.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);for(let t of e)r.put(qt(t))};return}t.objectStoreNames.contains(Wt.SCOOPS)||t.createObjectStore(Wt.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function Yt(e){e.objectStoreNames.contains(Wt.WEBHOOKS)||e.createObjectStore(Wt.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(Wt.CRONTASKS)||e.createObjectStore(Wt.CRONTASKS,{keyPath:`id`})}function Xt(e){let t=e.target.result,n=e.oldVersion;n<1&&Kt(t),n<2&&Jt(e,t),n<3&&Yt(t)}function Zt(){if(!Gt)return null;let e=Object.values(Wt).every(e=>Gt.objectStoreNames.contains(e));return Gt.version===3&&e?Gt:(Gt.close(),Gt=null,null)}function Qt(e){e.onversionchange=()=>{e.close(),Gt===e&&(Gt=null)},e.onclose=()=>{Gt===e&&(Gt=null)}}async function $t(){return Zt()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=Xt,n.onsuccess=()=>{let t=n.result;Qt(t),Gt=t,e(t)},n.onerror=()=>t(n.error)})}async function en(e,t=`readonly`){return(await $t()).transaction(e,t).objectStore(e)}async function tn(e){let t=await en(Wt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function nn(){let e=await en(Wt.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 rn(e){let t=await en(Wt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function an(){let e=await en(Wt.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function on(e){let t=(await en(Wt.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 sn(e){let t=await en(Wt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function cn(e){let t=await en(Wt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ln(e){let t=(await en(Wt.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)})}async function un(e,t,n){let r=(await en(Wt.MESSAGES)).index(`chatJid_timestamp`),i=IDBKeyRange.bound([e,t],[e,`￿`],!0,!1);return new Promise((e,t)=>{let a=r.getAll(i);a.onsuccess=()=>{let t=a.result;n&&(t=t.filter(e=>e.senderName!==n)),e(t)},a.onerror=()=>t(a.error)})}async function dn(e){let t=await en(Wt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function fn(e){let t=await en(Wt.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function pn(){let e=await en(Wt.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function mn(e){let t=await en(Wt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function hn(e){let t=await en(Wt.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 gn(e,t){let n=await en(Wt.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 _n(){await $t()}async function vn(e){let t=await en(Wt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function yn(){try{let e=await en(Wt.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function bn(e){let t=await en(Wt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function xn(e){let t=await en(Wt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Sn(){try{let e=await en(Wt.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Cn(e){let t=await en(Wt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}function wn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``,t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)||`/`);let n=t.toString();return n.endsWith(`/`)?n.slice(0,-1):n}catch{return null}}function Tn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.toString(),r=t.pathname.split(`/`).filter(Boolean);if(r.length<2||r.at(-2)!==`join`)return null;let[i,a,...o]=decodeURIComponent(r.at(-1)).split(`.`);if(!i||!a||o.length>0)return null;r.splice(-2,2),t.pathname=r.length>0?`/${r.join(`/`)}`:`/`;let s=wn(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}const En=`slicc.trayWorkerBaseUrl`,Dn=`slicc.trayJoinUrl`,On=`https://www.sliccy.ai`;function kn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=null;if(n.length>=2&&n.at(-2)===`tray`)r=decodeURIComponent(n.at(-1)),n.splice(-2,2),t.pathname=n.length>0?`/${n.join(`/`)}`:`/`;else if(n.length>=2&&n.at(-2)===`join`)return Tn(t.toString());let i=wn(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function An(e){let t=kn(e);return t?.joinUrl?t:null}i(`tray-leader`);let jn={state:`inactive`,session:null,error:null};function Mn(){return{...jn,session:jn.session?{...jn.session}:null}}function Nn(){let e=Mn();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.leaderTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Pn=new Set;function Fn(e){return Pn.add(e),()=>{Pn.delete(e)}}const In=`sessions`;function Ln(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(In)||e.createObjectStore(In,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Rn=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Ln();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(In,`readwrite`);i.objectStore(In).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(In,`readonly`).objectStore(In).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(In,`readonly`).objectStore(In).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(In,`readwrite`);i.objectStore(In).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};const zn=i(`offscreen-bridge`);function Bn(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 Vn=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;activeScoopJid=null;agentEventListeners=new Set;fanOutMessageId=new Map;constructor(e){this._transport=e??null}get transport(){return this._transport||=mt(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Rn;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.currentMessageId.get(t);if(n){let r=e.getBuffer(t).find(e=>e.id===n);r&&(r.isStreaming=!1),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Hn()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),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.scoopStatuses.set(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onToolStart:(t,n,r)=>{ht.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{ht.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=Ft(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Hn(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=Lt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Rt(n),isError:r})}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.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),this.scoopStatuses.delete(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[offscreen-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.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){let t=e.config&&(e.config.modelId!==void 0||e.config.thinkingLevel!==void 0)?{...e.config.modelId===void 0?{}:{modelId:e.config.modelId},...e.config.thinkingLevel===void 0?{}:{thinkingLevel:e.config.thinkingLevel}}:void 0;return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.scoopStatuses.get(e.jid)??`ready`,...t?{config:t}:{}}}buildStateSnapshot(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[],t=e.find(e=>e.isCone);return{type:`state-snapshot`,scoops:e,activeScoopJid:this.getActiveScoopJid()??t?.jid??null,trayRuntimeStatus:this.buildTrayRuntimeStatus()}}emitTrayRuntimeStatus(){let e=this.buildTrayRuntimeStatus(),t={type:`tray-runtime-status`,leader:e.leader,follower:e.follower};this.emit(t)}buildTrayRuntimeStatus(){let e=Mn(),t=Vt();return{leader:{state:e.state,session:e.session,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}}}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}onAgentEvent(e){return this.agentEventListeners.add(e),()=>{this.agentEventListeners.delete(e)}}fanOutAgentEvent(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.fanOutMessageId.get(t);return e||(e=`scoop-${t}-${Hn()}`,this.fanOutMessageId.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});break}case`tool_end`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let e=this.fanOutMessageId.get(t);if(!e)return;r.push({type:`content_done`,messageId:e}),this.fanOutMessageId.delete(t);break}case`turn_end`:this.fanOutMessageId.delete(t);break}for(let e of r)for(let n of this.agentEventListeners)try{n(t,e)}catch(e){zn.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Bn(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=Mt({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.fanOutMessageId.delete(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{zn.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??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`});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});break}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopStatuses.set(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-BTPWICt_.js`);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:!1}))}async seedBuffersFromAgentState(){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.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];t.length>0&&(this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){zn.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}handleRequestSessionStats(e){let t=0,n=[],r=[],i=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=e.reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getContextFills()??[],r=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),i=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,fills:n,models:r,scoops:i})}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:Un(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-BTPWICt_.js`),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Un(a)});return}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){zn.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}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}-${Hn()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){import(`./sprinkle-proxy-B4nH2NxC.js`).then(({handleSprinkleOpResponse:t})=>{t(e.payload)});return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[offscreen-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);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(`[offscreen-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();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-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[offscreen-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:{let t=e;try{await this.orchestrator.setScoopThinkingLevel(t.scoopJid,t.level)}catch(e){console.error(`[offscreen-bridge] set-thinking-level failed:`,e)}break}case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);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`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[offscreen-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));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear());break}}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[offscreen-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),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};await this.orchestrator?.handleMessage(t),this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.scoopStatuses.delete(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[offscreen-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.fanOutMessageId.delete(t)),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(`[offscreen-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[offscreen-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=globalThis.__slicc_lickManager;if(!t){console.warn(`[offscreen-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.emitEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[offscreen-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`){x.markMounted(t);return}try{await x.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[offscreen-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),x.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[offscreen-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.fanOutAgentEvent(e)}};function Hn(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Un(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
5
+ `)}}function At(e,t){let n=wt(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 jt(e,t){let n=At(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\` with any branch/path scope from the body); 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 Mt(e){let t=Ct[e.type];return e.type===`session-reload`?Tt(e,t):e.type===`upgrade`?Et(e,t):e.type===`cherry`?Dt(e,t):e.type===`workflow`?Ot(e,t):e.type===`sudo-request`?kt(e,t):e.type===`navigate`?jt(e,t):At(e,t)}const Nt=64*1024;function Pt(e,t=Nt){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${zt(t)} of ${zt(e.length)} — the agent received the full output]`}function Ft(e,t=Nt,n=4){if(typeof e==`string`)return Pt(e,t);if(typeof e!=`object`||!e||n<=0)return e;if(Array.isArray(e)){let r=null;for(let i=0;i<e.length;i++){let a=Ft(e[i],t,n-1);a!==e[i]&&(r??=[...e],r[i]=a)}return r??e}let r=null;for(let[i,a]of Object.entries(e)){let o=Ft(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}const It=()=>/<img:data:image\/[^>]+>/g;function Lt(e,t=Nt){if(!e)return e;if(!It().test(e))return Pt(e,t);let n=Pt(e.replace(It(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function Rt(e,t=Nt){if(e.length<=t)return e;if(!It().test(e))return Pt(e,t);let n=[],r=0;for(let i of e.matchAll(It()))n.push(Pt(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(Pt(e.slice(r),t)),n.join(``)}function zt(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}let Bt={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Vt(){return{...Bt}}const Ht=new Set;function Ut(e){return Ht.add(e),()=>{Ht.delete(e)}}const Wt={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Gt=null;function Kt(e){if(!e.objectStoreNames.contains(Wt.MESSAGES)){let t=e.createObjectStore(Wt.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(Wt.SESSIONS)||e.createObjectStore(Wt.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(Wt.TASKS)||e.createObjectStore(Wt.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(Wt.STATE)||e.createObjectStore(Wt.STATE,{keyPath:`key`})}function qt(e){let t=e.isMain??!1;return{jid:e.jid,name:e.name,folder:e.folder,trigger:t?void 0:e.trigger||`@${e.folder}`,requiresTrigger:!t&&(e.requiresTrigger??!0),isCone:t,type:t?`cone`:`scoop`,assistantLabel:t?`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 Jt(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(Wt.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);for(let t of e)r.put(qt(t))};return}t.objectStoreNames.contains(Wt.SCOOPS)||t.createObjectStore(Wt.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function Yt(e){e.objectStoreNames.contains(Wt.WEBHOOKS)||e.createObjectStore(Wt.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(Wt.CRONTASKS)||e.createObjectStore(Wt.CRONTASKS,{keyPath:`id`})}function Xt(e){let t=e.target.result,n=e.oldVersion;n<1&&Kt(t),n<2&&Jt(e,t),n<3&&Yt(t)}function Zt(){if(!Gt)return null;let e=Object.values(Wt).every(e=>Gt.objectStoreNames.contains(e));return Gt.version===3&&e?Gt:(Gt.close(),Gt=null,null)}function Qt(e){e.onversionchange=()=>{e.close(),Gt===e&&(Gt=null)},e.onclose=()=>{Gt===e&&(Gt=null)}}async function $t(){return Zt()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=Xt,n.onsuccess=()=>{let t=n.result;Qt(t),Gt=t,e(t)},n.onerror=()=>t(n.error)})}async function en(e,t=`readonly`){return(await $t()).transaction(e,t).objectStore(e)}async function tn(e){let t=await en(Wt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function nn(){let e=await en(Wt.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 rn(e){let t=await en(Wt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function an(){let e=await en(Wt.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function on(e){let t=(await en(Wt.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 sn(e){let t=await en(Wt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function cn(e){let t=await en(Wt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ln(e){let t=(await en(Wt.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)})}async function un(e,t,n){let r=(await en(Wt.MESSAGES)).index(`chatJid_timestamp`),i=IDBKeyRange.bound([e,t],[e,`￿`],!0,!1);return new Promise((e,t)=>{let a=r.getAll(i);a.onsuccess=()=>{let t=a.result;n&&(t=t.filter(e=>e.senderName!==n)),e(t)},a.onerror=()=>t(a.error)})}async function dn(e){let t=await en(Wt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function fn(e){let t=await en(Wt.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function pn(){let e=await en(Wt.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function mn(e){let t=await en(Wt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function hn(e){let t=await en(Wt.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 gn(e,t){let n=await en(Wt.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 _n(){await $t()}async function vn(e){let t=await en(Wt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function yn(){try{let e=await en(Wt.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function bn(e){let t=await en(Wt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function xn(e){let t=await en(Wt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Sn(){try{let e=await en(Wt.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Cn(e){let t=await en(Wt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}function wn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``,t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)||`/`);let n=t.toString();return n.endsWith(`/`)?n.slice(0,-1):n}catch{return null}}function Tn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.toString(),r=t.pathname.split(`/`).filter(Boolean);if(r.length<2||r.at(-2)!==`join`)return null;let[i,a,...o]=decodeURIComponent(r.at(-1)).split(`.`);if(!i||!a||o.length>0)return null;r.splice(-2,2),t.pathname=r.length>0?`/${r.join(`/`)}`:`/`;let s=wn(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}const En=`slicc.trayWorkerBaseUrl`,Dn=`slicc.trayJoinUrl`,On=`https://www.sliccy.ai`;function kn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=null;if(n.length>=2&&n.at(-2)===`tray`)r=decodeURIComponent(n.at(-1)),n.splice(-2,2),t.pathname=n.length>0?`/${n.join(`/`)}`:`/`;else if(n.length>=2&&n.at(-2)===`join`)return Tn(t.toString());let i=wn(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function An(e){let t=kn(e);return t?.joinUrl?t:null}i(`tray-leader`);let jn={state:`inactive`,session:null,error:null};function Mn(){return{...jn,session:jn.session?{...jn.session}:null}}function Nn(){let e=Mn();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.leaderTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Pn=new Set;function Fn(e){return Pn.add(e),()=>{Pn.delete(e)}}const In=`sessions`;function Ln(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(In)||e.createObjectStore(In,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Rn=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Ln();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(In,`readwrite`);i.objectStore(In).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(In,`readonly`).objectStore(In).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(In,`readonly`).objectStore(In).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(In,`readwrite`);i.objectStore(In).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};const zn=i(`offscreen-bridge`);function Bn(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 Vn=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;activeScoopJid=null;agentEventListeners=new Set;fanOutMessageId=new Map;constructor(e){this._transport=e??null}get transport(){return this._transport||=mt(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Rn;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.currentMessageId.get(t);if(n){let r=e.getBuffer(t).find(e=>e.id===n);r&&(r.isStreaming=!1),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Hn()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),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.scoopStatuses.set(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onToolStart:(t,n,r)=>{ht.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{ht.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=Ft(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Hn(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=Lt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Rt(n),isError:r})}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.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),this.scoopStatuses.delete(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[offscreen-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.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){let t=e.config&&(e.config.modelId!==void 0||e.config.thinkingLevel!==void 0)?{...e.config.modelId===void 0?{}:{modelId:e.config.modelId},...e.config.thinkingLevel===void 0?{}:{thinkingLevel:e.config.thinkingLevel}}:void 0;return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.scoopStatuses.get(e.jid)??`ready`,...t?{config:t}:{}}}buildStateSnapshot(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[],t=e.find(e=>e.isCone);return{type:`state-snapshot`,scoops:e,activeScoopJid:this.getActiveScoopJid()??t?.jid??null,trayRuntimeStatus:this.buildTrayRuntimeStatus()}}emitTrayRuntimeStatus(){let e=this.buildTrayRuntimeStatus(),t={type:`tray-runtime-status`,leader:e.leader,follower:e.follower};this.emit(t)}buildTrayRuntimeStatus(){let e=Mn(),t=Vt();return{leader:{state:e.state,session:e.session,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}}}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}onAgentEvent(e){return this.agentEventListeners.add(e),()=>{this.agentEventListeners.delete(e)}}fanOutAgentEvent(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.fanOutMessageId.get(t);return e||(e=`scoop-${t}-${Hn()}`,this.fanOutMessageId.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});break}case`tool_end`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let e=this.fanOutMessageId.get(t);if(!e)return;r.push({type:`content_done`,messageId:e}),this.fanOutMessageId.delete(t);break}case`turn_end`:this.fanOutMessageId.delete(t);break}for(let e of r)for(let n of this.agentEventListeners)try{n(t,e)}catch(e){zn.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Bn(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=Mt({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.fanOutMessageId.delete(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{zn.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??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`});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});break}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopStatuses.set(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-C2HxC1av.js`);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:!1}))}async seedBuffersFromAgentState(){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.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];t.length>0&&(this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){zn.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}handleRequestSessionStats(e){let t=0,n=[],r=[],i=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=e.reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getContextFills()??[],r=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),i=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,fills:n,models:r,scoops:i})}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:Un(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-C2HxC1av.js`),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Un(a)});return}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){zn.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}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}-${Hn()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){import(`./sprinkle-proxy-B4nH2NxC.js`).then(({handleSprinkleOpResponse:t})=>{t(e.payload)});return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[offscreen-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);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(`[offscreen-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();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-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[offscreen-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:{let t=e;try{await this.orchestrator.setScoopThinkingLevel(t.scoopJid,t.level)}catch(e){console.error(`[offscreen-bridge] set-thinking-level failed:`,e)}break}case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);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`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[offscreen-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));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear());break}}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[offscreen-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),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};await this.orchestrator?.handleMessage(t),this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.scoopStatuses.delete(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[offscreen-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.fanOutMessageId.delete(t)),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(`[offscreen-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[offscreen-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=globalThis.__slicc_lickManager;if(!t){console.warn(`[offscreen-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.emitEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[offscreen-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`){x.markMounted(t);return}try{await x.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[offscreen-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),x.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[offscreen-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.fanOutAgentEvent(e)}};function Hn(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Un(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
6
6
  `)}const Wn=i(`cdp`);var Gn=class{ws=null;nextId=1;_superseded=!1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,Wn.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Wn.error(`Connection failed`,{url:t}),this.cleanup(),i(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),Wn.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};return t&&(a.params=t),n&&(a.sessionId=n),Wn.debug(`Send`,{method:e,id:i,sessionId:n}),new Promise((t,n)=>{let o=setTimeout(()=>{this.pending.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`))},r);this.pending.set(i,{resolve:e=>{clearTimeout(o),t(e)},reject:e=>{clearTimeout(o),n(e)}}),this.ws.send(JSON.stringify(a))})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Wn.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Wn.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),n.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):n.resolve(e.result??{}));return}if(`method`in t){let e=t;Wn.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){let t=e===4001;t?(this._superseded=!0,Wn.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Wn.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;for(let[,e]of this.pending)e.reject(Error(n));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};const Kn=`(function() {
7
7
  'use strict';
8
8
 
@@ -7652,7 +7652,7 @@ Install:
7652
7652
  `,Wge=new Set([`iife`,`cjs`,`esm`]),i6=new Set([`linked`,`inline`,`external`,`both`]),Gge={"-h":`showHelp`,"--help":`showHelp`,"-v":`showVersion`,"--version":`showVersion`,"--bundle":`bundle`,"--transform":`transform`,"--minify":`minify`};function Kge(e){if(e.startsWith(`--`)){let t=e.indexOf(`=`);if(t>0)return{key:e.slice(0,t),inlineValue:e.slice(t+1)}}return{key:e,inlineValue:null}}function a6(e,t,n){if(e.inlineValue!==null)return{value:e.inlineValue,advance:0};let r=t[n+1];if(typeof r!=`string`||r.startsWith(`-`))throw Error(`esbuild: ${e.key} requires a value`);return{value:r,advance:1}}function qge(e,t,n,r){if(t.inlineValue!==null){if(!i6.has(t.inlineValue))throw Error(`esbuild: --sourcemap value must be one of linked|inline|external|both (got "${t.inlineValue}")`);return e.sourcemap=t.inlineValue,0}let i=n[r+1];return typeof i==`string`&&i6.has(i)?(e.sourcemap=i,1):(e.sourcemap=!0,0)}function Jge(e,t,n,r){if(t.key===`--outfile`){let{value:i,advance:a}=a6(t,n,r);return e.outfile=i,a}if(t.key===`--format`){let{value:i,advance:a}=a6(t,n,r);if(!Wge.has(i))throw Error(`esbuild: --format must be one of iife|cjs|esm (got "${i}")`);return e.format=i,a}if(t.key===`--target`){let{value:i,advance:a}=a6(t,n,r);return e.target=i.split(`,`).map(e=>e.trim()).filter(Boolean),a}if(t.key===`--loader`){let{value:i,advance:a}=a6(t,n,r);return e.loader=i,a}return-1}function Yge(e){let t={entries:[],bundle:!1,transform:!1,outfile:null,format:null,minify:!1,sourcemap:null,target:null,loader:null,showHelp:!1,showVersion:!1};for(let n=0;n<e.length;n++){let r=e[n],i=Gge[r];if(i){t[i]=!0;continue}let a=Kge(r);if(a.key===`--sourcemap`){n+=qge(t,a,e,n);continue}let o=Jge(t,a,e,n);if(o>=0){n+=o;continue}if(r.startsWith(`-`))throw Error(`esbuild: unknown option: ${r}`);t.entries.push(r)}return t}function Xge(e,t,n){return{name:`slicc-vfs`,setup(r){r.onResolve({filter:/.*/},async r=>{if(/^[a-z]+:/.test(r.path)&&!r.path.startsWith(`file:`))return{path:r.path,external:!0};if(r.path.startsWith(`./`)||r.path.startsWith(`../`)||r.path.startsWith(`/`)){let n=r.importer?.startsWith(`/`)?FK(r.importer):t;return{path:await Zge(e,e.resolvePath(n,r.path))}}let i=r.importer?.startsWith(`/`)?FK(r.importer):n.fromDir;try{let e=await AK(r.path,i,n.reader);return e.type===`file`?{path:e.path}:{path:r.path,external:!0}}catch(e){return{errors:[{text:e instanceof Error?e.message:String(e)}]}}}),r.onLoad({filter:/.*/},async t=>t.namespace&&t.namespace!==`file`?null:{contents:await e.readFile(t.path),loader:o6(t.path),resolveDir:FK(t.path)})}}}function o6(e){let t=PK(e).toLowerCase(),n=t.lastIndexOf(`.`);if(n<0)return`js`;switch(t.slice(n+1)){case`ts`:return`ts`;case`tsx`:return`tsx`;case`jsx`:return`jsx`;case`mjs`:case`cjs`:case`js`:return`js`;case`json`:return`json`;case`css`:return`css`;case`txt`:return`text`;default:return`js`}}async function Zge(e,t){if(await e.exists(t))try{if(!(await e.stat(t)).isDirectory)return t}catch{return t}let n=[`.ts`,`.tsx`,`.jsx`,`.mjs`,`.cjs`,`.js`,`.json`];for(let r of n){let n=`${t}${r}`;if(await e.exists(n))return n}for(let r of n){let n=IK(t,`index${r}`);if(await e.exists(n))return n}return t}async function s6(e,t,n){let r=[];if(n.length>0){let t=await e(n,{kind:`warning`,color:!1});r.push(t.join(``))}if(t.length>0){let n=await e(t,{kind:`error`,color:!1});r.push(n.join(``))}return r.join(``)}function Qge(){return cA(`esbuild`,async(e,t)=>{let n;try{n=Yge(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}if(n.showHelp||e.length===0&&!t.stdin)return{stdout:r6,stderr:``,exitCode:0};if(!n.transform&&!n.bundle&&n.entries.length>1)return{stdout:``,stderr:`esbuild: multiple entry points require --bundle (transform mode accepts at most one entry)
7653
7653
  `,exitCode:2};let r;try{r=await r1({ipk:n6(t)})}catch(e){return{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return n.showVersion?{stdout:`${r.version}\n`,stderr:``,exitCode:0}:n.transform||!n.bundle&&n.entries.length<=1?$ge(n,t,r):e_e(n,t,r)})}async function $ge(e,t,n){let r,i=`<stdin>`;if(e.entries.length===1){let n=t.fs.resolvePath(t.cwd,e.entries[0]);if(!await t.fs.exists(n))return{stdout:``,stderr:`esbuild: ${e.entries[0]}: no such file\n`,exitCode:1};r=await t.fs.readFile(n),i=n}else if(r=Z1(t.stdin),!r)return{stdout:r6,stderr:``,exitCode:0};let a={loader:e.loader??o6(i),sourcefile:i,...e.format?{format:e.format}:{},...e.minify?{minify:!0}:{},...e.sourcemap?{sourcemap:e.sourcemap}:{},...e.target?{target:e.target}:{}};try{let i=await n.transform(r,a),o=await s6(n.formatMessages,[],i.warnings);if(e.outfile){let n=t.fs.resolvePath(t.cwd,e.outfile);return await t.fs.writeFile(n,i.code),i.map&&e.sourcemap&&e.sourcemap!==`inline`&&await t.fs.writeFile(`${n}.map`,i.map),{stdout:``,stderr:o,exitCode:0}}return{stdout:i.code,stderr:o,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await s6(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function e_e(e,t,n){if(e.entries.length===0)return{stdout:``,stderr:`esbuild: --bundle requires at least one entry point
7654
7654
  `,exitCode:2};let r=e.entries.map(e=>t.fs.resolvePath(t.cwd,e));for(let e of r)if(!await t.fs.exists(e))return{stdout:``,stderr:`esbuild: ${e}: no such file\n`,exitCode:1};let i={entryPoints:r,bundle:!0,write:!1,plugins:[Xge(t.fs,t.cwd,n6(t))],format:e.format??`esm`,...e.minify?{minify:!0}:{},...e.sourcemap?{sourcemap:e.sourcemap}:{},...e.target?{target:e.target}:{}};try{let r=await n.build(i),a=await s6(n.formatMessages,r.errors,r.warnings),o=r.outputFiles??[];if(e.outfile){if(o.length===0)return{stdout:``,stderr:`esbuild: build produced no output
7655
- `,exitCode:1};let n=t.fs.resolvePath(t.cwd,e.outfile);await t.fs.writeFile(n,o[0].text);let r=FK(n);for(let e=1;e<o.length;e++){let n=o[e],i=IK(r,PK(n.path));await t.fs.writeFile(i,n.text)}return{stdout:``,stderr:a,exitCode:0}}return{stdout:o.map(e=>e.text).join(``),stderr:a,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await s6(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function t_e(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var n_e=class{ops(){return import(`./esptool-operations-BDGwK7S3.js`)}registry(){if(!T1())throw Error(`Web Serial is unavailable in this browser`);return D1()}async chipInfo(e,t,n){return(await this.ops()).esptoolChipInfo(this.registry(),e,t,n)}async readMac(e,t,n){return(await this.ops()).esptoolReadMac(this.registry(),e,t,n)}async eraseFlash(e,t,n){await(await this.ops()).esptoolEraseFlash(this.registry(),e,t,n)}async flash(e,t,n,r,i){await(await this.ops()).esptoolFlash(this.registry(),e,t,n,r,i)}async readFlash(e,t,n,r,i){return(await this.ops()).esptoolReadFlash(this.registry(),e,t,n,r,i)}async readReg(e,t,n,r){return(await this.ops()).esptoolReadReg(this.registry(),e,t,n,r)}async flashId(e,t,n){return(await this.ops()).esptoolFlashId(this.registry(),e,t,n)}async eraseRegion(e,t,n,r,i){await(await this.ops()).esptoolEraseRegion(this.registry(),e,t,n,r,i)}async run(e,t,n){await(await this.ops()).esptoolRun(this.registry(),e,t,n)}},r_e=class e{rpc;constructor(e){this.rpc=e}static INFO_TIMEOUT_MS=12e4;static ERASE_TIMEOUT_MS=3e5;static FLASH_TIMEOUT_MS=6e5;async withProgress(e,t,n){let r=this.rpc.onEvent(`esptool-progress`,n=>{let r=n;!r||r.handle!==e||t(r.line)});try{return await n()}finally{r()}}async chipInfo(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-chip-info`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async readMac(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-read-mac`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async eraseFlash(t,n,r){await this.withProgress(t,r,()=>this.rpc.call(`esptool-erase-flash`,{handle:t,baudRate:n},{timeoutMs:e.ERASE_TIMEOUT_MS}))}async flash(t,n,r,i,a){await this.withProgress(t,a,()=>this.rpc.call(`esptool-flash`,{handle:t,baudRate:n,eraseAll:r,segments:i.map(e=>({address:e.address,bytes:t_e(e.data)}))},{timeoutMs:e.FLASH_TIMEOUT_MS}))}async readFlash(t,n,r,i,a){let{bytes:o}=await this.withProgress(t,a,()=>this.rpc.call(`esptool-read-flash`,{handle:t,baudRate:n,address:r,size:i},{timeoutMs:e.FLASH_TIMEOUT_MS}));return new Uint8Array(o)}async readReg(t,n,r,i){return this.withProgress(t,i,()=>this.rpc.call(`esptool-read-reg`,{handle:t,baudRate:n,address:r},{timeoutMs:e.INFO_TIMEOUT_MS}))}async flashId(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-flash-id`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async eraseRegion(t,n,r,i,a){await this.withProgress(t,a,()=>this.rpc.call(`esptool-erase-region`,{handle:t,baudRate:n,address:r,size:i},{timeoutMs:e.ERASE_TIMEOUT_MS}))}async run(t,n,r){await this.withProgress(t,r,()=>this.rpc.call(`esptool-run`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}};function i_e(e,t){return e&&T1()?new n_e:t?new r_e(t):null}const a_e=new Set([`--vid`,`--pid`,`--baud`,`--data-bits`,`--stop-bits`,`--parity`,`--flow-control`,`--buffer-size`,`--bytes`,`--until`,`--timeout-ms`,`--dtr`,`--rts`,`--break`,`--__resolved`]);function o_e(e){return dW(e,a_e)}function c6(e,t){let n=/^0x/i.test(e)?parseInt(e,16):parseInt(e,10);if(!Number.isFinite(n)||Number.isNaN(n))throw Error(`invalid ${t}: '${e}'`);return n}function s_e(e){let t=e.replace(/0x/gi,``).replace(/[\s:,]/g,``);if(t.length===0)return new Uint8Array;if(t.length%2!=0||/[^0-9a-f]/i.test(t))throw Error(`invalid hex string: '${e}'`);let n=new Uint8Array(t.length/2);for(let e=0;e<n.length;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function l6(e){let t={};return e.has(`--vid`)&&(t.usbVendorId=c6(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.usbProductId=c6(e.get(`--pid`),`pid`)),Object.keys(t).length>0?[t]:[]}const c_e=new Set([`none`,`even`,`odd`]),l_e=new Set([`none`,`hardware`]);function u_e(e){let t={baudRate:e.has(`--baud`)?c6(e.get(`--baud`),`baud`):9600};if(e.has(`--data-bits`)&&(t.dataBits=c6(e.get(`--data-bits`),`data-bits`)),e.has(`--stop-bits`)&&(t.stopBits=c6(e.get(`--stop-bits`),`stop-bits`)),e.has(`--parity`)){let n=e.get(`--parity`);if(!c_e.has(n))throw Error(`invalid --parity: '${n}'`);t.parity=n}if(e.has(`--flow-control`)){let n=e.get(`--flow-control`);if(!l_e.has(n))throw Error(`invalid --flow-control: '${n}'`);t.flowControl=n}return e.has(`--buffer-size`)&&(t.bufferSize=c6(e.get(`--buffer-size`),`buffer-size`)),t}function d_e(e){let t={};return e.has(`--bytes`)&&(t.maxBytes=c6(e.get(`--bytes`),`bytes`)),e.has(`--until`)&&(t.until=s_e(e.get(`--until`))),e.has(`--timeout-ms`)&&(t.timeoutMs=c6(e.get(`--timeout-ms`),`timeout-ms`)),t}function u6(e,t){let n=e.toLowerCase();if(n===`on`||n===`true`||n===`1`)return!0;if(n===`off`||n===`false`||n===`0`)return!1;throw Error(`invalid ${t}: '${e}' (use on/off)`)}function f_e(e){let t={};return e.has(`--dtr`)&&(t.dataTerminalReady=u6(e.get(`--dtr`),`dtr`)),e.has(`--rts`)&&(t.requestToSend=u6(e.get(`--rts`),`rts`)),e.has(`--break`)&&(t.break=u6(e.get(`--break`),`break`)),t}function p_e(e){let t=Q1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function m_e(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function d6(e){return`0x${e.toString(16).padStart(4,`0`)}`}function f6(e){let t=e.usbVendorId!==void 0||e.usbProductId!==void 0?`${d6(e.usbVendorId??0)}:${d6(e.usbProductId??0)}`:`(native serial)`,n=e.opened?` [open]`:``;return`${e.handle}\t${t}${n}`}function h_e(e){return`cts=${+!!e.clearToSend} dcd=${+!!e.dataCarrierDetect} dsr=${+!!e.dataSetReady} ri=${+!!e.ringIndicator}\n`}function p6(e){return{stdout:e,stderr:``,exitCode:0}}function m6(e){return{stdout:``,stderr:`serial: ${e}\n`,exitCode:1}}const g_e=`serial - access serial ports via Web Serial
7655
+ `,exitCode:1};let n=t.fs.resolvePath(t.cwd,e.outfile);await t.fs.writeFile(n,o[0].text);let r=FK(n);for(let e=1;e<o.length;e++){let n=o[e],i=IK(r,PK(n.path));await t.fs.writeFile(i,n.text)}return{stdout:``,stderr:a,exitCode:0}}return{stdout:o.map(e=>e.text).join(``),stderr:a,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await s6(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function t_e(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var n_e=class{ops(){return import(`./esptool-operations-7rkaEUJC.js`)}registry(){if(!T1())throw Error(`Web Serial is unavailable in this browser`);return D1()}async chipInfo(e,t,n){return(await this.ops()).esptoolChipInfo(this.registry(),e,t,n)}async readMac(e,t,n){return(await this.ops()).esptoolReadMac(this.registry(),e,t,n)}async eraseFlash(e,t,n){await(await this.ops()).esptoolEraseFlash(this.registry(),e,t,n)}async flash(e,t,n,r,i){await(await this.ops()).esptoolFlash(this.registry(),e,t,n,r,i)}async readFlash(e,t,n,r,i){return(await this.ops()).esptoolReadFlash(this.registry(),e,t,n,r,i)}async readReg(e,t,n,r){return(await this.ops()).esptoolReadReg(this.registry(),e,t,n,r)}async flashId(e,t,n){return(await this.ops()).esptoolFlashId(this.registry(),e,t,n)}async eraseRegion(e,t,n,r,i){await(await this.ops()).esptoolEraseRegion(this.registry(),e,t,n,r,i)}async run(e,t,n){await(await this.ops()).esptoolRun(this.registry(),e,t,n)}},r_e=class e{rpc;constructor(e){this.rpc=e}static INFO_TIMEOUT_MS=12e4;static ERASE_TIMEOUT_MS=3e5;static FLASH_TIMEOUT_MS=6e5;async withProgress(e,t,n){let r=this.rpc.onEvent(`esptool-progress`,n=>{let r=n;!r||r.handle!==e||t(r.line)});try{return await n()}finally{r()}}async chipInfo(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-chip-info`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async readMac(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-read-mac`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async eraseFlash(t,n,r){await this.withProgress(t,r,()=>this.rpc.call(`esptool-erase-flash`,{handle:t,baudRate:n},{timeoutMs:e.ERASE_TIMEOUT_MS}))}async flash(t,n,r,i,a){await this.withProgress(t,a,()=>this.rpc.call(`esptool-flash`,{handle:t,baudRate:n,eraseAll:r,segments:i.map(e=>({address:e.address,bytes:t_e(e.data)}))},{timeoutMs:e.FLASH_TIMEOUT_MS}))}async readFlash(t,n,r,i,a){let{bytes:o}=await this.withProgress(t,a,()=>this.rpc.call(`esptool-read-flash`,{handle:t,baudRate:n,address:r,size:i},{timeoutMs:e.FLASH_TIMEOUT_MS}));return new Uint8Array(o)}async readReg(t,n,r,i){return this.withProgress(t,i,()=>this.rpc.call(`esptool-read-reg`,{handle:t,baudRate:n,address:r},{timeoutMs:e.INFO_TIMEOUT_MS}))}async flashId(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-flash-id`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async eraseRegion(t,n,r,i,a){await this.withProgress(t,a,()=>this.rpc.call(`esptool-erase-region`,{handle:t,baudRate:n,address:r,size:i},{timeoutMs:e.ERASE_TIMEOUT_MS}))}async run(t,n,r){await this.withProgress(t,r,()=>this.rpc.call(`esptool-run`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}};function i_e(e,t){return e&&T1()?new n_e:t?new r_e(t):null}const a_e=new Set([`--vid`,`--pid`,`--baud`,`--data-bits`,`--stop-bits`,`--parity`,`--flow-control`,`--buffer-size`,`--bytes`,`--until`,`--timeout-ms`,`--dtr`,`--rts`,`--break`,`--__resolved`]);function o_e(e){return dW(e,a_e)}function c6(e,t){let n=/^0x/i.test(e)?parseInt(e,16):parseInt(e,10);if(!Number.isFinite(n)||Number.isNaN(n))throw Error(`invalid ${t}: '${e}'`);return n}function s_e(e){let t=e.replace(/0x/gi,``).replace(/[\s:,]/g,``);if(t.length===0)return new Uint8Array;if(t.length%2!=0||/[^0-9a-f]/i.test(t))throw Error(`invalid hex string: '${e}'`);let n=new Uint8Array(t.length/2);for(let e=0;e<n.length;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function l6(e){let t={};return e.has(`--vid`)&&(t.usbVendorId=c6(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.usbProductId=c6(e.get(`--pid`),`pid`)),Object.keys(t).length>0?[t]:[]}const c_e=new Set([`none`,`even`,`odd`]),l_e=new Set([`none`,`hardware`]);function u_e(e){let t={baudRate:e.has(`--baud`)?c6(e.get(`--baud`),`baud`):9600};if(e.has(`--data-bits`)&&(t.dataBits=c6(e.get(`--data-bits`),`data-bits`)),e.has(`--stop-bits`)&&(t.stopBits=c6(e.get(`--stop-bits`),`stop-bits`)),e.has(`--parity`)){let n=e.get(`--parity`);if(!c_e.has(n))throw Error(`invalid --parity: '${n}'`);t.parity=n}if(e.has(`--flow-control`)){let n=e.get(`--flow-control`);if(!l_e.has(n))throw Error(`invalid --flow-control: '${n}'`);t.flowControl=n}return e.has(`--buffer-size`)&&(t.bufferSize=c6(e.get(`--buffer-size`),`buffer-size`)),t}function d_e(e){let t={};return e.has(`--bytes`)&&(t.maxBytes=c6(e.get(`--bytes`),`bytes`)),e.has(`--until`)&&(t.until=s_e(e.get(`--until`))),e.has(`--timeout-ms`)&&(t.timeoutMs=c6(e.get(`--timeout-ms`),`timeout-ms`)),t}function u6(e,t){let n=e.toLowerCase();if(n===`on`||n===`true`||n===`1`)return!0;if(n===`off`||n===`false`||n===`0`)return!1;throw Error(`invalid ${t}: '${e}' (use on/off)`)}function f_e(e){let t={};return e.has(`--dtr`)&&(t.dataTerminalReady=u6(e.get(`--dtr`),`dtr`)),e.has(`--rts`)&&(t.requestToSend=u6(e.get(`--rts`),`rts`)),e.has(`--break`)&&(t.break=u6(e.get(`--break`),`break`)),t}function p_e(e){let t=Q1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function m_e(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function d6(e){return`0x${e.toString(16).padStart(4,`0`)}`}function f6(e){let t=e.usbVendorId!==void 0||e.usbProductId!==void 0?`${d6(e.usbVendorId??0)}:${d6(e.usbProductId??0)}`:`(native serial)`,n=e.opened?` [open]`:``;return`${e.handle}\t${t}${n}`}function h_e(e){return`cts=${+!!e.clearToSend} dcd=${+!!e.dataCarrierDetect} dsr=${+!!e.dataSetReady} ri=${+!!e.ringIndicator}\n`}function p6(e){return{stdout:e,stderr:``,exitCode:0}}function m6(e){return{stdout:``,stderr:`serial: ${e}\n`,exitCode:1}}const g_e=`serial - access serial ports via Web Serial
7656
7656
 
7657
7657
  Usage: serial <subcommand> [options]
7658
7658
 
@@ -7805,8 +7805,8 @@ Options:
7805
7805
  `;case`idle`:return`enhanced engine: not downloaded (run hear --warmup)
7806
7806
  `;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`enhanced engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function F6(e){return{stdout:``,stderr:`hear: ${e}\n`,exitCode:1}}function I6(e){return e instanceof Error?e.message:String(e)}function L6(e){let t=e.map((e,t)=>`${e.deviceId}\t${e.label||`Microphone ${t+1}`}`);return t.join(`
7807
7807
  `)+(t.length?`
7808
- `:``)}async function Rve(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:L6((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:F6(`device enumeration unavailable`):{stdout:L6((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return F6(I6(e))}}async function zve(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-C3VIZSct.js`);return{stdout:P6(t?n():e()),stderr:``,exitCode:0}}return{stdout:P6(t?await e.panelRpc.call(`hear-warmup`,void 0):await e.panelRpc.call(`hear-status`,void 0)),stderr:``,exitCode:0}}catch(e){return F6(I6(e))}}async function Bve(e,t,n){let r=t.inputFile,i=n.fs.resolvePath(n.cwd,r),a;try{a=new Uint8Array(await n.fs.readFileBuffer(i))}catch{return F6(`cannot open ${r}: No such file`)}let o=VK(i);if(!o.startsWith(`audio/`)&&!o.startsWith(`video/`))return F6(`${r} is not an audio file`);let s=new ArrayBuffer(a.byteLength);new Uint8Array(s).set(a);try{return{stdout:(e.local?await(await import(`./hear-C3VIZSct.js`)).hearTranscribe(s,t.lang):await e.panelRpc.call(`hear-transcribe`,{bytes:s,lang:t.lang},{timeoutMs:6e5})).transcript+`
7809
- `,stderr:``,exitCode:0}}catch(e){return F6(`transcription failed: ${I6(e)}`)}}async function Vve(e,t){let n=Math.round(t.timeoutSeconds*1e3);try{let r={lang:t.lang,timeoutMs:n,deviceId:t.deviceId,engine:t.engine},i=e.local?await(await import(`./hear-C3VIZSct.js`)).hearCapture(r):await e.panelRpc.call(`hear-capture`,r,{timeoutMs:n+3e4});return i.transcript?{stdout:i.transcript+`
7808
+ `:``)}async function Rve(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:L6((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:F6(`device enumeration unavailable`):{stdout:L6((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return F6(I6(e))}}async function zve(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-BxIJ679h.js`);return{stdout:P6(t?n():e()),stderr:``,exitCode:0}}return{stdout:P6(t?await e.panelRpc.call(`hear-warmup`,void 0):await e.panelRpc.call(`hear-status`,void 0)),stderr:``,exitCode:0}}catch(e){return F6(I6(e))}}async function Bve(e,t,n){let r=t.inputFile,i=n.fs.resolvePath(n.cwd,r),a;try{a=new Uint8Array(await n.fs.readFileBuffer(i))}catch{return F6(`cannot open ${r}: No such file`)}let o=VK(i);if(!o.startsWith(`audio/`)&&!o.startsWith(`video/`))return F6(`${r} is not an audio file`);let s=new ArrayBuffer(a.byteLength);new Uint8Array(s).set(a);try{return{stdout:(e.local?await(await import(`./hear-BxIJ679h.js`)).hearTranscribe(s,t.lang):await e.panelRpc.call(`hear-transcribe`,{bytes:s,lang:t.lang},{timeoutMs:6e5})).transcript+`
7809
+ `,stderr:``,exitCode:0}}catch(e){return F6(`transcription failed: ${I6(e)}`)}}async function Vve(e,t){let n=Math.round(t.timeoutSeconds*1e3);try{let r={lang:t.lang,timeoutMs:n,deviceId:t.deviceId,engine:t.engine},i=e.local?await(await import(`./hear-BxIJ679h.js`)).hearCapture(r):await e.panelRpc.call(`hear-capture`,r,{timeoutMs:n+3e4});return i.transcript?{stdout:i.transcript+`
7810
7810
  `,stderr:``,exitCode:0}:{stdout:``,stderr:`hear: no speech detected
7811
7811
  `,exitCode:1}}catch(e){return F6(I6(e))}}function Hve(){return cA(`hear`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return Pve();let n=Lve(e);if(`exitCode`in n)return n;let r={local:de(),panelRpc:ue()};return!r.local&&!r.panelRpc?F6(`speech recognition unavailable in this environment`):n.devices?Rve(r):n.status||n.warmup?zve(r,n.warmup):n.inputFile?Bve(r,n,t):Vve(r,n)})}const R6=[`playwright-cli`,`playwright`,`puppeteer`],z6=new WeakMap;function Uve(e,t){let n=z6.get(e);n||(n=new WeakMap,z6.set(e,n));let r=n.get(t);return r||(r={snapshots:new Map,appTabId:null,harRecorder:null,sessionDirsCreated:!1,teleportWatchers:new Map},n.set(t,r)),r}function B6(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}const Wve=l,Gve=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`]);function V6(e){return e.toISOString().replace(/:/g,`-`)}function Kve(e){return e instanceof O||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}const H6=`function(text) {
7812
7812
  const el = this;
@@ -8329,20 +8329,20 @@ authorization-code flow, stores the access token, and retries.
8329
8329
  On success, the server is persisted to /workspace/.mcp/servers.json and
8330
8330
  an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
8331
8331
  short name resolves on the PATH.
8332
- `);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return R5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return R5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return R5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-D7gdAWiV.js`).then(e=>e.r);if(await a(i,t.fs))return R5(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>k5),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await iSe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>H5(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await SSe(i,t);let m=await G5(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-bddnu4fF.js`);e({name:i,serverUrl:r,auth:u})}return L5([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${I5}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
8332
+ `);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return R5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return R5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return R5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-CfsRJWtN.js`).then(e=>e.r);if(await a(i,t.fs))return R5(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>k5),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await iSe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>H5(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await SSe(i,t);let m=await G5(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-BcaFySUk.js`);e({name:i,serverUrl:r,auth:u})}return L5([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${I5}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
8333
8333
  `)+`
8334
8334
  `)}async function iSe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await Promise.resolve().then(()=>y6),c=await bSe(r.oauthFetchImpl),l=r.oauthLauncher??await U5(),u=await i(e,n,c);F5.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await ySe(),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function aSe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return L5(`usage: mcp list
8335
- `);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-bddnu4fF.js`);await n();let{listServers:r}=await import(`./store-D7gdAWiV.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return L5("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return L5(z5(o))}function z5(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
8335
+ `);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-BcaFySUk.js`);await n();let{listServers:r}=await import(`./store-CfsRJWtN.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return L5("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return L5(z5(o))}function z5(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
8336
8336
  `)+`
8337
8337
  `}async function oSe(e,t){if(e[0]===`--help`||e[0]===`-h`)return L5(`usage: mcp search <query>
8338
8338
 
8339
8339
  Case-insensitive substring search across the cached tools of every
8340
8340
  registered MCP server. Matches tool name OR description and prints a
8341
8341
  table of (server, tool, description, match-field) rows.
8342
- `);if(e.length===0)return R5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-bddnu4fF.js`);await i();let{listServers:a}=await import(`./store-D7gdAWiV.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return L5("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return L5(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,sSe(e.description),e.match]);return L5(z5(l))}function sSe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function cSe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?R5(`mcp delete: expected <name>`):L5(`usage: mcp delete <name>
8343
- `);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-bddnu4fF.js`);await r(n);let{deleteServer:a}=await import(`./store-D7gdAWiV.js`).then(e=>e.r),o=await a(n,t.fs);await CSe(n,t),await wSe(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await Promise.resolve().then(()=>y6);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){F5.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?R5(`mcp delete: no server, alias, or account found for "${n}"`):L5([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
8342
+ `);if(e.length===0)return R5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-BcaFySUk.js`);await i();let{listServers:a}=await import(`./store-CfsRJWtN.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return L5("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return L5(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,sSe(e.description),e.match]);return L5(z5(l))}function sSe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function cSe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?R5(`mcp delete: expected <name>`):L5(`usage: mcp delete <name>
8343
+ `);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-BcaFySUk.js`);await r(n);let{deleteServer:a}=await import(`./store-CfsRJWtN.js`).then(e=>e.r),o=await a(n,t.fs);await CSe(n,t),await wSe(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await Promise.resolve().then(()=>y6);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){F5.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?R5(`mcp delete: no server, alias, or account found for "${n}"`):L5([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
8344
8344
  `)+`
8345
- `)}async function lSe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?R5(`mcp invoke: expected <name>`):L5(dSe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-bddnu4fF.js`);await i(n);let{getServer:a}=await import(`./store-D7gdAWiV.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return R5(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return L5(fSe(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return R5(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=uSe(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return L5(pSe(n,l));let p=mSe(d,l.inputSchema);if(!p.ok)return R5(`mcp invoke: ${p.error}`);let{McpClient:m}=await Promise.resolve().then(()=>k5),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>H5(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=gSe(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function uSe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=B5(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=B5(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function B5(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function dSe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
8345
+ `)}async function lSe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?R5(`mcp invoke: expected <name>`):L5(dSe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-BcaFySUk.js`);await i(n);let{getServer:a}=await import(`./store-CfsRJWtN.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return R5(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return L5(fSe(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return R5(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=uSe(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return L5(pSe(n,l));let p=mSe(d,l.inputSchema);if(!p.ok)return R5(`mcp invoke: ${p.error}`);let{McpClient:m}=await Promise.resolve().then(()=>k5),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>H5(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=gSe(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function uSe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=B5(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=B5(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function B5(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function dSe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
8346
8346
 
8347
8347
  mcp invoke <name> List tools on <name>.
8348
8348
  mcp invoke <name> <tool> --help Show flags for <tool>.
@@ -8372,7 +8372,7 @@ Arguments are coerced according to the tool's JSON Schema:
8372
8372
 
8373
8373
  Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
8374
8374
  OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
8375
- `);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-bddnu4fF.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-D7gdAWiV.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return R5(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>k5),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>H5(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return R5(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,sessionId:void 0,tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await G5(n,d,t);return L5(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function vSe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return L5(`usage: mcp auth <name> [--silent | --interactive]
8375
+ `);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-BcaFySUk.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-CfsRJWtN.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return R5(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>k5),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>H5(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return R5(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,sessionId:void 0,tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await G5(n,d,t);return L5(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function vSe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return L5(`usage: mcp auth <name> [--silent | --interactive]
8376
8376
 
8377
8377
  Re-authenticate an existing MCP server. By default, attempts a silent
8378
8378
  token renewal using the persisted refresh_token; if that returns no
@@ -8384,7 +8384,7 @@ Options:
8384
8384
  -i, --interactive Skip silent renewal and open the OAuth popup
8385
8385
  directly. Use after revoking a refresh token or
8386
8386
  when the AS no longer accepts the cached one.
8387
- `);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return R5(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return R5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-bddnu4fF.js`),s=await o(r),{getServer:c}=await import(`./store-D7gdAWiV.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return R5(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return R5(`mcp auth: server "${r}" does not use OAuth`);if(!s)return R5(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-BcBKUoGy.js`).then(e=>e.r),f=d(u);if(!f)return R5(`mcp auth: provider "${u}" is not registered`);if(a)return await V5(r,f,t);if(!f.onSilentRenew)return i?R5(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await V5(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return R5(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);F5.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?L5(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?R5(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await V5(r,f,t)}async function V5(e,t,n){if(!t.onOAuthLogin)return R5(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await U5(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?L5(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):R5(`mcp auth: interactive login for "${e}" did not complete`)}async function H5(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await Promise.resolve().then(()=>y6),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-BcBKUoGy.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){F5.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function U5(){let{createOAuthLauncher:e}=await import(`./oauth-service-D-lmxdpH.js`);return e()}async function ySe(){let e=typeof chrome<`u`?chrome:void 0;if(e?.runtime?.id)return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`;let{getOAuthPageOrigin:t}=await import(`./oauth-service-D-lmxdpH.js`),{origin:n}=await t();return`${n}/auth/callback`}async function bSe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-I4cndszg.js`).then(e=>e.a),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function W5(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-BOToGWsE.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await Promise.resolve().then(()=>oW);return await t.create({dbName:n})}function xSe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
8387
+ `);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return R5(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return R5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-BcaFySUk.js`),s=await o(r),{getServer:c}=await import(`./store-CfsRJWtN.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return R5(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return R5(`mcp auth: server "${r}" does not use OAuth`);if(!s)return R5(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-Cfi3--kj.js`).then(e=>e.r),f=d(u);if(!f)return R5(`mcp auth: provider "${u}" is not registered`);if(a)return await V5(r,f,t);if(!f.onSilentRenew)return i?R5(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await V5(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return R5(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);F5.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?L5(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?R5(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await V5(r,f,t)}async function V5(e,t,n){if(!t.onOAuthLogin)return R5(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await U5(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?L5(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):R5(`mcp auth: interactive login for "${e}" did not complete`)}async function H5(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await Promise.resolve().then(()=>y6),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-Cfi3--kj.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){F5.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function U5(){let{createOAuthLauncher:e}=await import(`./oauth-service-D-lmxdpH.js`);return e()}async function ySe(){let e=typeof chrome<`u`?chrome:void 0;if(e?.runtime?.id)return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`;let{getOAuthPageOrigin:t}=await import(`./oauth-service-D-lmxdpH.js`),{origin:n}=await t();return`${n}/auth/callback`}async function bSe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-I4cndszg.js`).then(e=>e.a),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function W5(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-DBM0MxFX.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await Promise.resolve().then(()=>oW);return await t.create({dbName:n})}function xSe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
8388
8388
  // Auto-generated by \`mcp add ${e}\`; do not edit by hand.
8389
8389
  const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
8390
8390
  const escape = (s) => {
@@ -8398,7 +8398,7 @@ const r = await exec(cmd);
8398
8398
  if (r.stdout) process.stdout.write(r.stdout);
8399
8399
  if (r.stderr) process.stderr.write(r.stderr);
8400
8400
  process.exit(r.exitCode || 0);
8401
- `}async function SSe(e,t){let n=await W5(t.fs);await n.mkdir(I5,{recursive:!0}),await n.writeFile(`${I5}/${e}.jsh`,xSe(e)),t.scriptCatalog?.invalidateJsh()}async function CSe(e,t){let n=await W5(t.fs),r=`${I5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){F5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function wSe(e,t){let{removeAppSprinkles:n}=await import(`./apps-DFoUcI2B.js`);await n(e,t.fs)}async function G5(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-DFoUcI2B.js`);return(await r(e,t,n.fs)).length}catch(t){return F5.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const K5=`/.cache/artificial-analysis.json`;async function TSe(e,t=!1){if(e&&!t)try{let t=await e.readFile(K5),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=f(),a;try{a=await i(`https://artificialanalysis.ai/api/v2/data/llms/models`,{method:`GET`,headers:r})}catch{return[]}if(a.status===401||a.status<200||a.status>=300)return[];let o;try{let e=new TextDecoder().decode(a.body);o=JSON.parse(e)}catch{return[]}let s=(Array.isArray(o)?o:o?.data??o?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&s.length>0){let t={fetchedAt:Date.now(),models:s};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(K5,JSON.stringify(t))}catch{}}return s}function q5(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function ESe(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=q5(e),a=t.find(e=>q5(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function DSe(){return`models - list available LLM models
8401
+ `}async function SSe(e,t){let n=await W5(t.fs);await n.mkdir(I5,{recursive:!0}),await n.writeFile(`${I5}/${e}.jsh`,xSe(e)),t.scriptCatalog?.invalidateJsh()}async function CSe(e,t){let n=await W5(t.fs),r=`${I5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){F5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function wSe(e,t){let{removeAppSprinkles:n}=await import(`./apps-BC_uzGPk.js`);await n(e,t.fs)}async function G5(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-BC_uzGPk.js`);return(await r(e,t,n.fs)).length}catch(t){return F5.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const K5=`/.cache/artificial-analysis.json`;async function TSe(e,t=!1){if(e&&!t)try{let t=await e.readFile(K5),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=f(),a;try{a=await i(`https://artificialanalysis.ai/api/v2/data/llms/models`,{method:`GET`,headers:r})}catch{return[]}if(a.status===401||a.status<200||a.status>=300)return[];let o;try{let e=new TextDecoder().decode(a.body);o=JSON.parse(e)}catch{return[]}let s=(Array.isArray(o)?o:o?.data??o?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&s.length>0){let t={fetchedAt:Date.now(),models:s};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(K5,JSON.stringify(t))}catch{}}return s}function q5(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function ESe(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=q5(e),a=t.find(e=>q5(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function DSe(){return`models - list available LLM models
8402
8402
 
8403
8403
  Usage: models [options]
8404
8404
 
@@ -8511,11 +8511,11 @@ Examples:
8511
8511
  --authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
8512
8512
  --redirect-pattern 'http://127.0.0.1:56121/*'
8513
8513
  curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
8514
- `}function WSe(){return cA(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await Promise.resolve().then(()=>y6),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-BcBKUoGy.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:USe(),stderr:``,exitCode:0};if(e.includes(`--list`))return qSe(i,o,a,n);if(e.includes(`--renew`))return GSe(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return KSe(e,t);let s,c=e.indexOf(`--scope`);if(c>=0){if(s=e[c+1]?.trim(),!s||s.startsWith(`-`))return{stdout:``,stderr:`oauth-token: --scope requires a value
8514
+ `}function WSe(){return cA(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await Promise.resolve().then(()=>y6),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-Cfi3--kj.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:USe(),stderr:``,exitCode:0};if(e.includes(`--list`))return qSe(i,o,a,n);if(e.includes(`--renew`))return GSe(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return KSe(e,t);let s,c=e.indexOf(`--scope`);if(c>=0){if(s=e[c+1]?.trim(),!s||s.startsWith(`-`))return{stdout:``,stderr:`oauth-token: --scope requires a value
8515
8515
  `,exitCode:1};e.splice(c,2)}let l,u=e.indexOf(`--provider`);if(u>=0){if(l=e[u+1],!l)return{stdout:``,stderr:`oauth-token: --provider requires a value
8516
8516
  `,exitCode:1}}else if(e.length>0)l=e[0];else{let e=r(),t=a(e);if(t?.isOAuth&&(t.onOAuthLogin||t.onOAuthLoginIntercepted))l=e;else if(l=o().find(e=>{let t=a(e);return t?.isOAuth&&(t.onOAuthLogin||t.onOAuthLoginIntercepted)}),!l)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
8517
8517
  `,exitCode:1}}let d=a(l);if(!d)return{stdout:``,stderr:`oauth-token: unknown provider "${l}"\n`,exitCode:1};if(!d.isOAuth||!d.onOAuthLogin&&!d.onOAuthLoginIntercepted)return{stdout:``,stderr:`oauth-token: provider "${l}" is not an OAuth provider\n`,exitCode:1};if(!s){let e=n(l);if(e&&!e.expired){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${l} (try logging in again)\n`,exitCode:1}}}try{if(d.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:e}=await import(`./oauth-service-D-lmxdpH.js`),t=await e();if(!t)return{stdout:``,stderr:`oauth-token: provider "${l}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.\n`,exitCode:1};await d.onOAuthLoginIntercepted(t,()=>{},s?{scopes:s}:void 0)}else if(d.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-D-lmxdpH.js`),t=e();await d.onOAuthLogin(t,()=>{},s?{scopes:s}:void 0)}else return{stdout:``,stderr:`oauth-token: provider "${l}" has no OAuth login hook\n`,exitCode:1};let e=n(l);if(e?.token){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${l} (try logging in again)\n`,exitCode:1}}return console.error(`[oauth-token] Provider ${l}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
8518
- `,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${l}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}async function GSe(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await Promise.resolve().then(()=>y6),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-BcBKUoGy.js`).then(e=>e.r),a=e.filter(e=>!e.startsWith(`-`))[0];if(!a){let e=t();a=r(e)?.onSilentRenew?e:i().find(e=>r(e)?.onSilentRenew)}if(!a)return Q5(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return Q5(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return Q5(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${X5(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${X5(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
8518
+ `,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${l}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}async function GSe(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await Promise.resolve().then(()=>y6),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-Cfi3--kj.js`).then(e=>e.r),a=e.filter(e=>!e.startsWith(`-`))[0];if(!a){let e=t();a=r(e)?.onSilentRenew?e:i().find(e=>r(e)?.onSilentRenew)}if(!a)return Q5(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return Q5(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return Q5(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${X5(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${X5(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
8519
8519
  `)+`
8520
8520
  `,stderr:``,exitCode:+!u}}function X5(e){if(!e)return`no token`;if(e.expired)return`expired`;if(e.expiresAt){let t=e.expiresAt-Date.now();if(t>0){let e=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4);return e>0?`valid, expires in ${e}h ${n}m`:`valid, expires in ${n}m`}}return`valid`}async function KSe(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-E9BfBX02.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-D-lmxdpH.js`),i,a=e.indexOf(`--from-file`);if(a>=0){let n=e[a+1];if(!n)return Q5(`oauth-token: --from-file requires a path`);try{let e=t.fs.resolvePath(t.cwd,n),r=await t.fs.readFile(e);i=JSON.parse(typeof r==`string`?r:new TextDecoder().decode(r))}catch(e){return Q5(`oauth-token: failed to read ${n}: ${e instanceof Error?e.message:String(e)}`)}}else{let t=Z5(e,`--authorize-url`),n=Z5(e,`--redirect-pattern`);if(!t)return Q5(`oauth-token: --authorize-url is required`);if(!n)return Q5(`oauth-token: --redirect-pattern is required`);let r=[];for(let t=0;t<e.length;t++){if(e[t]!==`--rewrite`)continue;let n=e[t+1];if(!n)return Q5(`oauth-token: --rewrite requires a value`);let i=n.split(`=`);if(i.length<3)return Q5(`oauth-token: --rewrite "${n}" must be "<match>=<key>=<value>"`);let[a,o,...s]=i;r.push({match:a,appendParams:{[o]:s.join(`=`)}})}i={authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.length>0?{rewrite:r}:{}}}let o=n(i);if(!o.ok)return Q5(`oauth-token: invalid intercept config: ${o.error}`);let s=await r();if(!s)return Q5(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let c=await s(o.config);return c?{stdout:`${c}\n`,stderr:``,exitCode:0}:Q5(`oauth-token: intercept timed out or was cancelled`)}function Z5(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function Q5(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function qSe(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
8521
8521
  `,stderr:``,exitCode:0};let a=[];for(let e of i){let t=r(e);if(!t)a.push(`${e} (no token)`);else if(t.expired){let n=t.userName?` as ${t.userName}`:``;a.push(`${e} (expired${n})`)}else{let n=[];if(t.userName?n.push(`logged in as ${t.userName}`):n.push(`logged in`),t.expiresAt){let e=t.expiresAt-Date.now();if(e>0){let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4);t>0?n.push(`expires in ${t}h`):n.push(`expires in ${r}m`)}}a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
@@ -8639,7 +8639,7 @@ Examples:
8639
8639
  `)+`
8640
8640
  `,stderr:``,exitCode:0}}function VCe(e={}){let t=e.fs,n=e.getSendFsRequest??FCe;return cA(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return p7();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
8641
8641
  `,exitCode:1};let r=n();if(!r)return{stdout:``,stderr:`rsync: not connected to a tray — rsync requires a tray connection
8642
- `,exitCode:1};let i=ICe(e);if(`error`in i)return i.error===`__help__`?p7():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await zCe(t,r,i):await BCe(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function _7(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [--list] <text>
8642
+ `,exitCode:1};let i=ICe(e);if(`error`in i)return i.error===`__help__`?p7():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await zCe(t,r,i):await BCe(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function _7(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [-o file] [--list] <text>
8643
8643
  say --status | --warmup
8644
8644
 
8645
8645
  Speaks the given text. Uses on-device Kokoro voices when the model
@@ -8650,6 +8650,8 @@ Examples:
8650
8650
  once the model is ready)
8651
8651
  -r rate Speech rate (0.1 to 10, default 1)
8652
8652
  -l lang Language tag (required, BCP 47, e.g. en-US, es-ES, fr-FR)
8653
+ -o file Write 16-bit mono WAV to <file> instead of playing it out
8654
+ loud (kokoro-only, English-only; --out is an alias)
8653
8655
  --list List voices with an engine marker ([kokoro] = on-device,
8654
8656
  [web speech] otherwise); kokoro voices lead when ready
8655
8657
  --status Show the on-device voice state (downloading/ready + ETA)
@@ -8657,11 +8659,11 @@ Examples:
8657
8659
  `,stderr:``,exitCode:0}}function v7(e){switch(e.state){case`ready`:return`voice engine: ready
8658
8660
  `;case`failed`:return`voice engine: failed (re-run say --warmup to retry)
8659
8661
  `;case`idle`:return`voice engine: not downloaded (run say --warmup)
8660
- `;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`voice engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function y7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function b7(e){return e instanceof Error?e.message:String(e)}let x7=!1,S7=null;function C7(){return x7?Promise.resolve(speechSynthesis.getVoices()):(S7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){x7=!0,e(t);return}let n=()=>{x7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),x7=!0,e(speechSynthesis.getVoices())},1e3)}),S7)}const w7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`};function HCe(e,t,n){switch(t){case`-v`:return e.voiceName=n,null;case`-l`:return e.lang=n,null;case`-r`:{let t=parseFloat(n);return Number.isNaN(t)||t<.1||t>10?`rate must be between 0.1 and 10`:(e.rate=t,null)}default:return`unknown option: ${t}`}}function UCe(e){let t={voiceName:null,rate:1,lang:null,text:``},n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i in w7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return y7(`${i} requires ${w7[i]}`);let a=HCe(t,i,n);if(a)return y7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return y7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function T7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function WCe(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-BGc6bNZS.js`),t=e().map(e=>T7({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await C7()).map(e=>T7({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
8662
+ `;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`voice engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function y7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function b7(e){return e instanceof Error?e.message:String(e)}let x7=!1,S7=null;function C7(){return x7?Promise.resolve(speechSynthesis.getVoices()):(S7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){x7=!0,e(t);return}let n=()=>{x7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),x7=!0,e(speechSynthesis.getVoices())},1e3)}),S7)}const w7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function HCe(e,t,n){switch(t){case`-v`:return e.voiceName=n,null;case`-l`:return e.lang=n,null;case`-o`:case`--out`:return e.outFile=n,null;case`-r`:{let t=parseFloat(n);return Number.isNaN(t)||t<.1||t>10?`rate must be between 0.1 and 10`:(e.rate=t,null)}default:return`unknown option: ${t}`}}function UCe(e){let t={voiceName:null,rate:1,lang:null,outFile:null,text:``},n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i in w7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return y7(`${i} requires ${w7[i]}`);let a=HCe(t,i,n);if(a)return y7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return y7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function T7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function WCe(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-BhvC2qYp.js`),t=e().map(e=>T7({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await C7()).map(e=>T7({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
8661
8663
  `)+`
8662
8664
  `,stderr:``,exitCode:0}}try{return{stdout:(await e.panelRpc.call(`list-voices`,void 0)).voices.map(e=>T7(e)).join(`
8663
8665
  `)+`
8664
- `,stderr:``,exitCode:0}}catch(e){return y7(b7(e))}}async function GCe(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-BGc6bNZS.js`),n=t().map(e=>({name:e.id})),r=(await C7()).map(e=>({name:e.name}));return[...n,...r]}async function KCe(e,t){let n=(await GCe(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:y7(`voice "${t}" not found. Use --list to see available voices.`)}}async function E7(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speak-BGc6bNZS.js`);return{stdout:v7(t?n():e()),stderr:``,exitCode:0}}return{stdout:v7(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return y7(b7(e))}}async function qCe(e,t){return t.includes(`--list`)?WCe(e):t.includes(`--status`)?E7(e,!1):t.includes(`--warmup`)?E7(e,!0):null}async function JCe(e){try{let{speak:t}=await import(`./speak-BGc6bNZS.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return y7(`speech synthesis error: ${b7(e)}`)}}async function YCe(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(e){return y7(b7(e))}}function XCe(){return cA(`say`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return _7();let t={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:ue()};if(!t.local&&!t.panelRpc)return y7(`Web Speech API unavailable in this environment`);let n=await qCe(t,e);if(n)return n;let r=UCe(e);if(`exitCode`in r)return r;if(!r.text)return _7();if(!r.lang)return y7(`-l language tag is required`);let i;if(r.voiceName){let{resolved:e,error:n}=await KCe(t,r.voiceName);if(n)return n;i=e}let a={text:r.text,lang:r.lang,voice:i,rate:r.rate};return t.local?JCe(a):YCe(t,a)})}function ZCe(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
8666
+ `,stderr:``,exitCode:0}}catch(e){return y7(b7(e))}}async function GCe(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-BhvC2qYp.js`),n=t().map(e=>({name:e.id})),r=(await C7()).map(e=>({name:e.name}));return[...n,...r]}async function KCe(e,t){let n=(await GCe(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:y7(`voice "${t}" not found. Use --list to see available voices.`)}}async function E7(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speak-BhvC2qYp.js`);return{stdout:v7(t?n():e()),stderr:``,exitCode:0}}return{stdout:v7(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return y7(b7(e))}}async function qCe(e,t){return t.includes(`--list`)?WCe(e):t.includes(`--status`)?E7(e,!1):t.includes(`--warmup`)?E7(e,!0):null}async function JCe(e){try{let{speak:t}=await import(`./speak-BhvC2qYp.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return y7(`speech synthesis error: ${b7(e)}`)}}async function YCe(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(e){return y7(b7(e))}}async function XCe(e){let{synthesizeToWav:t}=await import(`./speak-BhvC2qYp.js`);try{return{bytes:await t(e)}}catch(e){return y7(b7(e))}}async function ZCe(e,t){try{let n=await e.panelRpc.call(`synthesize-to-wav`,{text:t.text,lang:t.lang,...t.voice?{voice:t.voice}:{},rate:t.rate},{timeoutMs:5*6e4});return{bytes:new Uint8Array(n.bytes)}}catch(e){return y7(b7(e))}}async function QCe(e,t,n,r){let i=e.local?await XCe(r):await ZCe(e,r);if(`exitCode`in i)return i;let a=t.fs.resolvePath(t.cwd,n);try{await t.fs.writeFile(a,i.bytes)}catch(e){return y7(`failed to write ${n}: ${b7(e)}`)}return{stdout:`wrote ${Math.max(1,Math.round(i.bytes.byteLength/1024))} KB to ${a}\n`,stderr:``,exitCode:0}}function $Ce(){return cA(`say`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return _7();let n={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:ue()};if(!n.local&&!n.panelRpc)return y7(`Web Speech API unavailable in this environment`);let r=await qCe(n,e);if(r)return r;let i=UCe(e);if(`exitCode`in i)return i;if(!i.text)return _7();if(!i.lang)return y7(`-l language tag is required`);let a;if(i.voiceName){let{resolved:e,error:t}=await KCe(n,i.voiceName);if(t)return t;a=e}let o={text:i.text,lang:i.lang,voice:a,rate:i.rate};return i.outFile?QCe(n,t,i.outFile,o):n.local?JCe(o):YCe(n,o)})}function ewe(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
8665
8667
 
8666
8668
  Usage: screencapture [options] <output-file>
8667
8669
 
@@ -8677,12 +8679,12 @@ Examples:
8677
8679
  screencapture screenshot.png # Capture to file
8678
8680
  screencapture -c # Capture to clipboard
8679
8681
  screencapture -v capture.png # Capture and return for agent vision
8680
- `,stderr:``,exitCode:0}}function QCe(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function $Ce(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function ewe(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>r.play().then(()=>e()).catch(t),r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>setTimeout(e,100));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);s.drawImage(r,0,0,i,a);let c=await new Promise((n,r)=>{o.toBlob(e=>e?n(e):r(Error(`Failed to create image blob`)),e,t)});return{bytes:new Uint8Array(await c.arrayBuffer()),mimeType:e}}finally{n.getTracks().forEach(e=>{e.stop()})}}function twe(){return cA(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return ZCe();let n=de(),r=ue();if(!n&&!r)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
8682
+ `,stderr:``,exitCode:0}}function twe(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function nwe(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function rwe(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>r.play().then(()=>e()).catch(t),r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>setTimeout(e,100));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);s.drawImage(r,0,0,i,a);let c=await new Promise((n,r)=>{o.toBlob(e=>e?n(e):r(Error(`Failed to create image blob`)),e,t)});return{bytes:new Uint8Array(await c.arrayBuffer()),mimeType:e}}finally{n.getTracks().forEach(e=>{e.stop()})}}function iwe(){return cA(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return ewe();let n=de(),r=ue();if(!n&&!r)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
8681
8683
  `,exitCode:1};if(n&&!x6()&&!navigator.mediaDevices?.getDisplayMedia)return{stdout:``,stderr:`screencapture: screen capture is not supported in this browser
8682
8684
  `,exitCode:1};let i=e.includes(`--clipboard`)||e.includes(`-c`),a=e.includes(`--view`)||e.includes(`-v`),o=[`--clipboard`,`-c`,`--view`,`-v`,`--help`,`-h`],s=e.indexOf(`--`),c=(s>=0?e.slice(s+1):e.filter(e=>!o.includes(e)))[0];if(!i&&!c)return{stdout:``,stderr:`screencapture: output file required (or use -c for clipboard)
8683
- `,exitCode:1};let l=c||`screenshot.png`,u=$Ce(l),d=u===`image/png`?1:.92,f;try{if(x6())f=(await S6({kind:`screen`,mimeType:u,quality:d})).bytes;else if(n)f=(await ewe(u,d)).bytes;else{let e=await r.call(`screencapture`,{mimeType:u,quality:d},{timeoutMs:5*6e4});f=new Uint8Array(e.bytes)}}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{stdout:``,stderr:`screencapture: user cancelled or permission denied
8685
+ `,exitCode:1};let l=c||`screenshot.png`,u=nwe(l),d=u===`image/png`?1:.92,f;try{if(x6())f=(await S6({kind:`screen`,mimeType:u,quality:d})).bytes;else if(n)f=(await rwe(u,d)).bytes;else{let e=await r.call(`screencapture`,{mimeType:u,quality:d},{timeoutMs:5*6e4});f=new Uint8Array(e.bytes)}}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{stdout:``,stderr:`screencapture: user cancelled or permission denied
8684
8686
  `,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}if(i)try{if(x6()&&typeof document<`u`&&typeof document.hasFocus==`function`&&!document.hasFocus())return{stdout:``,stderr:`screencapture: clipboard capture needs a focused window; save to a file instead
8685
- `,exitCode:1};if(n){let e=await nwe(f,u),t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=new Blob([t],{type:`image/png`});return await rwe(),await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),{stdout:`captured ${Math.round(n.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}return await r.call(`clipboard-write-image`,{bytes:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength),mimeType:u},{timeoutMs:5*6e4}),{stdout:`captured ${Math.round(f.byteLength/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`screencapture: failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let p=t.fs.resolvePath(t.cwd,l);try{await t.fs.writeFile(p,f)}catch(e){return{stdout:``,stderr:`screencapture: failed to write file: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let m=Math.round(f.length/1024);return a?{stdout:`${p} (${m} KB)\n<img:data:${u};base64,${QCe(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${PK(p)}\n`,stderr:``,exitCode:0}})}async function nwe(e,t){if(t===`image/png`)return e;let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=new Blob([n],{type:t}),i=URL.createObjectURL(r);try{let e=new Image;await new Promise((t,n)=>{e.onload=()=>t(),e.onerror=()=>n(Error(`Failed to load image for conversion`)),e.src=i});let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);if(!n)throw Error(`Failed to get canvas context`);n.drawImage(e,0,0);let r=await new Promise((e,n)=>{t.toBlob(t=>t?e(t):n(Error(`Failed to create PNG blob`)),`image/png`)});return new Uint8Array(await r.arrayBuffer())}finally{URL.revokeObjectURL(i)}}async function rwe(e=5*6e4){typeof document>`u`||typeof document.hasFocus==`function`&&(document.hasFocus()||await new Promise((t,n)=>{let r=()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,a),clearTimeout(o)},i=()=>{document.hasFocus()&&(r(),t())},a=()=>{document.visibilityState===`visible`&&document.hasFocus()&&(r(),t())},o=setTimeout(()=>{r(),n(Error(`timed out waiting for window focus`))},e);window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,a)}))}function iwe(e){return new Promise((t,n)=>{chrome.runtime.sendMessage(e,e=>{let r=chrome.runtime.lastError;if(r){n(Error(r.message??`chrome.runtime.lastError`));return}t(e)})})}async function D7(e,t,n){let r={method:e,headers:_({"Content-Type":`application/json`})};n&&(r.body=JSON.stringify(n));let i=await fetch(p(`/api/secrets${t}`),r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function awe(){return{async list(){let[e,t]=await Promise.all([D7(`GET`,``),D7(`GET`,`/session`)]),n=[];if(e.ok)for(let t of e.data)n.push({name:t.name,domains:t.domains,persisted:!0});if(t.ok)for(let e of t.data)n.push({name:e.name,domains:e.domains,persisted:!1});return n},async getInfo(e){return(await this.list()).find(t=>t.name===e)??null},async getMasked(e){let{ok:t,data:n}=await D7(`GET`,`/masked`);return t?n.find(t=>t.name===e)??null:null},async peek(e){let{ok:t,data:n}=await D7(`GET`,`/peek?name=${encodeURIComponent(e)}`);return t?n:null},async setSession(e,t,n){let{ok:r,data:i}=await D7(`POST`,`/session`,{name:e,value:t,domains:n});if(!r)throw Error(k7(i)??`failed to set session secret`)},async setPersisted(e,t,n){let{ok:r,data:i}=await D7(`POST`,``,{name:e,value:t,domains:n});if(!r)throw Error(k7(i)??`failed to persist secret`)},async setScope(e,t){let{ok:n,data:r}=await D7(`POST`,`/scope`,{name:e,domains:t});if(!n)throw Error(k7(r)??`failed to update scope`)},async delete(e){let{ok:t,status:n,data:r}=await D7(`DELETE`,`/${encodeURIComponent(e)}`);if(n===404)return{removed:!1};if(!t)throw Error(k7(r)??`failed to delete secret`);return{removed:!0,fromSession:r&&typeof r==`object`&&`fromSession`in r?!!r.fromSession:void 0}}}}function O7(e){let t=t=>e(t);return{async list(){let[e,n]=await Promise.all([t({type:`secrets.list`}),t({type:`secrets.session.list`})]),r=[];for(let t of e?.entries??[])r.push({name:t.name,domains:t.domains,persisted:!0});for(let e of n?.entries??[])r.push({name:e.name,domains:e.domains,persisted:!1});return r},async getInfo(e){return(await this.list()).find(t=>t.name===e)??null},async getMasked(e){return((await t({type:`secrets.list-masked-entries`}))?.entries??[]).find(t=>t.name===e)??null},async peek(e){let n=await t({type:`secrets.peek`,name:e});if(n?.error)throw Error(n.error);return n?.record??null},async setSession(e,n,r){let i=await t({type:`secrets.session.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.session.set failed`)},async setPersisted(e,n,r){let i=await t({type:`secrets.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.set failed`)},async setScope(e,n){let r=await t({type:`secrets.set-domains`,name:e,domains:n});if(!r?.ok)throw Error(r?.error??`secrets.set-domains failed`)},async delete(e){let n=await t({type:`secrets.delete`,name:e});if(!n?.ok)throw Error(n?.error??`secrets.delete failed`);return{removed:n.removed??!0,fromSession:n.fromSession}}}}function owe(){return O7(e=>iwe(e))}function swe(){return O7(e=>{let{type:t,...n}=e;return Ae(t,n)})}function k7(e){if(e&&typeof e==`object`&&`error`in e){let t=e.error;if(typeof t==`string`)return t}}function cwe(e){switch(e){case`extension-direct`:return owe();case`extension-delegate`:return swe();default:return awe()}}function lwe(){return`secret — manage secrets for the fetch proxy and mount backends
8687
+ `,exitCode:1};if(n){let e=await awe(f,u),t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=new Blob([t],{type:`image/png`});return await owe(),await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),{stdout:`captured ${Math.round(n.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}return await r.call(`clipboard-write-image`,{bytes:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength),mimeType:u},{timeoutMs:5*6e4}),{stdout:`captured ${Math.round(f.byteLength/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`screencapture: failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let p=t.fs.resolvePath(t.cwd,l);try{await t.fs.writeFile(p,f)}catch(e){return{stdout:``,stderr:`screencapture: failed to write file: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let m=Math.round(f.length/1024);return a?{stdout:`${p} (${m} KB)\n<img:data:${u};base64,${twe(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${PK(p)}\n`,stderr:``,exitCode:0}})}async function awe(e,t){if(t===`image/png`)return e;let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=new Blob([n],{type:t}),i=URL.createObjectURL(r);try{let e=new Image;await new Promise((t,n)=>{e.onload=()=>t(),e.onerror=()=>n(Error(`Failed to load image for conversion`)),e.src=i});let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);if(!n)throw Error(`Failed to get canvas context`);n.drawImage(e,0,0);let r=await new Promise((e,n)=>{t.toBlob(t=>t?e(t):n(Error(`Failed to create PNG blob`)),`image/png`)});return new Uint8Array(await r.arrayBuffer())}finally{URL.revokeObjectURL(i)}}async function owe(e=5*6e4){typeof document>`u`||typeof document.hasFocus==`function`&&(document.hasFocus()||await new Promise((t,n)=>{let r=()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,a),clearTimeout(o)},i=()=>{document.hasFocus()&&(r(),t())},a=()=>{document.visibilityState===`visible`&&document.hasFocus()&&(r(),t())},o=setTimeout(()=>{r(),n(Error(`timed out waiting for window focus`))},e);window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,a)}))}function swe(e){return new Promise((t,n)=>{chrome.runtime.sendMessage(e,e=>{let r=chrome.runtime.lastError;if(r){n(Error(r.message??`chrome.runtime.lastError`));return}t(e)})})}async function D7(e,t,n){let r={method:e,headers:_({"Content-Type":`application/json`})};n&&(r.body=JSON.stringify(n));let i=await fetch(p(`/api/secrets${t}`),r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function cwe(){return{async list(){let[e,t]=await Promise.all([D7(`GET`,``),D7(`GET`,`/session`)]),n=[];if(e.ok)for(let t of e.data)n.push({name:t.name,domains:t.domains,persisted:!0});if(t.ok)for(let e of t.data)n.push({name:e.name,domains:e.domains,persisted:!1});return n},async getInfo(e){return(await this.list()).find(t=>t.name===e)??null},async getMasked(e){let{ok:t,data:n}=await D7(`GET`,`/masked`);return t?n.find(t=>t.name===e)??null:null},async peek(e){let{ok:t,data:n}=await D7(`GET`,`/peek?name=${encodeURIComponent(e)}`);return t?n:null},async setSession(e,t,n){let{ok:r,data:i}=await D7(`POST`,`/session`,{name:e,value:t,domains:n});if(!r)throw Error(k7(i)??`failed to set session secret`)},async setPersisted(e,t,n){let{ok:r,data:i}=await D7(`POST`,``,{name:e,value:t,domains:n});if(!r)throw Error(k7(i)??`failed to persist secret`)},async setScope(e,t){let{ok:n,data:r}=await D7(`POST`,`/scope`,{name:e,domains:t});if(!n)throw Error(k7(r)??`failed to update scope`)},async delete(e){let{ok:t,status:n,data:r}=await D7(`DELETE`,`/${encodeURIComponent(e)}`);if(n===404)return{removed:!1};if(!t)throw Error(k7(r)??`failed to delete secret`);return{removed:!0,fromSession:r&&typeof r==`object`&&`fromSession`in r?!!r.fromSession:void 0}}}}function O7(e){let t=t=>e(t);return{async list(){let[e,n]=await Promise.all([t({type:`secrets.list`}),t({type:`secrets.session.list`})]),r=[];for(let t of e?.entries??[])r.push({name:t.name,domains:t.domains,persisted:!0});for(let e of n?.entries??[])r.push({name:e.name,domains:e.domains,persisted:!1});return r},async getInfo(e){return(await this.list()).find(t=>t.name===e)??null},async getMasked(e){return((await t({type:`secrets.list-masked-entries`}))?.entries??[]).find(t=>t.name===e)??null},async peek(e){let n=await t({type:`secrets.peek`,name:e});if(n?.error)throw Error(n.error);return n?.record??null},async setSession(e,n,r){let i=await t({type:`secrets.session.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.session.set failed`)},async setPersisted(e,n,r){let i=await t({type:`secrets.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.set failed`)},async setScope(e,n){let r=await t({type:`secrets.set-domains`,name:e,domains:n});if(!r?.ok)throw Error(r?.error??`secrets.set-domains failed`)},async delete(e){let n=await t({type:`secrets.delete`,name:e});if(!n?.ok)throw Error(n?.error??`secrets.delete failed`);return{removed:n.removed??!0,fromSession:n.fromSession}}}}function lwe(){return O7(e=>swe(e))}function uwe(){return O7(e=>{let{type:t,...n}=e;return Ae(t,n)})}function k7(e){if(e&&typeof e==`object`&&`error`in e){let t=e.error;if(typeof t==`string`)return t}}function dwe(e){switch(e){case`extension-direct`:return lwe();case`extension-delegate`:return uwe();default:return cwe()}}function fwe(){return`secret — manage secrets for the fetch proxy and mount backends
8686
8688
 
8687
8689
  No approval (session-only, in-memory, never persisted):
8688
8690
  secret set <name> <value> [--domain <pat>] Set a session secret. Free for a
@@ -8719,24 +8721,24 @@ Examples:
8719
8721
  secret peek OPENAI_KEY
8720
8722
  secret set GITHUB_TOKEN ghp_… --domain "api.github.com" --persist # prompts
8721
8723
  secret scope GITHUB_TOKEN --domain "api.github.com,*.github.com" # prompts
8722
- `}function A7(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}const uwe={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},dwe=new Set;function j7(e,t){if(e===t)return!0;try{return KF(e).test(t)}catch{return!1}}function fwe(e,t){for(let n of e)if(j7(n,t))return!0;return!1}function M7(){return{stdout:``,stderr:`secret: approval denied
8723
- `,exitCode:1}}function pwe(e){let t=Ee(),n=e.isExtension??(t===`extension-direct`||t===`extension-delegate`),r=e.backend??cwe(t),i=e.grants??dwe,a=e.broker,o=()=>(a??=cI(),a);return{backend:r,inExtension:n,gate:async(e,t)=>{let n=`secret:${e}:${t}`;if(fwe(i,n))return!0;let r=await o().requestApproval({kind:`secret`,detail:`${uwe[e]}: ${t}`,suggestedPattern:n});if(r.decision===`deny`)return!1;if(r.decision===`always`){let e=r.pattern?.trim();i.add(e&&j7(e,n)?e:n)}return!0},injectMaskedEnv:async t=>{if(e.setEnv&&rR(t))try{let n=await r.getMasked(t);n&&e.setEnv(t,n.maskedValue)}catch{}}}}function mwe(e){let t=Z1(e);if(t.length!==0)return t.endsWith(`\r
8724
+ `}function A7(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}const pwe={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},mwe=new Set;function j7(e,t){if(e===t)return!0;try{return KF(e).test(t)}catch{return!1}}function hwe(e,t){for(let n of e)if(j7(n,t))return!0;return!1}function M7(){return{stdout:``,stderr:`secret: approval denied
8725
+ `,exitCode:1}}function gwe(e){let t=Ee(),n=e.isExtension??(t===`extension-direct`||t===`extension-delegate`),r=e.backend??dwe(t),i=e.grants??mwe,a=e.broker,o=()=>(a??=cI(),a);return{backend:r,inExtension:n,gate:async(e,t)=>{let n=`secret:${e}:${t}`;if(hwe(i,n))return!0;let r=await o().requestApproval({kind:`secret`,detail:`${pwe[e]}: ${t}`,suggestedPattern:n});if(r.decision===`deny`)return!1;if(r.decision===`always`){let e=r.pattern?.trim();i.add(e&&j7(e,n)?e:n)}return!0},injectMaskedEnv:async t=>{if(e.setEnv&&rR(t))try{let n=await r.getMasked(t);n&&e.setEnv(t,n.maskedValue)}catch{}}}}function _we(e){let t=Z1(e);if(t.length!==0)return t.endsWith(`\r
8724
8726
  `)?t.slice(0,-2):t.endsWith(`
8725
- `)?t.slice(0,-1):t}async function hwe(e,t,n,r){return n.length===0?{stdout:``,stderr:`secret: --domain is required to persist a secret
8726
- `,exitCode:1}:await r.gate(`persist`,e)?(await r.backend.setPersisted(e,t,n),await r.injectMaskedEnv(e),{stdout:`Persisted "${e}" (domains: ${n.join(`, `)})\n`,stderr:``,exitCode:0}):M7()}async function gwe(e,t,n,r){return await r.backend.getInfo(e)&&!await r.gate(`value`,e)?M7():(await r.backend.setSession(e,t,n),await r.injectMaskedEnv(e),{stdout:`Set session secret "${e}"${n.length>0?` (domains: ${n.join(`, `)})`:``} — in-memory only, not persisted.\n`,stderr:``,exitCode:0})}async function _we(e,t,n){let r=e[1];if(!r||r.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
8727
- `,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=mwe(t.stdin);if(i!==void 0&&a!==void 0)return{stdout:``,stderr:`secret: provide <value> as an argument OR via stdin, not both
8727
+ `)?t.slice(0,-1):t}async function vwe(e,t,n,r){return n.length===0?{stdout:``,stderr:`secret: --domain is required to persist a secret
8728
+ `,exitCode:1}:await r.gate(`persist`,e)?(await r.backend.setPersisted(e,t,n),await r.injectMaskedEnv(e),{stdout:`Persisted "${e}" (domains: ${n.join(`, `)})\n`,stderr:``,exitCode:0}):M7()}async function ywe(e,t,n,r){return await r.backend.getInfo(e)&&!await r.gate(`value`,e)?M7():(await r.backend.setSession(e,t,n),await r.injectMaskedEnv(e),{stdout:`Set session secret "${e}"${n.length>0?` (domains: ${n.join(`, `)})`:``} — in-memory only, not persisted.\n`,stderr:``,exitCode:0})}async function bwe(e,t,n){let r=e[1];if(!r||r.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
8729
+ `,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=_we(t.stdin);if(i!==void 0&&a!==void 0)return{stdout:``,stderr:`secret: provide <value> as an argument OR via stdin, not both
8728
8730
  `,exitCode:1};let o=i??a;if(o===void 0)return{stdout:``,stderr:`secret: set requires a <value>: secret set <name> <value> [--domain <patterns>] [--persist]
8729
8731
  or pipe the value on stdin: echo "$TOKEN" | secret set <name> [--domain ...]
8730
- `,exitCode:1};let s=A7(e)??[];return e.includes(`--persist`)?hwe(r,o,s,n):gwe(r,o,s,n)}async function vwe(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: get requires a <name>
8731
- `,exitCode:1};let r=await t.backend.getMasked(n);return r?{stdout:`${r.name}=${r.maskedValue}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function ywe(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: peek requires a <name>
8732
- `,exitCode:1};let r=await t.backend.peek(n);return r?{stdout:`${r.name}: ${r.preview}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function bwe(e,t){let n=e[1];if(!n||n.startsWith(`-`))return{stdout:``,stderr:`secret: scope requires a <name>
8732
+ `,exitCode:1};let s=A7(e)??[];return e.includes(`--persist`)?vwe(r,o,s,n):ywe(r,o,s,n)}async function xwe(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: get requires a <name>
8733
+ `,exitCode:1};let r=await t.backend.getMasked(n);return r?{stdout:`${r.name}=${r.maskedValue}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function Swe(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: peek requires a <name>
8734
+ `,exitCode:1};let r=await t.backend.peek(n);return r?{stdout:`${r.name}: ${r.preview}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function Cwe(e,t){let n=e[1];if(!n||n.startsWith(`-`))return{stdout:``,stderr:`secret: scope requires a <name>
8733
8735
  `,exitCode:1};let r=A7(e)??[];return r.length===0?{stdout:``,stderr:`secret: scope requires --domain <patterns>
8734
- `,exitCode:1}:await t.gate(`scope`,n)?(await t.backend.setScope(n,r),{stdout:`Updated scope for "${n}" (domains: ${r.join(`, `)})\n`,stderr:``,exitCode:0}):M7()}async function xwe(e){let t=await e.backend.list();if(t.length===0)return{stdout:`No secrets stored
8735
- `,stderr:``,exitCode:0};let n=Math.max(4,...t.map(e=>e.name.length)),r=`${`NAME`.padEnd(n)} TYPE DOMAINS\n`;for(let e of t){let t=e.persisted?`SAVED`:`SESSION`;r+=`${e.name.padEnd(n)} ${t.padEnd(7)} ${e.domains.join(`, `)}\n`}return{stdout:r,stderr:``,exitCode:0}}async function Swe(e,t,n){let r=e[1];if(!r)return{stdout:``,stderr:`secret: ${t} requires a <name>\n`,exitCode:1};let i=await n.backend.delete(r);return i.removed?{stdout:`Removed ${i.fromSession===!0?`session`:`persisted`} secret "${r}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${r}"\n`,exitCode:1}}async function Cwe(e,t){let n=e[1],r=e[2];if(!n||!r)return{stdout:``,stderr:`secret: test requires <name> <url>
8736
- `,exitCode:1};let i;try{i=new URL(r).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${r}"\n`,exitCode:1}}let a=(await t.backend.list()).find(e=>e.name===n);return a?m(a.domains,i)?{stdout:`✓ ${n} is allowed for ${i}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${n} is NOT allowed for ${i}\n Allowed domains: ${a.domains.join(`, `)}\n`,stderr:``,exitCode:1}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function wwe(e){if(!e.inExtension)return{stdout:`secret: in CLI mode, edit ~/.slicc/secrets.env directly with your text editor.
8736
+ `,exitCode:1}:await t.gate(`scope`,n)?(await t.backend.setScope(n,r),{stdout:`Updated scope for "${n}" (domains: ${r.join(`, `)})\n`,stderr:``,exitCode:0}):M7()}async function wwe(e){let t=await e.backend.list();if(t.length===0)return{stdout:`No secrets stored
8737
+ `,stderr:``,exitCode:0};let n=Math.max(4,...t.map(e=>e.name.length)),r=`${`NAME`.padEnd(n)} TYPE DOMAINS\n`;for(let e of t){let t=e.persisted?`SAVED`:`SESSION`;r+=`${e.name.padEnd(n)} ${t.padEnd(7)} ${e.domains.join(`, `)}\n`}return{stdout:r,stderr:``,exitCode:0}}async function Twe(e,t,n){let r=e[1];if(!r)return{stdout:``,stderr:`secret: ${t} requires a <name>\n`,exitCode:1};let i=await n.backend.delete(r);return i.removed?{stdout:`Removed ${i.fromSession===!0?`session`:`persisted`} secret "${r}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${r}"\n`,exitCode:1}}async function Ewe(e,t){let n=e[1],r=e[2];if(!n||!r)return{stdout:``,stderr:`secret: test requires <name> <url>
8738
+ `,exitCode:1};let i;try{i=new URL(r).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${r}"\n`,exitCode:1}}let a=(await t.backend.list()).find(e=>e.name===n);return a?m(a.domains,i)?{stdout:`✓ ${n} is allowed for ${i}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${n} is NOT allowed for ${i}\n Allowed domains: ${a.domains.join(`, `)}\n`,stderr:``,exitCode:1}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function Dwe(e){if(!e.inExtension)return{stdout:`secret: in CLI mode, edit ~/.slicc/secrets.env directly with your text editor.
8737
8739
  (changes are picked up on the next request — no restart needed)
8738
8740
  `,stderr:``,exitCode:0};try{return await chrome.runtime.openOptionsPage(),{stdout:`Opened Mount Secrets options page in a new tab.
8739
- `,stderr:``,exitCode:0}}catch{let e=chrome.runtime.getURL(`secrets.html`);return window.open(e,`_blank`),{stdout:`Opened ${e}\n`,stderr:``,exitCode:0}}}async function Twe(e,t,n){let r=e[0];switch(r){case`set`:return _we(e,t,n);case`get`:case`read`:return vwe(e,n);case`peek`:return ywe(e,n);case`scope`:return bwe(e,n);case`list`:return xwe(n);case`delete`:case`rm`:return Swe(e,r,n);case`test`:return Cwe(e,n);case`edit`:return wwe(n);default:return{stdout:``,stderr:`secret: unknown command "${r}"\n`,exitCode:1}}}function Ewe(e={}){let t=pwe(e);return cA(`secret`,async(e,n)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:lwe(),stderr:``,exitCode:0};try{return await Twe(e,n,t)}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function N7(){return{stdout:`usage: serve [--entry <relative-path>] [--project] <directory>
8741
+ `,stderr:``,exitCode:0}}catch{let e=chrome.runtime.getURL(`secrets.html`);return window.open(e,`_blank`),{stdout:`Opened ${e}\n`,stderr:``,exitCode:0}}}async function Owe(e,t,n){let r=e[0];switch(r){case`set`:return bwe(e,t,n);case`get`:case`read`:return xwe(e,n);case`peek`:return Swe(e,n);case`scope`:return Cwe(e,n);case`list`:return wwe(n);case`delete`:case`rm`:return Twe(e,r,n);case`test`:return Ewe(e,n);case`edit`:return Dwe(n);default:return{stdout:``,stderr:`secret: unknown command "${r}"\n`,exitCode:1}}}function kwe(e={}){let t=gwe(e);return cA(`secret`,async(e,n)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:fwe(),stderr:``,exitCode:0};try{return await Owe(e,n,t)}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function N7(){return{stdout:`usage: serve [--entry <relative-path>] [--project] <directory>
8740
8742
 
8741
8743
  Serve a VFS directory in a new browser tab via the preview service worker.
8742
8744
  Defaults to index.html inside the target directory.
@@ -8745,10 +8747,10 @@ Examples:
8745
8747
  --project Enable project serve mode. Root-relative paths (/scripts/,
8746
8748
  /styles/, etc.) resolve against the served directory.
8747
8749
  Use this for frameworks like EDS that expect a local dev server.
8748
- `,stderr:``,exitCode:0}}function Dwe(e){let t=`index.html`,n,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`--entry`){let n=e[i+1];if(!n)return{entry:t,project:r,error:`serve: missing value for --entry
8750
+ `,stderr:``,exitCode:0}}function Awe(e){let t=`index.html`,n,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`--entry`){let n=e[i+1];if(!n)return{entry:t,project:r,error:`serve: missing value for --entry
8749
8751
  `};t=n,i+=1;continue}if(a.startsWith(`--entry=`)){t=a.slice(8);continue}if(a===`--project`){r=!0;continue}if(a.startsWith(`-`))return{entry:t,project:r,error:`serve: unknown option: ${a}\n`};if(n)return{entry:t,project:r,error:`serve: expected a single directory argument
8750
- `};n=a}return{directory:n,entry:t,project:r}}function Owe(e,t){return cA(`serve`,async(n,r)=>{if(n.length===0||n.includes(`--help`)||n.includes(`-h`))return N7();let i=typeof window<`u`&&typeof window.open==`function`;if(!e&&!i)return{stdout:``,stderr:`serve: browser APIs are unavailable in this environment
8751
- `,exitCode:1};let a=Dwe(n);if(a.error)return{stdout:``,stderr:a.error,exitCode:1};if(!a.directory)return N7();if(!UK(a.entry))return{stdout:``,stderr:`serve: invalid entry file: ${a.entry}\n`,exitCode:1};let o=r.fs.resolvePath(r.cwd,a.directory),s;try{s=await r.fs.stat(o)}catch{return{stdout:``,stderr:`serve: no such directory: ${a.directory}\n`,exitCode:1}}if(!s.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${a.directory}\n`,exitCode:1};let c=WK(o,a.entry),l;try{l=await r.fs.stat(c)}catch{return{stdout:``,stderr:`serve: entry file not found: ${c}\n`,exitCode:1}}if(!l.isFile)return{stdout:``,stderr:`serve: entry is not a file: ${c}\n`,exitCode:1};let u=HK(c);if(a.project&&(u+=`?projectRoot=${encodeURIComponent(o)}`),e&&t){let t=await e.createPage(u);return{stdout:`serving ${o} → ${u} (targetId: ${t})\nUse: playwright-cli <command> --tab ${t}\n`,stderr:``,exitCode:0}}return typeof window<`u`&&typeof window.open==`function`&&window.open(u,`_blank`,`noopener,noreferrer`),{stdout:`serving ${o} → ${u}\n`,stderr:``,exitCode:0}})}const P7=`slicc-sprinkle-routes`;function F7(){try{let e=localStorage.getItem(P7);return e?JSON.parse(e):{}}catch{return{}}}function I7(e){try{localStorage.setItem(P7,JSON.stringify(e))}catch{}}function kwe(e){return F7()[e]}function Awe(e,t){let n=F7();n[e]=t,I7(n)}function jwe(e){let t=F7();delete t[e],I7(t)}function Mwe(){return F7()}function Nwe(){return{stdout:`usage: sprinkle <subcommand> [args]
8752
+ `};n=a}return{directory:n,entry:t,project:r}}function jwe(e,t){return cA(`serve`,async(n,r)=>{if(n.length===0||n.includes(`--help`)||n.includes(`-h`))return N7();let i=typeof window<`u`&&typeof window.open==`function`;if(!e&&!i)return{stdout:``,stderr:`serve: browser APIs are unavailable in this environment
8753
+ `,exitCode:1};let a=Awe(n);if(a.error)return{stdout:``,stderr:a.error,exitCode:1};if(!a.directory)return N7();if(!UK(a.entry))return{stdout:``,stderr:`serve: invalid entry file: ${a.entry}\n`,exitCode:1};let o=r.fs.resolvePath(r.cwd,a.directory),s;try{s=await r.fs.stat(o)}catch{return{stdout:``,stderr:`serve: no such directory: ${a.directory}\n`,exitCode:1}}if(!s.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${a.directory}\n`,exitCode:1};let c=WK(o,a.entry),l;try{l=await r.fs.stat(c)}catch{return{stdout:``,stderr:`serve: entry file not found: ${c}\n`,exitCode:1}}if(!l.isFile)return{stdout:``,stderr:`serve: entry is not a file: ${c}\n`,exitCode:1};let u=HK(c);if(a.project&&(u+=`?projectRoot=${encodeURIComponent(o)}`),e&&t){let t=await e.createPage(u);return{stdout:`serving ${o} → ${u} (targetId: ${t})\nUse: playwright-cli <command> --tab ${t}\n`,stderr:``,exitCode:0}}return typeof window<`u`&&typeof window.open==`function`&&window.open(u,`_blank`,`noopener,noreferrer`),{stdout:`serving ${o} → ${u}\n`,stderr:``,exitCode:0}})}const P7=`slicc-sprinkle-routes`;function F7(){try{let e=localStorage.getItem(P7);return e?JSON.parse(e):{}}catch{return{}}}function I7(e){try{localStorage.setItem(P7,JSON.stringify(e))}catch{}}function Mwe(e){return F7()[e]}function Nwe(e,t){let n=F7();n[e]=t,I7(n)}function Pwe(e){let t=F7();delete t[e],I7(t)}function Fwe(){return F7()}function Iwe(){return{stdout:`usage: sprinkle <subcommand> [args]
8752
8754
 
8753
8755
  list List available .shtml sprinkles
8754
8756
  open <name> Open a sprinkle by name
@@ -8761,25 +8763,25 @@ Examples:
8761
8763
  chat <html> Show inline HTML in chat (Tool UI)
8762
8764
  Use data-action="name" on buttons for callbacks
8763
8765
  Pipe HTML: echo "<div>...</div>" | sprinkle chat
8764
- `,stderr:``,exitCode:0}}function Pwe(){return globalThis.__slicc_sprinkleManager??null}function Fwe(){return cA(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return Nwe();let n=e[0];if(n===`chat`){let n=e.slice(1).join(` `);if(!n){let e=Z1(t.stdin);e&&(n=e)}if(!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
8766
+ `,stderr:``,exitCode:0}}function Lwe(){return globalThis.__slicc_sprinkleManager??null}function Rwe(){return cA(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return Iwe();let n=e[0];if(n===`chat`){let n=e.slice(1).join(` `);if(!n){let e=Z1(t.stdin);e&&(n=e)}if(!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
8765
8767
  `,exitCode:1};let r=await b({html:n,onAction:async(e,t)=>({action:e,data:t})});return r===null?{stdout:``,stderr:`sprinkle chat: not in tool execution context
8766
8768
  `,exitCode:1}:{stdout:JSON.stringify(r)+`
8767
- `,stderr:``,exitCode:0}}let r=Pwe();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
8769
+ `,stderr:``,exitCode:0}}let r=Lwe();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
8768
8770
  `,exitCode:1};switch(n){case`list`:{await r.refresh();let e=r.available();if(e.length===0)return{stdout:`No .shtml sprinkles found.
8769
8771
  `,stderr:``,exitCode:0};let t=new Set(r.opened());return{stdout:e.map(e=>{let n=t.has(e.name)?` [open]`:``;return` ${e.name}${n} ${e.title} (${e.path})`}).join(`
8770
8772
  `)+`
8771
8773
  `,stderr:``,exitCode:0}}case`open`:{let t=e[1];if(!t)return{stdout:``,stderr:`sprinkle open: name required
8772
8774
  `,exitCode:1};try{return await r.open(t),{stdout:`Sprinkle "${t}" opened.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}case`close`:{let t=e[1];return t?(r.close(t),{stdout:`Sprinkle "${t}" closed.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`sprinkle close: name required
8773
- `,exitCode:1}}case`refresh`:{await r.refresh();let e=r.available().length;return{stdout:`Found ${e} sprinkle${e===1?``:`s`}.\n`,stderr:``,exitCode:0}}case`route`:{let t=e[1];if(!t){let e=Mwe(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
8775
+ `,exitCode:1}}case`refresh`:{await r.refresh();let e=r.available().length;return{stdout:`Found ${e} sprinkle${e===1?``:`s`}.\n`,stderr:``,exitCode:0}}case`route`:{let t=e[1];if(!t){let e=Fwe(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
8774
8776
  `,stderr:``,exitCode:0}:{stdout:`Sprinkle routes:
8775
8777
  `+t.map(([e,t])=>` ${e} -> ${t}`).join(`
8776
8778
  `)+`
8777
- `,stderr:``,exitCode:0}}if(e.includes(`--clear`))return jwe(t),{stdout:`Route cleared for sprinkle "${t}" (licks will go to cone).\n`,stderr:``,exitCode:0};let n=e.indexOf(`--scoop`),r=n===-1?void 0:e[n+1];if(!r){let e=kwe(t);return e?{stdout:`${t} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${t} -> cone (default)\n`,stderr:``,exitCode:0}}return Awe(t,r),{stdout:`Sprinkle "${t}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}case`send`:{let t=e[1];if(!t)return{stdout:``,stderr:`sprinkle send: name required
8779
+ `,stderr:``,exitCode:0}}if(e.includes(`--clear`))return Pwe(t),{stdout:`Route cleared for sprinkle "${t}" (licks will go to cone).\n`,stderr:``,exitCode:0};let n=e.indexOf(`--scoop`),r=n===-1?void 0:e[n+1];if(!r){let e=Mwe(t);return e?{stdout:`${t} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${t} -> cone (default)\n`,stderr:``,exitCode:0}}return Nwe(t,r),{stdout:`Sprinkle "${t}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}case`send`:{let t=e[1];if(!t)return{stdout:``,stderr:`sprinkle send: name required
8778
8780
  `,exitCode:1};let n=e.slice(2).join(` `);if(!n)return{stdout:``,stderr:`sprinkle send: JSON data required
8779
8781
  `,exitCode:1};let i;try{i=JSON.parse(n)}catch{return{stdout:``,stderr:`sprinkle send: invalid JSON
8780
- `,exitCode:1}}return r.sendToSprinkle(t,i),{stdout:`Data sent to sprinkle "${t}".\n`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function Iwe(){return{stdout:`usage: sqlite3 [database] [sql]
8781
- `,stderr:``,exitCode:0}}function L7(e=`sqlite3`){return cA(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return Iwe();let r=`:memory:`,i=t;t.length>0&&!t[0].startsWith(`-`)&&(r=t[0],i=t.slice(1));let a=i.join(` `).trim()||Z1(n.stdin).trim();if(!a)return{stdout:``,stderr:`${e}: interactive mode is not supported; provide SQL as argument or stdin\n`,exitCode:1};try{let e=await JK(),t=r===`:memory:`,i=t?`:memory:`:n.fs.resolvePath(n.cwd,r),o;!t&&await n.fs.exists(i)&&(o=await n.fs.readFileBuffer(i));let s=o?new e.Database(o):new e.Database,c=s.exec(a);t||await n.fs.writeFile(i,s.export()),s.close();let l=[];for(let e of c)for(let t of e.values)l.push(t.map(BK).join(`|`));return{stdout:l.length>0?`${l.join(`
8782
- `)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function Lwe(e={}){let{broker:t,persistGrant:n,suppressNextGate:r}=e;return cA(`sudo`,async(e,i)=>{if(e.length===0)return{stdout:``,stderr:`sudo: usage: sudo <command> [args...]
8782
+ `,exitCode:1}}return r.sendToSprinkle(t,i),{stdout:`Data sent to sprinkle "${t}".\n`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function zwe(){return{stdout:`usage: sqlite3 [database] [sql]
8783
+ `,stderr:``,exitCode:0}}function L7(e=`sqlite3`){return cA(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return zwe();let r=`:memory:`,i=t;t.length>0&&!t[0].startsWith(`-`)&&(r=t[0],i=t.slice(1));let a=i.join(` `).trim()||Z1(n.stdin).trim();if(!a)return{stdout:``,stderr:`${e}: interactive mode is not supported; provide SQL as argument or stdin\n`,exitCode:1};try{let e=await JK(),t=r===`:memory:`,i=t?`:memory:`:n.fs.resolvePath(n.cwd,r),o;!t&&await n.fs.exists(i)&&(o=await n.fs.readFileBuffer(i));let s=o?new e.Database(o):new e.Database,c=s.exec(a);t||await n.fs.writeFile(i,s.export()),s.close();let l=[];for(let e of c)for(let t of e.values)l.push(t.map(BK).join(`|`));return{stdout:l.length>0?`${l.join(`
8784
+ `)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function Bwe(e={}){let{broker:t,persistGrant:n,suppressNextGate:r}=e;return cA(`sudo`,async(e,i)=>{if(e.length===0)return{stdout:``,stderr:`sudo: usage: sudo <command> [args...]
8783
8785
  `,exitCode:1};if(e[0]===`--help`||e[0]===`-h`)return{stdout:`usage: sudo <command> [args...]
8784
8786
 
8785
8787
  Request human approval to run <command> with elevation. If approved, the
@@ -8794,7 +8796,7 @@ Options:
8794
8796
  `,stderr:``,exitCode:0};if(!t)return{stdout:``,stderr:`sudo: command-level approval is not configured
8795
8797
  `,exitCode:1};if(!i.exec)return{stdout:``,stderr:`sudo: cannot dispatch inner command in this context
8796
8798
  `,exitCode:1};let a=e.join(` `).trim(),o=await t.requestApproval({kind:`command`,detail:a});if(o.decision===`deny`)return{stdout:``,stderr:`sudo: approval denied
8797
- `,exitCode:1};if(o.decision===`always`){let e=o.pattern?.trim()||a;if(n)try{await n(e)}catch{}}return r&&r(a),i.exec(e[0],{cwd:i.cwd,args:e.slice(1)})})}var Rwe=`/**
8799
+ `,exitCode:1};if(o.decision===`always`){let e=o.pattern?.trim()||a;if(n)try{await n(e)}catch{}}return r&&r(a),i.exec(e[0],{cwd:i.cwd,args:e.slice(1)})})}var Vwe=`/**
8798
8800
  * Standalone assertions - no dependency on test runner
8799
8801
  *
8800
8802
  * Each assertion:
@@ -8982,7 +8984,7 @@ function sameMembers(a, b) {
8982
8984
  }
8983
8985
 
8984
8986
  const slice = a => (isPrimitive(a) ? a : a.slice ? a.slice() : Object.assign({}, a))
8985
- `,zwe=`/**
8987
+ `,Hwe=`/**
8986
8988
  * tst - minimal test runner
8987
8989
  *
8988
8990
  * - Standalone assertions (assert.js works anywhere)
@@ -9636,28 +9638,28 @@ Install:
9636
9638
  Then \`tsc --version\` and the transpile commands above. There is no
9637
9639
  bundled binary, no CDN fallback; a missing package exits non-zero
9638
9640
  with a clear \`ipk add\` hint.
9639
- `;function Bwe(e){let t=[],n=!1,r=null,i=!1,a=!1;for(let o=0;o<e.length;o++){let s=e[o];if(s===`-h`||s===`--help`){i=!0;continue}if(s===`-v`||s===`--version`){a=!0;continue}if(s===`--noEmit`){n=!0;continue}if(s===`--outDir`){let t=e[o+1];if(typeof t!=`string`||t.startsWith(`-`))throw Error(`tsc: --outDir requires a value`);r=t,o+=1;continue}if(s.startsWith(`--outDir=`)){r=s.slice(9);continue}if(s.startsWith(`-`))throw Error(`tsc: unknown option: ${s}`);t.push(s)}return{files:t,noEmit:n,outDir:r,showHelp:i,showVersion:a}}function Vwe(e,t,n){let r=e[t],i=t+1;for(;i<e.length;){let t=e[i];if(r+=t,t===`\\`&&i+1<e.length){r+=e[i+1],i+=2;continue}if(i+=1,t===n)return{text:r,next:i}}return{text:r,next:i}}function Hwe(e,t){let n=t;for(;n<e.length&&e[n]!==`
9640
- `;)n+=1;return n}function Uwe(e,t){let n=t+2;for(;n<e.length&&!(e[n]===`*`&&e[n+1]===`/`);)n+=1;return n+2}function Wwe(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`"`||r===`'`){let{text:i,next:a}=Vwe(e,n,r);t+=i,n=a;continue}if(r===`/`&&e[n+1]===`/`){n=Hwe(e,n);continue}if(r===`/`&&e[n+1]===`*`){n=Uwe(e,n);continue}t+=r,n+=1}return t}function Gwe(e,t){let n=`${PK(e).replace(/\.(ts|tsx|mts|cts)$/i,``)}.js`;return t?`${t.endsWith(`/`)?t.slice(0,-1):t}/${n}`:`${FK(e)}/${n}`}async function Kwe(e,t){let n=t||`/`,r=``;for(;n&&n!==r;){let t=n===`/`?`/tsconfig.json`:`${n}/tsconfig.json`;if(await e.exists(t))return t;r=n,n=FK(n)}return null}const B7={target:`ES2022`,module:`ESNext`,moduleResolution:`Bundler`,esModuleInterop:!0,allowSyntheticDefaultImports:!0,isolatedModules:!0};async function qwe(e,t){let n=await Kwe(e,t);if(!n)return{compilerOptions:{...B7}};let r;try{r=await e.readFile(n)}catch{return{compilerOptions:{...B7}}}let i={};try{i=JSON.parse(Wwe(r))}catch{return{compilerOptions:{...B7}}}return{compilerOptions:{...B7,...i.compilerOptions??{}}}}function V7(e,t){let n=e.flattenDiagnosticMessageText(t.messageText,`
9641
- `);if(t.file&&typeof t.start==`number`){let{line:e,character:r}=t.file.getLineAndCharacterOfPosition(t.start);return`${t.file.fileName}(${e+1},${r+1}): error TS${t.code}: ${n}`}return`error TS${t.code}: ${n}`}function Jwe(e,t){let n=t.toLowerCase();return n.endsWith(`.tsx`)?e.ScriptKind.TSX:n.endsWith(`.jsx`)?e.ScriptKind.JSX:n.endsWith(`.js`)||n.endsWith(`.mjs`)||n.endsWith(`.cjs`)?e.ScriptKind.JS:e.ScriptKind.TS}function H7(e,t,n,r,i){let a=e.transpileModule(t,{compilerOptions:r,fileName:n,reportDiagnostics:i});return{outputText:a.outputText,diagnostics:a.diagnostics??[]}}function Ywe(e,t,n,r){let{outputText:i,diagnostics:a}=H7(e,r,`<stdin>.ts`,n.compilerOptions,!0),o=a.map(t=>V7(e,t)),s=o.length>0?`${o.join(`
9642
- `)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function Xwe(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,n);if(!await t.fs.exists(a))return{stderr:`tsc: ${n}: no such file\n`,hadError:!0};let o;try{o=await t.fs.readFile(a)}catch(e){return{stderr:`tsc: ${n}: ${e instanceof Error?e.message:String(e)}\n`,hadError:!0}}Jwe(e,a);let{outputText:s,diagnostics:c}=H7(e,o,a,i.compilerOptions,!0),l=[];for(let t of c)l.push(`${V7(e,t)}\n`);let u=c.length>0;if(r.noEmit)return{stderr:l.join(``),hadError:u};let d=t.fs.resolvePath(t.cwd,Gwe(a,r.outDir));try{await t.fs.writeFile(d,s)}catch(e){l.push(`tsc: ${d}: ${e instanceof Error?e.message:String(e)}\n`),u=!0}return{stderr:l.join(``),hadError:u}}async function Zwe(e,t){let n;try{n=Bwe(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:z7,stderr:``,exitCode:0}};let r;try{r=await XK(R7(t))}catch(e){return{done:{stdout:``,stderr:`tsc: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}return n.showVersion?{done:{stdout:`Version ${r.version}\n`,stderr:``,exitCode:0}}:{parsed:n,ts:r}}function Qwe(){return cA(`tsc`,async(e,t)=>{let n=await Zwe(e,t);if(`done`in n)return n.done;let{parsed:r,ts:i}=n,a=await qwe(t.fs,t.cwd);if(r.files.length===0){let e=Z1(t.stdin);return e?Ywe(i,r,a,e):{stdout:z7,stderr:``,exitCode:0}}let o=[],s=!1;for(let e of r.files){let n=await Xwe(i,t,e,r,a);n.stderr&&o.push(n.stderr),n.hadError&&(s=!0)}return{stdout:``,stderr:o.join(``),exitCode:+!!s}})}const $we=[`**/*.test.{js,ts}`];function eTe(e){let t=[],n=`tap`,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`-h`||a===`--help`){r=!0;continue}if(a===`--reporter`){let t=e[i+1];if(t!==`tap`&&t!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=t,i+=1;continue}if(a.startsWith(`--reporter=`)){let e=a.slice(11);if(e!==`tap`&&e!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=e;continue}if(a.startsWith(`-`))throw Error(`test: unknown option: ${a}`);t.push(a)}return{globs:t.length>0?t:[...$we],reporter:n,showHelp:r}}function U7(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=e.indexOf(`}`,t);if(n===-1)return[e];let r=e.slice(0,t),i=e.slice(n+1),a=e.slice(t+1,n).split(`,`),o=[];for(let e of a)for(let t of U7(`${r}${e}${i}`))o.push(t);return o}function tTe(e){let t=``,n=0;for(;n<e.length;){let r=e[n];r===`*`&&e[n+1]===`*`?(t+=`(?:.*/)?`,n+=2,e[n]===`/`&&(n+=1)):r===`*`?(t+=`[^/]*`,n+=1):r===`?`?(t+=`[^/]`,n+=1):`.+^$()[]|\\`.includes(r)?(t+=`\\${r}`,n+=1):(t+=r,n+=1)}return RegExp(`^${t}$`)}async function nTe(e,t,n){let r=n.flatMap(U7).map(tTe),i=new Set,a=t===`/`?``:t;async function o(t){let n;try{n=await e.readdir(t)}catch{return}for(let s of n){if(s===`node_modules`||s.startsWith(`.`))continue;let n=t===`/`?`/${s}`:`${t}/${s}`,c=!1;try{c=(await e.stat(n)).isDirectory}catch{continue}if(c){await o(n);continue}let l=n.startsWith(`${a}/`)?n.slice(a.length+1):n;r.some(e=>e.test(l))&&i.add(n)}}return await o(t),[...i].sort()}let W7=null;async function rTe(e){if(W7)return W7;let t={module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,esModuleInterop:!0,isolatedModules:!1};return W7=`
9641
+ `;function Uwe(e){let t=[],n=!1,r=null,i=!1,a=!1;for(let o=0;o<e.length;o++){let s=e[o];if(s===`-h`||s===`--help`){i=!0;continue}if(s===`-v`||s===`--version`){a=!0;continue}if(s===`--noEmit`){n=!0;continue}if(s===`--outDir`){let t=e[o+1];if(typeof t!=`string`||t.startsWith(`-`))throw Error(`tsc: --outDir requires a value`);r=t,o+=1;continue}if(s.startsWith(`--outDir=`)){r=s.slice(9);continue}if(s.startsWith(`-`))throw Error(`tsc: unknown option: ${s}`);t.push(s)}return{files:t,noEmit:n,outDir:r,showHelp:i,showVersion:a}}function Wwe(e,t,n){let r=e[t],i=t+1;for(;i<e.length;){let t=e[i];if(r+=t,t===`\\`&&i+1<e.length){r+=e[i+1],i+=2;continue}if(i+=1,t===n)return{text:r,next:i}}return{text:r,next:i}}function Gwe(e,t){let n=t;for(;n<e.length&&e[n]!==`
9642
+ `;)n+=1;return n}function Kwe(e,t){let n=t+2;for(;n<e.length&&!(e[n]===`*`&&e[n+1]===`/`);)n+=1;return n+2}function qwe(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`"`||r===`'`){let{text:i,next:a}=Wwe(e,n,r);t+=i,n=a;continue}if(r===`/`&&e[n+1]===`/`){n=Gwe(e,n);continue}if(r===`/`&&e[n+1]===`*`){n=Kwe(e,n);continue}t+=r,n+=1}return t}function Jwe(e,t){let n=`${PK(e).replace(/\.(ts|tsx|mts|cts)$/i,``)}.js`;return t?`${t.endsWith(`/`)?t.slice(0,-1):t}/${n}`:`${FK(e)}/${n}`}async function Ywe(e,t){let n=t||`/`,r=``;for(;n&&n!==r;){let t=n===`/`?`/tsconfig.json`:`${n}/tsconfig.json`;if(await e.exists(t))return t;r=n,n=FK(n)}return null}const B7={target:`ES2022`,module:`ESNext`,moduleResolution:`Bundler`,esModuleInterop:!0,allowSyntheticDefaultImports:!0,isolatedModules:!0};async function Xwe(e,t){let n=await Ywe(e,t);if(!n)return{compilerOptions:{...B7}};let r;try{r=await e.readFile(n)}catch{return{compilerOptions:{...B7}}}let i={};try{i=JSON.parse(qwe(r))}catch{return{compilerOptions:{...B7}}}return{compilerOptions:{...B7,...i.compilerOptions??{}}}}function V7(e,t){let n=e.flattenDiagnosticMessageText(t.messageText,`
9643
+ `);if(t.file&&typeof t.start==`number`){let{line:e,character:r}=t.file.getLineAndCharacterOfPosition(t.start);return`${t.file.fileName}(${e+1},${r+1}): error TS${t.code}: ${n}`}return`error TS${t.code}: ${n}`}function Zwe(e,t){let n=t.toLowerCase();return n.endsWith(`.tsx`)?e.ScriptKind.TSX:n.endsWith(`.jsx`)?e.ScriptKind.JSX:n.endsWith(`.js`)||n.endsWith(`.mjs`)||n.endsWith(`.cjs`)?e.ScriptKind.JS:e.ScriptKind.TS}function H7(e,t,n,r,i){let a=e.transpileModule(t,{compilerOptions:r,fileName:n,reportDiagnostics:i});return{outputText:a.outputText,diagnostics:a.diagnostics??[]}}function Qwe(e,t,n,r){let{outputText:i,diagnostics:a}=H7(e,r,`<stdin>.ts`,n.compilerOptions,!0),o=a.map(t=>V7(e,t)),s=o.length>0?`${o.join(`
9644
+ `)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function $we(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,n);if(!await t.fs.exists(a))return{stderr:`tsc: ${n}: no such file\n`,hadError:!0};let o;try{o=await t.fs.readFile(a)}catch(e){return{stderr:`tsc: ${n}: ${e instanceof Error?e.message:String(e)}\n`,hadError:!0}}Zwe(e,a);let{outputText:s,diagnostics:c}=H7(e,o,a,i.compilerOptions,!0),l=[];for(let t of c)l.push(`${V7(e,t)}\n`);let u=c.length>0;if(r.noEmit)return{stderr:l.join(``),hadError:u};let d=t.fs.resolvePath(t.cwd,Jwe(a,r.outDir));try{await t.fs.writeFile(d,s)}catch(e){l.push(`tsc: ${d}: ${e instanceof Error?e.message:String(e)}\n`),u=!0}return{stderr:l.join(``),hadError:u}}async function eTe(e,t){let n;try{n=Uwe(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:z7,stderr:``,exitCode:0}};let r;try{r=await XK(R7(t))}catch(e){return{done:{stdout:``,stderr:`tsc: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}return n.showVersion?{done:{stdout:`Version ${r.version}\n`,stderr:``,exitCode:0}}:{parsed:n,ts:r}}function tTe(){return cA(`tsc`,async(e,t)=>{let n=await eTe(e,t);if(`done`in n)return n.done;let{parsed:r,ts:i}=n,a=await Xwe(t.fs,t.cwd);if(r.files.length===0){let e=Z1(t.stdin);return e?Qwe(i,r,a,e):{stdout:z7,stderr:``,exitCode:0}}let o=[],s=!1;for(let e of r.files){let n=await $we(i,t,e,r,a);n.stderr&&o.push(n.stderr),n.hadError&&(s=!0)}return{stdout:``,stderr:o.join(``),exitCode:+!!s}})}const nTe=[`**/*.test.{js,ts}`];function rTe(e){let t=[],n=`tap`,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`-h`||a===`--help`){r=!0;continue}if(a===`--reporter`){let t=e[i+1];if(t!==`tap`&&t!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=t,i+=1;continue}if(a.startsWith(`--reporter=`)){let e=a.slice(11);if(e!==`tap`&&e!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=e;continue}if(a.startsWith(`-`))throw Error(`test: unknown option: ${a}`);t.push(a)}return{globs:t.length>0?t:[...nTe],reporter:n,showHelp:r}}function U7(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=e.indexOf(`}`,t);if(n===-1)return[e];let r=e.slice(0,t),i=e.slice(n+1),a=e.slice(t+1,n).split(`,`),o=[];for(let e of a)for(let t of U7(`${r}${e}${i}`))o.push(t);return o}function iTe(e){let t=``,n=0;for(;n<e.length;){let r=e[n];r===`*`&&e[n+1]===`*`?(t+=`(?:.*/)?`,n+=2,e[n]===`/`&&(n+=1)):r===`*`?(t+=`[^/]*`,n+=1):r===`?`?(t+=`[^/]`,n+=1):`.+^$()[]|\\`.includes(r)?(t+=`\\${r}`,n+=1):(t+=r,n+=1)}return RegExp(`^${t}$`)}async function aTe(e,t,n){let r=n.flatMap(U7).map(iTe),i=new Set,a=t===`/`?``:t;async function o(t){let n;try{n=await e.readdir(t)}catch{return}for(let s of n){if(s===`node_modules`||s.startsWith(`.`))continue;let n=t===`/`?`/${s}`:`${t}/${s}`,c=!1;try{c=(await e.stat(n)).isDirectory}catch{continue}if(c){await o(n);continue}let l=n.startsWith(`${a}/`)?n.slice(a.length+1):n;r.some(e=>e.test(l))&&i.add(n)}}return await o(t),[...i].sort()}let W7=null;async function oTe(e){if(W7)return W7;let t={module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,esModuleInterop:!0,isolatedModules:!1};return W7=`
9643
9645
  if (typeof process !== 'undefined' && !process.versions) {
9644
9646
  try { process.versions = { node: '20.0.0' }; } catch (_) { /* readonly process.versions is fine */ }
9645
9647
  }
9646
9648
  const __tst_assert_exports = (function () {
9647
9649
  const module = { exports: {} };
9648
9650
  const exports = module.exports;
9649
- ${e.transpileModule(Rwe,{compilerOptions:t,fileName:`assert.js`}).outputText}
9651
+ ${e.transpileModule(Vwe,{compilerOptions:t,fileName:`assert.js`}).outputText}
9650
9652
  return module.exports;
9651
9653
  })();
9652
9654
  const __tst_module_exports = (function () {
9653
9655
  const module = { exports: {} };
9654
9656
  const exports = module.exports;
9655
- ${e.transpileModule(zwe,{compilerOptions:t,fileName:`tst.js`}).outputText.replace(/require\(["']\.\/assert\.js["']\)/g,`__tst_assert_exports`).replace(/\bimport\.meta\b/g,`({url:""})`).replace(/await\s+import\(['"](?:worker_threads|fs|path)['"]\)/g,`await Promise.reject(new Error("test: fork mode is not supported in the realm"))`)}
9657
+ ${e.transpileModule(Hwe,{compilerOptions:t,fileName:`tst.js`}).outputText.replace(/require\(["']\.\/assert\.js["']\)/g,`__tst_assert_exports`).replace(/\bimport\.meta\b/g,`({url:""})`).replace(/await\s+import\(['"](?:worker_threads|fs|path)['"]\)/g,`await Promise.reject(new Error("test: fork mode is not supported in the realm"))`)}
9656
9658
  return module.exports;
9657
9659
  })();
9658
9660
  const __tst = __tst_module_exports.default || __tst_module_exports;
9659
9661
  __tst.manual = true;
9660
- `.trim(),W7}function G7(e,t=new Map){return e.replace(/(^|[^\w$.])require\(\s*(["'`])([^"'`]+)\2\s*\)/g,(e,n,r,i)=>i===`tst`||i===`tst/tst.js`?`${n}__tstReq("tst")`:i===`tst/assert`||i===`tst/assert.js`?`${n}__tstReq("tst/assert")`:t.has(i)?`${n}__localReq(${JSON.stringify(t.get(i))})`:e)}function iTe(e){let t=new Set,n=/(?:^|[^\w$.])require\(\s*(["'`])([^"'`]+)\1\s*\)/g,r;for(;(r=n.exec(e))!==null;)t.add(r[2]);return[...t]}async function aTe(e,t,n){let r=me(`${t}/${n}`),i=[r];r.endsWith(`.js`)&&i.push(`${r.slice(0,-3)}.ts`),/\.[a-zA-Z0-9]+$/.test(r)||i.push(`${r}.ts`,`${r}.js`);for(let t of i)if(await e.exists(t))return t;return null}async function oTe(e,t,n,r,i){let a=new Map,o=new Map,s=[{path:n,cjs:r}];for(;s.length>0;){let{path:n,cjs:r}=s.shift(),c=FK(n),l=new Map;for(let n of iTe(r)){if(!n.startsWith(`./`)&&!n.startsWith(`../`))continue;let r=await aTe(e,c,n);if(!r||(l.set(n,r),a.has(r)))continue;let o=await e.readFile(r),u=t.transpileModule(o,{compilerOptions:i,fileName:r}).outputText;a.set(r,u),s.push({path:r,cjs:u})}o.set(n,l)}return{modules:a,edgeRewrites:o}}function sTe(e,t,n,r,i,a){let o=r===`spec`?`pretty`:`tap`,s=[];for(let[e,t]of i.entries()){let n=G7(t,a.get(e)??new Map);s.push(`${JSON.stringify(e)}: function (module, exports, require) {\n${n}\n}`)}return`"use strict";
9662
+ `.trim(),W7}function G7(e,t=new Map){return e.replace(/(^|[^\w$.])require\(\s*(["'`])([^"'`]+)\2\s*\)/g,(e,n,r,i)=>i===`tst`||i===`tst/tst.js`?`${n}__tstReq("tst")`:i===`tst/assert`||i===`tst/assert.js`?`${n}__tstReq("tst/assert")`:t.has(i)?`${n}__localReq(${JSON.stringify(t.get(i))})`:e)}function sTe(e){let t=new Set,n=/(?:^|[^\w$.])require\(\s*(["'`])([^"'`]+)\1\s*\)/g,r;for(;(r=n.exec(e))!==null;)t.add(r[2]);return[...t]}async function cTe(e,t,n){let r=me(`${t}/${n}`),i=[r];r.endsWith(`.js`)&&i.push(`${r.slice(0,-3)}.ts`),/\.[a-zA-Z0-9]+$/.test(r)||i.push(`${r}.ts`,`${r}.js`);for(let t of i)if(await e.exists(t))return t;return null}async function lTe(e,t,n,r,i){let a=new Map,o=new Map,s=[{path:n,cjs:r}];for(;s.length>0;){let{path:n,cjs:r}=s.shift(),c=FK(n),l=new Map;for(let n of sTe(r)){if(!n.startsWith(`./`)&&!n.startsWith(`../`))continue;let r=await cTe(e,c,n);if(!r||(l.set(n,r),a.has(r)))continue;let o=await e.readFile(r),u=t.transpileModule(o,{compilerOptions:i,fileName:r}).outputText;a.set(r,u),s.push({path:r,cjs:u})}o.set(n,l)}return{modules:a,edgeRewrites:o}}function uTe(e,t,n,r,i,a){let o=r===`spec`?`pretty`:`tap`,s=[];for(let[e,t]of i.entries()){let n=G7(t,a.get(e)??new Map);s.push(`${JSON.stringify(e)}: function (module, exports, require) {\n${n}\n}`)}return`"use strict";
9661
9663
  ${e}
9662
9664
  const __tstReq = (id) => {
9663
9665
  if (id === "tst") return __tst_module_exports;
@@ -9689,7 +9691,7 @@ const __state = await __tst.run({ format: ${JSON.stringify(o)} });
9689
9691
  await Promise.resolve();
9690
9692
  await new Promise((resolve) => setTimeout(resolve));
9691
9693
  if (__state && __state.failed && __state.failed.length > 0) process.exit(1);
9692
- `}const cTe={esModuleInterop:!0,allowJs:!0,isolatedModules:!1};function lTe(e){return{module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,...cTe}}async function uTe(e,t){let n;try{n=eTe(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:`test - run *.test.{js,ts} files with the bundled tst runner
9694
+ `}const dTe={esModuleInterop:!0,allowJs:!0,isolatedModules:!1};function fTe(e){return{module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,...dTe}}async function pTe(e,t){let n;try{n=rTe(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:`test - run *.test.{js,ts} files with the bundled tst runner
9693
9695
 
9694
9696
  Usage:
9695
9697
  test [options] [glob...]
@@ -9702,12 +9704,12 @@ Notes:
9702
9704
  - Default glob: **/*.test.{js,ts}, walked from the current cwd.
9703
9705
  - .ts files are transpiled via the bundled typescript package.
9704
9706
  - Each file runs in its own realm (same engine as 'node').
9705
- `,stderr:``,exitCode:0}};let r=await nTe(t.fs,t.cwd,n.globs);if(r.length===0)return{done:{stdout:``,stderr:`test: no test files matched ${n.globs.join(` `)}\n`,exitCode:1}};let i;try{i=await XK(R7(t))}catch(e){return{done:{stdout:``,stderr:`test: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}let a=await rTe(i);return{parsed:n,files:r,ts:i,harness:a,userOpts:lTe(i)}}function dTe(e){return e.includes(`# fail `)||/(^|\n)not ok /.test(e)}async function fTe(e,t,n,r){let{ts:i,harness:a,userOpts:o,parsed:s}=t,c;try{c=await e.fs.readFile(n)}catch(e){return{stdout:``,stderr:`test: ${n}: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let l;try{l=i.transpileModule(c,{compilerOptions:o,fileName:n}).outputText}catch(e){return{stdout:``,stderr:`test: ${n}: transpile error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let u,d;try{({modules:u,edgeRewrites:d}=await oTe(e.fs,i,n,l,o))}catch(e){return{stdout:``,stderr:`test: ${n}: local-require resolve error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let f=await $1(sTe(a,n,l,s.reporter,u,d),[`node`,n],e,void 0,{filename:n});return{stdout:r?`# ${n}\n${f.stdout}`:f.stdout,stderr:f.stderr,failed:f.exitCode!==0||dTe(f.stdout)}}function pTe(){return cA(`test`,async(e,t)=>{let n=await uTe(e,t);if(`done`in n)return n.done;let r=n.files.length>1,i=``,a=``,o=!1;for(let e of n.files){let s=await fTe(t,n,e,r);i+=s.stdout,a+=s.stderr,s.failed&&(o=!0)}return{stdout:i,stderr:a,exitCode:+!!o}})}function mTe(){return{stdout:`usage: uname
9706
- `,stderr:``,exitCode:0}}function hTe(){return cA(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return mTe();if(e.length>0)return{stdout:``,stderr:`uname: unsupported arguments
9707
+ `,stderr:``,exitCode:0}};let r=await aTe(t.fs,t.cwd,n.globs);if(r.length===0)return{done:{stdout:``,stderr:`test: no test files matched ${n.globs.join(` `)}\n`,exitCode:1}};let i;try{i=await XK(R7(t))}catch(e){return{done:{stdout:``,stderr:`test: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}let a=await oTe(i);return{parsed:n,files:r,ts:i,harness:a,userOpts:fTe(i)}}function mTe(e){return e.includes(`# fail `)||/(^|\n)not ok /.test(e)}async function hTe(e,t,n,r){let{ts:i,harness:a,userOpts:o,parsed:s}=t,c;try{c=await e.fs.readFile(n)}catch(e){return{stdout:``,stderr:`test: ${n}: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let l;try{l=i.transpileModule(c,{compilerOptions:o,fileName:n}).outputText}catch(e){return{stdout:``,stderr:`test: ${n}: transpile error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let u,d;try{({modules:u,edgeRewrites:d}=await lTe(e.fs,i,n,l,o))}catch(e){return{stdout:``,stderr:`test: ${n}: local-require resolve error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let f=await $1(uTe(a,n,l,s.reporter,u,d),[`node`,n],e,void 0,{filename:n});return{stdout:r?`# ${n}\n${f.stdout}`:f.stdout,stderr:f.stderr,failed:f.exitCode!==0||mTe(f.stdout)}}function gTe(){return cA(`test`,async(e,t)=>{let n=await pTe(e,t);if(`done`in n)return n.done;let r=n.files.length>1,i=``,a=``,o=!1;for(let e of n.files){let s=await hTe(t,n,e,r);i+=s.stdout,a+=s.stderr,s.failed&&(o=!0)}return{stdout:i,stderr:a,exitCode:+!!o}})}function _Te(){return{stdout:`usage: uname
9708
+ `,stderr:``,exitCode:0}}function vTe(){return cA(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return _Te();if(e.length>0)return{stdout:``,stderr:`uname: unsupported arguments
9707
9709
  `,exitCode:1};let t=globalThis.navigator?.userAgent;return typeof t!=`string`||t.length===0?{stdout:``,stderr:`uname: navigator.userAgent is unavailable
9708
- `,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function gTe(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
9709
- `,stderr:``,exitCode:0}}function _Te(){return cA(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return gTe();let n=`.`,r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`-d`){n=e[t+1]??``,t++;continue}if(i.startsWith(`-`))return{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1};r.push(i)}if(r.length<1)return{stdout:``,stderr:`unzip: expected archive path
9710
- `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=vL(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!RK(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=FK(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}const vTe=new Set([`--vid`,`--pid`,`--class`,`--subclass`,`--protocol`,`--serial`,`--request-type`,`--recipient`,`--request`,`--value`,`--index`,`--__resolved`]);function yTe(e){return dW(e,vTe)}function K7(e,t){let n=/^0x/i.test(e)?parseInt(e,16):parseInt(e,10);if(!Number.isFinite(n)||Number.isNaN(n))throw Error(`invalid ${t}: '${e}'`);return n}function bTe(e){let t={};return e.has(`--vid`)&&(t.vendorId=K7(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=K7(e.get(`--pid`),`pid`)),e.has(`--class`)&&(t.classCode=K7(e.get(`--class`),`class`)),e.has(`--subclass`)&&(t.subclassCode=K7(e.get(`--subclass`),`subclass`)),e.has(`--protocol`)&&(t.protocolCode=K7(e.get(`--protocol`),`protocol`)),e.has(`--serial`)&&(t.serialNumber=e.get(`--serial`)),Object.keys(t).length>0?[t]:[]}const xTe=new Set([`standard`,`class`,`vendor`]),STe=new Set([`device`,`interface`,`endpoint`,`other`]);function q7(e){let t=e.get(`--request-type`)??`vendor`,n=e.get(`--recipient`)??`device`;if(!xTe.has(t))throw Error(`invalid --request-type: '${t}'`);if(!STe.has(n))throw Error(`invalid --recipient: '${n}'`);return{requestType:t,recipient:n,request:K7(e.get(`--request`)??`0`,`request`),value:K7(e.get(`--value`)??`0`,`value`),index:K7(e.get(`--index`)??`0`,`index`)}}function J7(e){let t=Q1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function CTe(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function Y7(e){return`0x${e.toString(16).padStart(4,`0`)}`}function X7(e){let t=[e.manufacturerName,e.productName].filter(Boolean).join(` `)||`(unknown)`,n=e.serialNumber?` serial=${e.serialNumber}`:``,r=e.opened?` [open]`:``;return`${e.handle}\t${Y7(e.vendorId)}:${Y7(e.productId)}\t${t}${n}${r}`}function Z7(e){return{stdout:e,stderr:``,exitCode:0}}function Q7(e){return{stdout:``,stderr:`usb: ${e}\n`,exitCode:1}}const wTe=`usb - access USB devices via WebUSB
9710
+ `,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function yTe(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
9711
+ `,stderr:``,exitCode:0}}function bTe(){return cA(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return yTe();let n=`.`,r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`-d`){n=e[t+1]??``,t++;continue}if(i.startsWith(`-`))return{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1};r.push(i)}if(r.length<1)return{stdout:``,stderr:`unzip: expected archive path
9712
+ `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=vL(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!RK(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=FK(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}const xTe=new Set([`--vid`,`--pid`,`--class`,`--subclass`,`--protocol`,`--serial`,`--request-type`,`--recipient`,`--request`,`--value`,`--index`,`--__resolved`]);function STe(e){return dW(e,xTe)}function K7(e,t){let n=/^0x/i.test(e)?parseInt(e,16):parseInt(e,10);if(!Number.isFinite(n)||Number.isNaN(n))throw Error(`invalid ${t}: '${e}'`);return n}function CTe(e){let t={};return e.has(`--vid`)&&(t.vendorId=K7(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=K7(e.get(`--pid`),`pid`)),e.has(`--class`)&&(t.classCode=K7(e.get(`--class`),`class`)),e.has(`--subclass`)&&(t.subclassCode=K7(e.get(`--subclass`),`subclass`)),e.has(`--protocol`)&&(t.protocolCode=K7(e.get(`--protocol`),`protocol`)),e.has(`--serial`)&&(t.serialNumber=e.get(`--serial`)),Object.keys(t).length>0?[t]:[]}const wTe=new Set([`standard`,`class`,`vendor`]),TTe=new Set([`device`,`interface`,`endpoint`,`other`]);function q7(e){let t=e.get(`--request-type`)??`vendor`,n=e.get(`--recipient`)??`device`;if(!wTe.has(t))throw Error(`invalid --request-type: '${t}'`);if(!TTe.has(n))throw Error(`invalid --recipient: '${n}'`);return{requestType:t,recipient:n,request:K7(e.get(`--request`)??`0`,`request`),value:K7(e.get(`--value`)??`0`,`value`),index:K7(e.get(`--index`)??`0`,`index`)}}function J7(e){let t=Q1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function ETe(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function Y7(e){return`0x${e.toString(16).padStart(4,`0`)}`}function X7(e){let t=[e.manufacturerName,e.productName].filter(Boolean).join(` `)||`(unknown)`,n=e.serialNumber?` serial=${e.serialNumber}`:``,r=e.opened?` [open]`:``;return`${e.handle}\t${Y7(e.vendorId)}:${Y7(e.productId)}\t${t}${n}${r}`}function Z7(e){return{stdout:e,stderr:``,exitCode:0}}function Q7(e){return{stdout:``,stderr:`usb: ${e}\n`,exitCode:1}}const DTe=`usb - access USB devices via WebUSB
9711
9713
 
9712
9714
  Usage: usb <subcommand> [options]
9713
9715
 
@@ -9736,9 +9738,9 @@ Options:
9736
9738
  -h, --help
9737
9739
 
9738
9740
  Transfers are capped at ${L1} bytes (4 MiB).
9739
- `;function $7(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return Z7(t)}return Z7(e.length?`${CTe(e)}\n`:``)}async function TTe(e){let t=await e.list();return t.length===0?Z7(`no granted USB devices
9741
+ `;function $7(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return Z7(t)}return Z7(e.length?`${ETe(e)}\n`:``)}async function OTe(e){let t=await e.list();return t.length===0?Z7(`no granted USB devices
9740
9742
  `):Z7(`${t.map(X7).join(`
9741
- `)}\n`)}async function ETe(e,t){let n=e.get(`--__resolved`);if(n)return Z7(`${X7(await t.info(n))}\n`);let r=bTe(e),i=y();if(i){let e=await T(`usb-device`,r,i);if(e.handle)return Z7(`${X7(await t.info(e.handle))}\n`);let n=e.info,a=P1();if(!a)return Q7(`request: WebUSB unavailable for device re-acquire`);let o=(await a.getDevices()).find(e=>e.vendorId===n.vendorId&&e.productId===n.productId&&(!n.serialNumber||e.serialNumber===n.serialNumber));return o?Z7(`${X7(R1(I1().register(o),o))}\n`):Q7(`request: granted device could not be re-acquired`)}return Z7(`${X7(await t.request(r))}\n`)}async function DTe(e,t,n){let r=t[1];return r?(e===`open`?await n.open(r):e===`close`?await n.close(r):await n.reset(r),Z7(``)):Q7(`${e}: handle required`)}async function OTe(e,t){let[,n,r]=e;return!n||r===void 0?Q7(`select-config: handle and value required`):(await t.selectConfig(n,K7(r,`configuration`)),Z7(``))}async function kTe(e,t,n){let[,r,i]=t;return!r||i===void 0?Q7(`${e}: handle and interface required`):(await(e===`claim`?n.claim:n.release).call(n,r,K7(i,`interface`)),Z7(``))}async function ATe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return Q7(`control-in: handle and length required`);let o=K7(a,`length`);return o>4194304?Q7(`control-in length exceeds 4 MiB limit`):$7((await n.controlIn(i,q7(t),o)).bytes,r)}async function jTe(e,t,n,r){let i=e[1];if(!i)return Q7(`control-out: handle required`);let a=J7(t);return a.length>4194304?Q7(`control-out payload exceeds 4 MiB limit`):Z7(`${(await r.controlOut(i,q7(n),a)).bytesWritten} bytes written\n`)}async function MTe(e,t,n,r){let[,i,a,o]=e;if(!i||a===void 0||o===void 0)return Q7(`transfer-in: handle, endpoint and length required`);let s=K7(o,`length`);return s>4194304?Q7(`transfer-in length exceeds 4 MiB limit`):$7((await n.transferIn(i,K7(a,`endpoint`),s)).bytes,r)}async function NTe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return Q7(`transfer-out: handle and endpoint required`);let o=J7(t);return o.length>4194304?Q7(`transfer-out payload exceeds 4 MiB limit`):Z7(`${(await r.transferOut(i,K7(a,`endpoint`),o)).bytesWritten} bytes written\n`)}async function PTe(e,t,n){let{positionals:r,flags:i,bools:a}=yTe(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return TTe(n);case`request`:return ETe(i,n);case`open`:case`close`:case`reset`:return DTe(o,r,n);case`select-config`:return OTe(r,n);case`claim`:case`release`:return kTe(o,r,n);case`control-in`:return ATe(r,i,n,s);case`control-out`:return jTe(r,t,i,n);case`transfer-in`:return MTe(r,i,n,s);case`transfer-out`:return NTe(r,t,i,n);default:return Q7(`unknown subcommand '${o??``}'. Try 'usb --help'.`)}}function FTe(){return cA(`usb`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Z7(wTe);let n=W1(de(),ue());if(!n)return Q7(`WebUSB is unavailable in this environment`);try{return await PTe(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?Q7(`user cancelled or no device selected`):Q7(t)}})}new Set([{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}].map(e=>e.id));function ITe(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function e9(e,t){return`${new URL(e).origin}/webhooks/${t}`}function t9(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function LTe(){return{stdout:`usage: webhook <command> [options]
9743
+ `)}\n`)}async function kTe(e,t){let n=e.get(`--__resolved`);if(n)return Z7(`${X7(await t.info(n))}\n`);let r=CTe(e),i=y();if(i){let e=await T(`usb-device`,r,i);if(e.handle)return Z7(`${X7(await t.info(e.handle))}\n`);let n=e.info,a=P1();if(!a)return Q7(`request: WebUSB unavailable for device re-acquire`);let o=(await a.getDevices()).find(e=>e.vendorId===n.vendorId&&e.productId===n.productId&&(!n.serialNumber||e.serialNumber===n.serialNumber));return o?Z7(`${X7(R1(I1().register(o),o))}\n`):Q7(`request: granted device could not be re-acquired`)}return Z7(`${X7(await t.request(r))}\n`)}async function ATe(e,t,n){let r=t[1];return r?(e===`open`?await n.open(r):e===`close`?await n.close(r):await n.reset(r),Z7(``)):Q7(`${e}: handle required`)}async function jTe(e,t){let[,n,r]=e;return!n||r===void 0?Q7(`select-config: handle and value required`):(await t.selectConfig(n,K7(r,`configuration`)),Z7(``))}async function MTe(e,t,n){let[,r,i]=t;return!r||i===void 0?Q7(`${e}: handle and interface required`):(await(e===`claim`?n.claim:n.release).call(n,r,K7(i,`interface`)),Z7(``))}async function NTe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return Q7(`control-in: handle and length required`);let o=K7(a,`length`);return o>4194304?Q7(`control-in length exceeds 4 MiB limit`):$7((await n.controlIn(i,q7(t),o)).bytes,r)}async function PTe(e,t,n,r){let i=e[1];if(!i)return Q7(`control-out: handle required`);let a=J7(t);return a.length>4194304?Q7(`control-out payload exceeds 4 MiB limit`):Z7(`${(await r.controlOut(i,q7(n),a)).bytesWritten} bytes written\n`)}async function FTe(e,t,n,r){let[,i,a,o]=e;if(!i||a===void 0||o===void 0)return Q7(`transfer-in: handle, endpoint and length required`);let s=K7(o,`length`);return s>4194304?Q7(`transfer-in length exceeds 4 MiB limit`):$7((await n.transferIn(i,K7(a,`endpoint`),s)).bytes,r)}async function ITe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return Q7(`transfer-out: handle and endpoint required`);let o=J7(t);return o.length>4194304?Q7(`transfer-out payload exceeds 4 MiB limit`):Z7(`${(await r.transferOut(i,K7(a,`endpoint`),o)).bytesWritten} bytes written\n`)}async function LTe(e,t,n){let{positionals:r,flags:i,bools:a}=STe(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return OTe(n);case`request`:return kTe(i,n);case`open`:case`close`:case`reset`:return ATe(o,r,n);case`select-config`:return jTe(r,n);case`claim`:case`release`:return MTe(o,r,n);case`control-in`:return NTe(r,i,n,s);case`control-out`:return PTe(r,t,i,n);case`transfer-in`:return FTe(r,i,n,s);case`transfer-out`:return ITe(r,t,i,n);default:return Q7(`unknown subcommand '${o??``}'. Try 'usb --help'.`)}}function RTe(){return cA(`usb`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Z7(DTe);let n=W1(de(),ue());if(!n)return Q7(`WebUSB is unavailable in this environment`);try{return await LTe(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?Q7(`user cancelled or no device selected`):Q7(t)}})}new Set([{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}].map(e=>e.id));function zTe(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function e9(e,t){return`${new URL(e).origin}/webhooks/${t}`}function t9(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function BTe(){return{stdout:`usage: webhook <command> [options]
9742
9744
 
9743
9745
  Commands:
9744
9746
  create --scoop <name> [--name <name>] [--filter <code>] Create a new webhook endpoint
@@ -9756,7 +9758,7 @@ Examples:
9756
9758
  webhook create --scoop slack-relay --name slack --filter "(e) => ({ text: e.body.text, user: e.body.user })"
9757
9759
  webhook list
9758
9760
  webhook delete abc123
9759
- `,stderr:``,exitCode:0}}const n9=typeof chrome<`u`&&!!chrome?.runtime?.id;function r9(){return globalThis.__slicc_lickManager??null}let i9=null;async function RTe(){if(i9)return i9;let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return i9=e(),i9}async function a9(){if(!n9||r9())return Mn().session?.webhookUrl??null;let{getTrayWebhookUrlAsync:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return await e()}function o9(e,t){return t?t9(t,e):n9?`(URL unavailable — connect a leader tray)`:e9(self.location.href,e)}async function s9(){let e=r9();if(e)return{createWebhook:(t,n,r)=>e.createWebhook(t,n,r),deleteWebhook:t=>e.deleteWebhook(t),listWebhooks:async()=>e.listWebhooks()};if(!n9)return null;let t=await RTe(),{listWebhooksAsync:n}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return{createWebhook:(e,n,r)=>t.createWebhook(e,n,r),deleteWebhook:e=>t.deleteWebhook(e),listWebhooks:()=>n()}}function c9(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}function zTe(){return cA(`webhook`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return LTe();let t=e[0];try{switch(t){case`create`:{let t=`default`,n,r,i=e.indexOf(`--name`);i!==-1&&e[i+1]&&(t=e[i+1]);let a=e.indexOf(`--filter`);a!==-1&&e[a+1]&&(n=e[a+1]);let o=e.indexOf(`--scoop`);if(o!==-1&&e[o+1]&&(r=e[o+1]),!r)return{stdout:``,stderr:`webhook create: --scoop is required (every webhook must route to a scoop)
9761
+ `,stderr:``,exitCode:0}}const n9=typeof chrome<`u`&&!!chrome?.runtime?.id;function r9(){return globalThis.__slicc_lickManager??null}let i9=null;async function VTe(){if(i9)return i9;let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return i9=e(),i9}async function a9(){if(!n9||r9())return Mn().session?.webhookUrl??null;let{getTrayWebhookUrlAsync:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return await e()}function o9(e,t){return t?t9(t,e):n9?`(URL unavailable — connect a leader tray)`:e9(self.location.href,e)}async function s9(){let e=r9();if(e)return{createWebhook:(t,n,r)=>e.createWebhook(t,n,r),deleteWebhook:t=>e.deleteWebhook(t),listWebhooks:async()=>e.listWebhooks()};if(!n9)return null;let t=await VTe(),{listWebhooksAsync:n}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return{createWebhook:(e,n,r)=>t.createWebhook(e,n,r),deleteWebhook:e=>t.deleteWebhook(e),listWebhooks:()=>n()}}function c9(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}function HTe(){return cA(`webhook`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return BTe();let t=e[0];try{switch(t){case`create`:{let t=`default`,n,r,i=e.indexOf(`--name`);i!==-1&&e[i+1]&&(t=e[i+1]);let a=e.indexOf(`--filter`);a!==-1&&e[a+1]&&(n=e[a+1]);let o=e.indexOf(`--scoop`);if(o!==-1&&e[o+1]&&(r=e[o+1]),!r)return{stdout:``,stderr:`webhook create: --scoop is required (every webhook must route to a scoop)
9760
9762
  `,exitCode:1};if(n9&&n)return{stdout:``,stderr:`webhook create: --filter is not supported in extension mode (CSP forbids dynamic eval) — drop --filter, or use standalone CLI mode
9761
9763
  `,exitCode:1};if(n9&&!await a9()){let e=Mn().state;return{stdout:``,stderr:(e===`leader`?`webhook create: tray session is not connected yet — wait for the leader to attach`:`webhook create: requires extension-leader mode with a tray worker URL configured (current state: "${e}")`)+`
9762
9764
  `,exitCode:1}}let s=await s9();if(!s)return c9(`create`);let c=await s.createWebhook(t,r,n),l;try{let e=await a9();l=o9(c.id,e)}catch(e){l=`(URL resolution failed: ${e instanceof Error?e.message:String(e)})`}let u=`Created webhook "${c.name}"\nID: ${c.id}\nURL: ${l}\n`;return c.scoop&&(u+=`Scoop: ${c.scoop}\n`),c.filter&&(u+=`Filter: ${c.filter}\n`),{stdout:u,stderr:``,exitCode:0}}case`list`:{let e=await s9();if(!e)return c9(`list`);let t=await e.listWebhooks();if(t.length===0)return{stdout:`No active webhooks
@@ -9765,7 +9767,7 @@ Examples:
9765
9767
  `;return r?a+=`\nNote: webhook URL resolution failed (${r}). Try again once the tray is connected.\n`:n9&&!n&&(a+=`
9766
9768
  Note: webhook URLs require a leader tray. Configure one in Settings to expose POST endpoints.
9767
9769
  `),{stdout:a,stderr:``,exitCode:0}}case`delete`:{let t=e[1];if(!t)return{stdout:``,stderr:`webhook delete: requires an ID
9768
- `,exitCode:1};let n=await s9();return n?await n.deleteWebhook(t)?{stdout:`Deleted webhook "${t}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`webhook delete: webhook "${t}" not found\n`,exitCode:1}:c9(`delete`)}default:return{stdout:``,stderr:`webhook: unknown command "${t}"\n`,exitCode:1}}}catch(e){let n=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`webhook ${t??`?`}: ${n}\n`,exitCode:1}}})}function BTe(){return{stdout:`usage: websocat [FLAGS] [OPTIONS] <ws://URL | wss://URL>
9770
+ `,exitCode:1};let n=await s9();return n?await n.deleteWebhook(t)?{stdout:`Deleted webhook "${t}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`webhook delete: webhook "${t}" not found\n`,exitCode:1}:c9(`delete`)}default:return{stdout:``,stderr:`webhook: unknown command "${t}"\n`,exitCode:1}}}catch(e){let n=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`webhook ${t??`?`}: ${n}\n`,exitCode:1}}})}function UTe(){return{stdout:`usage: websocat [FLAGS] [OPTIONS] <ws://URL | wss://URL>
9769
9771
 
9770
9772
  Minimal websocat client. Sends stdin lines as WebSocket messages and prints
9771
9773
  received messages to stdout. Server mode and advanced specifiers (exec:, tcp:,
@@ -9807,19 +9809,19 @@ EXAMPLES:
9807
9809
  echo 'Page.navigate {"url":"https://example.com"}' \\
9808
9810
  | websocat -1 --jsonrpc --jsonrpc-omit-jsonrpc \\
9809
9811
  ws://127.0.0.1:9222/devtools/page/<id>
9810
- `,stderr:``,exitCode:0}}const l9=new Set([`-s`,`--server-mode`,`--oneshot`,`--socks5`,`--basic-auth`,`--basic-auth-file`,`--header-to-env`,`--server-header`,`--exec`,`--ws-c-uri`,`--restrict-uri`,`--unlink`,`--strict`,`-S`]);function VTe(e){let t={text:!0,binary:!1,oneMessage:!1,noClose:!1,exitOnEof:!1,unidirectional:!1,unidirectionalReverse:!1,insecure:!1,quiet:!1,verbose:0,nullTerminated:!1,base64:!1,jsonrpc:!1,jsonrpcOmit:!1,bufferSize:65536,connTimeoutMs:3e4,customHeaders:[],showHelp:!1},n=(n,r)=>{let i=e[n].indexOf(`=`);if(i!==-1&&e[n].startsWith(r))return{value:e[n].slice(i+1),next:n};let a=e[n+1];return a===void 0?(t.error=`websocat: missing value for ${r}\n`,null):{value:a,next:n+1}};for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`-h`||i===`--help`)return t.showHelp=!0,t;if(l9.has(i)||l9.has(i.split(`=`)[0]))return t.error=`websocat: flag '${i}' is not supported in slicc's minimal client\n`,t;if(i===`-t`||i===`--text`){t.text=!0,t.binary=!1;continue}if(i===`-b`||i===`--binary`){t.binary=!0,t.text=!1;continue}if(i===`-1n`||i===`-n1`){t.oneMessage=!0,t.noClose=!0;continue}if(i===`-1`||i===`--one-message`){t.oneMessage=!0;continue}if(i===`-n`||i===`--no-close`){t.noClose=!0;continue}if(i===`-E`||i===`--exit-on-eof`){t.exitOnEof=!0;continue}if(i===`-u`||i===`--unidirectional`){t.unidirectional=!0;continue}if(i===`-U`||i===`--unidirectional-reverse`){t.unidirectionalReverse=!0;continue}if(i===`-k`||i===`--insecure`){t.insecure=!0;continue}if(i===`-q`){t.quiet=!0;continue}if(i===`-v`){t.verbose+=1;continue}if(i===`-vv`){t.verbose+=2;continue}if(i===`-0`||i===`--null-terminated`){t.nullTerminated=!0;continue}if(i===`--base64`){t.base64=!0;continue}if(i===`--jsonrpc`){t.jsonrpc=!0;continue}if(i===`--jsonrpc-omit-jsonrpc`){t.jsonrpcOmit=!0,t.jsonrpc=!0;continue}if(i===`--close-status-code`||i.startsWith(`--close-status-code=`)){let e=n(r,`--close-status-code`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<1e3||i>4999)return t.error=`websocat: --close-status-code expects 1000..4999, got '${e.value}'\n`,t;t.closeStatus=i,r=e.next;continue}if(i===`--close-reason`||i.startsWith(`--close-reason=`)){let e=n(r,`--close-reason`);if(!e)return t;t.closeReason=e.value,r=e.next;continue}if(i===`-B`||i===`--buffer-size`||i.startsWith(`--buffer-size=`)){let e=n(r,i===`-B`?`-B`:`--buffer-size`);if(!e)return t;let a=Number(e.value);if(!Number.isFinite(a)||a<=0)return t.error=`websocat: --buffer-size expects positive integer
9812
+ `,stderr:``,exitCode:0}}const l9=new Set([`-s`,`--server-mode`,`--oneshot`,`--socks5`,`--basic-auth`,`--basic-auth-file`,`--header-to-env`,`--server-header`,`--exec`,`--ws-c-uri`,`--restrict-uri`,`--unlink`,`--strict`,`-S`]);function WTe(e){let t={text:!0,binary:!1,oneMessage:!1,noClose:!1,exitOnEof:!1,unidirectional:!1,unidirectionalReverse:!1,insecure:!1,quiet:!1,verbose:0,nullTerminated:!1,base64:!1,jsonrpc:!1,jsonrpcOmit:!1,bufferSize:65536,connTimeoutMs:3e4,customHeaders:[],showHelp:!1},n=(n,r)=>{let i=e[n].indexOf(`=`);if(i!==-1&&e[n].startsWith(r))return{value:e[n].slice(i+1),next:n};let a=e[n+1];return a===void 0?(t.error=`websocat: missing value for ${r}\n`,null):{value:a,next:n+1}};for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`-h`||i===`--help`)return t.showHelp=!0,t;if(l9.has(i)||l9.has(i.split(`=`)[0]))return t.error=`websocat: flag '${i}' is not supported in slicc's minimal client\n`,t;if(i===`-t`||i===`--text`){t.text=!0,t.binary=!1;continue}if(i===`-b`||i===`--binary`){t.binary=!0,t.text=!1;continue}if(i===`-1n`||i===`-n1`){t.oneMessage=!0,t.noClose=!0;continue}if(i===`-1`||i===`--one-message`){t.oneMessage=!0;continue}if(i===`-n`||i===`--no-close`){t.noClose=!0;continue}if(i===`-E`||i===`--exit-on-eof`){t.exitOnEof=!0;continue}if(i===`-u`||i===`--unidirectional`){t.unidirectional=!0;continue}if(i===`-U`||i===`--unidirectional-reverse`){t.unidirectionalReverse=!0;continue}if(i===`-k`||i===`--insecure`){t.insecure=!0;continue}if(i===`-q`){t.quiet=!0;continue}if(i===`-v`){t.verbose+=1;continue}if(i===`-vv`){t.verbose+=2;continue}if(i===`-0`||i===`--null-terminated`){t.nullTerminated=!0;continue}if(i===`--base64`){t.base64=!0;continue}if(i===`--jsonrpc`){t.jsonrpc=!0;continue}if(i===`--jsonrpc-omit-jsonrpc`){t.jsonrpcOmit=!0,t.jsonrpc=!0;continue}if(i===`--close-status-code`||i.startsWith(`--close-status-code=`)){let e=n(r,`--close-status-code`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<1e3||i>4999)return t.error=`websocat: --close-status-code expects 1000..4999, got '${e.value}'\n`,t;t.closeStatus=i,r=e.next;continue}if(i===`--close-reason`||i.startsWith(`--close-reason=`)){let e=n(r,`--close-reason`);if(!e)return t;t.closeReason=e.value,r=e.next;continue}if(i===`-B`||i===`--buffer-size`||i.startsWith(`--buffer-size=`)){let e=n(r,i===`-B`?`-B`:`--buffer-size`);if(!e)return t;let a=Number(e.value);if(!Number.isFinite(a)||a<=0)return t.error=`websocat: --buffer-size expects positive integer
9811
9813
  `,t;t.bufferSize=a,r=e.next;continue}if(i===`--max-messages`||i.startsWith(`--max-messages=`)){let e=n(r,`--max-messages`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<=0)return t.error=`websocat: --max-messages expects positive integer
9812
9814
  `,t;t.maxMessages=i,r=e.next;continue}if(i===`--protocol`||i.startsWith(`--protocol=`)){let e=n(r,`--protocol`);if(!e)return t;t.protocol=e.value,r=e.next;continue}if(i===`--ping-interval`||i.startsWith(`--ping-interval=`)){let e=n(r,`--ping-interval`);if(!e)return t;t.pingInterval=Number(e.value),r=e.next;continue}if(i===`--conn-timeout`||i.startsWith(`--conn-timeout=`)){let e=n(r,`--conn-timeout`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<=0)return t.error=`websocat: --conn-timeout expects positive seconds
9813
9815
  `,t;t.connTimeoutMs=Math.round(i*1e3),r=e.next;continue}if(i===`-H`||i===`--header`||i.startsWith(`--header=`)){let e=n(r,i===`-H`?`-H`:`--header`);if(!e)return t;t.customHeaders.push(e.value),r=e.next;continue}if(i.startsWith(`-`))return t.error=`websocat: unknown flag '${i}'\n`,t;if(t.url)return t.error=`websocat: extra positional argument '${i}' — advanced mode is not supported\n`,t;t.url=i}return t.closeReason!==void 0&&t.closeStatus===void 0&&(t.error=`websocat: --close-reason requires --close-status-code (the WebSocket close frame cannot carry a reason without a status code)
9814
- `),t}function HTe(e,t){if(!e)return[];let n=t?`\0`:`
9815
- `,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function UTe(e,t,n){let r=e.trim();if(!r)return e;let i=r.search(/\s/),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i+1).trim(),s=[];if(o)try{s=JSON.parse(o)}catch{s=[o]}let c={id:t,method:a,params:s};return n||(c.jsonrpc=`2.0`),JSON.stringify(c)}function u9(e){let t=``;for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t)}function WTe(e){try{return new TextDecoder(`utf-8`,{fatal:!1}).decode(e)}catch{return u9(e)}}async function GTe(e,t,n={}){let r=VTe(e);if(r.showHelp)return BTe();if(r.error)return{stdout:``,stderr:r.error,exitCode:2};if(!r.url)return{stdout:``,stderr:`websocat: missing ws:// or wss:// URL (use --help for usage)
9816
+ `),t}function GTe(e,t){if(!e)return[];let n=t?`\0`:`
9817
+ `,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function KTe(e,t,n){let r=e.trim();if(!r)return e;let i=r.search(/\s/),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i+1).trim(),s=[];if(o)try{s=JSON.parse(o)}catch{s=[o]}let c={id:t,method:a,params:s};return n||(c.jsonrpc=`2.0`),JSON.stringify(c)}function u9(e){let t=``;for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t)}function qTe(e){try{return new TextDecoder(`utf-8`,{fatal:!1}).decode(e)}catch{return u9(e)}}async function JTe(e,t,n={}){let r=WTe(e);if(r.showHelp)return UTe();if(r.error)return{stdout:``,stderr:r.error,exitCode:2};if(!r.url)return{stdout:``,stderr:`websocat: missing ws:// or wss:// URL (use --help for usage)
9816
9818
  `,exitCode:2};if(!/^wss?:\/\//i.test(r.url))return{stdout:``,stderr:`websocat: URL must start with ws:// or wss://, got '${r.url}'\n`,exitCode:2};let i=n.WebSocketCtor??(typeof WebSocket<`u`?WebSocket:void 0);if(!i)return{stdout:``,stderr:`websocat: no WebSocket implementation available in this runtime
9817
9819
  `,exitCode:1};let a=[],o=e=>{r.quiet||a.push(`websocat: ${e}`)};r.verbose>=1&&(r.customHeaders.length>0&&o(`-H/--header is accepted for parity but browsers do not allow setting WebSocket request headers; only --protocol is honored`),r.pingInterval!==void 0&&o(`--ping-interval has no effect in browsers (no ping API exposed)`),r.insecure&&o(`-k/--insecure has no effect in browsers`));let s=[],c=r.nullTerminated?`\0`:`
9818
- `,l;try{l=r.protocol?new i(r.url,r.protocol):new i(r.url)}catch(e){return{stdout:``,stderr:`websocat: connect failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}l.binaryType=`arraybuffer`;let u=0,d=1e4,f=0,p=!1,m,h,g=new Promise((e,t)=>{m=e,h=t}),_,v=!1,y=new Promise(e=>{_=t=>{v||(v=!0,e(t))}}),b=0,x=!1,S=setTimeout(()=>{x=!0;try{l.close()}catch{}p||h(Error(`connect timeout`))},r.connTimeoutMs);l.onopen=()=>{clearTimeout(S),p=!0,m()};let C=!1;l.onmessage=e=>{if(!C){if(!r.unidirectional){let t,n=!1;typeof e.data==`string`?t=new TextEncoder().encode(e.data):e.data instanceof ArrayBuffer?(t=new Uint8Array(e.data),n=!0):ArrayBuffer.isView(e.data)?(t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength),n=!0):t=new TextEncoder().encode(String(e.data)),t.length>r.bufferSize&&(o(`inbound message of ${t.length} bytes exceeds --buffer-size ${r.bufferSize}; truncating`),t=t.slice(0,r.bufferSize));let i=n&&r.base64?u9(t):WTe(t);s.length<d?s.push(i):(f===0&&o(`output buffer reached ${d} messages; dropping further inbound messages — use -1, --max-messages, or pipe to a file with a different tool for long-running streams`),f+=1)}if(u+=1,r.maxMessages!==void 0&&u>=r.maxMessages){C=!0,T();return}r.oneMessage&&(C=!0,T())}},l.onerror=()=>{x||(o(`websocket error`),b=1,p||h(Error(`connect failed`)))},l.onclose=e=>{if(clearTimeout(S),x){_(124);return}r.verbose>=1&&o(`closed code=${e.code} reason=${JSON.stringify(e.reason||``)}`),b===0&&e.code!==1e3&&e.code!==1005&&e.code!==1001&&(b=1),p||h(Error(`connect closed (code ${e.code})`)),_(b)};function w(e,t){try{t===void 0?l.close(e):l.close(e,t)}catch{}}function T(){if(r.noClose){_(b);return}w(r.closeStatus??1e3,r.closeReason)}try{await g}catch(e){clearTimeout(S);let t=e instanceof Error?e.message:String(e);return{stdout:s.join(c)+(s.length?c:``),stderr:a.concat([`websocat: ${t}`]).join(`
9820
+ `,l;try{l=r.protocol?new i(r.url,r.protocol):new i(r.url)}catch(e){return{stdout:``,stderr:`websocat: connect failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}l.binaryType=`arraybuffer`;let u=0,d=1e4,f=0,p=!1,m,h,g=new Promise((e,t)=>{m=e,h=t}),_,v=!1,y=new Promise(e=>{_=t=>{v||(v=!0,e(t))}}),b=0,x=!1,S=setTimeout(()=>{x=!0;try{l.close()}catch{}p||h(Error(`connect timeout`))},r.connTimeoutMs);l.onopen=()=>{clearTimeout(S),p=!0,m()};let C=!1;l.onmessage=e=>{if(!C){if(!r.unidirectional){let t,n=!1;typeof e.data==`string`?t=new TextEncoder().encode(e.data):e.data instanceof ArrayBuffer?(t=new Uint8Array(e.data),n=!0):ArrayBuffer.isView(e.data)?(t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength),n=!0):t=new TextEncoder().encode(String(e.data)),t.length>r.bufferSize&&(o(`inbound message of ${t.length} bytes exceeds --buffer-size ${r.bufferSize}; truncating`),t=t.slice(0,r.bufferSize));let i=n&&r.base64?u9(t):qTe(t);s.length<d?s.push(i):(f===0&&o(`output buffer reached ${d} messages; dropping further inbound messages — use -1, --max-messages, or pipe to a file with a different tool for long-running streams`),f+=1)}if(u+=1,r.maxMessages!==void 0&&u>=r.maxMessages){C=!0,T();return}r.oneMessage&&(C=!0,T())}},l.onerror=()=>{x||(o(`websocket error`),b=1,p||h(Error(`connect failed`)))},l.onclose=e=>{if(clearTimeout(S),x){_(124);return}r.verbose>=1&&o(`closed code=${e.code} reason=${JSON.stringify(e.reason||``)}`),b===0&&e.code!==1e3&&e.code!==1005&&e.code!==1001&&(b=1),p||h(Error(`connect closed (code ${e.code})`)),_(b)};function w(e,t){try{t===void 0?l.close(e):l.close(e,t)}catch{}}function T(){if(r.noClose){_(b);return}w(r.closeStatus??1e3,r.closeReason)}try{await g}catch(e){clearTimeout(S);let t=e instanceof Error?e.message:String(e);return{stdout:s.join(c)+(s.length?c:``),stderr:a.concat([`websocat: ${t}`]).join(`
9819
9821
  `)+`
9820
- `,exitCode:t===`connect timeout`?124:1}}if(r.unidirectionalReverse)!r.noClose&&r.exitOnEof&&!r.oneMessage&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0);else{let e=HTe(t.stdin,r.nullTerminated),n=1,i=0,a=r.oneMessage?e.slice(0,1):e;for(let e of a){let t=e;r.jsonrpc&&(t=UTe(e,n,r.jsonrpcOmit),n+=1),r.binary?l.send(new TextEncoder().encode(t).buffer):l.send(t),i+=1}!r.oneMessage&&!r.noClose&&(r.exitOnEof||i===0)&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0)}let E=await y;return f>0&&o(`dropped ${f} inbound message(s) due to output buffer cap`),{stdout:s.length?s.join(c)+c:``,stderr:a.length?a.join(`
9822
+ `,exitCode:t===`connect timeout`?124:1}}if(r.unidirectionalReverse)!r.noClose&&r.exitOnEof&&!r.oneMessage&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0);else{let e=GTe(t.stdin,r.nullTerminated),n=1,i=0,a=r.oneMessage?e.slice(0,1):e;for(let e of a){let t=e;r.jsonrpc&&(t=KTe(e,n,r.jsonrpcOmit),n+=1),r.binary?l.send(new TextEncoder().encode(t).buffer):l.send(t),i+=1}!r.oneMessage&&!r.noClose&&(r.exitOnEof||i===0)&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0)}let E=await y;return f>0&&o(`dropped ${f} inbound message(s) due to output buffer cap`),{stdout:s.length?s.join(c)+c:``,stderr:a.length?a.join(`
9821
9823
  `)+`
9822
- `:``,exitCode:E}}function KTe(){return cA(`websocat`,async(e,t)=>GTe(e,{stdin:Z1(t.stdin)}))}function qTe(){return cA(`__wf_progress`,async()=>({stdout:``,stderr:``,exitCode:0}))}async function JTe(e){return e.scriptCatalog?e.scriptCatalog.getJshCommands():e.fs?n0(e.fs):new Map}async function YTe(e){return e.scriptCatalog?e.scriptCatalog.getWorkflowCommands():e.fs?l0(e.fs):new Map}function XTe(e,t,n,r,i){if(r.has(e)){let r=[`/usr/bin/${e}`];return(t||n)&&r.push(` (shadowed by built-in ${e})`),{lines:r,found:!0}}if(t){let e=[t];return n&&e.push(` ${n.path} (workflow, shadowed by .jsh)`),{lines:e,found:!0}}return n?{lines:[`${n.path} (workflow)`],found:!0}:i.has(e)?{lines:[`/usr/bin/${e}`],found:!0}:{lines:[],found:!1}}function ZTe(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return cA(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
9824
+ `:``,exitCode:E}}function YTe(){return cA(`websocat`,async(e,t)=>JTe(e,{stdin:Z1(t.stdin)}))}function XTe(){return cA(`__wf_progress`,async()=>({stdout:``,stderr:``,exitCode:0}))}async function ZTe(e){return e.scriptCatalog?e.scriptCatalog.getJshCommands():e.fs?n0(e.fs):new Map}async function QTe(e){return e.scriptCatalog?e.scriptCatalog.getWorkflowCommands():e.fs?l0(e.fs):new Map}function $Te(e,t,n,r,i){if(r.has(e)){let r=[`/usr/bin/${e}`];return(t||n)&&r.push(` (shadowed by built-in ${e})`),{lines:r,found:!0}}if(t){let e=[t];return n&&e.push(` ${n.path} (workflow, shadowed by .jsh)`),{lines:e,found:!0}}return n?{lines:[`${n.path} (workflow)`],found:!0}:i.has(e)?{lines:[`/usr/bin/${e}`],found:!0}:{lines:[],found:!1}}function eEe(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return cA(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
9823
9825
 
9824
9826
  Usage: which <command> [command...]
9825
9827
 
@@ -9829,9 +9831,9 @@ Prints the path of the given command(s).
9829
9831
 
9830
9832
  Exit code 0 if all commands found, 1 if any not found.
9831
9833
  `,stderr:``,exitCode:0};if(e.length===0)return{stdout:``,stderr:`which: missing argument
9832
- `,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=await JTe(t),o=await YTe(t),s=typeof t.getStaticBuiltins==`function`?new Set(t.getStaticBuiltins()):i,c=[],l=!0;for(let t of e){let e=XTe(t,a.get(t),o.get(t),s,i);c.push(...e.lines),e.found||(l=!1)}return{stdout:c.length>0?c.join(`
9834
+ `,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=await ZTe(t),o=await QTe(t),s=typeof t.getStaticBuiltins==`function`?new Set(t.getStaticBuiltins()):i,c=[],l=!0;for(let t of e){let e=$Te(t,a.get(t),o.get(t),s,i);c.push(...e.lines),e.found||(l=!1)}return{stdout:c.length>0?c.join(`
9833
9835
  `)+`
9834
- `:``,stderr:``,exitCode:+!l}})}const d9=i(`workflow-run-manager`),f9=`__slicc_workflows`,p9=`/shared/workflow-runs`,m9=1e3;function QTe(e){let t=new Map,n=new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){d9.warn(`observeRun handler threw`,e)}},i=t=>t===void 0?`terminal`:t===e.getConeJid()?`cone`:`scoop`,a=(e,n)=>rEe(e,n,t,()=>r(n));async function o(o){let l=o.runId??e.makeRunId(),u=o.sentinel,d={id:l,name:o.name,source:o.source,origin:i(o.parentJid),status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:new Date().toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(l,d),tEe(t,n);let f=a(o.ctx,l),p=nEe(e.processManager,d,l,()=>r(l));return e.runRealm(o.code,[`workflow`,o.filename,l],f).then(e=>s(l,u,e)).catch(e=>c(l,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>d9.warn(`workflow run lifecycle error`,e)),{runId:l}}async function s(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?l(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?l(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):l(t,`done`,i,null)}function c(e,t){return l(e,`error`,null,t)}async function l(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${p9}/${n}.json`,l=new Date().toISOString();try{await e.sharedFs.mkdir(p9,{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:l},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);d9.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=l,s.preview=i===`done`?eEe(a):o??``,r(n),u(s)}function u(t){t.origin===`cone`&&e.fireLick({type:`workflow`,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:new Date().toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:o,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){d9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function $Te(e){let t=QTe(e);return globalThis[f9]=t,d9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function eEe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function tEe(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 nEe(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 rEe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?iEe(n,t,a?.args??[],r):e===`agent`?aEe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function iEe(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>m9&&i.logs.splice(0,i.logs.length-m9),r()}return{stdout:``,stderr:``,exitCode:0}}async function aEe(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 oEe=String.raw`
9836
+ `:``,stderr:``,exitCode:+!l}})}const d9=i(`workflow-run-manager`),f9=`__slicc_workflows`,p9=`/shared/workflow-runs`,m9=1e3;function tEe(e){let t=new Map,n=new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){d9.warn(`observeRun handler threw`,e)}},i=t=>t===void 0?`terminal`:t===e.getConeJid()?`cone`:`scoop`,a=(e,n)=>oEe(e,n,t,()=>r(n));async function o(o){let l=o.runId??e.makeRunId(),u=o.sentinel,d={id:l,name:o.name,source:o.source,origin:i(o.parentJid),status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:new Date().toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(l,d),iEe(t,n);let f=a(o.ctx,l),p=aEe(e.processManager,d,l,()=>r(l));return e.runRealm(o.code,[`workflow`,o.filename,l],f).then(e=>s(l,u,e)).catch(e=>c(l,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>d9.warn(`workflow run lifecycle error`,e)),{runId:l}}async function s(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?l(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?l(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):l(t,`done`,i,null)}function c(e,t){return l(e,`error`,null,t)}async function l(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${p9}/${n}.json`,l=new Date().toISOString();try{await e.sharedFs.mkdir(p9,{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:l},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);d9.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=l,s.preview=i===`done`?rEe(a):o??``,r(n),u(s)}function u(t){t.origin===`cone`&&e.fireLick({type:`workflow`,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:new Date().toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:o,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){d9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function nEe(e){let t=tEe(e);return globalThis[f9]=t,d9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function rEe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function iEe(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 aEe(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 oEe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?sEe(n,t,a?.args??[],r):e===`agent`?cEe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function sEe(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>m9&&i.logs.splice(0,i.logs.length-m9),r()}return{stdout:``,stderr:``,exitCode:0}}async function cEe(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 lEe=String.raw`
9835
9837
  class WorkflowError extends Error {}
9836
9838
  class WorkflowDeterminismError extends WorkflowError {}
9837
9839
  class WorkflowAgentCapError extends WorkflowError {}
@@ -9941,11 +9943,11 @@ function log(message) {
9941
9943
  }
9942
9944
  const budget = { total: (__WF.budget == null ? null : __WF.budget), spent() { return 0; }, remaining() { return this.total == null ? Infinity : Math.max(0, this.total - this.spent()); } };
9943
9945
  function workflow() { throw new WorkflowNestingUnsupportedError('nested workflow() unsupported in SP1'); }
9944
- `;function h9(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function sEe(e){let t=uEe(e);return t===null?{name:null,description:null}:{name:_9(t,`name`),description:_9(t,`description`)}}function cEe(e){return e.replace(/\bexport\s+(const|let|var|function|async\s+function|class)\b/g,`$1`)}function lEe(e){return`const __emit = console.log.bind(console);
9946
+ `;function h9(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function uEe(e){let t=pEe(e);return t===null?{name:null,description:null}:{name:_9(t,`name`),description:_9(t,`description`)}}function dEe(e){return e.replace(/\bexport\s+(const|let|var|function|async\s+function|class)\b/g,`$1`)}function fEe(e){return`const __emit = console.log.bind(console);
9945
9947
  const __stringify = JSON.stringify.bind(JSON);
9946
- const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${cEe(e.body)}\n})();\n__emit(${JSON.stringify(e.sentinel)} + __stringify(__r ?? null));\n`}function g9(e,t){let n=e.split(`
9948
+ const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${dEe(e.body)}\n})();\n__emit(${JSON.stringify(e.sentinel)} + __stringify(__r ?? null));\n`}function g9(e,t){let n=e.split(`
9947
9949
  `);for(let e=n.length-1;e>=0;e--)if(n[e].startsWith(t)){let r=[...n.slice(0,e),...n.slice(e+1)].join(`
9948
- `).replace(/\n+$/,``);try{return{result:JSON.parse(n[e].slice(t.length)),log:r,hadResult:!0}}catch{return{result:null,log:r,hadResult:!0}}}return{result:null,log:e.replace(/\n+$/,``),hadResult:!1}}function uEe(e){let t=/\bmeta\s*=\s*\{/.exec(e);if(!t)return null;let n=t.index+t[0].length-1,r=0;for(let t=n;t<e.length;t++)if(e[t]===`{`)r++;else if(e[t]===`}`&&--r===0)return e.slice(n+1,t);return null}function _9(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1`).exec(e);return n?n[2]:null}const v9=i(`workflow-command`);function y9(){return globalThis[f9]}function dEe(){let e=globalThis.navigator?.hardwareConcurrency??8;return Math.min(16,Math.max(8,e*4))}function fEe(e,t,n,r){let i=t[n];switch(i){case`-h`:case`--help`:return{i:n,help:!0};case`--script`:return e.script=t[++n],{i:n};case`--wait`:return e.wait=!0,{i:n};case`--args`:try{e.args=JSON.parse(t[++n]??``),e.hasArgs=!0}catch{return{i:n,error:`workflow: --args must be valid JSON`}}return{i:n};case`--budget`:{let r=Number(t[++n]);return Number.isFinite(r)?(e.budget=r,{i:n}):{i:n,error:`workflow: --budget must be a number`}}case`--concurrency`:{let i=Number(t[++n]);return Number.isFinite(i)?(e.cap=Math.min(r,Math.max(1,Math.trunc(i))),{i:n}):{i:n,error:`workflow: --concurrency must be a number`}}default:return i.startsWith(`-`)?{i:n,error:`workflow: unknown flag '${i}'`}:e.file===void 0?(e.file=i,{i:n}):{i:n,error:`workflow: too many arguments`}}}function pEe(e){if(e[0]!==`run`)return e.length===0||e.includes(`-h`)||e.includes(`--help`)?{help:!0}:{error:`workflow: unknown subcommand '${e[0]}' (only 'run' in SP1)`};let t=dEe(),n={budget:null,cap:Math.min(8,t)};for(let r=1;r<e.length;r++){let i=fEe(n,e,r,t);if(i.help)return{help:!0};if(i.error)return{error:i.error};r=i.i}return n.script===void 0&&n.file===void 0?{error:`workflow: a <file.js> or --script is required`}:n}function mEe(e={}){return cA(`workflow`,async(t,n)=>{if(t[0]===`list`||t[0]===`status`||t[0]===`stop`)return yEe(t,n);if(t[0]===`save`)return vEe(t,n,e);let r=pEe(t);if(r.help)return{stdout:`usage: workflow run <file.js> [--args <json>] [--budget <n>] [--concurrency <n>] [--wait]
9950
+ `).replace(/\n+$/,``);try{return{result:JSON.parse(n[e].slice(t.length)),log:r,hadResult:!0}}catch{return{result:null,log:r,hadResult:!0}}}return{result:null,log:e.replace(/\n+$/,``),hadResult:!1}}function pEe(e){let t=/\bmeta\s*=\s*\{/.exec(e);if(!t)return null;let n=t.index+t[0].length-1,r=0;for(let t=n;t<e.length;t++)if(e[t]===`{`)r++;else if(e[t]===`}`&&--r===0)return e.slice(n+1,t);return null}function _9(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1`).exec(e);return n?n[2]:null}const v9=i(`workflow-command`);function y9(){return globalThis[f9]}function mEe(){let e=globalThis.navigator?.hardwareConcurrency??8;return Math.min(16,Math.max(8,e*4))}function hEe(e,t,n,r){let i=t[n];switch(i){case`-h`:case`--help`:return{i:n,help:!0};case`--script`:return e.script=t[++n],{i:n};case`--wait`:return e.wait=!0,{i:n};case`--args`:try{e.args=JSON.parse(t[++n]??``),e.hasArgs=!0}catch{return{i:n,error:`workflow: --args must be valid JSON`}}return{i:n};case`--budget`:{let r=Number(t[++n]);return Number.isFinite(r)?(e.budget=r,{i:n}):{i:n,error:`workflow: --budget must be a number`}}case`--concurrency`:{let i=Number(t[++n]);return Number.isFinite(i)?(e.cap=Math.min(r,Math.max(1,Math.trunc(i))),{i:n}):{i:n,error:`workflow: --concurrency must be a number`}}default:return i.startsWith(`-`)?{i:n,error:`workflow: unknown flag '${i}'`}:e.file===void 0?(e.file=i,{i:n}):{i:n,error:`workflow: too many arguments`}}}function gEe(e){if(e[0]!==`run`)return e.length===0||e.includes(`-h`)||e.includes(`--help`)?{help:!0}:{error:`workflow: unknown subcommand '${e[0]}' (only 'run' in SP1)`};let t=mEe(),n={budget:null,cap:Math.min(8,t)};for(let r=1;r<e.length;r++){let i=hEe(n,e,r,t);if(i.help)return{help:!0};if(i.error)return{error:i.error};r=i.i}return n.script===void 0&&n.file===void 0?{error:`workflow: a <file.js> or --script is required`}:n}function _Ee(e={}){return cA(`workflow`,async(t,n)=>{if(t[0]===`list`||t[0]===`status`||t[0]===`stop`)return SEe(t,n);if(t[0]===`save`)return xEe(t,n,e);let r=gEe(t);if(r.help)return{stdout:`usage: workflow run <file.js> [--args <json>] [--budget <n>] [--concurrency <n>] [--wait]
9949
9951
  workflow run --script '<inline js>' [...]
9950
9952
  workflow list
9951
9953
  workflow status <runId>
@@ -9954,24 +9956,24 @@ const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (asyn
9954
9956
  Runs a Claude-Code-format dynamic workflow. Default is non-blocking (returns a run id);
9955
9957
  pass --wait to block and print the full result.
9956
9958
  `,stderr:``,exitCode:0};if(r.error)return{stdout:``,stderr:r.error+`
9957
- `,exitCode:1};let i,a;if(r.script!==void 0)i=r.script,a=`<workflow>`;else{let e=n.fs.resolvePath(n.cwd,r.file);if(!await n.fs.exists(e))return{stdout:``,stderr:`workflow: file not found: ${r.file}\n`,exitCode:1};i=await n.fs.readFile(e),a=r.file}let o=sEe(i);if(!o.name)return{stdout:``,stderr:`workflow: script must define a meta block with a name (description optional)
9958
- `,exitCode:1};let s=h9().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=h9(),u=lEe({prelude:oEe,config:{...r.hasArgs?{args:r.args}:{},cap:r.cap??8,budget:r.budget??null,cwd:n.cwd,agentCwd:c},body:i,sentinel:l});return r.wait?hEe(u,a,l,o,n):gEe({code:u,source:i,name:o.name,filename:a,sentinel:l,runId:s,ctx:n,options:e})})}async function hEe(e,t,n,r,i){let a;try{a=await $1(e,[`workflow`,t],i,void 0,{filename:t})}catch(e){return v9.error(`workflow run failed`,e),{stdout:``,stderr:`workflow: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return bEe(r,a,n)}async function gEe(e){let t=y9();if(!t)return{stdout:``,stderr:`workflow: run manager not available
9959
- `,exitCode:1};let n=e.options.getParentJid?.(),{runId:r}=await t.start({code:e.code,source:e.source,name:e.name,filename:e.filename,parentJid:n,ctx:e.ctx,sentinel:e.sentinel,runId:e.runId});return{stdout:`▶ workflow '${e.name}' started (run ${r}). Watch: workflow status ${r}\n`,stderr:``,exitCode:0}}const _Ee=/^[a-z0-9][a-z0-9-]*$/,b9=`/workspace/.workflows`;async function vEe(e,t,n){let r=!1,i=[];for(let t of e.slice(1))t===`--force`?r=!0:i.push(t);let[a,o,...s]=i;if(!a||!o||s.length>0)return{stdout:``,stderr:`usage: workflow save <runId> <name> [--force]
9960
- `,exitCode:1};if(!_Ee.test(o))return{stdout:``,stderr:`workflow: invalid name '${o}' (use [a-z0-9][a-z0-9-]*)\n`,exitCode:1};let c=y9()?.getRun(a);if(!c)return{stdout:``,stderr:`workflow: no run '${a}' (only backgrounded runs are saveable; --wait runs are not)\n`,exitCode:1};if(!c.source)return{stdout:``,stderr:`workflow: run '${a}' has no source to save\n`,exitCode:1};let l=`${b9}/${o}.workflow.js`;if(await t.fs.exists(l)){if(!r)return{stdout:``,stderr:`workflow: ${l} already exists (pass --force to overwrite)\n`,exitCode:1}}else if(new Set(t.getRegisteredCommands?.()??[]).has(o))return{stdout:``,stderr:`workflow: '${o}' is already a command — choose another name\n`,exitCode:1};await t.fs.mkdir(b9,{recursive:!0}),await t.fs.writeFile(l,c.source);try{await n.syncScriptCommands?.()}catch(e){v9.warn(`workflow save: command re-sync failed; workflow saved, will register on next sync`,{name:o,error:e instanceof Error?e.message:String(e)})}return{stdout:`saved workflow '${o}' → ${l}\nrun it as '${o}' (or 'workflow run ${l}' if a built-in/.jsh shadows the name)\n`,stderr:``,exitCode:0}}async function yEe(e,t){let n=y9();if(e[0]===`list`){if(!n)return{stdout:``,stderr:`workflow: run manager not available
9959
+ `,exitCode:1};let i,a;if(r.script!==void 0)i=r.script,a=`<workflow>`;else{let e=n.fs.resolvePath(n.cwd,r.file);if(!await n.fs.exists(e))return{stdout:``,stderr:`workflow: file not found: ${r.file}\n`,exitCode:1};i=await n.fs.readFile(e),a=r.file}let o=uEe(i);if(!o.name)return{stdout:``,stderr:`workflow: script must define a meta block with a name (description optional)
9960
+ `,exitCode:1};let s=h9().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=h9(),u=fEe({prelude:lEe,config:{...r.hasArgs?{args:r.args}:{},cap:r.cap??8,budget:r.budget??null,cwd:n.cwd,agentCwd:c},body:i,sentinel:l});return r.wait?vEe(u,a,l,o,n):yEe({code:u,source:i,name:o.name,filename:a,sentinel:l,runId:s,ctx:n,options:e})})}async function vEe(e,t,n,r,i){let a;try{a=await $1(e,[`workflow`,t],i,void 0,{filename:t})}catch(e){return v9.error(`workflow run failed`,e),{stdout:``,stderr:`workflow: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return CEe(r,a,n)}async function yEe(e){let t=y9();if(!t)return{stdout:``,stderr:`workflow: run manager not available
9961
+ `,exitCode:1};let n=e.options.getParentJid?.(),{runId:r}=await t.start({code:e.code,source:e.source,name:e.name,filename:e.filename,parentJid:n,ctx:e.ctx,sentinel:e.sentinel,runId:e.runId});return{stdout:`▶ workflow '${e.name}' started (run ${r}). Watch: workflow status ${r}\n`,stderr:``,exitCode:0}}const bEe=/^[a-z0-9][a-z0-9-]*$/,b9=`/workspace/.workflows`;async function xEe(e,t,n){let r=!1,i=[];for(let t of e.slice(1))t===`--force`?r=!0:i.push(t);let[a,o,...s]=i;if(!a||!o||s.length>0)return{stdout:``,stderr:`usage: workflow save <runId> <name> [--force]
9962
+ `,exitCode:1};if(!bEe.test(o))return{stdout:``,stderr:`workflow: invalid name '${o}' (use [a-z0-9][a-z0-9-]*)\n`,exitCode:1};let c=y9()?.getRun(a);if(!c)return{stdout:``,stderr:`workflow: no run '${a}' (only backgrounded runs are saveable; --wait runs are not)\n`,exitCode:1};if(!c.source)return{stdout:``,stderr:`workflow: run '${a}' has no source to save\n`,exitCode:1};let l=`${b9}/${o}.workflow.js`;if(await t.fs.exists(l)){if(!r)return{stdout:``,stderr:`workflow: ${l} already exists (pass --force to overwrite)\n`,exitCode:1}}else if(new Set(t.getRegisteredCommands?.()??[]).has(o))return{stdout:``,stderr:`workflow: '${o}' is already a command — choose another name\n`,exitCode:1};await t.fs.mkdir(b9,{recursive:!0}),await t.fs.writeFile(l,c.source);try{await n.syncScriptCommands?.()}catch(e){v9.warn(`workflow save: command re-sync failed; workflow saved, will register on next sync`,{name:o,error:e instanceof Error?e.message:String(e)})}return{stdout:`saved workflow '${o}' → ${l}\nrun it as '${o}' (or 'workflow run ${l}' if a built-in/.jsh shadows the name)\n`,stderr:``,exitCode:0}}async function SEe(e,t){let n=y9();if(e[0]===`list`){if(!n)return{stdout:``,stderr:`workflow: run manager not available
9961
9963
  `,exitCode:1};let e=n.listRuns().map(e=>`${e.id} ${e.status.padEnd(7)} ${e.agentsDone}/${e.agentsStarted} ${e.name??``}`);return{stdout:(e.length?e.join(`
9962
9964
  `):`(no runs)`)+`
9963
9965
  `,stderr:``,exitCode:0}}let r=e[1],i=n?.getRun(r??``);if(!i)return{stdout:``,stderr:`workflow: no run '${r}'\n`,exitCode:1};if(e[0]===`status`)return{stdout:[`run ${i.id} (${i.name??`unnamed`}) status=${i.status}`,`agents ${i.agentsDone}/${i.agentsStarted} phase=${i.currentPhase??`-`}`,i.resultPath?`result: ${i.resultPath}`:``,i.preview?`preview: ${i.preview}`:``,i.error?`error: ${i.error}`:``].filter(Boolean).join(`
9964
9966
  `)+`
9965
- `,stderr:``,exitCode:0};if(i.pid==null)return{stdout:`workflow: run ${i.id} has not started a realm process yet (nothing to stop)\n`,stderr:``,exitCode:0};if(i.status!==`running`&&i.status!==`paused`)return{stdout:`workflow: run ${i.id} already ${i.status}\n`,stderr:``,exitCode:0};let a=await t.exec?.(`kill`,{cwd:t.cwd,args:[`-KILL`,String(i.pid)]});return a&&a.exitCode!==0?{stdout:``,stderr:a.stderr||`workflow: kill failed (exit ${a.exitCode})\n`,exitCode:a.exitCode}:{stdout:`stopped run ${i.id} (pid ${i.pid})\n`,stderr:``,exitCode:0}}function bEe(e,t,n){let{result:r,log:i,hadResult:a}=g9(t.stdout,n),o=e.name?`workflow: ${e.name}${e.description?` — `+e.description:``}\n`:``,s=i?xEe(i)+`
9967
+ `,stderr:``,exitCode:0};if(i.pid==null)return{stdout:`workflow: run ${i.id} has not started a realm process yet (nothing to stop)\n`,stderr:``,exitCode:0};if(i.status!==`running`&&i.status!==`paused`)return{stdout:`workflow: run ${i.id} already ${i.status}\n`,stderr:``,exitCode:0};let a=await t.exec?.(`kill`,{cwd:t.cwd,args:[`-KILL`,String(i.pid)]});return a&&a.exitCode!==0?{stdout:``,stderr:a.stderr||`workflow: kill failed (exit ${a.exitCode})\n`,exitCode:a.exitCode}:{stdout:`stopped run ${i.id} (pid ${i.pid})\n`,stderr:``,exitCode:0}}function CEe(e,t,n){let{result:r,log:i,hadResult:a}=g9(t.stdout,n),o=e.name?`workflow: ${e.name}${e.description?` — `+e.description:``}\n`:``,s=i?wEe(i)+`
9966
9968
  `:``;return t.exitCode!==0||!a?{stdout:o+s,stderr:t.stderr||(a?``:`workflow: script produced no result
9967
9969
  `),exitCode:t.exitCode||1}:{stdout:o+s+(typeof r==`string`?r:JSON.stringify(r))+`
9968
- `,stderr:t.stderr,exitCode:0}}function xEe(e){return e.split(`
9970
+ `,stderr:t.stderr,exitCode:0}}function wEe(e){return e.split(`
9969
9971
  `).map(e=>e.replace(/^WFPHASE/,`▸ `).replace(/^WFLOG/,`· `)).join(`
9970
- `)}async function x9(e,t,n,r){if((await e.fs.stat(t)).isFile)return r[n]=await e.fs.readFileBuffer(t),1;let i=await e.fs.readdir(t),a=0;for(let o of i){let i=IK(t,o),s=n?`${n}/${o}`:o;a+=await x9(e,i,s,r)}return a}function SEe(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
9971
- `,stderr:``,exitCode:0}}function CEe(){return cA(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return SEe();let n=!1,r=[];for(let t of e){if(t===`-r`){n=!0;continue}if(t.startsWith(`-`))return{stdout:``,stderr:`zip: unsupported option ${t}\n`,exitCode:1};r.push(t)}if(r.length<2)return{stdout:``,stderr:`zip: expected archive path and at least one input path
9972
+ `)}async function x9(e,t,n,r){if((await e.fs.stat(t)).isFile)return r[n]=await e.fs.readFileBuffer(t),1;let i=await e.fs.readdir(t),a=0;for(let o of i){let i=IK(t,o),s=n?`${n}/${o}`:o;a+=await x9(e,i,s,r)}return a}function TEe(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
9973
+ `,stderr:``,exitCode:0}}function EEe(){return cA(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return TEe();let n=!1,r=[];for(let t of e){if(t===`-r`){n=!0;continue}if(t.startsWith(`-`))return{stdout:``,stderr:`zip: unsupported option ${t}\n`,exitCode:1};r.push(t)}if(r.length<2)return{stdout:``,stderr:`zip: expected archive path and at least one input path
9972
9974
  `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=r.slice(1),o={},s=0;for(let e of a){let r=t.fs.resolvePath(t.cwd,e),i=await t.fs.stat(r),a=(e.startsWith(`/`)?e.slice(1):e.replace(/^\.\//,``))||PK(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await x9(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
9973
- `,exitCode:1};let c=Tce(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function wEe(e={}){let t=[bbe({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),the(),Owe(e.browserAPI,e.fs),rCe(),Ybe(e),CEe(),_Te(),L7(`sqlite3`),L7(`sqllite`),Qwe(),pTe(),Qge(),Kme(),RSe({buildProcessConfig:e.buildProcessConfig}),l7(`python3`,{buildProcessConfig:e.buildProcessConfig}),l7(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[s5(`ipk`,{fs:e.fs,fetch:e.fetch}),s5(`npm`,{fs:e.fs,fetch:e.fetch}),s5(`i`,{fs:e.fs,fetch:e.fetch}),h5(`ipx`,{fs:e.fs,fetch:e.fetch}),h5(`npx`,{fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[jbe({fetch:e.fetch})]:[],vve(),zTe(),KTe(),Sge(),nSe({fs:e.fs,scriptCatalog:e.scriptCatalog}),Nve(),Fwe(),s7(`pdftk`),s7(`pdf`),U3(`convert`),U3(`magick`),ZTe({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins}),hTe(),Xxe(),Lge(),WSe(),HSe(),qxe(),Ewe({setEnv:e.setEnv}),VCe({fs:e.fs}),twe(),vhe(),yhe(),D2(`xclip`),D2(`xsel`),XCe(),Hve(),fme(),pme(),FSe(e.fs),RF(),BSe(),Ame({getParentJid:e.getParentJid}),Uge(),lCe({processManager:e.processManager}),Mxe({processManager:e.processManager}),FTe(),qbe(),E_e(),N_e(),mhe({registry:e.cherryRuntimeRegistry}),Dge(),jge({fs:e.fs}),Mge({fs:e.fs}),Lwe(e.sudoCommand),mEe({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),qTe()];return e.fs&&t.push(...R6.map(t=>_be(t,e.browserAPI,e.fs))),t}const TEe=Reflect.get(es,`DefenseInDepthBox`);var EEe=class{vfs;registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}canWrite(e){let t=this.vfs;return typeof t.canWrite==`function`?t.canWrite(e):!0}listMountPoints(){let e=this.vfs;return typeof e.listMountPoints==`function`?e.listMountPoints():[]}trusted(e){let t=TEe?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=me(e),n=await this.vfs.readFile(t,{encoding:`binary`}),r=n instanceof Uint8Array?n:new TextEncoder().encode(n);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(r)}catch{let e=Array(r.length);for(let t=0;t<r.length;t++)e[t]=String.fromCharCode(r[t]);return e.join(``)}})}async readFileBuffer(e){return this.trusted(async()=>{let t=me(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)})}async writeFile(e,t,n){return this.trusted(async()=>{let n=me(e);if(typeof t==`string`){let e=s(t);if(e){await this.vfs.writeFile(n,e);return}let r=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){r=!0;break}if(r)await this.vfs.writeFile(n,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(n,e)}}else await this.vfs.writeFile(n,t)})}async appendFile(e,t,n){return this.trusted(async()=>{let n=me(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new O(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof O&&e.code===`EISDIR`)throw e}let r=new Uint8Array;try{let e=await this.vfs.readFile(n,{encoding:`binary`});r=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof O&&e.code===`ENOENT`))throw e}let i;if(typeof t==`string`){i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e)&255}else i=t instanceof Uint8Array?t:new Uint8Array(t);let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),await this.vfs.writeFile(n,a)})}async exists(e){return this.trusted(async()=>{let t=me(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=me(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=this.vfs.statSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.stat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime)}})}async lstat(e){return this.trusted(async()=>{let t=me(e),n=this.vfs.lstatSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.lstat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime)}})}async mkdir(e,t){return this.trusted(async()=>{await this.vfs.mkdir(me(e),t)})}async readdir(e){return this.trusted(async()=>{let t=me(e);if(t===`/usr`)return[`bin`];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort();let n=this.vfs.readDirSync(t);return n===null?(await this.vfs.readDir(t)).map(e=>e.name):n.map(e=>e.name)})}async readdirWithFileTypes(e){return this.trusted(async()=>{let t=me(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=this.vfs.readDirSync(t);if(n!==null)return this.mapFastEntriesToDirents(n);let r=await this.vfs.readDir(t);return this.mapAsyncEntriesToDirents(r)})}mapFastEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}mapAsyncEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}entryToDirent(e){return e.type===`symlink`?{name:e.name,isFile:!1,isDirectory:!1,isSymbolicLink:!0}:{name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1}}async rm(e,t){return this.trusted(async()=>{await this.vfs.rm(me(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=me(e),i=me(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new O(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)})}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=he(e,r.name),i=he(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){return this.trusted(async()=>{await this.vfs.rename(me(e),me(t))})}resolvePath(e,t){return t.startsWith(`/`)?me(t):me(he(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,me(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(me(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(me(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function S9(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?S9(e.getUnderlyingFS?.()):null}var C9=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;resolveJshProcessConfig=()=>this.buildJshProcessConfig();static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}constructor(t){this.options=t,this.vfsAdapter=new EEe(t.fs),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:n,...t.env};this.gitCommands=new BW({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new nle({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=S9(i)??S9(a);this.scriptCatalog=t.scriptCatalog??new v0({jshFs:i,bshFs:a,watcher:o}),this.ownsScriptCatalog=!t.scriptCatalog,o&&o.watch(`/`,e=>e.endsWith(`.jsh`)||e.endsWith(`.workflow.js`),()=>{this.syncJshCommands().catch(()=>void 0)});let s=this.createGitCustomCommand(),c=f(),l=wEe({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],fs:t.fs,fetch:c,scriptCatalog:this.scriptCatalog,browserAPI:t.browserAPI,getParentJid:t.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:t.processManager,sudoCommand:t.sudo?{broker:t.sudo.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},suppressNextGate:e=>this.registerSudoBypass(e)}:void 0,setEnv:(e,t)=>{this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t}}),u=[s,this.createMountCustomCommand(),ume(t.fs),sme(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...tA(),...nA()],p=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new jF({fs:this.vfsAdapter,cwd:n,env:r,fetch:c,commands:p,customCommands:u}),this.allowedCommands!==null){let e=this.bash;for(let t of nA())this.isCommandAllowed(t)||e.commands.delete(t)}if(this.isTransparentGatingEnabled()){let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForSudo(n))}let m=u.map(e=>e.name),h=p??[...tA(),...nA()];this.builtinCommandNames=new Set([...h,...m]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.syncJshCommands().catch(()=>void 0)}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight?(this.jshSyncDirty=!0,this.jshSyncInflight):(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight)}async executeCommand(e,t,n){let r=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);try{let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}finally{this.activeShellPid=r}}async executeScriptFile(e,t=[]){return Yfe(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig())}dispose(){this.ownsScriptCatalog&&this.scriptCatalog.dispose()}async renderMediaPreview(e){throw Error(`terminal preview is unavailable in headless mode`)}async runCommand(e,t){lr(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t},r=await this.bash.exec(e,n);if(await this.flushPendingCommandGrants(),r.env&&(this.lastEnv={...r.env}),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return this.syncJshCommands().catch(()=>void 0),t}return r}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForSudo(e){if(!this.isTransparentGatingEnabled())return e;let t=t=>this.gateCommandDispatch(e.name,t);return{name:e.name,trusted:e.trusted,async execute(n,r){return await t(n)||e.execute(n,r)}}}async gateCommandDispatch(e,t){let n=this.options.sudo;if(!n)return null;let r=`${e} ${t.join(` `)}`.trim();if(this.consumeSudoBypass(r))return null;let i=n.getPolicy();if(!i)return null;let a=await vpe(r,{policy:i,broker:n.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},defaultDisposition:n.defaultDisposition});return a.allowed?null:{stdout:``,stderr:`${a.message}\n`,exitCode:1}}registerSudoBypass(e){let t=e.trim();t&&this.pendingSudoBypasses.set(t,(this.pendingSudoBypasses.get(t)??0)+1)}consumeSudoBypass(e){let t=this.pendingSudoBypasses.get(e);return t?(t===1?this.pendingSudoBypasses.delete(e):this.pendingSudoBypasses.set(e,t-1),!0):!1}async flushPendingCommandGrants(){if(this.pendingCommandGrants.length===0)return;let e=this.pendingCommandGrants;this.pendingCommandGrants=[];for(let t of e)try{await this.persistCommandGrant(t)}catch{}}async persistCommandGrant(e){let t=this.options.sudo?.persistCommandGrant;if(t){await t(e);return}let n=JF(e);if(!n)return;let r=`${VF}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch{a=``}let o=a&&!a.endsWith(`
9974
- `)?`${a}\n`:a;await i.writeFile(r,`${o}NOPASSWD Cmnd ${n}\n`)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(),t=await this.getFilteredWorkflowCommands();for(let[t,n]of e)this.isCommandAllowed(t)&&(this.builtinCommandNames.has(t)&&!this.registeredJshCommands.has(t)||this.registeredJshCommands.get(t)!==n&&(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(t))),this.registeredJshCommands.set(t,n),this.builtinCommandNames.add(t)));for(let e of t.keys())if(!this.registeredWorkflowCommands.has(e)){if(this.registeredJshCommands.has(e)){this.registeredWorkflowCommands.add(e);continue}this.builtinCommandNames.has(e)||(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(e))),this.registeredWorkflowCommands.add(e),this.builtinCommandNames.add(e))}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}makeScriptCommand(e){let t=this.scriptCatalog,n=this,r=this.options.jshDiscoveryFs??this.options.fs,i=e;return{name:e,trusted:!0,async execute(e,a){let o=a.exec??((e,t)=>n.bash.exec(e,{env:Object.fromEntries(a.env),cwd:t?.cwd??a.cwd,args:t?.args})),s=(await t.getJshCommands()).get(i);if(s){let t;try{let e=await r.readFile(s,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${s}'\n`,exitCode:127}}return $1(t,[`node`,s,...e],{fs:a.fs,cwd:a.cwd,env:a.env,stdin:a.stdin,exec:o},n.buildJshProcessConfig())}let c=(await t.getWorkflowCommands()).get(i);if(c){let t=ppe(c.path,e);return o(t[0],{args:t.slice(1),cwd:a.cwd})}return{stdout:``,stderr:`${i}: command no longer exists\n`,exitCode:127}}}}createGitCustomCommand(){let e=this.gitCommands;return cA(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return cA(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||this.isCommandAllowed(n)&&t.set(n,r);return t}async getFilteredWorkflowCommands(){let e=await this.scriptCatalog.getWorkflowCommands(),t=new Map;for(let[n,r]of e)this.isCommandAllowed(n)&&t.set(n,r);return t}async getWorkflowCommandNames(){return[...(await this.getFilteredWorkflowCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?$fe(i):[],s=this.options.jshDiscoveryFs??this.options.fs,c;try{let e=await s.readFile(a,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${a}'\n`,exitCode:127,env:this.lastEnv}}let l=[`node`,a,...o],u=await $1(c,l,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig());return{stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode,env:this.lastEnv}}buildJshProcessConfig(){if(!(!this.options.processManager||!this.options.processOwner))return{processManager:this.options.processManager,owner:this.options.processOwner,getParentPid:()=>this.activeShellPid??this.options.getCurrentShellPid?.()}}};function w9(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}var DEe=class extends C9{terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;constructor(e){super(e)}async runCommand(e,t){return super.runCommand(e,t??this.execAbort?.signal)}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await import(`./xterm-B5O_KJMf.js`),{FitAddon:r}=await import(`./addon-fit-CuuUKmBe.js`);await Promise.resolve({ });let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
9975
+ `,exitCode:1};let c=Tce(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function DEe(e={}){let t=[bbe({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),the(),jwe(e.browserAPI,e.fs),rCe(),Ybe(e),EEe(),bTe(),L7(`sqlite3`),L7(`sqllite`),tTe(),gTe(),Qge(),Kme(),RSe({buildProcessConfig:e.buildProcessConfig}),l7(`python3`,{buildProcessConfig:e.buildProcessConfig}),l7(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[s5(`ipk`,{fs:e.fs,fetch:e.fetch}),s5(`npm`,{fs:e.fs,fetch:e.fetch}),s5(`i`,{fs:e.fs,fetch:e.fetch}),h5(`ipx`,{fs:e.fs,fetch:e.fetch}),h5(`npx`,{fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[jbe({fetch:e.fetch})]:[],vve(),HTe(),YTe(),Sge(),nSe({fs:e.fs,scriptCatalog:e.scriptCatalog}),Nve(),Rwe(),s7(`pdftk`),s7(`pdf`),U3(`convert`),U3(`magick`),eEe({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins}),vTe(),Xxe(),Lge(),WSe(),HSe(),qxe(),kwe({setEnv:e.setEnv}),VCe({fs:e.fs}),iwe(),vhe(),yhe(),D2(`xclip`),D2(`xsel`),$Ce(),Hve(),fme(),pme(),FSe(e.fs),RF(),BSe(),Ame({getParentJid:e.getParentJid}),Uge(),lCe({processManager:e.processManager}),Mxe({processManager:e.processManager}),RTe(),qbe(),E_e(),N_e(),mhe({registry:e.cherryRuntimeRegistry}),Dge(),jge({fs:e.fs}),Mge({fs:e.fs}),Bwe(e.sudoCommand),_Ee({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),XTe()];return e.fs&&t.push(...R6.map(t=>_be(t,e.browserAPI,e.fs))),t}const OEe=Reflect.get(es,`DefenseInDepthBox`);var kEe=class{vfs;registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}canWrite(e){let t=this.vfs;return typeof t.canWrite==`function`?t.canWrite(e):!0}listMountPoints(){let e=this.vfs;return typeof e.listMountPoints==`function`?e.listMountPoints():[]}trusted(e){let t=OEe?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=me(e),n=await this.vfs.readFile(t,{encoding:`binary`}),r=n instanceof Uint8Array?n:new TextEncoder().encode(n);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(r)}catch{let e=Array(r.length);for(let t=0;t<r.length;t++)e[t]=String.fromCharCode(r[t]);return e.join(``)}})}async readFileBuffer(e){return this.trusted(async()=>{let t=me(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)})}async writeFile(e,t,n){return this.trusted(async()=>{let n=me(e);if(typeof t==`string`){let e=s(t);if(e){await this.vfs.writeFile(n,e);return}let r=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){r=!0;break}if(r)await this.vfs.writeFile(n,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(n,e)}}else await this.vfs.writeFile(n,t)})}async appendFile(e,t,n){return this.trusted(async()=>{let n=me(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new O(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof O&&e.code===`EISDIR`)throw e}let r=new Uint8Array;try{let e=await this.vfs.readFile(n,{encoding:`binary`});r=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof O&&e.code===`ENOENT`))throw e}let i;if(typeof t==`string`){i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e)&255}else i=t instanceof Uint8Array?t:new Uint8Array(t);let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),await this.vfs.writeFile(n,a)})}async exists(e){return this.trusted(async()=>{let t=me(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=me(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=this.vfs.statSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.stat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime)}})}async lstat(e){return this.trusted(async()=>{let t=me(e),n=this.vfs.lstatSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.lstat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime)}})}async mkdir(e,t){return this.trusted(async()=>{await this.vfs.mkdir(me(e),t)})}async readdir(e){return this.trusted(async()=>{let t=me(e);if(t===`/usr`)return[`bin`];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort();let n=this.vfs.readDirSync(t);return n===null?(await this.vfs.readDir(t)).map(e=>e.name):n.map(e=>e.name)})}async readdirWithFileTypes(e){return this.trusted(async()=>{let t=me(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=this.vfs.readDirSync(t);if(n!==null)return this.mapFastEntriesToDirents(n);let r=await this.vfs.readDir(t);return this.mapAsyncEntriesToDirents(r)})}mapFastEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}mapAsyncEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}entryToDirent(e){return e.type===`symlink`?{name:e.name,isFile:!1,isDirectory:!1,isSymbolicLink:!0}:{name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1}}async rm(e,t){return this.trusted(async()=>{await this.vfs.rm(me(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=me(e),i=me(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new O(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)})}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=he(e,r.name),i=he(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){return this.trusted(async()=>{await this.vfs.rename(me(e),me(t))})}resolvePath(e,t){return t.startsWith(`/`)?me(t):me(he(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,me(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(me(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(me(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function S9(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?S9(e.getUnderlyingFS?.()):null}var C9=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;resolveJshProcessConfig=()=>this.buildJshProcessConfig();static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}constructor(t){this.options=t,this.vfsAdapter=new kEe(t.fs),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:n,...t.env};this.gitCommands=new BW({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new nle({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=S9(i)??S9(a);this.scriptCatalog=t.scriptCatalog??new v0({jshFs:i,bshFs:a,watcher:o}),this.ownsScriptCatalog=!t.scriptCatalog,o&&o.watch(`/`,e=>e.endsWith(`.jsh`)||e.endsWith(`.workflow.js`),()=>{this.syncJshCommands().catch(()=>void 0)});let s=this.createGitCustomCommand(),c=f(),l=DEe({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],fs:t.fs,fetch:c,scriptCatalog:this.scriptCatalog,browserAPI:t.browserAPI,getParentJid:t.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:t.processManager,sudoCommand:t.sudo?{broker:t.sudo.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},suppressNextGate:e=>this.registerSudoBypass(e)}:void 0,setEnv:(e,t)=>{this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t}}),u=[s,this.createMountCustomCommand(),ume(t.fs),sme(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...tA(),...nA()],p=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new jF({fs:this.vfsAdapter,cwd:n,env:r,fetch:c,commands:p,customCommands:u}),this.allowedCommands!==null){let e=this.bash;for(let t of nA())this.isCommandAllowed(t)||e.commands.delete(t)}if(this.isTransparentGatingEnabled()){let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForSudo(n))}let m=u.map(e=>e.name),h=p??[...tA(),...nA()];this.builtinCommandNames=new Set([...h,...m]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.syncJshCommands().catch(()=>void 0)}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight?(this.jshSyncDirty=!0,this.jshSyncInflight):(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight)}async executeCommand(e,t,n){let r=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);try{let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}finally{this.activeShellPid=r}}async executeScriptFile(e,t=[]){return Yfe(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig())}dispose(){this.ownsScriptCatalog&&this.scriptCatalog.dispose()}async renderMediaPreview(e){throw Error(`terminal preview is unavailable in headless mode`)}async runCommand(e,t){lr(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t},r=await this.bash.exec(e,n);if(await this.flushPendingCommandGrants(),r.env&&(this.lastEnv={...r.env}),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return this.syncJshCommands().catch(()=>void 0),t}return r}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForSudo(e){if(!this.isTransparentGatingEnabled())return e;let t=t=>this.gateCommandDispatch(e.name,t);return{name:e.name,trusted:e.trusted,async execute(n,r){return await t(n)||e.execute(n,r)}}}async gateCommandDispatch(e,t){let n=this.options.sudo;if(!n)return null;let r=`${e} ${t.join(` `)}`.trim();if(this.consumeSudoBypass(r))return null;let i=n.getPolicy();if(!i)return null;let a=await vpe(r,{policy:i,broker:n.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},defaultDisposition:n.defaultDisposition});return a.allowed?null:{stdout:``,stderr:`${a.message}\n`,exitCode:1}}registerSudoBypass(e){let t=e.trim();t&&this.pendingSudoBypasses.set(t,(this.pendingSudoBypasses.get(t)??0)+1)}consumeSudoBypass(e){let t=this.pendingSudoBypasses.get(e);return t?(t===1?this.pendingSudoBypasses.delete(e):this.pendingSudoBypasses.set(e,t-1),!0):!1}async flushPendingCommandGrants(){if(this.pendingCommandGrants.length===0)return;let e=this.pendingCommandGrants;this.pendingCommandGrants=[];for(let t of e)try{await this.persistCommandGrant(t)}catch{}}async persistCommandGrant(e){let t=this.options.sudo?.persistCommandGrant;if(t){await t(e);return}let n=JF(e);if(!n)return;let r=`${VF}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch{a=``}let o=a&&!a.endsWith(`
9976
+ `)?`${a}\n`:a;await i.writeFile(r,`${o}NOPASSWD Cmnd ${n}\n`)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(),t=await this.getFilteredWorkflowCommands();for(let[t,n]of e)this.isCommandAllowed(t)&&(this.builtinCommandNames.has(t)&&!this.registeredJshCommands.has(t)||this.registeredJshCommands.get(t)!==n&&(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(t))),this.registeredJshCommands.set(t,n),this.builtinCommandNames.add(t)));for(let e of t.keys())if(!this.registeredWorkflowCommands.has(e)){if(this.registeredJshCommands.has(e)){this.registeredWorkflowCommands.add(e);continue}this.builtinCommandNames.has(e)||(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(e))),this.registeredWorkflowCommands.add(e),this.builtinCommandNames.add(e))}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}makeScriptCommand(e){let t=this.scriptCatalog,n=this,r=this.options.jshDiscoveryFs??this.options.fs,i=e;return{name:e,trusted:!0,async execute(e,a){let o=a.exec??((e,t)=>n.bash.exec(e,{env:Object.fromEntries(a.env),cwd:t?.cwd??a.cwd,args:t?.args})),s=(await t.getJshCommands()).get(i);if(s){let t;try{let e=await r.readFile(s,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${s}'\n`,exitCode:127}}return $1(t,[`node`,s,...e],{fs:a.fs,cwd:a.cwd,env:a.env,stdin:a.stdin,exec:o},n.buildJshProcessConfig())}let c=(await t.getWorkflowCommands()).get(i);if(c){let t=ppe(c.path,e);return o(t[0],{args:t.slice(1),cwd:a.cwd})}return{stdout:``,stderr:`${i}: command no longer exists\n`,exitCode:127}}}}createGitCustomCommand(){let e=this.gitCommands;return cA(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return cA(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||this.isCommandAllowed(n)&&t.set(n,r);return t}async getFilteredWorkflowCommands(){let e=await this.scriptCatalog.getWorkflowCommands(),t=new Map;for(let[n,r]of e)this.isCommandAllowed(n)&&t.set(n,r);return t}async getWorkflowCommandNames(){return[...(await this.getFilteredWorkflowCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?$fe(i):[],s=this.options.jshDiscoveryFs??this.options.fs,c;try{let e=await s.readFile(a,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${a}'\n`,exitCode:127,env:this.lastEnv}}let l=[`node`,a,...o],u=await $1(c,l,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig());return{stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode,env:this.lastEnv}}buildJshProcessConfig(){if(!(!this.options.processManager||!this.options.processOwner))return{processManager:this.options.processManager,owner:this.options.processOwner,getParentPid:()=>this.activeShellPid??this.options.getCurrentShellPid?.()}}};function w9(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}var AEe=class extends C9{terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;constructor(e){super(e)}async runCommand(e,t){return super.runCommand(e,t??this.execAbort?.signal)}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await import(`./xterm-B5O_KJMf.js`),{FitAddon:r}=await import(`./addon-fit-CuuUKmBe.js`);await Promise.resolve({ });let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
9975
9977
  `),this.showPrompt(),this.setupInputHandler()}refit(){this.fitAddon?.fit()}setPreviewStateListener(e){this.previewStateListener=e,this.previewStateListener?.(this.hasPreview)}async executeCommandInTerminal(e){let t=e.trim();if(!t)return{stdout:``,stderr:``,exitCode:0};if(!this.terminal)return this.executeCommand(t);if(this.isExecuting||this.currentLine.length>0||this.continuationBuffer.length>0)return{stdout:``,stderr:`terminal is busy; finish current input first
9976
9978
  `,exitCode:1};this.history[this.history.length-1]!==t&&this.history.push(t),this.historyIndex=-1,this.terminal.write(t),this.terminal.writeln(``),this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(t),n=this.execAbort.signal.aborted;return this.execAbort=null,n?{stdout:``,stderr:``,exitCode:130}:(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0),{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode})}catch(e){if(this.execAbort?.signal.aborted)return this.execAbort=null,{stdout:``,stderr:``,exitCode:130};this.execAbort=null;let t=`Error: ${e instanceof Error?e.message:String(e)}\n`;return this.writeToTerminal(t,!0),{stdout:``,stderr:t,exitCode:1}}finally{this.isExecuting=!1,this.showPrompt()}}clearTerminal(){this.terminal?.clear(),this.clearMediaPreview()}dispose(){this.themeObserver?.disconnect(),this.themeObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.clearMediaPreview(),this.terminal?.dispose(),this.terminal=null,this.fitAddon=null,this.terminalHost=null,this.previewHost=null,super.dispose()}showPrompt(){if(!this.terminal)return;let e=this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd;this.terminal.write(`\x1b[34m${e}\x1b[0m \x1b[90m$\x1b[0m `)}setupInputHandler(){this.terminal&&this.terminal.onData(e=>{if(this.isExecuting){(e===``||e.length===1&&e.charCodeAt(0)===3)&&(this.execAbort?.abort(),this.terminal?.writeln(`^C`));return}if(e.startsWith(`\x1B[`)||e.startsWith(`\x1BO`)){switch(e){case`\x1B[A`:this.handleHistoryUp();return;case`\x1B[B`:this.handleHistoryDown();return;case`\x1B[C`:this.handleArrowRight();return;case`\x1B[D`:this.handleArrowLeft();return;case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:this.handleHome();return;case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:this.handleEnd();return;case`\x1B[3~`:this.handleDelete();return}return}for(let t of e)switch(t){case`\r`:this.handleEnter();break;case``:this.handleBackspace();break;case``:this.handleCtrlC();break;case` `:this.handleTab();break;default:t>=` `&&this.insertChar(t)}})}getPromptWidth(){return(this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd).length+3}getCursorVisualLine(){let e=0;for(let[t,n]of this.currentLine.split(`
9977
9979
  `).entries()){if(e+n.length>=this.cursorPos)return t;e+=n.length+1}return 0}positionTerminalCursor(){let e=this.currentLine.split(`
@@ -9986,15 +9988,15 @@ pass --wait to block and print the full result.
9986
9988
  `,this.cursorPos);if(e===-1&&(e=this.currentLine.length),this.cursorPos===e)return;let t=e-this.cursorPos;this.cursorPos=e,this.terminal?.write(`\x1b[${t}C`)}handleCtrlC(){this.terminal?.writeln(`^C`),this.currentLine=``,this.cursorPos=0,this.continuationBuffer=``,this.showPrompt()}handleHistoryUp(){this.history.length!==0&&this.historyIndex<this.history.length-1&&(this.historyIndex++,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex]))}handleHistoryDown(){this.historyIndex>0?(this.historyIndex--,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex])):this.historyIndex===0&&(this.historyIndex=-1,this.continuationBuffer=``,this.replaceCurrentLine(``))}insertAtCursor(e){e&&(this.currentLine=this.currentLine.slice(0,this.cursorPos)+e+this.currentLine.slice(this.cursorPos),this.cursorPos+=e.length,this.terminal?.write(e))}async handleTab(){if(!this.terminal)return;let e=this.currentLine.slice(0,this.cursorPos).split(/\s+/),t=e[e.length-1]||``,n=e.length<=1||e.length===2&&e[0]===``,r=t?`'`+t.replace(/'/g,`'\\''`)+`'`:`''`,i=n?`compgen -A command -- ${r}`:`compgen -f -- ${r}`;try{let e=(await this.bash.exec(i,{env:this.lastEnv,cwd:this.cwd})).stdout.split(`
9987
9989
  `).filter(Boolean);if(e.length===0)return;e.length===1?await this.applySingleCompletion(t,e[0],n,r):this.applyMultiCompletion(t,e)}catch(e){console.warn(`[Shell] Tab completion failed:`,e instanceof Error?e.message:String(e))}}async applySingleCompletion(e,t,n,r){let i=t.slice(e.length);this.insertAtCursor(i);let a=` `;n||(await this.bash.exec(`compgen -d -- ${r.slice(0,-1)}${i}'`,{env:this.lastEnv,cwd:this.cwd})).stdout.trim()===t&&(a=`/`),this.insertAtCursor(a)}applyMultiCompletion(e,t){let n=t[0];for(let e of t)for(;!e.startsWith(n);)n=n.slice(0,-1);let r=n.slice(e.length);if(r){this.insertAtCursor(r);return}this.terminal?.writeln(``),this.terminal?.writeln(t.map(e=>e.split(`/`).pop()??e).join(` `)),this.showPrompt(),this.terminal?.write(this.currentLine);let i=this.currentLine.length-this.cursorPos;i>0&&this.terminal?.write(`\x1b[${i}D`)}replaceCurrentLine(e){let t=this.getCursorVisualLine();t>0&&this.terminal?.write(`\x1b[${t}A`),this.terminal?.write(`\r\x1B[J`),this.showPrompt(),this.currentLine=e,this.cursorPos=e.length,this.terminal?.write(e)}isIncomplete(e){if(e.endsWith(`\\`))return!0;let t=!1,n=!1,r=!1;for(let i of e){if(r){r=!1;continue}if(i===`\\`&&!t){r=!0;continue}if(i===`'`&&!n){t=!t;continue}i===`"`&&!t&&(n=!n)}return t||n}async handleEnter(){let e=this.currentLine.split(`
9988
9990
  `);if(e.length>1){let t=this.getCursorVisualLine(),n=e.length-1-t;n>0&&this.terminal?.write(`\x1b[${n}B`);let r=e[e.length-1].length;this.terminal?.write(`\r`),r>0&&this.terminal?.write(`\x1b[${r}C`)}this.terminal?.writeln(``);let t=this.currentLine;this.currentLine=``,this.cursorPos=0;let n=this.continuationBuffer?this.continuationBuffer+`
9989
- `+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${w9(t.path)} · ${t.mimeType}`,r.appendChild(i),t.mimeType.startsWith(`video/`)){let e=document.createElement(`video`);e.className=`terminal-panel__preview-media`,e.controls=!0,e.autoplay=!0,e.loop=!0,e.muted=!0,e.playsInline=!0,e.src=n,e.addEventListener(`loadedmetadata`,()=>this.refit(),{once:!0}),r.appendChild(e)}else{let e=document.createElement(`img`);e.className=`terminal-panel__preview-media`,e.alt=w9(t.path),e.src=n,e.addEventListener(`load`,()=>this.refit(),{once:!0}),r.appendChild(e)}this.previewHost.appendChild(r)}this.previewHost.classList.add(`terminal-panel__preview--visible`),this.hasPreview=e.length>0,this.previewStateListener?.(this.hasPreview),requestAnimationFrame(()=>this.refit())}};const T9=i(`tool:bash`),OEe=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function kEe(e){let t=[],n=``,r=null,i=!1,a=()=>{t.push(n),n=``};for(let t=0;t<e.length;t++){let o=e[t];if(i){n+=o,i=!1;continue}if(o===`\\`){n+=o,i=!0;continue}if(r){n+=o,o===r&&(r=null);continue}if(o===`"`||o===`'`){n+=o,r=o;continue}if((o===`&`||o===`|`)&&e[t+1]===o){a(),t++;continue}if(o===`;`||o===`|`){a();continue}n+=o}return a(),t}function AEe(e){let t=kEe(e);return(t[t.length-1]??``).trim()}function jEe(e,t,n){return t!==1||n.trim()?!1:OEe.test(AEe(e))}function MEe(e){return{name:`bash`,description:"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.",inputSchema:{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`}},required:[`command`]},async execute(t,n){let r=t.command;T9.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);T9.debug(`Result`,{exitCode:t.exitCode,stdoutLength:t.stdout.length,stderrLength:t.stderr.length});let i=``;return t.stdout&&(i+=t.stdout),t.stderr&&(i+=t.stderr),i||=`(exit code: ${t.exitCode})`,{content:i,isError:t.exitCode!==0&&!jEe(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return T9.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}const E9=i(`tool:fs`);function NEe(e){return[PEe(e),FEe(e),IEe(e)]}function PEe(e){return{name:`read_file`,description:`Read the contents of a file. Returns the file content as a string with line numbers.`,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;E9.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
9991
+ `+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${w9(t.path)} · ${t.mimeType}`,r.appendChild(i),t.mimeType.startsWith(`video/`)){let e=document.createElement(`video`);e.className=`terminal-panel__preview-media`,e.controls=!0,e.autoplay=!0,e.loop=!0,e.muted=!0,e.playsInline=!0,e.src=n,e.addEventListener(`loadedmetadata`,()=>this.refit(),{once:!0}),r.appendChild(e)}else{let e=document.createElement(`img`);e.className=`terminal-panel__preview-media`,e.alt=w9(t.path),e.src=n,e.addEventListener(`load`,()=>this.refit(),{once:!0}),r.appendChild(e)}this.previewHost.appendChild(r)}this.previewHost.classList.add(`terminal-panel__preview--visible`),this.hasPreview=e.length>0,this.previewStateListener?.(this.hasPreview),requestAnimationFrame(()=>this.refit())}};const T9=i(`tool:bash`),jEe=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function MEe(e){let t=[],n=``,r=null,i=!1,a=()=>{t.push(n),n=``};for(let t=0;t<e.length;t++){let o=e[t];if(i){n+=o,i=!1;continue}if(o===`\\`){n+=o,i=!0;continue}if(r){n+=o,o===r&&(r=null);continue}if(o===`"`||o===`'`){n+=o,r=o;continue}if((o===`&`||o===`|`)&&e[t+1]===o){a(),t++;continue}if(o===`;`||o===`|`){a();continue}n+=o}return a(),t}function NEe(e){let t=MEe(e);return(t[t.length-1]??``).trim()}function PEe(e,t,n){return t!==1||n.trim()?!1:jEe.test(NEe(e))}function FEe(e){return{name:`bash`,description:"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.",inputSchema:{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`}},required:[`command`]},async execute(t,n){let r=t.command;T9.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);T9.debug(`Result`,{exitCode:t.exitCode,stdoutLength:t.stdout.length,stderrLength:t.stderr.length});let i=``;return t.stdout&&(i+=t.stdout),t.stderr&&(i+=t.stderr),i||=`(exit code: ${t.exitCode})`,{content:i,isError:t.exitCode!==0&&!PEe(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return T9.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}const E9=i(`tool:fs`);function IEe(e){return[LEe(e),REe(e),zEe(e)]}function LEe(e){return{name:`read_file`,description:`Read the contents of a file. Returns the file content as a string with line numbers.`,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;E9.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
9990
9992
  `),a=Math.max(0,r-1),o=i===void 0?t.length:a+i;return{content:t.slice(a,o).map((e,t)=>`${String(a+t+1).padStart(6)} | ${e}`).join(`
9991
- `)}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function FEe(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;E9.debug(`Write`,{path:n,contentLength:r.length});try{return await e.writeFile(n,r),{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function IEe(e){return{name:`edit_file`,description:`Edit a file by replacing an exact string match. The old_string must appear exactly once in the file. Use this instead of write_file when making targeted changes to existing files.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to edit.`},old_string:{type:`string`,description:`The exact string to find and replace. Must be unique in the file.`},new_string:{type:`string`,description:`The replacement string.`}},required:[`path`,`old_string`,`new_string`]},async execute(t){let n=t.path,r=t.old_string,i=t.new_string;E9.debug(`Edit`,{path:n,oldLength:r.length,newLength:i.length});try{let t=await e.readTextFile(n),a=t.split(r).length-1;if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1)return{content:`old_string found ${a} times in ${n}. It must be unique. Provide more context.`,isError:!0};let o=t.replace(r,i);return await e.writeFile(n,o),{content:`File edited: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}i(`tool:search`);const D9=i(`scoop-management-tools`);function O9(e,t){let n=t(),r=[],i=[];for(let t of e){let e=n.find(e=>!e.isCone&&(e.folder===t||e.name===t));e?r.push(e):i.push(t)}return{resolved:r,unknown:i}}const k9=[`command`,`read`,`write`,`secret`];function LEe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`}function REe(e){return e===void 0?{ok:!0}:Xr(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${Yr.join(`, `)}.`,isError:!0}}function A9(e,t){return{content:`Scoop "${e}" not found. Available: ${t().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0}}function zEe(e,t){let n=t?.(e.jid),r=n?.status??`unknown`,i=n?.lastActivity?new Date(n.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,a=i?` — ${r} (since ${i})`:` — ${r}`;return e.isCone?`- ${e.assistantLabel} (${e.folder}) [CONE]${a}`:`- ${e.name} (${e.folder})${a}`}async function BEe(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),D9.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function VEe(e){let{kind:t,detail:n,suggested_pattern:r}=e;return k9.includes(t)?typeof n!=`string`||n.trim().length===0?{ok:!1,result:{content:`detail must be a non-empty string.`,isError:!0}}:{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{}}}:{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${k9.join(`, `)}.`,isError:!0}}}function HEe(e){let t=[`Cone decision: ${e.decision}.`];return e.decision===`always`&&e.pattern&&t.push(`Persisted pattern: ${e.pattern}`),e.decision===`deny`&&t.push(`The sensitive action was not approved. Do not retry without addressing the reason for refusal.`),t.join(`
9992
- `)}async function UEe(e,t){let n=VEe(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return D9.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:HEe(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function WEe(e,t){let{scoop_name:n,prompt:r}=e,i=t.getScoops().find(e=>e.folder===n||e.name===n);if(!i)return A9(n,t.getScoops);if(i.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await t.onFeedScoop(i.jid,r),D9.info(`Fed scoop`,{target:i.folder,promptLength:r.length}),{content:`Task sent to ${i.folder}. You will be notified when it completes.`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function GEe(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>zEe(t,e.getScoopTabState)).join(`
9993
- `)}`}}function KEe(e,t,n,r,i,a,o){return{name:e,folder:t,trigger:`@${t}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:t,addedAt:new Date().toISOString(),config:{...n?{modelId:n}:{},visiblePaths:r??[`/workspace/`],writablePaths:i??[`/scoops/${t}/`,`/shared/`],...a?{allowedCommands:a}:{},...o?{thinkingLevel:o}:{}},configSchemaVersion:2}}async function qEe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return D9.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 JEe(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c}=e,l=REe(c);if(!l.ok)return{content:l.content,isError:l.isError};let u=LEe(n);try{let e=KEe(n,u,r,a,o,s,l.level),c=await t.onScoopScoop(e);return D9.info(`Scoop created`,{name:n,folder:u}),i&&t.onFeedScoop?qEe(c,i,n,u,t.onFeedScoop):{content:`Scoop "${n}" created as "${u}". 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 YEe(e,t){let{scoop_name:n}=e,r=t.getScoops().find(e=>e.folder===n||e.name===n);if(!r)return A9(n,t.getScoops);if(r.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await t.onDropScoop(r.jid),D9.info(`Scoop dropped`,{name:r.name,folder:r.folder}),{content:`Scoop "${r.name}" (${r.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function j9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function M9(e){return{content:`No matching scoops found. Unknown: ${e.join(`, `)}`,isError:!0}}async function XEe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return j9();let{resolved:r,unknown:i}=O9(n,t.getScoops);return r.length===0?M9(i):(t.onMuteScoops(r.map(e=>e.jid)),D9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function ZEe(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 QEe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return j9();let{resolved:r,unknown:i}=O9(n,t.getScoops);if(r.length===0)return M9(i);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);D9.info(`Scoops unmuted`,{names:r.map(e=>e.folder),stashedCount:s.length});let c=[`Unmuted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`];return c.push(...ZEe(s,o)),{content:c.join(`
9994
- `)}}function $Ee(e,t){return!Array.isArray(e)||e.length===0?j9():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 eDe(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 tDe(e,t){let{scoop_names:n,timeout_ms:r}=e,i=$Ee(n,r);if(i)return i;let{resolved:a,unknown:o}=O9(n,t.getScoops);if(a.length===0)return M9(o);let s=a.map(e=>e.jid),c=t.onScheduleScoopWait(s,r),l=new Map(a.map(e=>[e.jid,e.folder])),u=c.scheduled.map(e=>l.get(e)??e).join(`, `),d=c.unknown.map(e=>l.get(e)??e).join(`, `);return D9.info(`Wait scheduled`,{scheduled:c.scheduled.map(e=>l.get(e)??e),droppedAtSchedule:d?d.split(`, `):[],unknownNames:o,timeout_ms:r}),c.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${d||c.unknown.join(`, `)}).${o.length>0?` Unknown names: ${o.join(`, `)}.`:``}`,isError:!0}:{content:eDe(u,o,d,r)}}function nDe(e,t){return t?e.persisted?`Approved (always) — persisted NOPASSWD rule for ${e.kind??`unknown`} pattern "${e.persistedPattern}" in /scoops/${e.scoopFolder??`<unknown>`}/etc/sudoers.`: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 rDe(e,t){let{lick_id:n,always:r,pattern:i}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let a=r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`};try{let e=await t.onSudoResolve(n,a);return e.settled?(D9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:nDe(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 iDe(e,t){let{lick_id:n}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};try{let e=await t.onSudoResolve(n,{decision:`deny`});return e.settled?(D9.info(`Lick dismissed`,{id:n}),e.message?{content:e.message}:{content:`Denied — the scoop will not run this action.`}):{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 aDe(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})`:``;return`- ${t.id} — ${n} — ${t.request.kind}: ${t.request.detail}${r}`}).join(`
9995
- `)}`}}async function oDe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),D9.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 sDe(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=>BEe(t,e)}}function cDe(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). 'always' durably widens your sandbox by appending a NOPASSWD rule to /scoops/<folder>/etc/sudoers. 'deny' (or a timeout / dropped cone) resolves fail-closed.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...k9],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.`}},required:[`kind`,`detail`]},execute:t=>UEe(t,e)}}function lDe(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"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>WEe(t,e)}}function uDe(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>GEe(e)}}function dDe(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, 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 ["/workspace/"] which exposes the shared skills tree. 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 regardless. 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. Trailing slash recommended.`},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:[...Yr],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.`}},required:[`name`]},execute:t=>JEe(t,e)}}function fDe(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"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:t=>YEe(t,e)}}function pDe(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"]).`}},required:[`scoop_names`]},execute:t=>XEe(t,e)}}function mDe(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"]).`}},required:[`scoop_names`]},execute:t=>QEe(t,e)}}function hDe(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 to wait for (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."}},required:[`scoop_names`]},execute:t=>tDe(t,e)}}function gDe(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 /scoops/<folder>/etc/sudoers 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.`}},required:[`lick_id`]},execute:t=>rDe(t,e)}}function _De(e){return{name:`lick_dismiss`,description:`Dismiss (refuse) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. The scoop receives a deny decision and the sensitive action does NOT run.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification). Use list_sudo_requests to see outstanding ids.`}},required:[`lick_id`]},execute:t=>iDe(t,e)}}function vDe(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:()=>aDe(e)}}function yDe(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=>oDe(t,e)}}function bDe(e){let t=[],n=e.scoop.isCone;return n||(t.push(sDe(e)),e.onSudoRequest&&t.push(cDe(e))),n&&(e.onFeedScoop&&t.push(lDe(e)),t.push(uDe(e)),e.onScoopScoop&&t.push(dDe(e)),e.onDropScoop&&t.push(fDe(e)),e.onMuteScoops&&t.push(pDe(e)),e.onUnmuteScoops&&t.push(mDe(e)),e.onScheduleScoopWait&&t.push(hDe(e)),e.onSudoResolve&&(t.push(gDe(e)),t.push(_De(e))),e.onListSudoRequests&&t.push(vDe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(yDe(e))),t}const N9=i(`scoop-context`);function P9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!M(t).includes(`xhigh`)?`high`:e}function xDe(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}function SDe(e){return/\b(401|403|404|405|410|422)\b/.test(e)||/unauthorized|forbidden|authentication.*failed|invalid.*api.?key/i.test(e)||/session expired|log in again|re-?authenticate/i.test(e)||/model.*not.*found|invalid.*model|unknown.*model|does.*not.*exist/i.test(e)||/decommissioned|no longer supported|deprecated.*model|model.*deprecated|model.*retired/i.test(e)||/insufficient.*quota|billing|payment.*required|account.*suspended/i.test(e)||/invalid.*request|malformed|bad.*request/i.test(e)}function F9(e){return/\b429\b|rate.*limit|too.*many.*requests|quota.*exceeded/i.test(e)||/\b(500|502|503|504)\b|internal.*server|bad.*gateway|service.*unavailable|gateway.*timeout/i.test(e)||/network.*error|failed to fetch|connection.*refused|timeout|econnreset|socket.*hang.*up/i.test(e)||/overloaded|temporarily.*unavailable|try.*again/i.test(e)}function I9(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}var CDe=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;coneJid;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,t=this.scoop.isCone,n=this.scoop.folder,r=this.callbacks.onSudoRequest,i=t||!r?e.getBroker():{requestApproval:e=>r(e)},a=t?()=>e.getPolicy():()=>e.getPolicyForScoop(n),o=t?`allow`:`require-approval`,s=e.getShellConfig(),c=t?s.persistCommandGrant:async()=>{};return{broker:i,getPolicy:a,defaultDisposition:o,shellConfig:{...s,broker:i,getPolicy:a,defaultDisposition:o,persistCommandGrant:c}}}async initShellAndSkills(){let e=this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await wL(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await tle(),i=this.buildSudoWiring(),a=i?Roe(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new DEe({fs:a,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0,allowedCommands:this.scoop.config?.allowedCommands,getParentJid:()=>this.scoop.jid,isScoop:()=>!this.scoop.isCone,sudo:i?.shellConfig,processManager:this.processManager??void 0,processOwner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getCurrentShellPid:()=>this.currentTurnProcess?.pid}),N9.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await CL(n,this.skillsDir)}}async buildTools(e){let t=bDe({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onMuteScoops:this.callbacks.onMuteScoops,onUnmuteScoops:this.callbacks.onUnmuteScoops,onScheduleScoopWait:this.callbacks.onScheduleScoopWait,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory,onSudoRequest:this.callbacks.onSudoRequest,onSudoResolve:this.callbacks.onSudoResolve,onListSudoRequests:this.callbacks.onListSudoRequests}),n=[...NEe(e),MEe(this.shell),...t];if(this.scoop.config?.structuredOutputSchema){let{createStructuredOutputTool:e}=await import(`./structured-output-tool-BDaIhclx.js`);n.push(e(this.scoop.config.structuredOutputSchema,e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0}))}let r={scrubToolResult:Oe()};return this.processManager?Ue(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):Ue(n,void 0,r)}async loadMemories(){let e=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,t=``;try{let n=await this.fs.readFile(e,{encoding:`utf-8`});t=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}let n=await this.callbacks.getGlobalMemory();if(n&&this.scoop.isCone)try{await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,n)}catch{}return{scoopMemory:t,globalMemory:n}}async restoreSession(){if(!this.sessionStore)return[];try{let e=await this.sessionStore.load(this.sessionId);if(e){let t=F(e.messages);return this.sessionCreatedAt=e.createdAt,N9.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){N9.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}return[]}async buildSessionHelpers(e){let t=await Hoe(this.scoop,this.coneJid),n=(e,n,r)=>e.provider===`adobe`?_e(e,n,{...r,headers:{...r?.headers,"X-Session-Id":t}}):_e(e,n,r),r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=this.scoop.isCone&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:qe()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:P({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>qe()??void 0,headers:r,onMemoryUpdates:i,onCompactionStateChange:this.callbacks.onCompactionStateChange})}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);N9.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let{gatedFs:e,skills:t}=await this.initShellAndSkills(),n=await this.buildTools(e),{scoopMemory:r,globalMemory:i}=await this.loadMemories();if(!qe()){N9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?N(this.scoop.config.modelId):Ne(),o=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${o} using model: ${a.id} (provider: ${a.provider})`);let s=this.buildSystemPrompt(i,r,t),c=await this.restoreSession(),{streamWithSessionId:l,compactFn:u}=await this.buildSessionHelpers(a);if(this.disposed)return;let d=P9(this.scoop.config?.thinkingLevel,a);this.agent=new Ce({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>qe()??void 0,transformContext:u,streamFn:l,afterToolCall:async e=>{this.scoop.config?.structuredOutputSchema&&e.toolCall.name===`StructuredOutput`&&(this.structuredOutputValue=e.args,this.structuredOutputCaptured=!0)}}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),N9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:n.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);N9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){if(this.agent)return!0;if(await this.init(),!this.agent){let e=``;try{e=$e()}catch{}return this.callbacks.onError(e?`No API key configured for provider "${e}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`),!1}return!0}queuePromptIfBusy(e,t){let n=this.agent.state?.isStreaming??!1;return this.isProcessing||n?(N9.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:n}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e},...t],timestamp:Date.now()}),!0):!1}registerTurnProcess(e,t){if(!this.processManager)return null;let n=[`prompt`,e.length>200?e.slice(0,197)+`…`:e];return this.processManager.spawn({kind:`scoop-turn`,argv:n,cwd:this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},adoptAbort:t})}handleNonRetryableError(e){return SDe(e)?(N9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),rr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!F9(e)||t>=n)return!1;let a=r*2**(t-1);return N9.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await I9(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;N9.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),rr(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{return await e.prompt(t,n),this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(N9.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:F9(a)}),!!(t<n&&(await I9(r*2**(t-1),i)||this.disposed)))}async runAgentWithRetries(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.disposed||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n);if(!o||this.disposed||r.aborted||(i=o,await this.handlePromptAttemptError(o,a,3,1e3,r)))return null}return i}async prompt(e,t=[]){if(!await this.ensureAgentReady()||this.queuePromptIfBusy(e,t))return;let n=this.agent;this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal;this.isProcessing=!0,this.setStatus(`processing`);let a=this.registerTurnProcess(e,r);this.currentTurnProcess=a;let o=null;try{if(o=await this.runAgentWithRetries(n,e,t,i),o&&!this.disposed&&!i.aborted){this.handleExhaustedRetries(o,3);return}!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,a,o,i)}}stop(){this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGINT`):this.promptAbortController?.abort(),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){let e=this.agent?.state?.messages??[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role!==`assistant`||!n.usage)continue;let r=n.usage.input+n.usage.cacheRead+n.usage.output,i=2e5;try{let e=this.scoop.config?.modelId?N(this.scoop.config.modelId):Ne();typeof e.contextWindow==`number`&&e.contextWindow>0&&(i=e.contextWindow)}catch{}return Math.min(1,r/i)}return 0}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=Ne();this.agent.state.model=e;let t=this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=P9(t,e),N9.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id,thinkingLevel:this.agent.state.thinkingLevel})}async reloadSkills(){if(!this.agent)return;let e=await CL(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,N9.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e){if(!this.agent)return`off`;let t=P9(e,this.agent.state.model);return this.agent.state.thinkingLevel=t,t}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.disposed=!0,this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGTERM`):this.promptAbortController?.abort(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleToolUIEvents(e){let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId)}formatToolResult(e){let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);let r=n.join(`
9993
+ `)}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function REe(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;E9.debug(`Write`,{path:n,contentLength:r.length});try{return await e.writeFile(n,r),{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function zEe(e){return{name:`edit_file`,description:`Edit a file by replacing an exact string match. The old_string must appear exactly once in the file. Use this instead of write_file when making targeted changes to existing files.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to edit.`},old_string:{type:`string`,description:`The exact string to find and replace. Must be unique in the file.`},new_string:{type:`string`,description:`The replacement string.`}},required:[`path`,`old_string`,`new_string`]},async execute(t){let n=t.path,r=t.old_string,i=t.new_string;E9.debug(`Edit`,{path:n,oldLength:r.length,newLength:i.length});try{let t=await e.readTextFile(n),a=t.split(r).length-1;if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1)return{content:`old_string found ${a} times in ${n}. It must be unique. Provide more context.`,isError:!0};let o=t.replace(r,i);return await e.writeFile(n,o),{content:`File edited: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}i(`tool:search`);const D9=i(`scoop-management-tools`);function O9(e,t){let n=t(),r=[],i=[];for(let t of e){let e=n.find(e=>!e.isCone&&(e.folder===t||e.name===t));e?r.push(e):i.push(t)}return{resolved:r,unknown:i}}const k9=[`command`,`read`,`write`,`secret`];function BEe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`}function VEe(e){return e===void 0?{ok:!0}:Xr(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${Yr.join(`, `)}.`,isError:!0}}function A9(e,t){return{content:`Scoop "${e}" not found. Available: ${t().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0}}function HEe(e,t){let n=t?.(e.jid),r=n?.status??`unknown`,i=n?.lastActivity?new Date(n.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,a=i?` — ${r} (since ${i})`:` — ${r}`;return e.isCone?`- ${e.assistantLabel} (${e.folder}) [CONE]${a}`:`- ${e.name} (${e.folder})${a}`}async function UEe(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),D9.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function WEe(e){let{kind:t,detail:n,suggested_pattern:r}=e;return k9.includes(t)?typeof n!=`string`||n.trim().length===0?{ok:!1,result:{content:`detail must be a non-empty string.`,isError:!0}}:{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{}}}:{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${k9.join(`, `)}.`,isError:!0}}}function GEe(e){let t=[`Cone decision: ${e.decision}.`];return e.decision===`always`&&e.pattern&&t.push(`Persisted pattern: ${e.pattern}`),e.decision===`deny`&&t.push(`The sensitive action was not approved. Do not retry without addressing the reason for refusal.`),t.join(`
9994
+ `)}async function KEe(e,t){let n=WEe(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return D9.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:GEe(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function qEe(e,t){let{scoop_name:n,prompt:r}=e,i=t.getScoops().find(e=>e.folder===n||e.name===n);if(!i)return A9(n,t.getScoops);if(i.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await t.onFeedScoop(i.jid,r),D9.info(`Fed scoop`,{target:i.folder,promptLength:r.length}),{content:`Task sent to ${i.folder}. You will be notified when it completes.`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function JEe(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>HEe(t,e.getScoopTabState)).join(`
9995
+ `)}`}}function YEe(e,t,n,r,i,a,o){return{name:e,folder:t,trigger:`@${t}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:t,addedAt:new Date().toISOString(),config:{...n?{modelId:n}:{},visiblePaths:r??[`/workspace/`],writablePaths:i??[`/scoops/${t}/`,`/shared/`],...a?{allowedCommands:a}:{},...o?{thinkingLevel:o}:{}},configSchemaVersion:2}}async function XEe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return D9.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 ZEe(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c}=e,l=VEe(c);if(!l.ok)return{content:l.content,isError:l.isError};let u=BEe(n);try{let e=YEe(n,u,r,a,o,s,l.level),c=await t.onScoopScoop(e);return D9.info(`Scoop created`,{name:n,folder:u}),i&&t.onFeedScoop?XEe(c,i,n,u,t.onFeedScoop):{content:`Scoop "${n}" created as "${u}". 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 QEe(e,t){let{scoop_name:n}=e,r=t.getScoops().find(e=>e.folder===n||e.name===n);if(!r)return A9(n,t.getScoops);if(r.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await t.onDropScoop(r.jid),D9.info(`Scoop dropped`,{name:r.name,folder:r.folder}),{content:`Scoop "${r.name}" (${r.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function j9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function M9(e){return{content:`No matching scoops found. Unknown: ${e.join(`, `)}`,isError:!0}}async function $Ee(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return j9();let{resolved:r,unknown:i}=O9(n,t.getScoops);return r.length===0?M9(i):(t.onMuteScoops(r.map(e=>e.jid)),D9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function eDe(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 tDe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return j9();let{resolved:r,unknown:i}=O9(n,t.getScoops);if(r.length===0)return M9(i);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);D9.info(`Scoops unmuted`,{names:r.map(e=>e.folder),stashedCount:s.length});let c=[`Unmuted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`];return c.push(...eDe(s,o)),{content:c.join(`
9996
+ `)}}function nDe(e,t){return!Array.isArray(e)||e.length===0?j9():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 rDe(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 iDe(e,t){let{scoop_names:n,timeout_ms:r}=e,i=nDe(n,r);if(i)return i;let{resolved:a,unknown:o}=O9(n,t.getScoops);if(a.length===0)return M9(o);let s=a.map(e=>e.jid),c=t.onScheduleScoopWait(s,r),l=new Map(a.map(e=>[e.jid,e.folder])),u=c.scheduled.map(e=>l.get(e)??e).join(`, `),d=c.unknown.map(e=>l.get(e)??e).join(`, `);return D9.info(`Wait scheduled`,{scheduled:c.scheduled.map(e=>l.get(e)??e),droppedAtSchedule:d?d.split(`, `):[],unknownNames:o,timeout_ms:r}),c.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${d||c.unknown.join(`, `)}).${o.length>0?` Unknown names: ${o.join(`, `)}.`:``}`,isError:!0}:{content:rDe(u,o,d,r)}}function aDe(e,t){return t?e.persisted?`Approved (always) — persisted NOPASSWD rule for ${e.kind??`unknown`} pattern "${e.persistedPattern}" in /scoops/${e.scoopFolder??`<unknown>`}/etc/sudoers.`: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 oDe(e,t){let{lick_id:n,always:r,pattern:i}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let a=r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`};try{let e=await t.onSudoResolve(n,a);return e.settled?(D9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:aDe(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 sDe(e,t){let{lick_id:n}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};try{let e=await t.onSudoResolve(n,{decision:`deny`});return e.settled?(D9.info(`Lick dismissed`,{id:n}),e.message?{content:e.message}:{content:`Denied — the scoop will not run this action.`}):{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 cDe(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})`:``;return`- ${t.id} — ${n} — ${t.request.kind}: ${t.request.detail}${r}`}).join(`
9997
+ `)}`}}async function lDe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),D9.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 uDe(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=>UEe(t,e)}}function dDe(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). 'always' durably widens your sandbox by appending a NOPASSWD rule to /scoops/<folder>/etc/sudoers. 'deny' (or a timeout / dropped cone) resolves fail-closed.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...k9],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.`}},required:[`kind`,`detail`]},execute:t=>KEe(t,e)}}function fDe(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"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>qEe(t,e)}}function pDe(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>JEe(e)}}function mDe(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, 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 ["/workspace/"] which exposes the shared skills tree. 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 regardless. 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. Trailing slash recommended.`},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:[...Yr],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.`}},required:[`name`]},execute:t=>ZEe(t,e)}}function hDe(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"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:t=>QEe(t,e)}}function gDe(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"]).`}},required:[`scoop_names`]},execute:t=>$Ee(t,e)}}function _De(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"]).`}},required:[`scoop_names`]},execute:t=>tDe(t,e)}}function vDe(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 to wait for (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."}},required:[`scoop_names`]},execute:t=>iDe(t,e)}}function yDe(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 /scoops/<folder>/etc/sudoers 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.`}},required:[`lick_id`]},execute:t=>oDe(t,e)}}function bDe(e){return{name:`lick_dismiss`,description:`Dismiss (refuse) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. The scoop receives a deny decision and the sensitive action does NOT run.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification). Use list_sudo_requests to see outstanding ids.`}},required:[`lick_id`]},execute:t=>sDe(t,e)}}function xDe(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:()=>cDe(e)}}function SDe(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=>lDe(t,e)}}function CDe(e){let t=[],n=e.scoop.isCone;return n||(t.push(uDe(e)),e.onSudoRequest&&t.push(dDe(e))),n&&(e.onFeedScoop&&t.push(fDe(e)),t.push(pDe(e)),e.onScoopScoop&&t.push(mDe(e)),e.onDropScoop&&t.push(hDe(e)),e.onMuteScoops&&t.push(gDe(e)),e.onUnmuteScoops&&t.push(_De(e)),e.onScheduleScoopWait&&t.push(vDe(e)),e.onSudoResolve&&(t.push(yDe(e)),t.push(bDe(e))),e.onListSudoRequests&&t.push(xDe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(SDe(e))),t}const N9=i(`scoop-context`);function P9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!M(t).includes(`xhigh`)?`high`:e}function wDe(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}function TDe(e){return/\b(401|403|404|405|410|422)\b/.test(e)||/unauthorized|forbidden|authentication.*failed|invalid.*api.?key/i.test(e)||/session expired|log in again|re-?authenticate/i.test(e)||/model.*not.*found|invalid.*model|unknown.*model|does.*not.*exist/i.test(e)||/decommissioned|no longer supported|deprecated.*model|model.*deprecated|model.*retired/i.test(e)||/insufficient.*quota|billing|payment.*required|account.*suspended/i.test(e)||/invalid.*request|malformed|bad.*request/i.test(e)}function F9(e){return/\b429\b|rate.*limit|too.*many.*requests|quota.*exceeded/i.test(e)||/\b(500|502|503|504)\b|internal.*server|bad.*gateway|service.*unavailable|gateway.*timeout/i.test(e)||/network.*error|failed to fetch|connection.*refused|timeout|econnreset|socket.*hang.*up/i.test(e)||/overloaded|temporarily.*unavailable|try.*again/i.test(e)}function I9(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}var EDe=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;coneJid;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,t=this.scoop.isCone,n=this.scoop.folder,r=this.callbacks.onSudoRequest,i=t||!r?e.getBroker():{requestApproval:e=>r(e)},a=t?()=>e.getPolicy():()=>e.getPolicyForScoop(n),o=t?`allow`:`require-approval`,s=e.getShellConfig(),c=t?s.persistCommandGrant:async()=>{};return{broker:i,getPolicy:a,defaultDisposition:o,shellConfig:{...s,broker:i,getPolicy:a,defaultDisposition:o,persistCommandGrant:c}}}async initShellAndSkills(){let e=this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await wL(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await tle(),i=this.buildSudoWiring(),a=i?Roe(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new AEe({fs:a,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0,allowedCommands:this.scoop.config?.allowedCommands,getParentJid:()=>this.scoop.jid,isScoop:()=>!this.scoop.isCone,sudo:i?.shellConfig,processManager:this.processManager??void 0,processOwner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getCurrentShellPid:()=>this.currentTurnProcess?.pid}),N9.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await CL(n,this.skillsDir)}}async buildTools(e){let t=CDe({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onMuteScoops:this.callbacks.onMuteScoops,onUnmuteScoops:this.callbacks.onUnmuteScoops,onScheduleScoopWait:this.callbacks.onScheduleScoopWait,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory,onSudoRequest:this.callbacks.onSudoRequest,onSudoResolve:this.callbacks.onSudoResolve,onListSudoRequests:this.callbacks.onListSudoRequests}),n=[...IEe(e),FEe(this.shell),...t];if(this.scoop.config?.structuredOutputSchema){let{createStructuredOutputTool:e}=await import(`./structured-output-tool-BDaIhclx.js`);n.push(e(this.scoop.config.structuredOutputSchema,e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0}))}let r={scrubToolResult:Oe()};return this.processManager?Ue(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):Ue(n,void 0,r)}async loadMemories(){let e=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,t=``;try{let n=await this.fs.readFile(e,{encoding:`utf-8`});t=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}let n=await this.callbacks.getGlobalMemory();if(n&&this.scoop.isCone)try{await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,n)}catch{}return{scoopMemory:t,globalMemory:n}}async restoreSession(){if(!this.sessionStore)return[];try{let e=await this.sessionStore.load(this.sessionId);if(e){let t=F(e.messages);return this.sessionCreatedAt=e.createdAt,N9.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){N9.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}return[]}async buildSessionHelpers(e){let t=await Hoe(this.scoop,this.coneJid),n=(e,n,r)=>e.provider===`adobe`?_e(e,n,{...r,headers:{...r?.headers,"X-Session-Id":t}}):_e(e,n,r),r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=this.scoop.isCone&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:qe()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:P({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>qe()??void 0,headers:r,onMemoryUpdates:i,onCompactionStateChange:this.callbacks.onCompactionStateChange})}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);N9.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let{gatedFs:e,skills:t}=await this.initShellAndSkills(),n=await this.buildTools(e),{scoopMemory:r,globalMemory:i}=await this.loadMemories();if(!qe()){N9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?N(this.scoop.config.modelId):Ne(),o=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${o} using model: ${a.id} (provider: ${a.provider})`);let s=this.buildSystemPrompt(i,r,t),c=await this.restoreSession(),{streamWithSessionId:l,compactFn:u}=await this.buildSessionHelpers(a);if(this.disposed)return;let d=P9(this.scoop.config?.thinkingLevel,a);this.agent=new Ce({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>qe()??void 0,transformContext:u,streamFn:l,afterToolCall:async e=>{this.scoop.config?.structuredOutputSchema&&e.toolCall.name===`StructuredOutput`&&(this.structuredOutputValue=e.args,this.structuredOutputCaptured=!0)}}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),N9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:n.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);N9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){if(this.agent)return!0;if(await this.init(),!this.agent){let e=``;try{e=$e()}catch{}return this.callbacks.onError(e?`No API key configured for provider "${e}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`),!1}return!0}queuePromptIfBusy(e,t){let n=this.agent.state?.isStreaming??!1;return this.isProcessing||n?(N9.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:n}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e},...t],timestamp:Date.now()}),!0):!1}registerTurnProcess(e,t){if(!this.processManager)return null;let n=[`prompt`,e.length>200?e.slice(0,197)+`…`:e];return this.processManager.spawn({kind:`scoop-turn`,argv:n,cwd:this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},adoptAbort:t})}handleNonRetryableError(e){return TDe(e)?(N9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),rr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!F9(e)||t>=n)return!1;let a=r*2**(t-1);return N9.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await I9(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;N9.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),rr(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{return await e.prompt(t,n),this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(N9.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:F9(a)}),!!(t<n&&(await I9(r*2**(t-1),i)||this.disposed)))}async runAgentWithRetries(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.disposed||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n);if(!o||this.disposed||r.aborted||(i=o,await this.handlePromptAttemptError(o,a,3,1e3,r)))return null}return i}async prompt(e,t=[]){if(!await this.ensureAgentReady()||this.queuePromptIfBusy(e,t))return;let n=this.agent;this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal;this.isProcessing=!0,this.setStatus(`processing`);let a=this.registerTurnProcess(e,r);this.currentTurnProcess=a;let o=null;try{if(o=await this.runAgentWithRetries(n,e,t,i),o&&!this.disposed&&!i.aborted){this.handleExhaustedRetries(o,3);return}!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,a,o,i)}}stop(){this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGINT`):this.promptAbortController?.abort(),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){let e=this.agent?.state?.messages??[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role!==`assistant`||!n.usage)continue;let r=n.usage.input+n.usage.cacheRead+n.usage.output,i=2e5;try{let e=this.scoop.config?.modelId?N(this.scoop.config.modelId):Ne();typeof e.contextWindow==`number`&&e.contextWindow>0&&(i=e.contextWindow)}catch{}return Math.min(1,r/i)}return 0}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=Ne();this.agent.state.model=e;let t=this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=P9(t,e),N9.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id,thinkingLevel:this.agent.state.thinkingLevel})}async reloadSkills(){if(!this.agent)return;let e=await CL(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,N9.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e){if(!this.agent)return`off`;let t=P9(e,this.agent.state.model);return this.agent.state.thinkingLevel=t,t}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.disposed=!0,this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGTERM`):this.promptAbortController?.abort(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleToolUIEvents(e){let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId)}formatToolResult(e){let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);let r=n.join(`
9996
9998
  `);if(e.isError){let t=n.filter(e=>!e.startsWith(`<img:`)).join(`
9997
- `);rr(`tool`,`${e.toolName}: ${t}`)}this.callbacks.onToolEnd?.(e.toolName,r,e.isError)}handleAgentEndEvent(e){if(e.length>0){let t=e[e.length-1];if(t.role===`assistant`&&t.errorMessage){let n=t.errorMessage;if(!this.isRecovering&&xDe(n)){this.recoverFromImageError(e);return}if(!this.isRecovering&&ve(t)){this.recoverFromOverflow(e);return}if(!this.isRecovering&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=n;return}this.isRecovering=!1,rr(`llm`,n),this.callbacks.onError(n)}else this.isRecovering=!1}let t=this.agent?.state?.messages??e;this.sessionStore&&t.length>0&&this.sessionStore.save({id:this.sessionId,messages:t,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{N9.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}handleAgentEvent(e){if(!this.disposed)switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:this.handleToolUIEvents(e);break;case`tool_execution_end`:this.formatToolResult(e);break;case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:this.handleAgentEndEvent(e.messages);break}}trimOversizedMessages(e){let t=e.slice(0,-1),n=0;for(let e=t.length-1;e>=0&&n<5;e--){let r=t[e];if(!Array.isArray(r.content))continue;let i=0;for(let e of r.content)e.type===`text`&&e.text&&(i+=e.text.length),e.type===`image`&&e.data&&(i+=e.data.length);if(i>4e4){let a={type:`text`,text:`[Content removed: ${r.role===`toolResult`?`tool result`:r.role} was too large for context window (${Math.round(i/1e3)}K chars). The operation completed but output could not be retained.]`};if(r.role===`assistant`){let n=r.content.filter(e=>e.type===`toolCall`);t[e]={...r,content:[a,...n]}}else t[e]={...r,content:[a]};n++,N9.info(`Replaced oversized message`,{index:e,role:r.role,size:i,preservedToolCalls:r.role===`assistant`?r.content.filter(e=>e.type===`toolCall`).length:0})}}return{trimmed:t,replaced:n}}recoverFromOverflow(e){if(this.agent){N9.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`overflow`,this.callbacks.onResponse(`Context window exceeded — recovering by trimming oversized messages...`,!1);try{let{trimmed:t,replaced:n}=this.trimOversizedMessages(e);this.agent.state.messages=t;let r=n>0?`[System: Context overflow recovered. ${n} oversized message(s) were replaced with placeholders to fit within the context window. The conversation continues — you may need to re-read files or re-run commands if their output was removed.]`:`[System: Context overflow recovered. Older messages were trimmed. The conversation continues — compaction will summarize history on the next turn.]`;this.agent.prompt(r).catch(e=>{N9.error(`Recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){N9.error(`Recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}recoverFromImageError(e){if(this.agent){N9.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`image`,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{N9.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){N9.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.scoop.isCone?[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
9999
+ `);rr(`tool`,`${e.toolName}: ${t}`)}this.callbacks.onToolEnd?.(e.toolName,r,e.isError)}handleAgentEndEvent(e){if(e.length>0){let t=e[e.length-1];if(t.role===`assistant`&&t.errorMessage){let n=t.errorMessage;if(!this.isRecovering&&wDe(n)){this.recoverFromImageError(e);return}if(!this.isRecovering&&ve(t)){this.recoverFromOverflow(e);return}if(!this.isRecovering&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=n;return}this.isRecovering=!1,rr(`llm`,n),this.callbacks.onError(n)}else this.isRecovering=!1}let t=this.agent?.state?.messages??e;this.sessionStore&&t.length>0&&this.sessionStore.save({id:this.sessionId,messages:t,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{N9.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}handleAgentEvent(e){if(!this.disposed)switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:this.handleToolUIEvents(e);break;case`tool_execution_end`:this.formatToolResult(e);break;case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:this.handleAgentEndEvent(e.messages);break}}trimOversizedMessages(e){let t=e.slice(0,-1),n=0;for(let e=t.length-1;e>=0&&n<5;e--){let r=t[e];if(!Array.isArray(r.content))continue;let i=0;for(let e of r.content)e.type===`text`&&e.text&&(i+=e.text.length),e.type===`image`&&e.data&&(i+=e.data.length);if(i>4e4){let a={type:`text`,text:`[Content removed: ${r.role===`toolResult`?`tool result`:r.role} was too large for context window (${Math.round(i/1e3)}K chars). The operation completed but output could not be retained.]`};if(r.role===`assistant`){let n=r.content.filter(e=>e.type===`toolCall`);t[e]={...r,content:[a,...n]}}else t[e]={...r,content:[a]};n++,N9.info(`Replaced oversized message`,{index:e,role:r.role,size:i,preservedToolCalls:r.role===`assistant`?r.content.filter(e=>e.type===`toolCall`).length:0})}}return{trimmed:t,replaced:n}}recoverFromOverflow(e){if(this.agent){N9.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`overflow`,this.callbacks.onResponse(`Context window exceeded — recovering by trimming oversized messages...`,!1);try{let{trimmed:t,replaced:n}=this.trimOversizedMessages(e);this.agent.state.messages=t;let r=n>0?`[System: Context overflow recovered. ${n} oversized message(s) were replaced with placeholders to fit within the context window. The conversation continues — you may need to re-read files or re-run commands if their output was removed.]`:`[System: Context overflow recovered. Older messages were trimmed. The conversation continues — compaction will summarize history on the next turn.]`;this.agent.prompt(r).catch(e=>{N9.error(`Recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){N9.error(`Recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}recoverFromImageError(e){if(this.agent){N9.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`image`,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{N9.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){N9.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.scoop.isCone?[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
9998
10000
 
9999
10001
  ${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
10000
10002
  Folder: ${this.scoop.folder}
@@ -10075,14 +10077,14 @@ ${e}
10075
10077
  ---
10076
10078
  ${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
10077
10079
  ${t}
10078
- ---`);let a=Mce(n);return a&&(i+=a),i}};const L9=i(`scoop-lifecycle-manager`);var wDe=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){L9.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){L9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)L9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{L9.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new ot(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new CDe(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),L9.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),L9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(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 L9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[]){let a=this.contexts.get(e);a||=(await this.createTab(e),this.contexts.get(e));let o=this.tabs.get(e);if(o?.status===`initializing`){if(L9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){L9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}a=this.contexts.get(e),o=this.tabs.get(e)}if(!a){L9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),o&&(o.status=`processing`,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),L9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await a.prompt(t,i)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),L9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||or(`spawn`,e.folder)}catch(n){L9.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){L9.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=>{L9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=r.getLicksForScoop(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{L9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{L9.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.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&L9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),L9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){L9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();L9.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{L9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),L9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t){let n=this.deps.getScoops().get(e);if(!n)return null;let r=this.contexts.get(e),i=r?r.setThinkingLevel(t):null;if(t===void 0){if(n.config&&n.config.thinkingLevel!==void 0){let{thinkingLevel:e,...t}=n.config;n.config=t}}else n.config={...n.config??{},thinkingLevel:t};try{await this.deps.db.saveScoop(n)}catch(t){L9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return i}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),or(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await i.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);L9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),or(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){L9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{L9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const R9=i(`scoop-message-router`);var TDe=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;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.messageQueues.delete(e),this.lastAgentTimestamp.delete(e)}async handleMessage(e){if(R9.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){R9.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}`);or(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),R9.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);R9.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){R9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){R9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.deps.getTabs().get(e.chatJid);if(R9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){R9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),i=this.deps.getTabs().get(e.chatJid)}catch{R9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){R9.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){R9.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);if(R9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){R9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${je(e.content,e.attachments)}`).join(`
10079
- `),c=o.flatMap(e=>rt(e.attachments));this.messageQueues.set(e,[]);let l=o[o.length-1];this.lastAgentTimestamp.set(e,l.timestamp),await this.deps.db.setState(`lastAgentTs_${e}`,l.timestamp),await this.deps.sendPrompt(e,s,l.senderId,l.senderName,c)}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys())this.deps.getTabs().get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);R9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{R9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{R9.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,[]),R9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{R9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),R9.info(`All messages cleared`)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await this.deps.db.deleteMessage(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await this.deps.db.deleteMessage(t)}};const z9=i(`orchestrator`);var EDe=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Fce({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new ele({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new $ce({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Xce({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),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;approvalRouter=new qce({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>ln(e),saveMessage:e=>sn(e)});lickRegistry=new Gce({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new TDe({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i??[]),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>sn(e),deleteMessage:e=>cn(e),clearMessagesForScoop:e=>on(e),clearAllMessages:()=>an(),getMessagesSince:(e,t,n)=>un(e,t,n),setState:(e,t)=>gn(e,t)},isExternalLickChannel:St});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new wDe({getScoops:()=>this.scoops,getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>tn(e),deleteScoop:e=>rn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>WL(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(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)=>this.scheduleScoopWait(e,t),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)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await _n(),this.sharedFs=await at.create({dbName:`slicc-fs`}),this.sessionStore=new De,this.fsWatcher=new it,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new fI({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await nn();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await hn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Kce({onTaskRun:async(e,t)=>{z9.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(),z9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())await this.createScoopTab(e.jid);FF(()=>this.getSessionCosts()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/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}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await at.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await wL(this.sharedFs).catch(e=>{z9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new fI({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),z9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}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)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return ln(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t){return this.lifecycle.setThinkingLevel(e,t)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&z9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,z9.info(`Orchestrator shutdown`)}},DDe=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=V9(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))}if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new O(`ENOENT`,`no such file or directory`,e);return B9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new O(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new O(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new O(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new O(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new O(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=V9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new O(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new O(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new O(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new O(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new O(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new O(`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 O(`EBADF`,`mount closed`,e)}pidExists(e){return e===1?!0: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}renderProcFile(e,t){if(e===1)return NDe(t);let n=this.pm.get(e);switch(t){case`status`:return ODe(n);case`cmdline`:return kDe(n);case`cwd`:return ADe(n);case`stat`:return jDe(n)}}};const B9=[`status`,`cmdline`,`cwd`,`stat`];function V9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function H9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function ODe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${MDe(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(`
10080
+ ---`);let a=Mce(n);return a&&(i+=a),i}};const L9=i(`scoop-lifecycle-manager`);var DDe=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){L9.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){L9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)L9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{L9.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new ot(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new EDe(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),L9.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),L9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(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 L9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[]){let a=this.contexts.get(e);a||=(await this.createTab(e),this.contexts.get(e));let o=this.tabs.get(e);if(o?.status===`initializing`){if(L9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){L9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}a=this.contexts.get(e),o=this.tabs.get(e)}if(!a){L9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),o&&(o.status=`processing`,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),L9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await a.prompt(t,i)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),L9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||or(`spawn`,e.folder)}catch(n){L9.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){L9.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=>{L9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=r.getLicksForScoop(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{L9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{L9.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.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&L9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),L9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){L9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();L9.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{L9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),L9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t){let n=this.deps.getScoops().get(e);if(!n)return null;let r=this.contexts.get(e),i=r?r.setThinkingLevel(t):null;if(t===void 0){if(n.config&&n.config.thinkingLevel!==void 0){let{thinkingLevel:e,...t}=n.config;n.config=t}}else n.config={...n.config??{},thinkingLevel:t};try{await this.deps.db.saveScoop(n)}catch(t){L9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return i}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),or(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await i.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);L9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),or(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){L9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{L9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const R9=i(`scoop-message-router`);var ODe=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;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.messageQueues.delete(e),this.lastAgentTimestamp.delete(e)}async handleMessage(e){if(R9.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){R9.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}`);or(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),R9.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);R9.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){R9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){R9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.deps.getTabs().get(e.chatJid);if(R9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){R9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),i=this.deps.getTabs().get(e.chatJid)}catch{R9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){R9.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){R9.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);if(R9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){R9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${je(e.content,e.attachments)}`).join(`
10081
+ `),c=o.flatMap(e=>rt(e.attachments));this.messageQueues.set(e,[]);let l=o[o.length-1];this.lastAgentTimestamp.set(e,l.timestamp),await this.deps.db.setState(`lastAgentTs_${e}`,l.timestamp),await this.deps.sendPrompt(e,s,l.senderId,l.senderName,c)}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys())this.deps.getTabs().get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);R9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{R9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{R9.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,[]),R9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{R9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),R9.info(`All messages cleared`)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await this.deps.db.deleteMessage(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await this.deps.db.deleteMessage(t)}};const z9=i(`orchestrator`);var kDe=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Fce({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new ele({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new $ce({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Xce({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),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;approvalRouter=new qce({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>ln(e),saveMessage:e=>sn(e)});lickRegistry=new Gce({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new ODe({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i??[]),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>sn(e),deleteMessage:e=>cn(e),clearMessagesForScoop:e=>on(e),clearAllMessages:()=>an(),getMessagesSince:(e,t,n)=>un(e,t,n),setState:(e,t)=>gn(e,t)},isExternalLickChannel:St});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new DDe({getScoops:()=>this.scoops,getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>tn(e),deleteScoop:e=>rn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>WL(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(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)=>this.scheduleScoopWait(e,t),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)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await _n(),this.sharedFs=await at.create({dbName:`slicc-fs`}),this.sessionStore=new De,this.fsWatcher=new it,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new fI({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await nn();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await hn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Kce({onTaskRun:async(e,t)=>{z9.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(),z9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())await this.createScoopTab(e.jid);FF(()=>this.getSessionCosts()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/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}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await at.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await wL(this.sharedFs).catch(e=>{z9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new fI({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),z9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}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)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return ln(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t){return this.lifecycle.setThinkingLevel(e,t)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&z9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,z9.info(`Orchestrator shutdown`)}},ADe=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=V9(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))}if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new O(`ENOENT`,`no such file or directory`,e);return B9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new O(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new O(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new O(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new O(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new O(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=V9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new O(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new O(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new O(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new O(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new O(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new O(`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 O(`EBADF`,`mount closed`,e)}pidExists(e){return e===1?!0: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}renderProcFile(e,t){if(e===1)return IDe(t);let n=this.pm.get(e);switch(t){case`status`:return jDe(n);case`cmdline`:return MDe(n);case`cwd`:return NDe(n);case`stat`:return PDe(n)}}};const B9=[`status`,`cmdline`,`cwd`,`stat`];function V9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function H9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function jDe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${FDe(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(`
10080
10082
  `)+`
10081
- `}function kDe(e){return e.argv.join(`\0`)+`\0`}function ADe(e){return e.cwd+`
10082
- `}function jDe(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
10083
- `}function U9(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function MDe(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function NDe(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
10083
+ `}function MDe(e){return e.argv.join(`\0`)+`\0`}function NDe(e){return e.cwd+`
10084
+ `}function PDe(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
10085
+ `}function U9(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function FDe(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function IDe(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
10084
10086
  `)+`
10085
10087
  `;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
10086
10088
  `;case`stat`:return`1 (kernel-host) R 0 - 0 -
10087
- `}}function PDe(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;default:return e.cronName}}function FDe(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`}`;default:return e.cronId}}function IDe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}LDe(e,t)}function LDe(e,{orchestrator:t,log:n}){e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`&&(e.lickId=t.registerUpgradeLick(e));let r=Mt(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=PDe(e),a=FDe(e),o=e.type,s=t.getScoops(),c;if(c=e.targetScoop?s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):s.find(e=>e.isCone),!c){n.warn(`Lick target scoop not found`,e.targetScoop);return}let l={id:`${o}-${a}-${Date.now()}`,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:o,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l)}async function RDe(e,t,n,r){let i=new KW,a=new EDe(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=Fn(()=>n.emitTrayRuntimeStatus()),s=Ut(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function zDe(e,t,n){let{registerSessionCostsProvider:r}=await Promise.resolve().then(()=>Soe);r(()=>e.getSessionCosts());let{getLickManager:i}=await Promise.resolve().then(()=>Vce),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??IDe,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function BDe(e){e.getScoops().some(e=>e.isCone)||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function VDe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;$Te({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>$1(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>h9().slice(10,22),splitResult:(e,t)=>g9(e,t)})}async function HDe(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-D_PY6ku1.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-Dzuxa2F7.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
10088
- `,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 UDe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C9Grc0G_.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).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 WDe(e,t,n){let r=e.getTransport();if(r.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 Jr(r,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function GDe(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-ggb440m4.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>gt),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function KDe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-D6VrdGgM.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function qDe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-aV3rA0w_.js`),{ScriptCatalog:r}=await Promise.resolve().then(()=>hpe),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}}}async function JDe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1,isExtension:o=!1}=e,s=e.logger??console,{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await RDe(t,n,r,i);if(f?si(l,f,l.getSessionStore()):s.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new DDe(c))}catch(e){s.warn(`Failed to mount /proc`,e)}let p=await zDe(l,e,s);f&&VDe({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),globalThis.__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await HDe({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:s});globalThis.__slicc_wsSubscribers=h;let g=null;o||(g=await UDe(p,s,e.localLickWsUrl??null));let _=null;o||(_=WDe(n,p,s)),f&&GDe(f,p,s),a||await BDe(l),f&&KDe(p,s);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await qDe(f,n,s));let b=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:p,sharedFs:f??null,processManager:c,async dispose(){b||(b=!0,await YDe({unsubLeader:u,unsubFollower:d,bshWatchdogStop:v,scriptCatalogDispose:y,lickWsBridgeStop:g,navigationWatcherStop:_,sharedFs:f,wsRegistry:h,wsBridge:m,processManager:c,lickManager:p,browser:n,log:s}))}}}async function YDe(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.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),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)}XDe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function XDe(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,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[f9]}const W9=`x-bypass-llm-proxy`;function ZDe(e,t,n){return t?(r,i)=>{if(!QDe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(W9)||a.set(W9,`1`),e(r,{...i,headers:a})}:e}function QDe(e,t,n){if(eOe(e,t))return!0;let r=n?.()??null;return r?$De(e,r,t):!1}function $De(e,t,n){let r=G9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname===`/api/fetch-proxy`}function eOe(e,t){let n=G9(e);try{return new URL(n,t).origin===t}catch{return!0}}function G9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function tOe(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var nOe=class{transport;createShell;log;pm;defaultOwner;sessions=new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!rOe(e)||e.source!==`panel`)return;let t=e.payload;iOe(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;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=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?K9(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,K9(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 rOe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function K9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function iOe(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 aOe=class extends C9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function oOe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new nOe({transport:t,processManager:i,createShell:(e,a)=>new aOe(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function sOe(e){let t=new cOe(e);return t.start(),{stop:()=>t.dispose()}}var cOe=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!lOe(e)||e.source!==`panel`)return;let t=e.payload;if(uOe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(q9(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}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=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{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new O(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new O(`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 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(dOe(e.type),e.requestId,new O(`EACCES`,`vfs-rpc-host has no writable backend wired`),fOe(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)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new O(`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 O(`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,``)}}emitError(e,t,n,r){let i=J9(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=J9(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}}}};function lOe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function uOe(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 q9(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`}function dOe(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`}}function fOe(e){return e.type===`vfs-flush`?``:e.path}function J9(e,t){return e instanceof O?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function pOe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=ZDe(e.bind(globalThis),t,mOe)}function mOe(){let e=u();if(!e)return null;try{return new URL(e).origin}catch{return null}}function hOe(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 Y9=null,X9=null,Z9=null,Q9=null,$9=null;const gOe=tOe(e=>_Oe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&gOe.handle(e.data)});async function _Oe(e){pOe(),d(e.localApiBaseUrl??null),g(e.bridgeToken??null),o(e.extensionDelegateId??null),hOe(e.localStorageSeed??{}),mr().catch(()=>{}),await fe();let t=Er(e.kernelPort),n=new Vn(t),r=Vn.createCallbacks(n),i=new Dr(e.cdpPort);await i.connect();let a=new Xn(i);Y9=await JDe({container:{},browser:a,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:s}=await import(`./sprinkle-bridge-channel-BceIr6aT.js`);globalThis.__slicc_sprinkleManager=s({instanceId:e.instanceId});let{createPanelRpcClient:c}=await import(`./panel-rpc-D0J5pskz.js`).then(e=>e.i);$9=c({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,a.setTrayTargetProvider(er(ue));let l=await vOe({host:Y9,transport:t,browser:a,instanceId:e.instanceId});l&&(X9=l.stopTerminalHost,Z9=l.stopVfsRpcHost,Q9=l.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}async function vOe(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=oOe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=sOe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await yOe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function yOe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CvjxCMP-.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-I4cndszg.js`).then(e=>e.a),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});export{hn as C,ht as D,Ft as E,En as S,Pt as T,oR as _,n5 as a,Mn as b,P_e as c,aQ as d,VK as f,sR as g,sW as h,_5 as i,N3 as l,SW as m,t9 as n,E8 as o,HK as p,e9 as r,w8 as s,ITe as t,cQ as u,tI as v,gn as w,On as x,Nn as y};
10089
+ `}}function LDe(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;default:return e.cronName}}function RDe(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`}`;default:return e.cronId}}function zDe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}BDe(e,t)}function BDe(e,{orchestrator:t,log:n}){e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`&&(e.lickId=t.registerUpgradeLick(e));let r=Mt(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=LDe(e),a=RDe(e),o=e.type,s=t.getScoops(),c;if(c=e.targetScoop?s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):s.find(e=>e.isCone),!c){n.warn(`Lick target scoop not found`,e.targetScoop);return}let l={id:`${o}-${a}-${Date.now()}`,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:o,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l)}async function VDe(e,t,n,r){let i=new KW,a=new kDe(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=Fn(()=>n.emitTrayRuntimeStatus()),s=Ut(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function HDe(e,t,n){let{registerSessionCostsProvider:r}=await Promise.resolve().then(()=>Soe);r(()=>e.getSessionCosts());let{getLickManager:i}=await Promise.resolve().then(()=>Vce),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??zDe,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function UDe(e){e.getScoops().some(e=>e.isCone)||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function WDe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;nEe({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>$1(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>h9().slice(10,22),splitResult:(e,t)=>g9(e,t)})}async function GDe(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-D_PY6ku1.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-Dzuxa2F7.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
10090
+ `,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 KDe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-DCvSQxqb.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).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 W9(e,t,n){let r=e.getTransport();if(r.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 Jr(r,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function qDe(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-ggb440m4.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>gt),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function JDe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-CWYyBGAq.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function YDe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-aV3rA0w_.js`),{ScriptCatalog:r}=await Promise.resolve().then(()=>hpe),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}}}async function XDe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1,isExtension:o=!1}=e,s=e.logger??console,{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await VDe(t,n,r,i);if(f?si(l,f,l.getSessionStore()):s.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new ADe(c))}catch(e){s.warn(`Failed to mount /proc`,e)}let p=await HDe(l,e,s);f&&WDe({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),globalThis.__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await GDe({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:s});globalThis.__slicc_wsSubscribers=h;let g=null;o||(g=await KDe(p,s,e.localLickWsUrl??null));let _=null;o||(_=W9(n,p,s)),f&&qDe(f,p,s),a||await UDe(l),f&&JDe(p,s);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await YDe(f,n,s));let b=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:p,sharedFs:f??null,processManager:c,async dispose(){b||(b=!0,await ZDe({unsubLeader:u,unsubFollower:d,bshWatchdogStop:v,scriptCatalogDispose:y,lickWsBridgeStop:g,navigationWatcherStop:_,sharedFs:f,wsRegistry:h,wsBridge:m,processManager:c,lickManager:p,browser:n,log:s}))}}}async function ZDe(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.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),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)}QDe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function QDe(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,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[f9]}const G9=`x-bypass-llm-proxy`;function $De(e,t,n){return t?(r,i)=>{if(!eOe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function eOe(e,t,n){if(nOe(e,t))return!0;let r=n?.()??null;return r?tOe(e,r,t):!1}function tOe(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname===`/api/fetch-proxy`}function nOe(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function rOe(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var iOe=class{transport;createShell;log;pm;defaultOwner;sessions=new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!aOe(e)||e.source!==`panel`)return;let t=e.payload;oOe(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;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=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?q9(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,q9(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 aOe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function oOe(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 sOe=class extends C9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function cOe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new iOe({transport:t,processManager:i,createShell:(e,a)=>new sOe(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function lOe(e){let t=new uOe(e);return t.start(),{stop:()=>t.dispose()}}var uOe=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!dOe(e)||e.source!==`panel`)return;let t=e.payload;if(fOe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(pOe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}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=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{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new O(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new O(`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 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(mOe(e.type),e.requestId,new O(`EACCES`,`vfs-rpc-host has no writable backend wired`),hOe(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)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new O(`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 O(`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,``)}}emitError(e,t,n,r){let i=J9(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=J9(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}}}};function dOe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function fOe(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 pOe(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`}function mOe(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`}}function hOe(e){return e.type===`vfs-flush`?``:e.path}function J9(e,t){return e instanceof O?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function gOe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=$De(e.bind(globalThis),t,_Oe)}function _Oe(){let e=u();if(!e)return null;try{return new URL(e).origin}catch{return null}}function vOe(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 Y9=null,X9=null,Z9=null,Q9=null,$9=null;const yOe=rOe(e=>bOe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&yOe.handle(e.data)});async function bOe(e){gOe(),d(e.localApiBaseUrl??null),g(e.bridgeToken??null),o(e.extensionDelegateId??null),vOe(e.localStorageSeed??{}),mr().catch(()=>{}),await fe();let t=Er(e.kernelPort),n=new Vn(t),r=Vn.createCallbacks(n),i=new Dr(e.cdpPort);await i.connect();let a=new Xn(i);Y9=await XDe({container:{},browser:a,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:s}=await import(`./sprinkle-bridge-channel-BceIr6aT.js`);globalThis.__slicc_sprinkleManager=s({instanceId:e.instanceId});let{createPanelRpcClient:c}=await import(`./panel-rpc-D0J5pskz.js`).then(e=>e.i);$9=c({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,a.setTrayTargetProvider(er(ue));let l=await xOe({host:Y9,transport:t,browser:a,instanceId:e.instanceId});l&&(X9=l.stopTerminalHost,Z9=l.stopVfsRpcHost,Q9=l.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}async function xOe(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=cOe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=lOe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await SOe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function SOe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-BUpIrjiI.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-I4cndszg.js`).then(e=>e.a),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});export{hn as C,ht as D,Ft as E,En as S,Pt as T,oR as _,n5 as a,Mn as b,P_e as c,aQ as d,VK as f,sR as g,sW as h,_5 as i,N3 as l,SW as m,t9 as n,E8 as o,HK as p,e9 as r,w8 as s,zTe as t,cQ as u,tI as v,gn as w,On as x,Nn as y};