sliccy 5.46.1 → 5.47.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 (79) hide show
  1. package/dist/ui/assets/{account-store-BcXlCboa.js → account-store-B6DLHNP3.js} +1 -1
  2. package/dist/ui/assets/{account-store-C9vT6I3G.js → account-store-Ctw4fGlD.js} +2 -2
  3. package/dist/ui/assets/{adobe-4j65HPbv.js → adobe-BYjenfss.js} +1 -1
  4. package/dist/ui/assets/{adobe-LvBvAolU.js → adobe-kcrGRYPW.js} +1 -1
  5. package/dist/ui/assets/{adobe-oauth-state-D_CnbHWP.js → adobe-oauth-state-0tdMoV3j.js} +1 -1
  6. package/dist/ui/assets/{agent-message-to-chat-BE_cztfd.js → agent-message-to-chat-9Cet57OK.js} +1 -1
  7. package/dist/ui/assets/{apps-B3_R7Dti.js → apps-DV7qNbNz.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-DkiboyOC.js → azure-openai-BJ_eYivI.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-C4vhEzyQ.js → azure-openai-DbpBANNc.js} +1 -1
  10. package/dist/ui/assets/{cerebras-CPc6t5F5.js → cerebras-BtQiA40_.js} +1 -1
  11. package/dist/ui/assets/{cerebras-DNLjBhWp.js → cerebras-BwpLhnKW.js} +1 -1
  12. package/dist/ui/assets/{connect-surface-DIKZq30_.js → connect-surface-CNFLjqp_.js} +1 -1
  13. package/dist/ui/assets/dip-CCDljM87.js +1 -0
  14. package/dist/ui/assets/{dist-DpbCe5zu.js → dist-4JCCvXtX.js} +1 -1
  15. package/dist/ui/assets/{dist-5Kr58-Xs.js → dist-D3BOe6dj.js} +1 -1
  16. package/dist/ui/assets/{ensure-speech-assets-BjFLbrTH.js → ensure-speech-assets-BUJcf-hE.js} +1 -1
  17. package/dist/ui/assets/esp8266-OWnoymsz.js +1 -0
  18. package/dist/ui/assets/{esptool-operations-Dnb3j1SN.js → esptool-operations-B1u4wB4r.js} +2 -2
  19. package/dist/ui/assets/{fs-D4wLFAbu.js → fs-Dj7O6EYP.js} +2 -2
  20. package/dist/ui/assets/{fs-DYAybeQR.js → fs-DlxlTbL_.js} +1 -1
  21. package/dist/ui/assets/{github-DW5dccQz.js → github-BNxo_n6F.js} +2 -2
  22. package/dist/ui/assets/{github-B88eKsEh.js → github-IATLboIB.js} +1 -1
  23. package/dist/ui/assets/{github-copilot-Co2Qp5Ju.js → github-copilot-C5dZ55f9.js} +1 -1
  24. package/dist/ui/assets/{github-copilot-4dOu9stG.js → github-copilot-vg2gEIp8.js} +1 -1
  25. package/dist/ui/assets/{hear-DYCeab6-.js → hear-C7EVXWrs.js} +1 -1
  26. package/dist/ui/assets/{kernel-worker-BzJKapC_.js → kernel-worker-DrXSFkPd.js} +146 -146
  27. package/dist/ui/assets/{kokoro-engine-h3CNVwna.js → kokoro-engine-BLDuiZZ4.js} +1 -1
  28. package/dist/ui/assets/{lick-ws-bridge-BzYGVgks.js → lick-ws-bridge-CQSyrpuD.js} +1 -1
  29. package/dist/ui/assets/{lick-ws-bridge-CumcaQUE.js → lick-ws-bridge-dfeVyw_G.js} +1 -1
  30. package/dist/ui/assets/{local-llm-XL5d-1iX.js → local-llm-Cad_GYO0.js} +1 -1
  31. package/dist/ui/assets/{main-BYg0PaE1.js → main-Bj_Y9AYw.js} +5 -5
  32. package/dist/ui/assets/{mount-Cenhiu9B.js → mount-CQBtHK7x.js} +1 -1
  33. package/dist/ui/assets/{mount-BDkX16A_.js → mount-gcmy2Pc8.js} +2 -2
  34. package/dist/ui/assets/{new-session-DPEq6imJ.js → new-session-B_y0uwND.js} +2 -2
  35. package/dist/ui/assets/{oauth-bootstrap-B6qv5sYG.js → oauth-bootstrap-ojZHCEEn.js} +2 -2
  36. package/dist/ui/assets/{openai-codex-1XOGnHeO.js → openai-codex-B9528jVo.js} +1 -1
  37. package/dist/ui/assets/{openai-codex-DUj5PlED.js → openai-codex-P-xjtnnt.js} +1 -1
  38. package/dist/ui/assets/{page-follower-tray-Besb3U67.js → page-follower-tray-DvloQUai.js} +1 -1
  39. package/dist/ui/assets/{panel-rpc-handlers-CVHrhGWc.js → panel-rpc-handlers-CQ9N4ZGN.js} +2 -2
  40. package/dist/ui/assets/{provider-BHTnAthy.js → provider-BBGS0lxK.js} +2 -2
  41. package/dist/ui/assets/{provider-hONoxn8T.js → provider-NWuqXsHS.js} +1 -1
  42. package/dist/ui/assets/provider-store-access-BNTZByef.js +1 -0
  43. package/dist/ui/assets/provider-store-access-BXfVlW7g.js +1 -0
  44. package/dist/ui/assets/{providers-CyUIFsNN.js → providers-BlHFP33i.js} +1 -1
  45. package/dist/ui/assets/{providers-BkFnT44A.js → providers-C-i5JR96.js} +2 -2
  46. package/dist/ui/assets/{quick-llm-BxdMFxAy.js → quick-llm-CcYs2ljK.js} +1 -1
  47. package/dist/ui/assets/session-freezer-CpmJSuYD.js +1 -0
  48. package/dist/ui/assets/{speak-Xwr6Wl9m.js → speak-B2BbgJmn.js} +1 -1
  49. package/dist/ui/assets/{sprinkle-manager-CoE9sMp9.js → sprinkle-manager-CPsnXGpN.js} +1 -1
  50. package/dist/ui/assets/{sprinkle-renderer-Cx1zoxx1.js → sprinkle-renderer-B9HCs4PN.js} +4 -4
  51. package/dist/ui/assets/{store-n4U_vb_u.js → store-DcrycunN.js} +1 -1
  52. package/dist/ui/assets/{sudo-CA-I-Jex.js → sudo-B3r2KA7c.js} +1 -1
  53. package/dist/ui/assets/{transformers-env-C4Avg6xw.js → transformers-env-KC56bVzn.js} +1 -1
  54. package/dist/ui/assets/{tray-leader-DUqYWjk1.js → tray-leader-CtO-D4A6.js} +1 -1
  55. package/dist/ui/assets/{tray-leave-runtime-OpRI23FI.js → tray-leave-runtime-Bfubz6rS.js} +1 -1
  56. package/dist/ui/assets/{upgrade-detection-CBbp183e.js → upgrade-detection-BrSe-3a9.js} +1 -1
  57. package/dist/ui/assets/{voice-reply-y9S63mUY.js → voice-reply-D9xDenb8.js} +1 -1
  58. package/dist/ui/assets/{wc-attach-DcwEQX_w.js → wc-attach-VXN4MlpB.js} +2 -2
  59. package/dist/ui/assets/{wc-extension-8juSLEoM.js → wc-extension--OcmNkB1.js} +2 -2
  60. package/dist/ui/assets/{wc-follower-QlCQL3yu.js → wc-follower-DnEn0MCV.js} +3 -3
  61. package/dist/ui/assets/{wc-live-wfHMNdmD.js → wc-live-uOEWr3yy.js} +5 -5
  62. package/dist/ui/assets/{wc-nav-Dqgeqsgr.js → wc-nav-C1PcjQto.js} +2 -2
  63. package/dist/ui/assets/{wc-onboarding-Cj-3MMA5.js → wc-onboarding-BRsfB6kX.js} +2 -2
  64. package/dist/ui/assets/{wc-placeholder-DHd2nPiI.js → wc-placeholder-BWmfdJjT.js} +3 -3
  65. package/dist/ui/assets/{wc-settings-qaDRz8hs.js → wc-settings-CI3zmVo_.js} +3 -3
  66. package/dist/ui/assets/{wc-shell-HXbzlUHd.js → wc-shell-C_NEtgd6.js} +3 -3
  67. package/dist/ui/assets/{wc-sprinkles-oM-yO1lk.js → wc-sprinkles-ycORDSUK.js} +2 -2
  68. package/dist/ui/assets/{wc-tray-Dmjoy6x6.js → wc-tray-BpuTt27A.js} +2 -2
  69. package/dist/ui/assets/{whisper-engine-DSzBJ2mm.js → whisper-engine-ykd2YqdE.js} +1 -1
  70. package/dist/ui/assets/{xai-grok-BLZnZyjA.js → xai-grok-BCgkvvBp.js} +1 -1
  71. package/dist/ui/assets/{xai-grok-DLOWJ0VT.js → xai-grok-DhLxxdIX.js} +1 -1
  72. package/dist/ui/index.html +3 -3
  73. package/dist/ui/packages/webapp/index.html +3 -3
  74. package/package.json +1 -1
  75. package/dist/ui/assets/dip-BEccuSET.js +0 -1
  76. package/dist/ui/assets/esp8266-C36kbb5M.js +0 -1
  77. package/dist/ui/assets/provider-store-access-BEURN-gB.js +0 -1
  78. package/dist/ui/assets/provider-store-access-CDteERF2.js +0 -1
  79. package/dist/ui/assets/session-freezer-BkqJVmIq.js +0 -1
@@ -1,8 +1,8 @@
1
- import{i as e,n as t,r as n,t as r}from"./rolldown-runtime-aKtaBQYM.js";import{t as i}from"./logger-LESFN7Hj.js";import{c as a,n as o,o as s,s as c,t as l}from"./src-BQoW5KdD.js";import{n as u,o as d,s as f}from"./tool-ui-t6ocn6AG.js";import{a as p,i as m,n as h,o as g,r as _,t as v}from"./backend-local-Xd3x-KgI.js";import{t as y}from"./runtime-env-byAg9ij-.js";import{t as b}from"./types-idfTVsM8.js";import{n as x,t as S}from"./mime-types-BqLkKWa7.js";import{a as C,i as w,n as T,r as E}from"./mount-Cenhiu9B.js";import{t as D}from"./mount-id-nJcx05eu.js";import{c as O,d as ee,f as te,i as ne,l as k,n as A,o as re,r as ie,s as ae,t as oe,u as se}from"./proxied-fetch-CMT-jCdn.js";import{n as ce,r as le,t as ue}from"./fetch-body-DDu_AU5I.js";import{t as de}from"./remote-cache-D59F5FOx.js";import{n as j}from"./mount-table-store-s20mtVA3.js";import{n as M,r as fe,t as pe}from"./panel-rpc-CjFVE0nK.js";import{a as me}from"./providers-CyUIFsNN.js";import{A as he,B as ge,C as _e,D as ve,E as ye,F as N,I as be,L as xe,M as Se,N as Ce,O as we,P,R as Te,S as F,T as I,V as Ee,_ as De,a as Oe,b as ke,c as Ae,d as je,f as Me,g as Ne,h as Pe,i as Fe,j as Ie,k as Le,l as Re,m as ze,o as Be,p as Ve,r as He,s as Ue,t as We,u as Ge,v as Ke,w as qe,x as Je,y as Ye,z as Xe}from"./account-store-C9vT6I3G.js";import{i as Ze,n as Qe,t as $e}from"./path-utils-DU6QhF_k.js";import{p as et,u as tt}from"./transform-messages-ZX8cvJiJ.js";import{_ as nt,l as rt,m as it,p as at,x as ot}from"./bedrock-camp-Czep_VHL.js";import{t as st}from"./__vite-browser-external-SwrSgYTf.js";import{a as ct,i as lt,n as ut,r as L}from"./fs-DYAybeQR.js";const dt=`__slicc_binary__`;function ft(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[dt]===`b64`&&typeof t.data==`string`}function pt(e){if(e instanceof Uint8Array)return{[dt]:`b64`,data:a(e)};if(Array.isArray(e))return e.map(pt);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=pt(r);return t}return e}function mt(e){if(ft(e))return c(e.data);if(Array.isArray(e))return e.map(mt);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=mt(r);return t}return e}const ht=i(`panel-transport`);function gt(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function _t(){return{onMessage:e=>{let t=(t,n,r)=>(gt(t)&&e(mt(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=pt(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)||ht.error(`Offscreen → panel transport send failed`,{error:t})})}}}const vt=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]);var yt=t({formatMountRecoveryPrompt:()=>Ct,mdInlineCode:()=>St,recoverMounts:()=>bt,shellQuote:()=>xt});async function bt(e,t,n){let r=[],i=[];for(let a of e){let{targetPath:e,descriptor:o}=a;if(o.kind===`local`){let a=await j(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=v.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 de({mountId:o.mountId,ttlMs:3e4}),a=new w({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:E(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 de({mountId:o.mountId,ttlMs:3e4}),a=new C({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:T()});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 xt(e){return`'${e.replace(/'/g,`'\\''`)}'`}function St(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 Ct(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 ${St(t)})`:``;return`- ${St(e)}${n}`}),i=r.map(({path:e})=>` mount ${xt(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 ${xt(n)}`,a=`mount --source ${xt(t)}${i} ${xt(e)}`;return`- ${St(e)} (${St(t)}, profile ${St(n)}) — ${r}\n Retry: ${St(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"./rolldown-runtime-aKtaBQYM.js";import{t as i}from"./logger-LESFN7Hj.js";import{c as a,n as o,o as s,s as c,t as l}from"./src-BQoW5KdD.js";import{n as u,o as d,s as f}from"./tool-ui-t6ocn6AG.js";import{a as p,i as m,n as h,o as g,r as _,t as v}from"./backend-local-Xd3x-KgI.js";import{t as y}from"./runtime-env-byAg9ij-.js";import{t as b}from"./types-idfTVsM8.js";import{n as x,t as S}from"./mime-types-BqLkKWa7.js";import{a as C,i as w,n as T,r as E}from"./mount-CQBtHK7x.js";import{t as D}from"./mount-id-nJcx05eu.js";import{c as O,d as ee,f as te,i as ne,l as k,n as A,o as re,r as ie,s as ae,t as oe,u as se}from"./proxied-fetch-CMT-jCdn.js";import{n as ce,r as le,t as ue}from"./fetch-body-DDu_AU5I.js";import{t as de}from"./remote-cache-D59F5FOx.js";import{n as j}from"./mount-table-store-s20mtVA3.js";import{n as M,r as fe,t as pe}from"./panel-rpc-CjFVE0nK.js";import{a as me}from"./providers-BlHFP33i.js";import{A as he,B as ge,C as _e,D as ve,E as ye,F as N,I as be,L as xe,M as Se,N as Ce,O as we,P,R as Te,S as F,T as I,V as Ee,_ as De,a as Oe,b as ke,c as Ae,d as je,f as Me,g as Ne,h as Pe,i as Fe,j as Ie,k as Le,l as Re,m as ze,o as Be,p as Ve,r as He,s as Ue,t as We,u as Ge,v as Ke,w as qe,x as Je,y as Ye,z as Xe}from"./account-store-Ctw4fGlD.js";import{i as Ze,n as Qe,t as $e}from"./path-utils-DU6QhF_k.js";import{p as et,u as tt}from"./transform-messages-ZX8cvJiJ.js";import{_ as nt,l as rt,m as it,p as at,x as ot}from"./bedrock-camp-Czep_VHL.js";import{t as st}from"./__vite-browser-external-SwrSgYTf.js";import{a as ct,i as lt,n as ut,r as L}from"./fs-DlxlTbL_.js";const dt=`__slicc_binary__`;function ft(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[dt]===`b64`&&typeof t.data==`string`}function pt(e){if(e instanceof Uint8Array)return{[dt]:`b64`,data:a(e)};if(Array.isArray(e))return e.map(pt);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=pt(r);return t}return e}function mt(e){if(ft(e))return c(e.data);if(Array.isArray(e))return e.map(mt);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=mt(r);return t}return e}const ht=i(`panel-transport`);function gt(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function _t(){return{onMessage:e=>{let t=(t,n,r)=>(gt(t)&&e(mt(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=pt(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)||ht.error(`Offscreen → panel transport send failed`,{error:t})})}}}const vt=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]);var yt=t({formatMountRecoveryPrompt:()=>Ct,mdInlineCode:()=>St,recoverMounts:()=>bt,shellQuote:()=>xt});async function bt(e,t,n){let r=[],i=[];for(let a of e){let{targetPath:e,descriptor:o}=a;if(o.kind===`local`){let a=await j(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=v.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 de({mountId:o.mountId,ttlMs:3e4}),a=new w({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:E(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 de({mountId:o.mountId,ttlMs:3e4}),a=new C({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:T()});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 xt(e){return`'${e.replace(/'/g,`'\\''`)}'`}function St(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 Ct(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 ${St(t)})`:``;return`- ${St(e)}${n}`}),i=r.map(({path:e})=>` mount ${xt(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 ${xt(n)}`,a=`mount --source ${xt(t)}${i} ${xt(e)}`;return`- ${St(e)} (${St(t)}, profile ${St(n)}) — ${r}\n Retry: ${St(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 wt=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`sudo-request`,`preview`]);function Tt(e){return e!=null&&wt.has(e)}const Et={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`,preview:`Preview`};function Dt(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 Ot(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=Ct(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=Pt(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 kt(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 At(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 jt(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function Mt(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 Nt(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 Pt(e,t){let n=Dt(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 Ft(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Pt(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function It(e,t){let n=Pt(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 Lt(e){let t=Et[e.type];return e.type===`session-reload`?Ot(e,t):e.type===`upgrade`?kt(e,t):e.type===`cherry`?At(e,t):e.type===`preview`?jt(e,t):e.type===`workflow`?Mt(e,t):e.type===`sudo-request`?Nt(e,t):e.type===`navigate`?It(e,t):e.type===`webhook`?Ft(e,t):Pt(e,t)}const Rt=64*1024;function zt(e,t=Rt){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${Wt(t)} of ${Wt(e.length)} — the agent received the full output]`}function Bt(e,t=Rt,n=4){if(typeof e==`string`)return zt(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=Bt(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=Bt(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}const Vt=()=>/<img:data:image\/[^>]+>/g;function Ht(e,t=Rt){if(!e)return e;if(!Vt().test(e))return zt(e,t);let n=zt(e.replace(Vt(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function Ut(e,t=Rt){if(e.length<=t)return e;if(!Vt().test(e))return zt(e,t);let n=[],r=0;for(let i of e.matchAll(Vt()))n.push(zt(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(zt(e.slice(r),t)),n.join(``)}function Wt(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}let Gt={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Kt(){return{...Gt}}function qt(){let e=Kt();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.followerTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Jt=new Set;function Yt(e){return Jt.add(e),()=>{Jt.delete(e)}}const Xt={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Zt=null;function Qt(e){if(!e.objectStoreNames.contains(Xt.MESSAGES)){let t=e.createObjectStore(Xt.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(Xt.SESSIONS)||e.createObjectStore(Xt.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(Xt.TASKS)||e.createObjectStore(Xt.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(Xt.STATE)||e.createObjectStore(Xt.STATE,{keyPath:`key`})}function $t(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 en(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(Xt.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);for(let t of e)r.put($t(t))};return}t.objectStoreNames.contains(Xt.SCOOPS)||t.createObjectStore(Xt.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function tn(e){e.objectStoreNames.contains(Xt.WEBHOOKS)||e.createObjectStore(Xt.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(Xt.CRONTASKS)||e.createObjectStore(Xt.CRONTASKS,{keyPath:`id`})}function nn(e){let t=e.target.result,n=e.oldVersion;n<1&&Qt(t),n<2&&en(e,t),n<3&&tn(t)}function rn(){if(!Zt)return null;let e=Object.values(Xt).every(e=>Zt.objectStoreNames.contains(e));return Zt.version===3&&e?Zt:(Zt.close(),Zt=null,null)}function an(e){e.onversionchange=()=>{e.close(),Zt===e&&(Zt=null)},e.onclose=()=>{Zt===e&&(Zt=null)}}async function on(){return rn()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=nn,n.onsuccess=()=>{let t=n.result;an(t),Zt=t,e(t)},n.onerror=()=>t(n.error)})}async function sn(e,t=`readonly`){return(await on()).transaction(e,t).objectStore(e)}async function cn(e){let t=await sn(Xt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ln(){let e=await sn(Xt.SCOOPS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>{let e={};for(let t of r.result)e[t.jid]=t;t(e)},r.onerror=()=>n(r.error)})}async function un(e){let t=await sn(Xt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function dn(){let e=await sn(Xt.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function fn(e){let t=(await sn(Xt.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 pn(e){let t=await sn(Xt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function mn(e){let t=await sn(Xt.MESSAGES,`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 sn(Xt.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 gn(e,t,n){let r=(await sn(Xt.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 _n(e){let t=await sn(Xt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function vn(e){let t=await sn(Xt.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function yn(){let e=await sn(Xt.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function bn(e){let t=await sn(Xt.TASKS,`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 sn(Xt.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 Sn(e,t){let n=await sn(Xt.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 Cn(){await on()}async function wn(e){let t=await sn(Xt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Tn(){try{let e=await sn(Xt.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function En(e){let t=await sn(Xt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Dn(e){let t=await sn(Xt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function On(){try{let e=await sn(Xt.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function kn(e){let t=await sn(Xt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}function An(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 jn(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=An(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}const Mn=`slicc.trayWorkerBaseUrl`,Nn=`slicc.trayJoinUrl`,Pn=s;function Fn(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 jn(t.toString());let i=An(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function In(e){let t=Fn(e);return t?.joinUrl?t:null}i(`tray-leader`);let Ln={state:`inactive`,session:null,error:null};function Rn(){return{...Ln,session:Ln.session?{...Ln.session}:null}}function zn(){let e=Rn();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 Bn=new Set;function Vn(e){return Bn.add(e),()=>{Bn.delete(e)}}const Hn=`sessions`;function Un(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Hn)||e.createObjectStore(Hn,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Wn=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Un();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(Hn,`readwrite`);i.objectStore(Hn).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(Hn,`readonly`).objectStore(Hn).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(Hn,`readonly`).objectStore(Hn).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(Hn,`readwrite`);i.objectStore(Hn).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 Gn=i(`offscreen-bridge`);function Kn(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 qn=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||=_t(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Wn;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-${Jn()}`;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)=>{vt.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{vt.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=Bt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Jn(),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=Ht(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Ut(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=Rn(),t=Kt();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}-${Jn()}`,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){Gn.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=Kn(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=Lt({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=>{Gn.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-BE_cztfd.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){Gn.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:Yn(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-BE_cztfd.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:Yn(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}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){Gn.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}-${Jn()}`,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-scoop-chat-messages`:await this.handleRequestScoopChatMessages(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,t.effortOverride)}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`lick-preview`:this.orchestrator.handlePreviewLick(e.event);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`){f.markMounted(t);return}try{await f.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}),f.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 Jn(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Yn(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 Pt(e,t){let n=Dt(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 Ft(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Pt(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function It(e,t){let n=Pt(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 Lt(e){let t=Et[e.type];return e.type===`session-reload`?Ot(e,t):e.type===`upgrade`?kt(e,t):e.type===`cherry`?At(e,t):e.type===`preview`?jt(e,t):e.type===`workflow`?Mt(e,t):e.type===`sudo-request`?Nt(e,t):e.type===`navigate`?It(e,t):e.type===`webhook`?Ft(e,t):Pt(e,t)}const Rt=64*1024;function zt(e,t=Rt){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${Wt(t)} of ${Wt(e.length)} — the agent received the full output]`}function Bt(e,t=Rt,n=4){if(typeof e==`string`)return zt(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=Bt(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=Bt(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}const Vt=()=>/<img:data:image\/[^>]+>/g;function Ht(e,t=Rt){if(!e)return e;if(!Vt().test(e))return zt(e,t);let n=zt(e.replace(Vt(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function Ut(e,t=Rt){if(e.length<=t)return e;if(!Vt().test(e))return zt(e,t);let n=[],r=0;for(let i of e.matchAll(Vt()))n.push(zt(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(zt(e.slice(r),t)),n.join(``)}function Wt(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}let Gt={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Kt(){return{...Gt}}function qt(){let e=Kt();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.followerTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Jt=new Set;function Yt(e){return Jt.add(e),()=>{Jt.delete(e)}}const Xt={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Zt=null;function Qt(e){if(!e.objectStoreNames.contains(Xt.MESSAGES)){let t=e.createObjectStore(Xt.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(Xt.SESSIONS)||e.createObjectStore(Xt.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(Xt.TASKS)||e.createObjectStore(Xt.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(Xt.STATE)||e.createObjectStore(Xt.STATE,{keyPath:`key`})}function $t(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 en(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(Xt.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);for(let t of e)r.put($t(t))};return}t.objectStoreNames.contains(Xt.SCOOPS)||t.createObjectStore(Xt.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function tn(e){e.objectStoreNames.contains(Xt.WEBHOOKS)||e.createObjectStore(Xt.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(Xt.CRONTASKS)||e.createObjectStore(Xt.CRONTASKS,{keyPath:`id`})}function nn(e){let t=e.target.result,n=e.oldVersion;n<1&&Qt(t),n<2&&en(e,t),n<3&&tn(t)}function rn(){if(!Zt)return null;let e=Object.values(Xt).every(e=>Zt.objectStoreNames.contains(e));return Zt.version===3&&e?Zt:(Zt.close(),Zt=null,null)}function an(e){e.onversionchange=()=>{e.close(),Zt===e&&(Zt=null)},e.onclose=()=>{Zt===e&&(Zt=null)}}async function on(){return rn()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=nn,n.onsuccess=()=>{let t=n.result;an(t),Zt=t,e(t)},n.onerror=()=>t(n.error)})}async function sn(e,t=`readonly`){return(await on()).transaction(e,t).objectStore(e)}async function cn(e){let t=await sn(Xt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ln(){let e=await sn(Xt.SCOOPS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>{let e={};for(let t of r.result)e[t.jid]=t;t(e)},r.onerror=()=>n(r.error)})}async function un(e){let t=await sn(Xt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function dn(){let e=await sn(Xt.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function fn(e){let t=(await sn(Xt.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 pn(e){let t=await sn(Xt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function mn(e){let t=await sn(Xt.MESSAGES,`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 sn(Xt.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 gn(e,t,n){let r=(await sn(Xt.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 _n(e){let t=await sn(Xt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function vn(e){let t=await sn(Xt.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function yn(){let e=await sn(Xt.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function bn(e){let t=await sn(Xt.TASKS,`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 sn(Xt.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 Sn(e,t){let n=await sn(Xt.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 Cn(){await on()}async function wn(e){let t=await sn(Xt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Tn(){try{let e=await sn(Xt.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function En(e){let t=await sn(Xt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Dn(e){let t=await sn(Xt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function On(){try{let e=await sn(Xt.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function kn(e){let t=await sn(Xt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}function An(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 jn(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=An(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}const Mn=`slicc.trayWorkerBaseUrl`,Nn=`slicc.trayJoinUrl`,Pn=s;function Fn(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 jn(t.toString());let i=An(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function In(e){let t=Fn(e);return t?.joinUrl?t:null}i(`tray-leader`);let Ln={state:`inactive`,session:null,error:null};function Rn(){return{...Ln,session:Ln.session?{...Ln.session}:null}}function zn(){let e=Rn();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 Bn=new Set;function Vn(e){return Bn.add(e),()=>{Bn.delete(e)}}const Hn=`sessions`;function Un(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Hn)||e.createObjectStore(Hn,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Wn=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Un();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(Hn,`readwrite`);i.objectStore(Hn).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(Hn,`readonly`).objectStore(Hn).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(Hn,`readonly`).objectStore(Hn).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(Hn,`readwrite`);i.objectStore(Hn).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 Gn=i(`offscreen-bridge`);function Kn(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 qn=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||=_t(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Wn;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-${Jn()}`;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)=>{vt.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{vt.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=Bt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Jn(),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=Ht(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Ut(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=Rn(),t=Kt();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}-${Jn()}`,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){Gn.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=Kn(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=Lt({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=>{Gn.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-9Cet57OK.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){Gn.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:Yn(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-9Cet57OK.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:Yn(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}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){Gn.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}-${Jn()}`,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-scoop-chat-messages`:await this.handleRequestScoopChatMessages(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,t.effortOverride)}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`lick-preview`:this.orchestrator.handlePreviewLick(e.event);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`){f.markMounted(t);return}try{await f.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}),f.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 Jn(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Yn(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 Xn=i(`cdp`);var Zn=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,Xn.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Xn.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(),Xn.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),Xn.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;Xn.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Xn.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;Xn.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,Xn.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Xn.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 Qn=`(function() {
7
7
  'use strict';
8
8
 
@@ -7745,7 +7745,7 @@ Install:
7745
7745
  `,DSe=new Set([`iife`,`cjs`,`esm`]),z3=new Set([`linked`,`inline`,`external`,`both`]),OSe={"-h":`showHelp`,"--help":`showHelp`,"-v":`showVersion`,"--version":`showVersion`,"--bundle":`bundle`,"--transform":`transform`,"--minify":`minify`};function kSe(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 B3(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 ASe(e,t,n,r){if(t.inlineValue!==null){if(!z3.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`&&z3.has(i)?(e.sourcemap=i,1):(e.sourcemap=!0,0)}function jSe(e,t,n,r){if(t.key===`--outfile`){let{value:i,advance:a}=B3(t,n,r);return e.outfile=i,a}if(t.key===`--format`){let{value:i,advance:a}=B3(t,n,r);if(!DSe.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}=B3(t,n,r);return e.target=i.split(`,`).map(e=>e.trim()).filter(Boolean),a}if(t.key===`--loader`){let{value:i,advance:a}=B3(t,n,r);return e.loader=i,a}return-1}function MSe(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=OSe[r];if(i){t[i]=!0;continue}let a=kSe(r);if(a.key===`--sourcemap`){n+=ASe(t,a,e,n);continue}let o=jSe(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 NSe(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 PSe(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:V3(t.path),resolveDir:FK(t.path)})}}}function V3(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 PSe(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 H3(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 FSe(){return SA(`esbuild`,async(e,t)=>{let n;try{n=MSe(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:R3,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)
7746
7746
  `,exitCode:2};let r;try{r=await O$({ipk:L3(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?ISe(n,t,r):LSe(n,t,r)})}async function ISe(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=T1(t.stdin),!r)return{stdout:R3,stderr:``,exitCode:0};let a={loader:e.loader??V3(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 H3(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 H3(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function LSe(e,t,n){if(e.entries.length===0)return{stdout:``,stderr:`esbuild: --bundle requires at least one entry point
7747
7747
  `,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:[NSe(t.fs,t.cwd,L3(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 H3(n.formatMessages,r.errors,r.warnings),o=r.outputFiles??[];if(e.outfile){if(o.length===0)return{stdout:``,stderr:`esbuild: build produced no output
7748
- `,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 H3(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function RSe(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var zSe=class{ops(){return import(`./esptool-operations-Dnb3j1SN.js`)}registry(){if(!X$())throw Error(`Web Serial is unavailable in this browser`);return Q$()}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)}},BSe=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:RSe(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 VSe(e,t){return e&&X$()?new zSe:t?new BSe(t):null}const HSe=new Set([`--vid`,`--pid`,`--baud`,`--data-bits`,`--stop-bits`,`--parity`,`--flow-control`,`--buffer-size`,`--bytes`,`--until`,`--timeout-ms`,`--dtr`,`--rts`,`--break`,`--__resolved`]);function USe(e){return qV(e,HSe)}function U3(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 WSe(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 W3(e){let t={};return e.has(`--vid`)&&(t.usbVendorId=U3(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.usbProductId=U3(e.get(`--pid`),`pid`)),Object.keys(t).length>0?[t]:[]}const GSe=new Set([`none`,`even`,`odd`]),KSe=new Set([`none`,`hardware`]);function qSe(e){let t={baudRate:e.has(`--baud`)?U3(e.get(`--baud`),`baud`):9600};if(e.has(`--data-bits`)&&(t.dataBits=U3(e.get(`--data-bits`),`data-bits`)),e.has(`--stop-bits`)&&(t.stopBits=U3(e.get(`--stop-bits`),`stop-bits`)),e.has(`--parity`)){let n=e.get(`--parity`);if(!GSe.has(n))throw Error(`invalid --parity: '${n}'`);t.parity=n}if(e.has(`--flow-control`)){let n=e.get(`--flow-control`);if(!KSe.has(n))throw Error(`invalid --flow-control: '${n}'`);t.flowControl=n}return e.has(`--buffer-size`)&&(t.bufferSize=U3(e.get(`--buffer-size`),`buffer-size`)),t}function JSe(e){let t={};return e.has(`--bytes`)&&(t.maxBytes=U3(e.get(`--bytes`),`bytes`)),e.has(`--until`)&&(t.until=WSe(e.get(`--until`))),e.has(`--timeout-ms`)&&(t.timeoutMs=U3(e.get(`--timeout-ms`),`timeout-ms`)),t}function G3(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 YSe(e){let t={};return e.has(`--dtr`)&&(t.dataTerminalReady=G3(e.get(`--dtr`),`dtr`)),e.has(`--rts`)&&(t.requestToSend=G3(e.get(`--rts`),`rts`)),e.has(`--break`)&&(t.break=G3(e.get(`--break`),`break`)),t}function XSe(e){let t=E1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function ZSe(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function K3(e){return`0x${e.toString(16).padStart(4,`0`)}`}function q3(e){let t=e.usbVendorId!==void 0||e.usbProductId!==void 0?`${K3(e.usbVendorId??0)}:${K3(e.usbProductId??0)}`:`(native serial)`,n=e.opened?` [open]`:``;return`${e.handle}\t${t}${n}`}function QSe(e){return`cts=${+!!e.clearToSend} dcd=${+!!e.dataCarrierDetect} dsr=${+!!e.dataSetReady} ri=${+!!e.ringIndicator}\n`}function J3(e){return{stdout:e,stderr:``,exitCode:0}}function Y3(e){return{stdout:``,stderr:`serial: ${e}\n`,exitCode:1}}const $Se=`serial - access serial ports via Web Serial
7748
+ `,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 H3(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function RSe(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var zSe=class{ops(){return import(`./esptool-operations-B1u4wB4r.js`)}registry(){if(!X$())throw Error(`Web Serial is unavailable in this browser`);return Q$()}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)}},BSe=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:RSe(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 VSe(e,t){return e&&X$()?new zSe:t?new BSe(t):null}const HSe=new Set([`--vid`,`--pid`,`--baud`,`--data-bits`,`--stop-bits`,`--parity`,`--flow-control`,`--buffer-size`,`--bytes`,`--until`,`--timeout-ms`,`--dtr`,`--rts`,`--break`,`--__resolved`]);function USe(e){return qV(e,HSe)}function U3(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 WSe(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 W3(e){let t={};return e.has(`--vid`)&&(t.usbVendorId=U3(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.usbProductId=U3(e.get(`--pid`),`pid`)),Object.keys(t).length>0?[t]:[]}const GSe=new Set([`none`,`even`,`odd`]),KSe=new Set([`none`,`hardware`]);function qSe(e){let t={baudRate:e.has(`--baud`)?U3(e.get(`--baud`),`baud`):9600};if(e.has(`--data-bits`)&&(t.dataBits=U3(e.get(`--data-bits`),`data-bits`)),e.has(`--stop-bits`)&&(t.stopBits=U3(e.get(`--stop-bits`),`stop-bits`)),e.has(`--parity`)){let n=e.get(`--parity`);if(!GSe.has(n))throw Error(`invalid --parity: '${n}'`);t.parity=n}if(e.has(`--flow-control`)){let n=e.get(`--flow-control`);if(!KSe.has(n))throw Error(`invalid --flow-control: '${n}'`);t.flowControl=n}return e.has(`--buffer-size`)&&(t.bufferSize=U3(e.get(`--buffer-size`),`buffer-size`)),t}function JSe(e){let t={};return e.has(`--bytes`)&&(t.maxBytes=U3(e.get(`--bytes`),`bytes`)),e.has(`--until`)&&(t.until=WSe(e.get(`--until`))),e.has(`--timeout-ms`)&&(t.timeoutMs=U3(e.get(`--timeout-ms`),`timeout-ms`)),t}function G3(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 YSe(e){let t={};return e.has(`--dtr`)&&(t.dataTerminalReady=G3(e.get(`--dtr`),`dtr`)),e.has(`--rts`)&&(t.requestToSend=G3(e.get(`--rts`),`rts`)),e.has(`--break`)&&(t.break=G3(e.get(`--break`),`break`)),t}function XSe(e){let t=E1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function ZSe(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function K3(e){return`0x${e.toString(16).padStart(4,`0`)}`}function q3(e){let t=e.usbVendorId!==void 0||e.usbProductId!==void 0?`${K3(e.usbVendorId??0)}:${K3(e.usbProductId??0)}`:`(native serial)`,n=e.opened?` [open]`:``;return`${e.handle}\t${t}${n}`}function QSe(e){return`cts=${+!!e.clearToSend} dcd=${+!!e.dataCarrierDetect} dsr=${+!!e.dataSetReady} ri=${+!!e.ringIndicator}\n`}function J3(e){return{stdout:e,stderr:``,exitCode:0}}function Y3(e){return{stdout:``,stderr:`serial: ${e}\n`,exitCode:1}}const $Se=`serial - access serial ports via Web Serial
7749
7749
 
7750
7750
  Usage: serial <subcommand> [options]
7751
7751
 
@@ -7898,8 +7898,8 @@ Options:
7898
7898
  `;case`idle`:return`enhanced engine: not downloaded (run hear --warmup)
7899
7899
  `;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 g6(e){return{stdout:``,stderr:`hear: ${e}\n`,exitCode:1}}function _6(e){return e instanceof Error?e.message:String(e)}function v6(e){let t=e.map((e,t)=>`${e.deviceId}\t${e.label||`Microphone ${t+1}`}`);return t.join(`
7900
7900
  `)+(t.length?`
7901
- `:``)}async function Swe(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:v6((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:g6(`device enumeration unavailable`):{stdout:v6((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return g6(_6(e))}}async function Cwe(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-DYCeab6-.js`);return{stdout:h6(t?n():e()),stderr:``,exitCode:0}}return{stdout:h6(t?await e.panelRpc.call(`hear-warmup`,void 0):await e.panelRpc.call(`hear-status`,void 0)),stderr:``,exitCode:0}}catch(e){return g6(_6(e))}}async function wwe(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 g6(`cannot open ${r}: No such file`)}let o=VK(i);if(!o.startsWith(`audio/`)&&!o.startsWith(`video/`))return g6(`${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-DYCeab6-.js`)).hearTranscribe(s,t.lang):await e.panelRpc.call(`hear-transcribe`,{bytes:s,lang:t.lang},{timeoutMs:6e5})).transcript+`
7902
- `,stderr:``,exitCode:0}}catch(e){return g6(`transcription failed: ${_6(e)}`)}}async function Twe(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-DYCeab6-.js`)).hearCapture(r):await e.panelRpc.call(`hear-capture`,r,{timeoutMs:n+3e4});return i.transcript?{stdout:i.transcript+`
7901
+ `:``)}async function Swe(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:v6((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:g6(`device enumeration unavailable`):{stdout:v6((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return g6(_6(e))}}async function Cwe(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-C7EVXWrs.js`);return{stdout:h6(t?n():e()),stderr:``,exitCode:0}}return{stdout:h6(t?await e.panelRpc.call(`hear-warmup`,void 0):await e.panelRpc.call(`hear-status`,void 0)),stderr:``,exitCode:0}}catch(e){return g6(_6(e))}}async function wwe(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 g6(`cannot open ${r}: No such file`)}let o=VK(i);if(!o.startsWith(`audio/`)&&!o.startsWith(`video/`))return g6(`${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-C7EVXWrs.js`)).hearTranscribe(s,t.lang):await e.panelRpc.call(`hear-transcribe`,{bytes:s,lang:t.lang},{timeoutMs:6e5})).transcript+`
7902
+ `,stderr:``,exitCode:0}}catch(e){return g6(`transcription failed: ${_6(e)}`)}}async function Twe(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-C7EVXWrs.js`)).hearCapture(r):await e.panelRpc.call(`hear-capture`,r,{timeoutMs:n+3e4});return i.transcript?{stdout:i.transcript+`
7903
7903
  `,stderr:``,exitCode:0}:{stdout:``,stderr:`hear: no speech detected
7904
7904
  `,exitCode:1}}catch(e){return g6(_6(e))}}function Ewe(){return SA(`hear`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return vwe();let n=xwe(e);if(`exitCode`in n)return n;let r={local:fe(),panelRpc:M()};return!r.local&&!r.panelRpc?g6(`speech recognition unavailable in this environment`):n.devices?Swe(r):n.status||n.warmup?Cwe(r,n.warmup):n.inputFile?wwe(r,n,t):Twe(r,n)})}const y6=[`playwright-cli`,`playwright`,`puppeteer`],b6=new WeakMap;function Dwe(e,t){let n=b6.get(e);n||(n=new WeakMap,b6.set(e,n));let r=n.get(t);return r||(r={snapshots:new Map,appTabId:null,harRecorder:null,sessionDirsCreated:!1,teleportWatchers:new Map,consoleMessages:new Map,consoleCleanup:new Map,networkRequests:new Map,networkRequestIndex:new Map,networkCleanup:new Map,routes:new Map,routeCleanup:new Map,lastMousePosition:new Map},n.set(t,r)),r}function x6(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}const S6=c,Owe=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`,`drop`]);function C6(e){return e.toISOString().replace(/:/g,`-`)}function kwe(e){return e instanceof b||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}const w6=`function(text) {
7905
7905
  const el = this;
@@ -8610,20 +8610,20 @@ authorization-code flow, stores the access token, and retries.
8610
8610
  On success, the server is persisted to /workspace/.mcp/servers.json and
8611
8611
  an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
8612
8612
  short name resolves on the PATH.
8613
- `);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return j5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return j5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return j5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-n4U_vb_u.js`).then(e=>e.r);if(await a(i,t.fs))return j5(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>S5),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await kOe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>F5(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 YOe(i,t);let m=await R5(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-hONoxn8T.js`);e({name:i,serverUrl:r,auth:u})}return A5([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${k5}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
8613
+ `);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return j5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return j5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return j5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-DcrycunN.js`).then(e=>e.r);if(await a(i,t.fs))return j5(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>S5),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await kOe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>F5(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 YOe(i,t);let m=await R5(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-NWuqXsHS.js`);e({name:i,serverUrl:r,auth:u})}return A5([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${k5}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
8614
8614
  `)+`
8615
8615
  `)}async function kOe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await Promise.resolve().then(()=>e6),c=await qOe(r.oauthFetchImpl),l=r.oauthLauncher??await I5(),u=await i(e,n,c);O5.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await KOe(),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 AOe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return A5(`usage: mcp list
8616
- `);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-hONoxn8T.js`);await n();let{listServers:r}=await import(`./store-n4U_vb_u.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return A5("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 A5(M5(o))}function M5(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(`
8616
+ `);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-NWuqXsHS.js`);await n();let{listServers:r}=await import(`./store-DcrycunN.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return A5("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 A5(M5(o))}function M5(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(`
8617
8617
  `)+`
8618
8618
  `}async function jOe(e,t){if(e[0]===`--help`||e[0]===`-h`)return A5(`usage: mcp search <query>
8619
8619
 
8620
8620
  Case-insensitive substring search across the cached tools of every
8621
8621
  registered MCP server. Matches tool name OR description and prints a
8622
8622
  table of (server, tool, description, match-field) rows.
8623
- `);if(e.length===0)return j5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-hONoxn8T.js`);await i();let{listServers:a}=await import(`./store-n4U_vb_u.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return A5("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 A5(`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,MOe(e.description),e.match]);return A5(M5(l))}function MOe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function NOe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?j5(`mcp delete: expected <name>`):A5(`usage: mcp delete <name>
8624
- `);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-hONoxn8T.js`);await r(n);let{deleteServer:a}=await import(`./store-n4U_vb_u.js`).then(e=>e.r),o=await a(n,t.fs);await XOe(n,t),await ZOe(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await Promise.resolve().then(()=>e6);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){O5.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?j5(`mcp delete: no server, alias, or account found for "${n}"`):A5([`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(`
8623
+ `);if(e.length===0)return j5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-NWuqXsHS.js`);await i();let{listServers:a}=await import(`./store-DcrycunN.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return A5("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 A5(`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,MOe(e.description),e.match]);return A5(M5(l))}function MOe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function NOe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?j5(`mcp delete: expected <name>`):A5(`usage: mcp delete <name>
8624
+ `);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-NWuqXsHS.js`);await r(n);let{deleteServer:a}=await import(`./store-DcrycunN.js`).then(e=>e.r),o=await a(n,t.fs);await XOe(n,t),await ZOe(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await Promise.resolve().then(()=>e6);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){O5.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?j5(`mcp delete: no server, alias, or account found for "${n}"`):A5([`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(`
8625
8625
  `)+`
8626
- `)}async function POe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?j5(`mcp invoke: expected <name>`):A5(IOe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-hONoxn8T.js`);await i(n);let{getServer:a}=await import(`./store-n4U_vb_u.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return j5(`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 A5(LOe(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return j5(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=FOe(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return A5(ROe(n,l));let p=zOe(d,l.inputSchema);if(!p.ok)return j5(`mcp invoke: ${p.error}`);let{McpClient:m}=await Promise.resolve().then(()=>S5),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>F5(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=UOe(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function FOe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=N5(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=N5(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 N5(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 IOe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
8626
+ `)}async function POe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?j5(`mcp invoke: expected <name>`):A5(IOe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-NWuqXsHS.js`);await i(n);let{getServer:a}=await import(`./store-DcrycunN.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return j5(`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 A5(LOe(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return j5(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=FOe(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return A5(ROe(n,l));let p=zOe(d,l.inputSchema);if(!p.ok)return j5(`mcp invoke: ${p.error}`);let{McpClient:m}=await Promise.resolve().then(()=>S5),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>F5(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=UOe(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function FOe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=N5(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=N5(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 N5(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 IOe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
8627
8627
 
8628
8628
  mcp invoke <name> List tools on <name>.
8629
8629
  mcp invoke <name> <tool> --help Show flags for <tool>.
@@ -8653,7 +8653,7 @@ Arguments are coerced according to the tool's JSON Schema:
8653
8653
 
8654
8654
  Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
8655
8655
  OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
8656
- `);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-hONoxn8T.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-n4U_vb_u.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return j5(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>S5),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>F5(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return j5(`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 R5(n,d,t);return A5(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function GOe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return A5(`usage: mcp auth <name> [--silent | --interactive]
8656
+ `);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-NWuqXsHS.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-DcrycunN.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return j5(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>S5),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>F5(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return j5(`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 R5(n,d,t);return A5(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function GOe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return A5(`usage: mcp auth <name> [--silent | --interactive]
8657
8657
 
8658
8658
  Re-authenticate an existing MCP server. By default, attempts a silent
8659
8659
  token renewal using the persisted refresh_token; if that returns no
@@ -8665,7 +8665,7 @@ Options:
8665
8665
  -i, --interactive Skip silent renewal and open the OAuth popup
8666
8666
  directly. Use after revoking a refresh token or
8667
8667
  when the AS no longer accepts the cached one.
8668
- `);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return j5(`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 j5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-hONoxn8T.js`),s=await o(r),{getServer:c}=await import(`./store-n4U_vb_u.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return j5(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return j5(`mcp auth: server "${r}" does not use OAuth`);if(!s)return j5(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-CyUIFsNN.js`).then(e=>e.r),f=d(u);if(!f)return j5(`mcp auth: provider "${u}" is not registered`);if(a)return await P5(r,f,t);if(!f.onSilentRenew)return i?j5(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await P5(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 j5(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);O5.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?A5(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?j5(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await P5(r,f,t)}async function P5(e,t,n){if(!t.onOAuthLogin)return j5(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await I5(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?A5(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):j5(`mcp auth: interactive login for "${e}" did not complete`)}async function F5(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await Promise.resolve().then(()=>e6),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-CyUIFsNN.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){O5.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function I5(){let{createOAuthLauncher:e}=await import(`./oauth-service-DEl1qBCa.js`);return e()}async function KOe(){if(y()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-DEl1qBCa.js`),{origin:t}=await e();return`${t}/auth/callback`}async function qOe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-CMT-jCdn.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 L5(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-DYAybeQR.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await Promise.resolve().then(()=>HV);return await t.create({dbName:n})}function JOe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
8668
+ `);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return j5(`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 j5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-NWuqXsHS.js`),s=await o(r),{getServer:c}=await import(`./store-DcrycunN.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return j5(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return j5(`mcp auth: server "${r}" does not use OAuth`);if(!s)return j5(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-BlHFP33i.js`).then(e=>e.r),f=d(u);if(!f)return j5(`mcp auth: provider "${u}" is not registered`);if(a)return await P5(r,f,t);if(!f.onSilentRenew)return i?j5(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await P5(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 j5(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);O5.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?A5(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?j5(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await P5(r,f,t)}async function P5(e,t,n){if(!t.onOAuthLogin)return j5(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await I5(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?A5(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):j5(`mcp auth: interactive login for "${e}" did not complete`)}async function F5(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await Promise.resolve().then(()=>e6),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-BlHFP33i.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){O5.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function I5(){let{createOAuthLauncher:e}=await import(`./oauth-service-DEl1qBCa.js`);return e()}async function KOe(){if(y()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-DEl1qBCa.js`),{origin:t}=await e();return`${t}/auth/callback`}async function qOe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-CMT-jCdn.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 L5(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-DlxlTbL_.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await Promise.resolve().then(()=>HV);return await t.create({dbName:n})}function JOe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
8669
8669
  // Auto-generated by \`mcp add ${e}\`; do not edit by hand.
8670
8670
  const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
8671
8671
  const escape = (s) => {
@@ -8679,7 +8679,7 @@ const r = await exec(cmd);
8679
8679
  if (r.stdout) process.stdout.write(r.stdout);
8680
8680
  if (r.stderr) process.stderr.write(r.stderr);
8681
8681
  process.exit(r.exitCode || 0);
8682
- `}async function YOe(e,t){let n=await L5(t.fs);await n.mkdir(k5,{recursive:!0}),await n.writeFile(`${k5}/${e}.jsh`,JOe(e)),t.scriptCatalog?.invalidateJsh()}async function XOe(e,t){let n=await L5(t.fs),r=`${k5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){O5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function ZOe(e,t){let{removeAppSprinkles:n}=await import(`./apps-B3_R7Dti.js`);await n(e,t.fs)}async function R5(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-B3_R7Dti.js`);return(await r(e,t,n.fs)).length}catch(t){return O5.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const z5=`/.cache/artificial-analysis.json`;async function QOe(e,t=!1){if(e&&!t)try{let t=await e.readFile(z5),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=A(),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(z5,JSON.stringify(t))}catch{}}return s}function B5(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function $Oe(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=B5(e),a=t.find(e=>B5(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 eke(){return`models - list available LLM models
8682
+ `}async function YOe(e,t){let n=await L5(t.fs);await n.mkdir(k5,{recursive:!0}),await n.writeFile(`${k5}/${e}.jsh`,JOe(e)),t.scriptCatalog?.invalidateJsh()}async function XOe(e,t){let n=await L5(t.fs),r=`${k5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){O5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function ZOe(e,t){let{removeAppSprinkles:n}=await import(`./apps-DV7qNbNz.js`);await n(e,t.fs)}async function R5(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-DV7qNbNz.js`);return(await r(e,t,n.fs)).length}catch(t){return O5.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const z5=`/.cache/artificial-analysis.json`;async function QOe(e,t=!1){if(e&&!t)try{let t=await e.readFile(z5),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=A(),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(z5,JSON.stringify(t))}catch{}}return s}function B5(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function $Oe(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=B5(e),a=t.find(e=>B5(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 eke(){return`models - list available LLM models
8683
8683
 
8684
8684
  Usage: models [options]
8685
8685
 
@@ -8701,15 +8701,15 @@ Options:
8701
8701
  `,stderr:``,exitCode:0}}function uke(){return{stdout:`v20.0.0-js-shim
8702
8702
  `,stderr:``,exitCode:0}}function dke(e={}){return{name:`node`,trusted:!0,async execute(t,n){if(t.includes(`--help`)||t.includes(`-h`))return lke();if(t.includes(`--version`)||t.includes(`-v`))return uke();let r=``,i,a,o=n;if(t.length>0&&(t[0]===`-e`||t[0]===`--eval`)){if(!t[1])return{stdout:``,stderr:`node: option requires an argument -- eval
8703
8703
  `,exitCode:9};r=t[1],i=`[eval]`,a=[`node`,...t.slice(2)]}else if(t.length>0&&!t[0].startsWith(`-`)){let e=t[0],o=n.fs.resolvePath(n.cwd,e);if(!await n.fs.exists(o))return{stdout:``,stderr:`node: cannot find module '${e}'\n`,exitCode:1};r=await n.fs.readFile(o),i=o,a=[`node`,o,...t.slice(1)]}else if(T1(n.stdin).trim().length>0)r=T1(n.stdin),i=`<stdin>`,a=[`node`],o={...n,stdin:``};else if(t.length>0)return{stdout:``,stderr:`node: unsupported option '${t[0]}'\n`,exitCode:9};else return{stdout:``,stderr:`node: REPL mode is not supported in this environment; use node -e "code"
8704
- `,exitCode:9};return D1(N$(r),a,o,e.buildProcessConfig?.(),{filename:i})}}}const fke=[`slicc:welcome-flow-fired`,`slicc.trayJoinUrl`,`slicc.trayWorkerBaseUrl`];function pke(){return SA(`nuke`,async e=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`Usage: nuke <launch-code>
8704
+ `,exitCode:9};return D1(N$(r),a,o,e.buildProcessConfig?.(),{filename:i})}}}const fke=[`slicc:welcome-flow-fired`,`slicc.trayJoinUrl`,`slicc.trayWorkerBaseUrl`];async function pke(){try{let e=await navigator.serviceWorker?.getRegistrations?.();e&&await Promise.all(e.map(e=>e.unregister().catch(()=>!1)))}catch{}try{let e=await indexedDB.databases();await Promise.all(e.filter(e=>!!e.name).map(e=>new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()})))}catch{}try{let e=navigator.storage;if(typeof e?.getDirectory==`function`){let t=await e.getDirectory(),n=[];for await(let e of t.keys())n.push(e);await Promise.all(n.map(e=>t.removeEntry(e,{recursive:!0}).catch(()=>{})))}}catch{}}function mke(){return SA(`nuke`,async e=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`Usage: nuke <launch-code>
8705
8705
 
8706
8706
  Completely reset the environment by deleting all local data and reloading.
8707
8707
  Destroys the file system, chat history, and scoops database.
8708
8708
  Requires the secret launch code to proceed.
8709
- `,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?((async()=>{try{let e=await navigator.serviceWorker?.getRegistrations?.();e&&await Promise.all(e.map(e=>e.unregister().catch(()=>!1)))}catch{}try{let e=await indexedDB.databases();await Promise.all(e.filter(e=>!!e.name).map(e=>new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()})))}catch{}try{let e=navigator.storage;if(typeof e?.getDirectory==`function`){let t=await e.getDirectory(),n=[];for await(let e of t.keys())n.push(e);await Promise.all(n.map(e=>t.removeEntry(e,{recursive:!0}).catch(()=>{})))}}catch{}mke(fke)})(),{stdout:`Nuking everything…
8709
+ `,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?((async()=>{await pke(),hke(fke)})(),{stdout:`Nuking everything…
8710
8710
  `,stderr:``,exitCode:0}):{stdout:``,stderr:`⚠️ WARNING: this will reset the entire environment, file system, chats, and scoops.
8711
8711
  Run nuke again with the secret launch code to proceed.
8712
- `,exitCode:1})}function mke(e=[]){let t=[...e];try{if(typeof BroadcastChannel==`function`){let e=new BroadcastChannel(`slicc-nuke-control`);e.postMessage({type:`nuke-reload`,keysToRemove:t}),setTimeout(()=>e.close(),100)}}catch{}for(let e of t)try{globalThis.localStorage?.removeItem(e)}catch{}try{globalThis.location?.reload?.()}catch{}}function H5(){return`oauth-domain — manage extra allowed domains for OAuth-issued tokens
8712
+ `,exitCode:1})}function hke(e=[]){let t=[...e];try{if(typeof BroadcastChannel==`function`){let e=new BroadcastChannel(`slicc-nuke-control`);e.postMessage({type:`nuke-reload`,keysToRemove:t}),setTimeout(()=>e.close(),100)}}catch{}for(let e of t)try{globalThis.localStorage?.removeItem(e)}catch{}try{globalThis.location?.reload?.()}catch{}}function H5(){return`oauth-domain — manage extra allowed domains for OAuth-issued tokens
8713
8713
 
8714
8714
  Usage:
8715
8715
  oauth-domain list List extra domains for every provider
@@ -8734,7 +8734,7 @@ Examples:
8734
8734
  oauth-domain add adobe '*.da.live'
8735
8735
  oauth-domain list adobe
8736
8736
  oauth-domain remove adobe admin.da.live
8737
- `}function hke(){return SA(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:H5(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await Promise.resolve().then(()=>e6),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
8737
+ `}function gke(){return SA(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:H5(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await Promise.resolve().then(()=>e6),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
8738
8738
  `)+`
8739
8739
  `,stderr:``,exitCode:0}}let e=r(),n=Object.entries(e).filter(([,e])=>e.length>0);return n.length===0?{stdout:`(no extra OAuth domains configured)
8740
8740
  `,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
@@ -8742,7 +8742,7 @@ Examples:
8742
8742
  `,stderr:``,exitCode:0}}case`add`:{if(!a||!o)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
8743
8743
  `,exitCode:1};let e=t(a),r=o.toLowerCase();return e.some(e=>e.toLowerCase()===r)?{stdout:`(${o} already in ${a} extras)\n`,stderr:``,exitCode:0}:(await n(a,[...e,o]),{stdout:`Added ${o} to ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0})}case`remove`:{if(!a||!o)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
8744
8744
  `,exitCode:1};let e=t(a),r=o.toLowerCase(),i=e.filter(e=>e.toLowerCase()!==r);return i.length===e.length?{stdout:`(${o} not found in ${a} extras)\n`,stderr:``,exitCode:0}:(await n(a,i),{stdout:`Removed ${o} from ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0})}case`clear`:return a?(await n(a,[]),{stdout:`Cleared extra domains for ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`oauth-domain clear: requires <providerId>
8745
- `,exitCode:1};default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${i}"\n${H5()}`,exitCode:1}}}catch(e){return{stdout:``,stderr:`oauth-domain: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function gke(){return`oauth-token — get an OAuth access token for a provider, or run an
8745
+ `,exitCode:1};default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${i}"\n${H5()}`,exitCode:1}}}catch(e){return{stdout:``,stderr:`oauth-domain: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function _ke(){return`oauth-token — get an OAuth access token for a provider, or run an
8746
8746
  ad-hoc OAuth interception against an arbitrary authorize URL.
8747
8747
 
8748
8748
  Usage:
@@ -8792,16 +8792,16 @@ Examples:
8792
8792
  --authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
8793
8793
  --redirect-pattern 'http://127.0.0.1:56121/*'
8794
8794
  curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
8795
- `}function _ke(){return SA(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await Promise.resolve().then(()=>e6),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-CyUIFsNN.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:gke(),stderr:``,exitCode:0};if(e.includes(`--list`))return bke(i,o,a,n);if(e.includes(`--renew`))return vke(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return yke(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
8795
+ `}function vke(){return SA(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await Promise.resolve().then(()=>e6),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-BlHFP33i.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:_ke(),stderr:``,exitCode:0};if(e.includes(`--list`))return xke(i,o,a,n);if(e.includes(`--renew`))return yke(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return bke(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
8796
8796
  `,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
8797
8797
  `,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
8798
8798
  `,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-DEl1qBCa.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-DEl1qBCa.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
8799
- `,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 vke(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await Promise.resolve().then(()=>e6),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-CyUIFsNN.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 G5(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return G5(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return G5(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${U5(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: ${U5(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(`
8799
+ `,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 yke(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await Promise.resolve().then(()=>e6),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-BlHFP33i.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 G5(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return G5(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return G5(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${U5(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: ${U5(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(`
8800
8800
  `)+`
8801
- `,stderr:``,exitCode:+!u}}function U5(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 yke(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-DEl1qBCa.js`),i,a=e.indexOf(`--from-file`);if(a>=0){let n=e[a+1];if(!n)return G5(`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 G5(`oauth-token: failed to read ${n}: ${e instanceof Error?e.message:String(e)}`)}}else{let t=W5(e,`--authorize-url`),n=W5(e,`--redirect-pattern`);if(!t)return G5(`oauth-token: --authorize-url is required`);if(!n)return G5(`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 G5(`oauth-token: --rewrite requires a value`);let i=n.split(`=`);if(i.length<3)return G5(`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 G5(`oauth-token: invalid intercept config: ${o.error}`);let s=await r();if(!s)return G5(`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}:G5(`oauth-token: intercept timed out or was cancelled`)}function W5(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function G5(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function bke(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
8801
+ `,stderr:``,exitCode:+!u}}function U5(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 bke(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-DEl1qBCa.js`),i,a=e.indexOf(`--from-file`);if(a>=0){let n=e[a+1];if(!n)return G5(`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 G5(`oauth-token: failed to read ${n}: ${e instanceof Error?e.message:String(e)}`)}}else{let t=W5(e,`--authorize-url`),n=W5(e,`--redirect-pattern`);if(!t)return G5(`oauth-token: --authorize-url is required`);if(!n)return G5(`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 G5(`oauth-token: --rewrite requires a value`);let i=n.split(`=`);if(i.length<3)return G5(`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 G5(`oauth-token: invalid intercept config: ${o.error}`);let s=await r();if(!s)return G5(`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}:G5(`oauth-token: intercept timed out or was cancelled`)}function W5(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function G5(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function xke(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
8802
8802
  `,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(`
8803
8803
  `)+`
8804
- `,stderr:``,exitCode:0}}const xke=new Set([`--download`,`-d`,`--view`,`-v`]),K5={low:256,medium:768,high:1536};function q5(){return{stdout:`usage: open [--download|-d] [--view|-v [--size <spec>]] <url|path> [url|path...]
8804
+ `,stderr:``,exitCode:0}}const Ske=new Set([`--download`,`-d`,`--view`,`-v`]),K5={low:256,medium:768,high:1536};function q5(){return{stdout:`usage: open [--download|-d] [--view|-v [--size <spec>]] <url|path> [url|path...]
8805
8805
 
8806
8806
  VFS paths are served in a new browser tab via the preview service worker.
8807
8807
  URLs (http/https/etc.) are opened directly in a new tab.
@@ -8815,19 +8815,19 @@ Examples:
8815
8815
  medium (768x768), high (1536x1536), or a custom WxH
8816
8816
  box like 512x512. The image is fit inside the box
8817
8817
  with aspect ratio preserved and is never upscaled.
8818
- `,stderr:``,exitCode:0}}function Ske(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 Cke(e){if(e in K5){let t=K5[e];return{maxW:t,maxH:t}}let t=/^(\d+)x(\d+)$/.exec(e);if(t){let e=parseInt(t[1],10),n=parseInt(t[2],10);if(e>0&&n>0)return{maxW:e,maxH:n}}return null}function wke(e,t){if(t===`image/png`||t===`image/apng`){if(e.length<26)return!1;let t=e[25];return t===4||t===6}if(t===`image/webp`){if(e.length<16)return!1;let t=String.fromCharCode(e[12],e[13],e[14],e[15]);return t===`VP8L`?!0:t===`VP8X`?e.length<21?!1:(e[20]&16)!=0:!1}return!1}function Tke(){return`open --view requires --size to bound the inlined image. Use one of:
8818
+ `,stderr:``,exitCode:0}}function Cke(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 wke(e){if(e in K5){let t=K5[e];return{maxW:t,maxH:t}}let t=/^(\d+)x(\d+)$/.exec(e);if(t){let e=parseInt(t[1],10),n=parseInt(t[2],10);if(e>0&&n>0)return{maxW:e,maxH:n}}return null}function Tke(e,t){if(t===`image/png`||t===`image/apng`){if(e.length<26)return!1;let t=e[25];return t===4||t===6}if(t===`image/webp`){if(e.length<16)return!1;let t=String.fromCharCode(e[12],e[13],e[14],e[15]);return t===`VP8L`?!0:t===`VP8X`?e.length<21?!1:(e[20]&16)!=0:!1}return!1}function Eke(){return`open --view requires --size to bound the inlined image. Use one of:
8819
8819
  --size low (256x256)
8820
8820
  --size medium (768x768)
8821
8821
  --size high (1536x1536)
8822
8822
  --size WxH (custom box, e.g. 512x512)
8823
- `}const Eke=new Set([`image/png`,`image/webp`]);function J5(e){let t=new ArrayBuffer(e.byteLength),n=new Uint8Array(t);return n.set(e),n}async function Dke(e,t){let n=J5(e),r=new Blob([n],{type:t}),i=await createImageBitmap(r);try{return{width:i.width,height:i.height}}finally{i.close?.()}}async function Oke(e,t,n,r){let i=J5(e),a=new Blob([i],{type:t}),o=await createImageBitmap(a);try{let i=o.width,a=o.height,s=Math.min(n/i,r/a,1),c=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(a*s)),u=new OffscreenCanvas(c,l),d=u.getContext(`2d`);if(!d)throw Error(`failed to acquire 2d context for resize`);d.drawImage(o,0,0,c,l);let f=wke(e,t)?Eke.has(t)?t:`image/png`:`image/jpeg`,p=await u.convertToBlob(f===`image/jpeg`?{type:`image/jpeg`,quality:.85}:{type:f});return{bytes:new Uint8Array(await p.arrayBuffer()),mime:f,width:c,height:l,nativeWidth:i,nativeHeight:a}}finally{o.close?.()}}function kke(e){let t={download:!1,view:!1,sizeSpec:void 0,targets:[]};for(let n=0;n<e.length;n++){let r=e[n];if(r===`--download`||r===`-d`)t.download=!0;else if(r===`--view`||r===`-v`)t.view=!0;else if(r===`--size`){let r=e[n+1];if(r===void 0||xke.has(r)||r===`--size`||r.startsWith(`--size=`))return t.error=`open: --size requires a value (low|medium|high|WxH)`,t;t.sizeSpec=r,n++}else r.startsWith(`--size=`)?t.sizeSpec=r.slice(7):t.targets.push(r)}return t}function Y5(e){return{ok:!0,message:e}}function X5(e){return{ok:!1,result:{stdout:``,stderr:e,exitCode:1}}}function Z5(e){return e?` (targetId: ${e})`:``}function Ake(e,t,n){return async r=>{if(e)return e.createPage(r);if(t){window.open(r,`_blank`,`noopener,noreferrer`);return}try{await n.call(`window-open`,{url:r,target:`_blank`,features:`noopener,noreferrer`})}catch(e){throw Error(`open: ${e instanceof Error?e.message:String(e)}`)}}}async function jke(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,e);if(n){let e=(a.split(`/`).pop()??``).replace(/\.shtml$/,``);try{return await n.open(e),Y5(`opened sprinkle ${e} from ${a}`)}catch(e){return X5(`open: ${e instanceof Error?e.message:String(e)}\n`)}}if(r){let e=WK(a,await UK(t.fs,FK(a))),n;try{n=await i(e)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${a} → ${e}${Z5(n)}`)}return X5(`open: sprinkle manager not initialized
8824
- `)}async function Mke(e,t,n){if(!t)return X5(`open: browser APIs are unavailable in this environment
8825
- `);let r;try{r=await n(e)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${e}${Z5(r)}`)}async function Nke(e,t,n,r){let i;try{i=await n.fs.stat(t)}catch{return X5(`open: no such file: ${e}\n`)}if(!i.isFile)return X5(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return X5(`open: failed to read: ${e}\n`)}let o=VK(t),s=new Uint8Array(a),c=null;if(r!==void 0&&(c=Cke(r),!c))return X5(`open: invalid --size spec '${r}' (expected low|medium|high or WxH such as 512x512)\n`);if(!c){let n;try{n=await Dke(s,o)}catch(t){return X5(`open: not an image or failed to decode: ${e} (${t instanceof Error?t.message:String(t)})\n`)}let r=Math.round(s.byteLength/1024);return X5(`open --view: ${t} is ${n.width}x${n.height} (${r} KB, ${o})\n`+Tke())}let l;try{l=await Oke(s,o,c.maxW,c.maxH)}catch(t){return X5(`open: not an image or failed to decode: ${e} (${t instanceof Error?t.message:String(t)})\n`)}let u=Ske(l.bytes),d=Math.round(l.bytes.byteLength/1024);return Y5(`${t} (${l.nativeWidth}x${l.nativeHeight} → ${l.width}x${l.height}, ${d} KB, ${l.mime})\n<img:data:${l.mime};base64,${u}>`)}async function Pke(e,t,n,r){if(!r)return X5(`open: --download requires the in-panel terminal (DOM-only)
8826
- `);let i;try{i=await n.fs.stat(t)}catch{return X5(`open: no such file: ${e}\n`)}if(!i.isFile)return X5(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return X5(`open: failed to read: ${e}\n`)}let o=new Uint8Array(a.byteLength);o.set(a);let s=new Blob([o.buffer],{type:VK(t)}),c=URL.createObjectURL(s),l=document.createElement(`a`);return l.href=c,l.download=PK(t)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),Y5(`downloaded ${t}`)}async function Fke(e,t,n,r){if(!n)return X5(`open: browser APIs are unavailable in this environment
8827
- `);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=WK(e,await UK(t.fs,i?e:FK(e))),o;try{o=await r(a)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${e} → ${a}${Z5(o)}`)}async function Ike(e,t,n,r){if(!LK(e)&&e.endsWith(`.shtml`)&&t.fs)return jke(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return X5(`open: browser APIs are unavailable in this environment
8828
- `);if(LK(e))return Mke(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?Nke(e,i,t,n.sizeSpec):n.download?Pke(e,i,t,r.hasDom):Fke(i,t,r.canOpenWindow,r.openExternal)}function Lke(e){return SA(`open`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return q5();let r=kke(t);if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{download:i,view:a,sizeSpec:o,targets:s}=r;if(s.length===0)return q5();let c=globalThis.__slicc_sprinkleManager,l=typeof window<`u`&&typeof document<`u`,u=l?null:M(),d={canOpenWindow:!!e||l||!!u,hasDom:l,sprinkleManager:c,openExternal:Ake(e,l,u)},f=[];for(let e of s){let t=await Ike(e,n,{view:a,download:i,sizeSpec:o},d);if(!t.ok)return t.result;f.push(t.message)}return{stdout:f.join(`
8823
+ `}const Dke=new Set([`image/png`,`image/webp`]);function J5(e){let t=new ArrayBuffer(e.byteLength),n=new Uint8Array(t);return n.set(e),n}async function Oke(e,t){let n=J5(e),r=new Blob([n],{type:t}),i=await createImageBitmap(r);try{return{width:i.width,height:i.height}}finally{i.close?.()}}async function kke(e,t,n,r){let i=J5(e),a=new Blob([i],{type:t}),o=await createImageBitmap(a);try{let i=o.width,a=o.height,s=Math.min(n/i,r/a,1),c=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(a*s)),u=new OffscreenCanvas(c,l),d=u.getContext(`2d`);if(!d)throw Error(`failed to acquire 2d context for resize`);d.drawImage(o,0,0,c,l);let f=Tke(e,t)?Dke.has(t)?t:`image/png`:`image/jpeg`,p=await u.convertToBlob(f===`image/jpeg`?{type:`image/jpeg`,quality:.85}:{type:f});return{bytes:new Uint8Array(await p.arrayBuffer()),mime:f,width:c,height:l,nativeWidth:i,nativeHeight:a}}finally{o.close?.()}}function Ake(e){let t={download:!1,view:!1,sizeSpec:void 0,targets:[]};for(let n=0;n<e.length;n++){let r=e[n];if(r===`--download`||r===`-d`)t.download=!0;else if(r===`--view`||r===`-v`)t.view=!0;else if(r===`--size`){let r=e[n+1];if(r===void 0||Ske.has(r)||r===`--size`||r.startsWith(`--size=`))return t.error=`open: --size requires a value (low|medium|high|WxH)`,t;t.sizeSpec=r,n++}else r.startsWith(`--size=`)?t.sizeSpec=r.slice(7):t.targets.push(r)}return t}function Y5(e){return{ok:!0,message:e}}function X5(e){return{ok:!1,result:{stdout:``,stderr:e,exitCode:1}}}function Z5(e){return e?` (targetId: ${e})`:``}function jke(e,t,n){return async r=>{if(e)return e.createPage(r);if(t){window.open(r,`_blank`,`noopener,noreferrer`);return}try{await n.call(`window-open`,{url:r,target:`_blank`,features:`noopener,noreferrer`})}catch(e){throw Error(`open: ${e instanceof Error?e.message:String(e)}`)}}}async function Mke(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,e);if(n){let e=(a.split(`/`).pop()??``).replace(/\.shtml$/,``);try{return await n.open(e),Y5(`opened sprinkle ${e} from ${a}`)}catch(e){return X5(`open: ${e instanceof Error?e.message:String(e)}\n`)}}if(r){let e=WK(a,await UK(t.fs,FK(a))),n;try{n=await i(e)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${a} → ${e}${Z5(n)}`)}return X5(`open: sprinkle manager not initialized
8824
+ `)}async function Nke(e,t,n){if(!t)return X5(`open: browser APIs are unavailable in this environment
8825
+ `);let r;try{r=await n(e)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${e}${Z5(r)}`)}async function Pke(e,t,n,r){let i;try{i=await n.fs.stat(t)}catch{return X5(`open: no such file: ${e}\n`)}if(!i.isFile)return X5(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return X5(`open: failed to read: ${e}\n`)}let o=VK(t),s=new Uint8Array(a),c=null;if(r!==void 0&&(c=wke(r),!c))return X5(`open: invalid --size spec '${r}' (expected low|medium|high or WxH such as 512x512)\n`);if(!c){let n;try{n=await Oke(s,o)}catch(t){return X5(`open: not an image or failed to decode: ${e} (${t instanceof Error?t.message:String(t)})\n`)}let r=Math.round(s.byteLength/1024);return X5(`open --view: ${t} is ${n.width}x${n.height} (${r} KB, ${o})\n`+Eke())}let l;try{l=await kke(s,o,c.maxW,c.maxH)}catch(t){return X5(`open: not an image or failed to decode: ${e} (${t instanceof Error?t.message:String(t)})\n`)}let u=Cke(l.bytes),d=Math.round(l.bytes.byteLength/1024);return Y5(`${t} (${l.nativeWidth}x${l.nativeHeight} → ${l.width}x${l.height}, ${d} KB, ${l.mime})\n<img:data:${l.mime};base64,${u}>`)}async function Fke(e,t,n,r){if(!r)return X5(`open: --download requires the in-panel terminal (DOM-only)
8826
+ `);let i;try{i=await n.fs.stat(t)}catch{return X5(`open: no such file: ${e}\n`)}if(!i.isFile)return X5(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return X5(`open: failed to read: ${e}\n`)}let o=new Uint8Array(a.byteLength);o.set(a);let s=new Blob([o.buffer],{type:VK(t)}),c=URL.createObjectURL(s),l=document.createElement(`a`);return l.href=c,l.download=PK(t)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),Y5(`downloaded ${t}`)}async function Ike(e,t,n,r){if(!n)return X5(`open: browser APIs are unavailable in this environment
8827
+ `);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=WK(e,await UK(t.fs,i?e:FK(e))),o;try{o=await r(a)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${e} → ${a}${Z5(o)}`)}async function Lke(e,t,n,r){if(!LK(e)&&e.endsWith(`.shtml`)&&t.fs)return Mke(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return X5(`open: browser APIs are unavailable in this environment
8828
+ `);if(LK(e))return Nke(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?Pke(e,i,t,n.sizeSpec):n.download?Fke(e,i,t,r.hasDom):Ike(i,t,r.canOpenWindow,r.openExternal)}function Rke(e){return SA(`open`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return q5();let r=Ake(t);if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{download:i,view:a,sizeSpec:o,targets:s}=r;if(s.length===0)return q5();let c=globalThis.__slicc_sprinkleManager,l=typeof window<`u`&&typeof document<`u`,u=l?null:M(),d={canOpenWindow:!!e||l||!!u,hasDom:l,sprinkleManager:c,openExternal:jke(e,l,u)},f=[];for(let e of s){let t=await Lke(e,n,{view:a,download:i,sizeSpec:o},d);if(!t.ok)return t.result;f.push(t.message)}return{stdout:f.join(`
8829
8829
  `)+`
8830
- `,stderr:``,exitCode:0}})}let Q5=null,$5=null;async function e7(){return Q5||=import(`./es-kEo2Tmh4.js`),Q5}async function Rke(){return $5||=import(`./dist-D58cmC11.js`),$5}function zke(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function t7(e){let{range:t,rotation:n}=zke(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function n7(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function Bke(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
8830
+ `,stderr:``,exitCode:0}})}let Q5=null,$5=null;async function e7(){return Q5||=import(`./es-kEo2Tmh4.js`),Q5}async function zke(){return $5||=import(`./dist-D58cmC11.js`),$5}function Bke(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function t7(e){let{range:t,rotation:n}=Bke(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function n7(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function Vke(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
8831
8831
 
8832
8832
  Operations:
8833
8833
  dump_data Print metadata (page count, title, author, etc.)
@@ -8851,14 +8851,14 @@ Page ranges:
8851
8851
  1-endright Pages 1 to end, rotated 90° clockwise
8852
8852
  3left Page 3 rotated 270° (counterclockwise)
8853
8853
  1-5down Pages 1-5 rotated 180°
8854
- `,stderr:``,exitCode:0}}function r7(e=`pdftk`){return SA(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Bke();try{let r=[],i=0;for(;i<t.length;){let e=t[i],a=e.match(/^([A-Z])=(.+)$/);if(a){let e=a[1],t=n.fs.resolvePath(n.cwd,a[2]);r.push({handle:e,path:t}),i++;continue}if([`dump_data`,`dump_data_utf8`,`cat`,`rotate`].includes(e))break;if(!e.startsWith(`-`)){let t=n.fs.resolvePath(n.cwd,e);r.push({handle:``,path:t}),i++;continue}break}if(r.length===0)return{stdout:``,stderr:`${e}: no input PDF specified\n`,exitCode:1};let a=t[i];if(i++,!a)return{stdout:``,stderr:`${e}: no operation specified\n`,exitCode:1};if(a===`dump_data`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data only supports a single input file\n`,exitCode:1};let t=await e7(),i=await n.fs.readFileBuffer(r[0].path),a=await t.PDFDocument.load(i),o=[];o.push(`NumberOfPages: ${a.getPageCount()}`);let s=a.getTitle();s&&o.push(`InfoBegin`),s&&o.push(`InfoKey: Title`),s&&o.push(`InfoValue: ${s}`);let c=a.getAuthor();c&&o.push(`InfoBegin`),c&&o.push(`InfoKey: Author`),c&&o.push(`InfoValue: ${c}`);let l=a.getCreator();l&&o.push(`InfoBegin`),l&&o.push(`InfoKey: Creator`),l&&o.push(`InfoValue: ${l}`);let u=a.getProducer();return u&&o.push(`InfoBegin`),u&&o.push(`InfoKey: Producer`),u&&o.push(`InfoValue: ${u}`),{stdout:o.join(`
8854
+ `,stderr:``,exitCode:0}}function r7(e=`pdftk`){return SA(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Vke();try{let r=[],i=0;for(;i<t.length;){let e=t[i],a=e.match(/^([A-Z])=(.+)$/);if(a){let e=a[1],t=n.fs.resolvePath(n.cwd,a[2]);r.push({handle:e,path:t}),i++;continue}if([`dump_data`,`dump_data_utf8`,`cat`,`rotate`].includes(e))break;if(!e.startsWith(`-`)){let t=n.fs.resolvePath(n.cwd,e);r.push({handle:``,path:t}),i++;continue}break}if(r.length===0)return{stdout:``,stderr:`${e}: no input PDF specified\n`,exitCode:1};let a=t[i];if(i++,!a)return{stdout:``,stderr:`${e}: no operation specified\n`,exitCode:1};if(a===`dump_data`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data only supports a single input file\n`,exitCode:1};let t=await e7(),i=await n.fs.readFileBuffer(r[0].path),a=await t.PDFDocument.load(i),o=[];o.push(`NumberOfPages: ${a.getPageCount()}`);let s=a.getTitle();s&&o.push(`InfoBegin`),s&&o.push(`InfoKey: Title`),s&&o.push(`InfoValue: ${s}`);let c=a.getAuthor();c&&o.push(`InfoBegin`),c&&o.push(`InfoKey: Author`),c&&o.push(`InfoValue: ${c}`);let l=a.getCreator();l&&o.push(`InfoBegin`),l&&o.push(`InfoKey: Creator`),l&&o.push(`InfoValue: ${l}`);let u=a.getProducer();return u&&o.push(`InfoBegin`),u&&o.push(`InfoKey: Producer`),u&&o.push(`InfoValue: ${u}`),{stdout:o.join(`
8855
8855
  `)+`
8856
- `,stderr:``,exitCode:0}}if(a===`dump_data_utf8`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data_utf8 only supports a single input file\n`,exitCode:1};let t=await Rke(),i=await n.fs.readFileBuffer(r[0].path);return{stdout:(await t.extractText(i)).text+`
8857
- `,stderr:``,exitCode:0}}if(a===`cat`){let a=await e7(),o=await a.PDFDocument.create(),s=t.slice(i),c=s.indexOf(`output`);if(c===-1)return{stdout:``,stderr:`${e}: cat operation requires 'output <filename>'\n`,exitCode:1};let l=s.slice(0,c),u=s[c+1];if(!u)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let d=n.fs.resolvePath(n.cwd,u),f=new Map;for(let e of r){let t=await n.fs.readFileBuffer(e.path),r=await a.PDFDocument.load(t),i=e.handle||`default`;f.set(i,r)}for(let t of l){if(/^[A-Z]$/.test(t)){let n=f.get(t);if(!n)return{stdout:``,stderr:`${e}: unknown handle '${t}'\n`,exitCode:1};let r=n.getPageCount(),i=Array.from({length:r},(e,t)=>t);(await o.copyPages(n,i)).forEach(e=>{o.addPage(e)});continue}let n=f.get(r[0].handle||`default`);if(!n)return{stdout:``,stderr:`${e}: no default input document\n`,exitCode:1};let i=n.getPageCount(),s=t7(t),c=n7(s,i).map(e=>e-1),l=await o.copyPages(n,c);for(let e of l)s.rotation&&e.setRotation(a.degrees(s.rotation)),o.addPage(e)}let p=await o.save();return await n.fs.writeFile(d,p),{stdout:`Created ${u}\n`,stderr:``,exitCode:0}}if(a===`rotate`){if(r.length>1)return{stdout:``,stderr:`${e}: rotate only supports a single input file\n`,exitCode:1};let a=await e7(),o=await n.fs.readFileBuffer(r[0].path),s=await a.PDFDocument.load(o),c=t.slice(i),l=c.indexOf(`output`);if(l===-1)return{stdout:``,stderr:`${e}: rotate operation requires 'output <filename>'\n`,exitCode:1};let u=c.slice(0,l),d=c[l+1];if(!d)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let f=n.fs.resolvePath(n.cwd,d),p=s.getPageCount(),m=new Map;for(let t of u){let n=t7(t);if(!n.rotation)return{stdout:``,stderr:`${e}: rotation suffix required (right/left/down) for range '${t}'\n`,exitCode:1};let r=n7(n,p);for(let e of r)m.set(e-1,n.rotation)}let h=s.getPages();for(let[e,t]of m.entries()){let n=h[e],r=(n.getRotation().angle+t)%360;n.setRotation(a.degrees(r))}let g=await s.save();return await n.fs.writeFile(f,g),{stdout:`Created ${d}\n`,stderr:``,exitCode:0}}return{stdout:``,stderr:`${e}: unknown operation '${a}'\n`,exitCode:1}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}const i7=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],Vke=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],Hke={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function Uke(e={}){return SA(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return tAe();let n=e.processManager??Wke();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
8858
- `,exitCode:1};let r=Vke,i=!1,a=!1;for(let e=0;e<t.length;e++){let n=t[e];if(n===`-a`||n===`-A`||n===`-e`||n===`--all`){a=!0;continue}if(n===`-T`||n===`--tree`){i=!0;continue}if(n===`-o`||n.startsWith(`--columns=`)||n.startsWith(`-o=`)){let i=n.startsWith(`-o=`)?n.slice(3):n.startsWith(`--columns=`)?n.slice(10):t[++e];if(typeof i!=`string`)return{stdout:``,stderr:`ps: -o requires an argument
8859
- `,exitCode:2};let a=Gke(i);if(a instanceof Error)return{stdout:``,stderr:`ps: ${a.message}\n`,exitCode:2};r=a;continue}return{stdout:``,stderr:`ps: unrecognized argument '${n}'\n`,exitCode:2}}let o=n.list().sort((e,t)=>e.pid-t.pid),s=a?o:o.filter(e=>e.status===`running`||e.status===`pending`),c=(i?eAe(s):s.map(e=>({proc:e,depth:0}))).map(({proc:e,depth:t})=>Jke(e,r,t,i));return{stdout:[Kke(r),...c].join(`
8856
+ `,stderr:``,exitCode:0}}if(a===`dump_data_utf8`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data_utf8 only supports a single input file\n`,exitCode:1};let t=await zke(),i=await n.fs.readFileBuffer(r[0].path);return{stdout:(await t.extractText(i)).text+`
8857
+ `,stderr:``,exitCode:0}}if(a===`cat`){let a=await e7(),o=await a.PDFDocument.create(),s=t.slice(i),c=s.indexOf(`output`);if(c===-1)return{stdout:``,stderr:`${e}: cat operation requires 'output <filename>'\n`,exitCode:1};let l=s.slice(0,c),u=s[c+1];if(!u)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let d=n.fs.resolvePath(n.cwd,u),f=new Map;for(let e of r){let t=await n.fs.readFileBuffer(e.path),r=await a.PDFDocument.load(t),i=e.handle||`default`;f.set(i,r)}for(let t of l){if(/^[A-Z]$/.test(t)){let n=f.get(t);if(!n)return{stdout:``,stderr:`${e}: unknown handle '${t}'\n`,exitCode:1};let r=n.getPageCount(),i=Array.from({length:r},(e,t)=>t);(await o.copyPages(n,i)).forEach(e=>{o.addPage(e)});continue}let n=f.get(r[0].handle||`default`);if(!n)return{stdout:``,stderr:`${e}: no default input document\n`,exitCode:1};let i=n.getPageCount(),s=t7(t),c=n7(s,i).map(e=>e-1),l=await o.copyPages(n,c);for(let e of l)s.rotation&&e.setRotation(a.degrees(s.rotation)),o.addPage(e)}let p=await o.save();return await n.fs.writeFile(d,p),{stdout:`Created ${u}\n`,stderr:``,exitCode:0}}if(a===`rotate`){if(r.length>1)return{stdout:``,stderr:`${e}: rotate only supports a single input file\n`,exitCode:1};let a=await e7(),o=await n.fs.readFileBuffer(r[0].path),s=await a.PDFDocument.load(o),c=t.slice(i),l=c.indexOf(`output`);if(l===-1)return{stdout:``,stderr:`${e}: rotate operation requires 'output <filename>'\n`,exitCode:1};let u=c.slice(0,l),d=c[l+1];if(!d)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let f=n.fs.resolvePath(n.cwd,d),p=s.getPageCount(),m=new Map;for(let t of u){let n=t7(t);if(!n.rotation)return{stdout:``,stderr:`${e}: rotation suffix required (right/left/down) for range '${t}'\n`,exitCode:1};let r=n7(n,p);for(let e of r)m.set(e-1,n.rotation)}let h=s.getPages();for(let[e,t]of m.entries()){let n=h[e],r=(n.getRotation().angle+t)%360;n.setRotation(a.degrees(r))}let g=await s.save();return await n.fs.writeFile(f,g),{stdout:`Created ${d}\n`,stderr:``,exitCode:0}}return{stdout:``,stderr:`${e}: unknown operation '${a}'\n`,exitCode:1}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}const i7=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],Hke=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],Uke={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function Wke(e={}){return SA(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return nAe();let n=e.processManager??Gke();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
8858
+ `,exitCode:1};let r=Hke,i=!1,a=!1;for(let e=0;e<t.length;e++){let n=t[e];if(n===`-a`||n===`-A`||n===`-e`||n===`--all`){a=!0;continue}if(n===`-T`||n===`--tree`){i=!0;continue}if(n===`-o`||n.startsWith(`--columns=`)||n.startsWith(`-o=`)){let i=n.startsWith(`-o=`)?n.slice(3):n.startsWith(`--columns=`)?n.slice(10):t[++e];if(typeof i!=`string`)return{stdout:``,stderr:`ps: -o requires an argument
8859
+ `,exitCode:2};let a=Kke(i);if(a instanceof Error)return{stdout:``,stderr:`ps: ${a.message}\n`,exitCode:2};r=a;continue}return{stdout:``,stderr:`ps: unrecognized argument '${n}'\n`,exitCode:2}}let o=n.list().sort((e,t)=>e.pid-t.pid),s=a?o:o.filter(e=>e.status===`running`||e.status===`pending`),c=(i?tAe(s):s.map(e=>({proc:e,depth:0}))).map(({proc:e,depth:t})=>Yke(e,r,t,i));return{stdout:[qke(r),...c].join(`
8860
8860
  `)+`
8861
- `,stderr:``,exitCode:0}})}function Wke(){let e=globalThis.__slicc_pm;return e instanceof Object&&typeof e.list==`function`?e:null}function Gke(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);if(t.length===0)return Error(`-o requires at least one column`);let n=[];for(let e of t){if(!i7.includes(e))return Error(`unknown column '${e}'; supported: ${i7.join(`, `)}`);n.push(e)}return n}function Kke(e){return e.map(e=>qke(e)).join(` `)}function qke(e){switch(e){case`pid`:return`PID`.padStart(5);case`ppid`:return`PPID`.padStart(5);case`kind`:return`KIND`.padEnd(10);case`stat`:return`STAT`;case`start`:return`START`;case`scoop`:return`SCOOP`.padEnd(10);case`command`:return`COMMAND`}}function Jke(e,t,n,r){return t.map(t=>Yke(e,t,n,r)).join(` `)}function Yke(e,t,n,r){switch(t){case`pid`:return String(e.pid).padStart(5);case`ppid`:return String(e.ppid).padStart(5);case`kind`:return e.kind.padEnd(10);case`stat`:return Hke[e.status];case`start`:return Xke(e.startedAt);case`scoop`:return Zke(e).padEnd(10);case`command`:return Qke(e,n,r)}}function Xke(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}`}function Zke(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?.slice(0,10)??`scoop`}function Qke(e,t,n){let r=n&&t>0?` `.repeat(t-1)+`└─ `:``,i=e.argv.length===0?`[${e.kind}]`:e.argv.map($ke).join(` `);return r+(i.length>80?i.slice(0,79)+`…`:i)}function $ke(e){return e===``?`''`:/^[A-Za-z0-9_./:=@%+-]+$/.test(e)?e:e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function eAe(e){let t=new Map;for(let n of e)t.set(n.pid,n);let n=new Map,r=[];for(let i of e)if(t.has(i.ppid)){let e=n.get(i.ppid)??[];e.push(i),n.set(i.ppid,e)}else r.push(i);let i=[],a=new Set,o=(e,t)=>{if(a.has(e.pid))return;a.add(e.pid),i.push({proc:e,depth:t});let r=n.get(e.pid)??[];for(let e of r.sort((e,t)=>e.pid-t.pid))o(e,t+1)};for(let e of r.sort((e,t)=>e.pid-t.pid))o(e,0);return i}function tAe(){return{stdout:`Usage: ps [-a] [-T] [-o col[,col…]]
8861
+ `,stderr:``,exitCode:0}})}function Gke(){let e=globalThis.__slicc_pm;return e instanceof Object&&typeof e.list==`function`?e:null}function Kke(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);if(t.length===0)return Error(`-o requires at least one column`);let n=[];for(let e of t){if(!i7.includes(e))return Error(`unknown column '${e}'; supported: ${i7.join(`, `)}`);n.push(e)}return n}function qke(e){return e.map(e=>Jke(e)).join(` `)}function Jke(e){switch(e){case`pid`:return`PID`.padStart(5);case`ppid`:return`PPID`.padStart(5);case`kind`:return`KIND`.padEnd(10);case`stat`:return`STAT`;case`start`:return`START`;case`scoop`:return`SCOOP`.padEnd(10);case`command`:return`COMMAND`}}function Yke(e,t,n,r){return t.map(t=>Xke(e,t,n,r)).join(` `)}function Xke(e,t,n,r){switch(t){case`pid`:return String(e.pid).padStart(5);case`ppid`:return String(e.ppid).padStart(5);case`kind`:return e.kind.padEnd(10);case`stat`:return Uke[e.status];case`start`:return Zke(e.startedAt);case`scoop`:return Qke(e).padEnd(10);case`command`:return $ke(e,n,r)}}function Zke(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}`}function Qke(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?.slice(0,10)??`scoop`}function $ke(e,t,n){let r=n&&t>0?` `.repeat(t-1)+`└─ `:``,i=e.argv.length===0?`[${e.kind}]`:e.argv.map(eAe).join(` `);return r+(i.length>80?i.slice(0,79)+`…`:i)}function eAe(e){return e===``?`''`:/^[A-Za-z0-9_./:=@%+-]+$/.test(e)?e:e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function tAe(e){let t=new Map;for(let n of e)t.set(n.pid,n);let n=new Map,r=[];for(let i of e)if(t.has(i.ppid)){let e=n.get(i.ppid)??[];e.push(i),n.set(i.ppid,e)}else r.push(i);let i=[],a=new Set,o=(e,t)=>{if(a.has(e.pid))return;a.add(e.pid),i.push({proc:e,depth:t});let r=n.get(e.pid)??[];for(let e of r.sort((e,t)=>e.pid-t.pid))o(e,t+1)};for(let e of r.sort((e,t)=>e.pid-t.pid))o(e,0);return i}function nAe(){return{stdout:`Usage: ps [-a] [-T] [-o col[,col…]]
8862
8862
 
8863
8863
  List processes tracked by the kernel.
8864
8864
 
@@ -8888,9 +8888,9 @@ Examples:
8888
8888
  ps -T live tree
8889
8889
  ps -a -T full tree
8890
8890
  ps -o pid,kind,stat just three columns
8891
- `,stderr:``,exitCode:0}}const nAe=new Set([`dev`,`proc`,`lib`,`bin`,`usr`,`etc`,`home`,`tmp`]);async function rAe(e,t=nAe){let n=[],r=new Set;try{let i=await e.readdir(`/`);for(let a of i){if(!a||a.includes(`/`)||t.has(a))continue;let i=`/${a}`,o=!1;try{o=!!(await e.stat(i)).isDirectory}catch{continue}o&&(r.has(i)||(r.add(i),n.push(i)))}}catch{}return r.has(`/tmp`)||(r.add(`/tmp`),n.push(`/tmp`)),n}function iAe(e,t){let n=e;if(typeof n.listMountPoints!=`function`)return[];let r=e=>{for(let n of t)if(e===n||e.startsWith(n===`/`?`/`:n+`/`)||n.startsWith(e+`/`))return!0;return!1},i=[];for(let e of n.listMountPoints())e.kind!==`proc`&&r(e.path)&&i.push({path:e.path,kind:e.kind});return i}function aAe(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`slicc-fs`}catch{}}function oAe(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},fromDir:e.cwd}}async function sAe(e,t){try{let n=await e.readFile(`${t}/package.json`),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}function cAe(e,t){return`installed pyodide ${e} is not the supported version ${t}: run \`ipk uninstall pyodide\` then \`ipk add pyodide@${t}\``}function lAe(){return{stdout:`usage: python3 [-c code | script.py] [args...]
8892
- `,stderr:``,exitCode:0}}function uAe(){return{stdout:`Python 3.14 (Pyodide)
8893
- `,stderr:``,exitCode:0}}async function dAe(e,t,n){if(t[0]===`-c`){if(!t[1])return{kind:`result`,result:{stdout:``,stderr:`${e}: option requires an argument -- 'c'\n`,exitCode:2}};let n=t[1];return{kind:`ok`,code:n,filename:`-c`,sysArgv:[`-c`,...t.slice(2)],procArgv:[e,`-c`,n,...t.slice(2)]}}if(t.length>0&&!t[0].startsWith(`-`)){let r=t[0],i=n.fs.resolvePath(n.cwd,r);return await n.fs.exists(i)?{kind:`ok`,code:await n.fs.readFile(i),filename:r,sysArgv:[r,...t.slice(1)],procArgv:[e,r,...t.slice(1)]}:{kind:`result`,result:{stdout:``,stderr:`${e}: can't open file '${r}': [Errno 2] No such file or directory\n`,exitCode:2}}}return T1(n.stdin).trim().length>0?{kind:`ok`,code:T1(n.stdin),filename:`<stdin>`,sysArgv:[`<stdin>`],procArgv:[e]}:t.length>0?{kind:`result`,result:{stdout:``,stderr:`${e}: unsupported option '${t[0]}'\n`,exitCode:2}}:{kind:`result`,result:{stdout:``,stderr:`${e}: no input provided (use -c CODE, script path, or stdin)\n`,exitCode:2}}}async function fAe(e){let t=oAe(e),n=await gJ(t);if(!n)return{kind:`result`,result:{stdout:``,stderr:`${mJ}\n`,exitCode:1}};let r=await sAe(t.reader,n);return r?r===fJ?{kind:`ok`,assetRoot:n}:{kind:`result`,result:{stdout:``,stderr:`${cAe(r,fJ)}\n`,exitCode:1}}:{kind:`result`,result:{stdout:``,stderr:`${mJ}\n`,exitCode:1}}}function a7(e,t={}){return SA(e,async(n,r)=>{if(n.includes(`--help`)||n.includes(`-h`))return lAe();if(n.includes(`--version`)||n.includes(`-V`))return uAe();let i=await dAe(e,n,r);if(i.kind===`result`)return i.result;let{code:a,filename:o,sysArgv:s,procArgv:c}=i,l=await rAe(r.fs),u=iAe(r.fs,l),d=t.buildProcessConfig?.(),f=d?.processManager??pAe(),p=d?.owner??{kind:`system`},m=d?.getParentPid?.(),h=t.realmFactory??C$(),g=t.pyodideIndexURL??$he(),_=t.pyodideAssetRoot;if(!_&&g===void 0){let e=await fAe(r);if(e.kind===`result`)return e.result;_=e.assetRoot}let v=o===`<stdin>`?``:T1(r.stdin),y=aAe();return f?w1({pm:f,realmFactory:h,owner:p,kind:`py`,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u,procKind:`py`,ppid:m}):mAe({realmFactory:h,owner:p,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u})})}function pAe(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}let o7=null;async function mAe(e){if(!o7){let{ProcessManager:e}=await Promise.resolve().then(()=>DW);o7=new e}return w1({pm:o7,realmFactory:e.realmFactory,owner:e.owner,kind:`py`,code:e.code,argv:e.argv,realmArgv:e.realmArgv,env:e.env,cwd:e.cwd,filename:e.filename,ctx:e.ctx,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,mountPoints:e.mountPoints,opfsMountDbName:e.opfsMountDbName,procKind:`py`})}function s7(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}function hAe(){return null}function gAe(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=c7(r),o=c7(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function c7(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function l7(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
8891
+ `,stderr:``,exitCode:0}}const rAe=new Set([`dev`,`proc`,`lib`,`bin`,`usr`,`etc`,`home`,`tmp`]);async function iAe(e,t=rAe){let n=[],r=new Set;try{let i=await e.readdir(`/`);for(let a of i){if(!a||a.includes(`/`)||t.has(a))continue;let i=`/${a}`,o=!1;try{o=!!(await e.stat(i)).isDirectory}catch{continue}o&&(r.has(i)||(r.add(i),n.push(i)))}}catch{}return r.has(`/tmp`)||(r.add(`/tmp`),n.push(`/tmp`)),n}function aAe(e,t){let n=e;if(typeof n.listMountPoints!=`function`)return[];let r=e=>{for(let n of t)if(e===n||e.startsWith(n===`/`?`/`:n+`/`)||n.startsWith(e+`/`))return!0;return!1},i=[];for(let e of n.listMountPoints())e.kind!==`proc`&&r(e.path)&&i.push({path:e.path,kind:e.kind});return i}function oAe(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`slicc-fs`}catch{}}function sAe(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},fromDir:e.cwd}}async function cAe(e,t){try{let n=await e.readFile(`${t}/package.json`),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}function lAe(e,t){return`installed pyodide ${e} is not the supported version ${t}: run \`ipk uninstall pyodide\` then \`ipk add pyodide@${t}\``}function uAe(){return{stdout:`usage: python3 [-c code | script.py] [args...]
8892
+ `,stderr:``,exitCode:0}}function dAe(){return{stdout:`Python 3.14 (Pyodide)
8893
+ `,stderr:``,exitCode:0}}async function fAe(e,t,n){if(t[0]===`-c`){if(!t[1])return{kind:`result`,result:{stdout:``,stderr:`${e}: option requires an argument -- 'c'\n`,exitCode:2}};let n=t[1];return{kind:`ok`,code:n,filename:`-c`,sysArgv:[`-c`,...t.slice(2)],procArgv:[e,`-c`,n,...t.slice(2)]}}if(t.length>0&&!t[0].startsWith(`-`)){let r=t[0],i=n.fs.resolvePath(n.cwd,r);return await n.fs.exists(i)?{kind:`ok`,code:await n.fs.readFile(i),filename:r,sysArgv:[r,...t.slice(1)],procArgv:[e,r,...t.slice(1)]}:{kind:`result`,result:{stdout:``,stderr:`${e}: can't open file '${r}': [Errno 2] No such file or directory\n`,exitCode:2}}}return T1(n.stdin).trim().length>0?{kind:`ok`,code:T1(n.stdin),filename:`<stdin>`,sysArgv:[`<stdin>`],procArgv:[e]}:t.length>0?{kind:`result`,result:{stdout:``,stderr:`${e}: unsupported option '${t[0]}'\n`,exitCode:2}}:{kind:`result`,result:{stdout:``,stderr:`${e}: no input provided (use -c CODE, script path, or stdin)\n`,exitCode:2}}}async function pAe(e){let t=sAe(e),n=await gJ(t);if(!n)return{kind:`result`,result:{stdout:``,stderr:`${mJ}\n`,exitCode:1}};let r=await cAe(t.reader,n);return r?r===fJ?{kind:`ok`,assetRoot:n}:{kind:`result`,result:{stdout:``,stderr:`${lAe(r,fJ)}\n`,exitCode:1}}:{kind:`result`,result:{stdout:``,stderr:`${mJ}\n`,exitCode:1}}}function a7(e,t={}){return SA(e,async(n,r)=>{if(n.includes(`--help`)||n.includes(`-h`))return uAe();if(n.includes(`--version`)||n.includes(`-V`))return dAe();let i=await fAe(e,n,r);if(i.kind===`result`)return i.result;let{code:a,filename:o,sysArgv:s,procArgv:c}=i,l=await iAe(r.fs),u=aAe(r.fs,l),d=t.buildProcessConfig?.(),f=d?.processManager??mAe(),p=d?.owner??{kind:`system`},m=d?.getParentPid?.(),h=t.realmFactory??C$(),g=t.pyodideIndexURL??$he(),_=t.pyodideAssetRoot;if(!_&&g===void 0){let e=await pAe(r);if(e.kind===`result`)return e.result;_=e.assetRoot}let v=o===`<stdin>`?``:T1(r.stdin),y=oAe();return f?w1({pm:f,realmFactory:h,owner:p,kind:`py`,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u,procKind:`py`,ppid:m}):hAe({realmFactory:h,owner:p,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u})})}function mAe(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}let o7=null;async function hAe(e){if(!o7){let{ProcessManager:e}=await Promise.resolve().then(()=>DW);o7=new e}return w1({pm:o7,realmFactory:e.realmFactory,owner:e.owner,kind:`py`,code:e.code,argv:e.argv,realmArgv:e.realmArgv,env:e.env,cwd:e.cwd,filename:e.filename,ctx:e.ctx,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,mountPoints:e.mountPoints,opfsMountDbName:e.opfsMountDbName,procKind:`py`})}function s7(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}function gAe(){return null}function _Ae(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=c7(r),o=c7(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function c7(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function l7(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
8894
8894
 
8895
8895
  Usage:
8896
8896
  rsync [flags] <local-path> <runtime-id>:<remote-path> # push
@@ -8906,21 +8906,21 @@ Examples:
8906
8906
  rsync /workspace follower-abc123:/workspace
8907
8907
  rsync --delete /shared leader:/shared
8908
8908
  rsync follower-abc123:/workspace/project /workspace/project
8909
- `,stderr:``,exitCode:0}}async function u7(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function d7(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function _Ae(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function vAe(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function f7(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function yAe(e,t,n){let r=[],{localPath:i,remotePath:o,runtimeId:s,verbose:c,dryRun:l}=n,u=s7(await u7(e,i),await d7(t,s,o),{delete:n.delete});if(c||l){for(let e of u.toAdd)r.push(`+ ${e}`);for(let e of u.toUpdate)r.push(`~ ${e}`);for(let e of u.toDelete)r.push(`- ${e}`);if(c)for(let e of u.toSkip)r.push(` ${e} (up to date)`)}let d=u.toAdd.length+u.toUpdate.length+u.toDelete.length;if(l)return r.push(`\n(dry run) ${d} file(s) would be transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
8909
+ `,stderr:``,exitCode:0}}async function u7(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function d7(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function vAe(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function yAe(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function f7(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function bAe(e,t,n){let r=[],{localPath:i,remotePath:o,runtimeId:s,verbose:c,dryRun:l}=n,u=s7(await u7(e,i),await d7(t,s,o),{delete:n.delete});if(c||l){for(let e of u.toAdd)r.push(`+ ${e}`);for(let e of u.toUpdate)r.push(`~ ${e}`);for(let e of u.toDelete)r.push(`- ${e}`);if(c)for(let e of u.toSkip)r.push(` ${e} (up to date)`)}let d=u.toAdd.length+u.toUpdate.length+u.toDelete.length;if(l)return r.push(`\n(dry run) ${d} file(s) would be transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
8910
8910
  `)+`
8911
- `,stderr:``,exitCode:0};for(let n of[...u.toAdd,...u.toUpdate]){let c=i+`/`+n,l=o+`/`+n;await vAe(t,s,f7(l));let u=await t(s,{op:`writeFile`,path:l,content:a(await e.readFile(c,{encoding:`binary`})),encoding:`base64`});if(!u[0].ok)return{stdout:r.join(`
8911
+ `,stderr:``,exitCode:0};for(let n of[...u.toAdd,...u.toUpdate]){let c=i+`/`+n,l=o+`/`+n;await yAe(t,s,f7(l));let u=await t(s,{op:`writeFile`,path:l,content:a(await e.readFile(c,{encoding:`binary`})),encoding:`base64`});if(!u[0].ok)return{stdout:r.join(`
8912
8912
  `)+`
8913
8913
  `,stderr:`Error writing ${l}: ${u[0].error}\n`,exitCode:1}}for(let e of u.toDelete){let n=o+`/`+e,i=await t(s,{op:`rm`,path:n});if(!i[0].ok)return{stdout:r.join(`
8914
8914
  `)+`
8915
8915
  `,stderr:`Error deleting ${n}: ${i[0].error}\n`,exitCode:1}}return r.push(`${d} file(s) transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
8916
8916
  `)+`
8917
- `,stderr:``,exitCode:0}}async function bAe(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:l}=n,u=s7(await d7(t,o,a),await u7(e,i),{delete:n.delete});if(s||l){for(let e of u.toAdd)r.push(`+ ${e}`);for(let e of u.toUpdate)r.push(`~ ${e}`);for(let e of u.toDelete)r.push(`- ${e}`);if(s)for(let e of u.toSkip)r.push(` ${e} (up to date)`)}let d=u.toAdd.length+u.toUpdate.length+u.toDelete.length;if(l)return r.push(`\n(dry run) ${d} file(s) would be transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
8917
+ `,stderr:``,exitCode:0}}async function xAe(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:l}=n,u=s7(await d7(t,o,a),await u7(e,i),{delete:n.delete});if(s||l){for(let e of u.toAdd)r.push(`+ ${e}`);for(let e of u.toUpdate)r.push(`~ ${e}`);for(let e of u.toDelete)r.push(`- ${e}`);if(s)for(let e of u.toSkip)r.push(` ${e} (up to date)`)}let d=u.toAdd.length+u.toUpdate.length+u.toDelete.length;if(l)return r.push(`\n(dry run) ${d} file(s) would be transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
8918
8918
  `)+`
8919
- `,stderr:``,exitCode:0};for(let n of[...u.toAdd,...u.toUpdate]){let r=a+`/`+n,s=i+`/`+n,l=f7(s);await e.exists(l)||await e.mkdir(l,{recursive:!0});let u=c(await _Ae(t,o,r));await e.writeFile(s,u)}for(let t of u.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${d} file(s) transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
8919
+ `,stderr:``,exitCode:0};for(let n of[...u.toAdd,...u.toUpdate]){let r=a+`/`+n,s=i+`/`+n,l=f7(s);await e.exists(l)||await e.mkdir(l,{recursive:!0});let u=c(await vAe(t,o,r));await e.writeFile(s,u)}for(let t of u.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${d} file(s) transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
8920
8920
  `)+`
8921
- `,stderr:``,exitCode:0}}function xAe(e={}){let t=e.fs,n=e.getSendFsRequest??hAe;return SA(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return l7();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
8921
+ `,stderr:``,exitCode:0}}function SAe(e={}){let t=e.fs,n=e.getSendFsRequest??gAe;return SA(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return l7();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
8922
8922
  `,exitCode:1};let r=n();if(!r)return{stdout:``,stderr:`rsync: not connected to a tray — rsync requires a tray connection
8923
- `,exitCode:1};let i=gAe(e);if(`error`in i)return i.error===`__help__`?l7():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await yAe(t,r,i):await bAe(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function p7(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [-o file] [--list] <text>
8923
+ `,exitCode:1};let i=_Ae(e);if(`error`in i)return i.error===`__help__`?l7():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await bAe(t,r,i):await xAe(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function p7(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [-o file] [--list] <text>
8924
8924
  say --status | --warmup
8925
8925
 
8926
8926
  Speaks the given text. Uses on-device Kokoro voices when the model
@@ -8940,11 +8940,11 @@ Examples:
8940
8940
  `,stderr:``,exitCode:0}}function m7(e){switch(e.state){case`ready`:return`voice engine: ready
8941
8941
  `;case`failed`:return`voice engine: failed (re-run say --warmup to retry)
8942
8942
  `;case`idle`:return`voice engine: not downloaded (run say --warmup)
8943
- `;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 h7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function g7(e){return e instanceof Error?e.message:String(e)}let _7=!1,v7=null;function y7(){return _7?Promise.resolve(speechSynthesis.getVoices()):(v7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){_7=!0,e(t);return}let n=()=>{_7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),_7=!0,e(speechSynthesis.getVoices())},1e3)}),v7)}const b7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function SAe(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 CAe(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 b7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return h7(`${i} requires ${b7[i]}`);let a=SAe(t,i,n);if(a)return h7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return h7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function x7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function wAe(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-Xwr6Wl9m.js`),t=e().map(e=>x7({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await y7()).map(e=>x7({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
8943
+ `;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 h7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function g7(e){return e instanceof Error?e.message:String(e)}let _7=!1,v7=null;function y7(){return _7?Promise.resolve(speechSynthesis.getVoices()):(v7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){_7=!0,e(t);return}let n=()=>{_7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),_7=!0,e(speechSynthesis.getVoices())},1e3)}),v7)}const b7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function CAe(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 wAe(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 b7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return h7(`${i} requires ${b7[i]}`);let a=CAe(t,i,n);if(a)return h7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return h7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function x7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function TAe(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-B2BbgJmn.js`),t=e().map(e=>x7({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await y7()).map(e=>x7({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
8944
8944
  `)+`
8945
8945
  `,stderr:``,exitCode:0}}try{return{stdout:(await e.panelRpc.call(`list-voices`,void 0)).voices.map(e=>x7(e)).join(`
8946
8946
  `)+`
8947
- `,stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function TAe(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-Xwr6Wl9m.js`),n=t().map(e=>({name:e.id})),r=(await y7()).map(e=>({name:e.name}));return[...n,...r]}async function EAe(e,t){let n=(await TAe(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:h7(`voice "${t}" not found. Use --list to see available voices.`)}}async function S7(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speak-Xwr6Wl9m.js`);return{stdout:m7(t?n():e()),stderr:``,exitCode:0}}return{stdout:m7(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function DAe(e,t){return t.includes(`--list`)?wAe(e):t.includes(`--status`)?S7(e,!1):t.includes(`--warmup`)?S7(e,!0):null}async function OAe(e){try{let{speak:t}=await import(`./speak-Xwr6Wl9m.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return h7(`speech synthesis error: ${g7(e)}`)}}async function kAe(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function AAe(e){let{synthesizeToWav:t}=await import(`./speak-Xwr6Wl9m.js`);try{return{bytes:await t(e)}}catch(e){return h7(g7(e))}}async function jAe(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 h7(g7(e))}}async function MAe(e,t,n,r){let i=e.local?await AAe(r):await jAe(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 h7(`failed to write ${n}: ${g7(e)}`)}return{stdout:`wrote ${Math.max(1,Math.round(i.bytes.byteLength/1024))} KB to ${a}\n`,stderr:``,exitCode:0}}function NAe(){return SA(`say`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return p7();let n={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:M()};if(!n.local&&!n.panelRpc)return h7(`Web Speech API unavailable in this environment`);let r=await DAe(n,e);if(r)return r;let i=CAe(e);if(`exitCode`in i)return i;if(!i.text)return p7();if(!i.lang)return h7(`-l language tag is required`);let a;if(i.voiceName){let{resolved:e,error:t}=await EAe(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?MAe(n,t,i.outFile,o):n.local?OAe(o):kAe(n,o)})}function PAe(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
8947
+ `,stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function EAe(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-B2BbgJmn.js`),n=t().map(e=>({name:e.id})),r=(await y7()).map(e=>({name:e.name}));return[...n,...r]}async function DAe(e,t){let n=(await EAe(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:h7(`voice "${t}" not found. Use --list to see available voices.`)}}async function S7(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speak-B2BbgJmn.js`);return{stdout:m7(t?n():e()),stderr:``,exitCode:0}}return{stdout:m7(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function OAe(e,t){return t.includes(`--list`)?TAe(e):t.includes(`--status`)?S7(e,!1):t.includes(`--warmup`)?S7(e,!0):null}async function kAe(e){try{let{speak:t}=await import(`./speak-B2BbgJmn.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return h7(`speech synthesis error: ${g7(e)}`)}}async function AAe(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function jAe(e){let{synthesizeToWav:t}=await import(`./speak-B2BbgJmn.js`);try{return{bytes:await t(e)}}catch(e){return h7(g7(e))}}async function MAe(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 h7(g7(e))}}async function NAe(e,t,n,r){let i=e.local?await jAe(r):await MAe(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 h7(`failed to write ${n}: ${g7(e)}`)}return{stdout:`wrote ${Math.max(1,Math.round(i.bytes.byteLength/1024))} KB to ${a}\n`,stderr:``,exitCode:0}}function PAe(){return SA(`say`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return p7();let n={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:M()};if(!n.local&&!n.panelRpc)return h7(`Web Speech API unavailable in this environment`);let r=await OAe(n,e);if(r)return r;let i=wAe(e);if(`exitCode`in i)return i;if(!i.text)return p7();if(!i.lang)return h7(`-l language tag is required`);let a;if(i.voiceName){let{resolved:e,error:t}=await DAe(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?NAe(n,t,i.outFile,o):n.local?kAe(o):AAe(n,o)})}function FAe(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
8948
8948
 
8949
8949
  Usage: screencapture [options] <output-file>
8950
8950
 
@@ -8960,12 +8960,12 @@ Examples:
8960
8960
  screencapture screenshot.png # Capture to file
8961
8961
  screencapture -c # Capture to clipboard
8962
8962
  screencapture -v capture.png # Capture and return for agent vision
8963
- `,stderr:``,exitCode:0}}function FAe(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 IAe(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function LAe(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 RAe(){return SA(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return PAe();let n=fe(),r=M();if(!n&&!r)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
8963
+ `,stderr:``,exitCode:0}}function IAe(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 LAe(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function RAe(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 zAe(){return SA(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return FAe();let n=fe(),r=M();if(!n&&!r)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
8964
8964
  `,exitCode:1};if(n&&!n6()&&!navigator.mediaDevices?.getDisplayMedia)return{stdout:``,stderr:`screencapture: screen capture is not supported in this browser
8965
8965
  `,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)
8966
- `,exitCode:1};let l=c||`screenshot.png`,u=IAe(l),d=u===`image/png`?1:.92,f;try{if(n6())f=(await r6({kind:`screen`,mimeType:u,quality:d})).bytes;else if(n)f=(await LAe(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
8966
+ `,exitCode:1};let l=c||`screenshot.png`,u=LAe(l),d=u===`image/png`?1:.92,f;try{if(n6())f=(await r6({kind:`screen`,mimeType:u,quality:d})).bytes;else if(n)f=(await RAe(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
8967
8967
  `,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}if(i)try{if(n6()&&typeof document<`u`&&typeof document.hasFocus==`function`&&!document.hasFocus())return{stdout:``,stderr:`screencapture: clipboard capture needs a focused window; save to a file instead
8968
- `,exitCode:1};if(n){let e=await zAe(f,u),t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=new Blob([t],{type:`image/png`});return await BAe(),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,${FAe(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${PK(p)}\n`,stderr:``,exitCode:0}})}async function zAe(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 BAe(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 VAe(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 C7(e,t,n){let r={method:e,headers:oe({"Content-Type":`application/json`})};n&&(r.body=JSON.stringify(n));let i=await fetch(re(`/api/secrets${t}`),r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function HAe(){return{async list(){let[e,t]=await Promise.all([C7(`GET`,``),C7(`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 C7(`GET`,`/masked`);return t?n.find(t=>t.name===e)??null:null},async peek(e){let{ok:t,data:n}=await C7(`GET`,`/peek?name=${encodeURIComponent(e)}`);return t?n:null},async setSession(e,t,n){let{ok:r,data:i}=await C7(`POST`,`/session`,{name:e,value:t,domains:n});if(!r)throw Error(T7(i)??`failed to set session secret`)},async setPersisted(e,t,n){let{ok:r,data:i}=await C7(`POST`,``,{name:e,value:t,domains:n});if(!r)throw Error(T7(i)??`failed to persist secret`)},async setScope(e,t){let{ok:n,data:r}=await C7(`POST`,`/scope`,{name:e,domains:t});if(!n)throw Error(T7(r)??`failed to update scope`)},async delete(e){let{ok:t,status:n,data:r}=await C7(`DELETE`,`/${encodeURIComponent(e)}`);if(n===404)return{removed:!1};if(!t)throw Error(T7(r)??`failed to delete secret`);return{removed:!0,fromSession:r&&typeof r==`object`&&`fromSession`in r?!!r.fromSession:void 0}}}}function w7(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 UAe(){return w7(e=>VAe(e))}function WAe(){return w7(e=>{let{type:t,...n}=e;return P(t,n)})}function T7(e){if(e&&typeof e==`object`&&`error`in e){let t=e.error;if(typeof t==`string`)return t}}function GAe(e){switch(e){case`extension-direct`:return UAe();case`extension-delegate`:return WAe();default:return HAe()}}function KAe(){return`secret — manage secrets for the fetch proxy and mount backends
8968
+ `,exitCode:1};if(n){let e=await BAe(f,u),t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=new Blob([t],{type:`image/png`});return await VAe(),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,${IAe(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${PK(p)}\n`,stderr:``,exitCode:0}})}async function BAe(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 VAe(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 HAe(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 C7(e,t,n){let r={method:e,headers:oe({"Content-Type":`application/json`})};n&&(r.body=JSON.stringify(n));let i=await fetch(re(`/api/secrets${t}`),r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function UAe(){return{async list(){let[e,t]=await Promise.all([C7(`GET`,``),C7(`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 C7(`GET`,`/masked`);return t?n.find(t=>t.name===e)??null:null},async peek(e){let{ok:t,data:n}=await C7(`GET`,`/peek?name=${encodeURIComponent(e)}`);return t?n:null},async setSession(e,t,n){let{ok:r,data:i}=await C7(`POST`,`/session`,{name:e,value:t,domains:n});if(!r)throw Error(T7(i)??`failed to set session secret`)},async setPersisted(e,t,n){let{ok:r,data:i}=await C7(`POST`,``,{name:e,value:t,domains:n});if(!r)throw Error(T7(i)??`failed to persist secret`)},async setScope(e,t){let{ok:n,data:r}=await C7(`POST`,`/scope`,{name:e,domains:t});if(!n)throw Error(T7(r)??`failed to update scope`)},async delete(e){let{ok:t,status:n,data:r}=await C7(`DELETE`,`/${encodeURIComponent(e)}`);if(n===404)return{removed:!1};if(!t)throw Error(T7(r)??`failed to delete secret`);return{removed:!0,fromSession:r&&typeof r==`object`&&`fromSession`in r?!!r.fromSession:void 0}}}}function w7(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 WAe(){return w7(e=>HAe(e))}function GAe(){return w7(e=>{let{type:t,...n}=e;return P(t,n)})}function T7(e){if(e&&typeof e==`object`&&`error`in e){let t=e.error;if(typeof t==`string`)return t}}function KAe(e){switch(e){case`extension-direct`:return WAe();case`extension-delegate`:return GAe();default:return UAe()}}function qAe(){return`secret — manage secrets for the fetch proxy and mount backends
8969
8969
 
8970
8970
  No approval (session-only, in-memory, never persisted):
8971
8971
  secret set <name> <value> [--domain <pat>] Set a session secret. Free for a
@@ -9002,24 +9002,24 @@ Examples:
9002
9002
  secret peek OPENAI_KEY
9003
9003
  secret set GITHUB_TOKEN ghp_… --domain "api.github.com" --persist # prompts
9004
9004
  secret scope GITHUB_TOKEN --domain "api.github.com,*.github.com" # prompts
9005
- `}function E7(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 qAe={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},JAe=new Set;function D7(e,t){if(e===t)return!0;try{return aP(e).test(t)}catch{return!1}}function YAe(e,t){for(let n of e)if(D7(n,t))return!0;return!1}function O7(){return{stdout:``,stderr:`secret: approval denied
9006
- `,exitCode:1}}function XAe(e){let t=Ee(),n=e.isExtension??(t===`extension-direct`||t===`extension-delegate`),r=e.backend??GAe(t),i=e.grants??JAe,a=e.broker,o=()=>(a??=xP(),a);return{backend:r,inExtension:n,gate:async(e,t)=>{let n=`secret:${e}:${t}`;if(YAe(i,n))return!0;let r=await o().requestApproval({kind:`secret`,detail:`${qAe[e]}: ${t}`,suggestedPattern:n});if(r.decision===`deny`)return!1;if(r.decision===`always`){let e=r.pattern?.trim();i.add(e&&D7(e,n)?e:n)}return!0},injectMaskedEnv:async t=>{if(e.setEnv&&gI(t))try{let n=await r.getMasked(t);n&&e.setEnv(t,n.maskedValue)}catch{}}}}function ZAe(e){let t=T1(e);if(t.length!==0)return t.endsWith(`\r
9005
+ `}function E7(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 JAe={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},YAe=new Set;function D7(e,t){if(e===t)return!0;try{return aP(e).test(t)}catch{return!1}}function XAe(e,t){for(let n of e)if(D7(n,t))return!0;return!1}function O7(){return{stdout:``,stderr:`secret: approval denied
9006
+ `,exitCode:1}}function ZAe(e){let t=Ee(),n=e.isExtension??(t===`extension-direct`||t===`extension-delegate`),r=e.backend??KAe(t),i=e.grants??YAe,a=e.broker,o=()=>(a??=xP(),a);return{backend:r,inExtension:n,gate:async(e,t)=>{let n=`secret:${e}:${t}`;if(XAe(i,n))return!0;let r=await o().requestApproval({kind:`secret`,detail:`${JAe[e]}: ${t}`,suggestedPattern:n});if(r.decision===`deny`)return!1;if(r.decision===`always`){let e=r.pattern?.trim();i.add(e&&D7(e,n)?e:n)}return!0},injectMaskedEnv:async t=>{if(e.setEnv&&gI(t))try{let n=await r.getMasked(t);n&&e.setEnv(t,n.maskedValue)}catch{}}}}function QAe(e){let t=T1(e);if(t.length!==0)return t.endsWith(`\r
9007
9007
  `)?t.slice(0,-2):t.endsWith(`
9008
- `)?t.slice(0,-1):t}async function QAe(e,t,n,r){return n.length===0?{stdout:``,stderr:`secret: --domain is required to persist a secret
9009
- `,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}):O7()}async function $Ae(e,t,n,r){return await r.backend.getInfo(e)&&!await r.gate(`value`,e)?O7():(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 eje(e,t,n){let r=e[1];if(!r||r.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
9010
- `,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=ZAe(t.stdin);if(i!==void 0&&a!==void 0)return{stdout:``,stderr:`secret: provide <value> as an argument OR via stdin, not both
9008
+ `)?t.slice(0,-1):t}async function $Ae(e,t,n,r){return n.length===0?{stdout:``,stderr:`secret: --domain is required to persist a secret
9009
+ `,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}):O7()}async function eje(e,t,n,r){return await r.backend.getInfo(e)&&!await r.gate(`value`,e)?O7():(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 tje(e,t,n){let r=e[1];if(!r||r.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
9010
+ `,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=QAe(t.stdin);if(i!==void 0&&a!==void 0)return{stdout:``,stderr:`secret: provide <value> as an argument OR via stdin, not both
9011
9011
  `,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]
9012
9012
  or pipe the value on stdin: echo "$TOKEN" | secret set <name> [--domain ...]
9013
- `,exitCode:1};let s=E7(e)??[];return e.includes(`--persist`)?QAe(r,o,s,n):$Ae(r,o,s,n)}async function tje(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: get requires a <name>
9014
- `,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 nje(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: peek requires a <name>
9015
- `,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 rje(e,t){let n=e[1];if(!n||n.startsWith(`-`))return{stdout:``,stderr:`secret: scope requires a <name>
9013
+ `,exitCode:1};let s=E7(e)??[];return e.includes(`--persist`)?$Ae(r,o,s,n):eje(r,o,s,n)}async function nje(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: get requires a <name>
9014
+ `,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 rje(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: peek requires a <name>
9015
+ `,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 ije(e,t){let n=e[1];if(!n||n.startsWith(`-`))return{stdout:``,stderr:`secret: scope requires a <name>
9016
9016
  `,exitCode:1};let r=E7(e)??[];return r.length===0?{stdout:``,stderr:`secret: scope requires --domain <patterns>
9017
- `,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}):O7()}async function ije(e){let t=await e.backend.list();if(t.length===0)return{stdout:`No secrets stored
9018
- `,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 aje(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 oje(e,t){let n=e[1],r=e[2];if(!n||!r)return{stdout:``,stderr:`secret: test requires <name> <url>
9019
- `,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?o(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 sje(e){if(!e.inExtension)return{stdout:`secret: in CLI mode, edit ~/.slicc/secrets.env directly with your text editor.
9017
+ `,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}):O7()}async function aje(e){let t=await e.backend.list();if(t.length===0)return{stdout:`No secrets stored
9018
+ `,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 oje(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 sje(e,t){let n=e[1],r=e[2];if(!n||!r)return{stdout:``,stderr:`secret: test requires <name> <url>
9019
+ `,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?o(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 cje(e){if(!e.inExtension)return{stdout:`secret: in CLI mode, edit ~/.slicc/secrets.env directly with your text editor.
9020
9020
  (changes are picked up on the next request — no restart needed)
9021
9021
  `,stderr:``,exitCode:0};try{return await chrome.runtime.openOptionsPage(),{stdout:`Opened Mount Secrets options page in a new tab.
9022
- `,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 cje(e,t,n){let r=e[0];switch(r){case`set`:return eje(e,t,n);case`get`:case`read`:return tje(e,n);case`peek`:return nje(e,n);case`scope`:return rje(e,n);case`list`:return ije(n);case`delete`:case`rm`:return aje(e,r,n);case`test`:return oje(e,n);case`edit`:return sje(n);default:return{stdout:``,stderr:`secret: unknown command "${r}"\n`,exitCode:1}}}function lje(e={}){let t=XAe(e);return SA(`secret`,async(e,n)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:KAe(),stderr:``,exitCode:0};try{return await cje(e,n,t)}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function uje(){return null}function k7(){return null}function dje(){return globalThis.__slicc_lickManager??null}let A7=null;async function fje(){if(A7)return A7;let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return A7=e(),A7}async function j7(){let e=dje();if(e)return{createWebhook:(t,n,r)=>e.createWebhook(t,n,r),deleteWebhook:t=>e.deleteWebhook(t),listWebhooks:async()=>e.listWebhooks()};if(ge())return null;let t=await fje(),{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 M7(){return{stdout:`usage: serve [--entry <relative-path>] [--bridge | --no-bridge] [--max-tabs <n>] [--quiet] [--stop <token>] [--list] <directory>
9022
+ `,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 lje(e,t,n){let r=e[0];switch(r){case`set`:return tje(e,t,n);case`get`:case`read`:return nje(e,n);case`peek`:return rje(e,n);case`scope`:return ije(e,n);case`list`:return aje(n);case`delete`:case`rm`:return oje(e,r,n);case`test`:return sje(e,n);case`edit`:return cje(n);default:return{stdout:``,stderr:`secret: unknown command "${r}"\n`,exitCode:1}}}function uje(e={}){let t=ZAe(e);return SA(`secret`,async(e,n)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:qAe(),stderr:``,exitCode:0};try{return await lje(e,n,t)}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function dje(){return null}function k7(){return null}function fje(){return globalThis.__slicc_lickManager??null}let A7=null;async function pje(){if(A7)return A7;let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return A7=e(),A7}async function j7(){let e=fje();if(e)return{createWebhook:(t,n,r)=>e.createWebhook(t,n,r),deleteWebhook:t=>e.deleteWebhook(t),listWebhooks:async()=>e.listWebhooks()};if(ge())return null;let t=await pje(),{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 M7(){return{stdout:`usage: serve [--entry <relative-path>] [--bridge | --no-bridge] [--max-tabs <n>] [--quiet] [--stop <token>] [--list] <directory>
9023
9023
 
9024
9024
  Mint a worker-hosted preview URL for a VFS directory, broadcast it to
9025
9025
  all connected followers, and open it in the leader's browser.
@@ -9035,17 +9035,17 @@ Examples:
9035
9035
  --list List active previews on this tray.
9036
9036
  --project Obsolete; ignored. Root-absolute paths work natively
9037
9037
  under unified preview.
9038
- `,stderr:``,exitCode:0}}function pje(e){return`error`in e}function mje(e,t,n){if(e===`--entry`)return t?(n.entry=t,{skip:1}):{error:`serve: missing value for --entry
9038
+ `,stderr:``,exitCode:0}}function mje(e){return`error`in e}function hje(e,t,n){if(e===`--entry`)return t?(n.entry=t,{skip:1}):{error:`serve: missing value for --entry
9039
9039
  `};if(e.startsWith(`--entry=`))return n.entry=e.slice(8),{skip:0};if(e===`--bridge`)return n.bridge=!0,{skip:0};if(e===`--no-bridge`)return n.noBridge=!0,{skip:0};if(e===`--project`)return n.project=!0,{skip:0};if(e===`--stop`)return t?(n.stop=t,{skip:1}):{error:`serve: missing value for --stop
9040
9040
  `};if(e.startsWith(`--stop=`))return n.stop=e.slice(7),{skip:0};if(e===`--list`)return n.list=!0,{skip:0};if(e===`--max-tabs`){if(!t)return{error:`serve: missing value for --max-tabs
9041
9041
  `};let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?{error:`serve: --max-tabs must be a positive integer
9042
9042
  `}:(n.maxTabs=e,{skip:1})}if(e.startsWith(`--max-tabs=`)){let t=Number.parseInt(e.slice(11),10);return!Number.isFinite(t)||t<=0?{error:`serve: --max-tabs must be a positive integer
9043
9043
  `}:(n.maxTabs=t,{skip:0})}return e===`--quiet`?(n.quiet=!0,{skip:0}):e.startsWith(`-`)?{error:`serve: unknown option: ${e}\n`}:n.directory?{error:`serve: expected a single directory argument
9044
- `}:(n.directory=e,{skip:0})}function hje(e){let t={entry:`index.html`,bridge:!1,noBridge:!1,project:!1,list:!1,quiet:!1};for(let n=0;n<e.length;n+=1){let r=mje(e[n],e[n+1],t);if(pje(r))return{...t,error:r.error};n+=r.skip}return t}async function gje(e,t,n,r){if(!GK(t))return{stdout:``,stderr:`serve: invalid entry file: ${t}\n`,exitCode:1};let i=n.resolvePath(r,e),a;try{a=await n.stat(i)}catch{return{stdout:``,stderr:`serve: no such directory: ${e}\n`,exitCode:1}}if(!a.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${e}\n`,exitCode:1};let o=KK(i,t),s;try{s=await n.stat(o)}catch{return{stdout:``,stderr:`serve: entry file not found: ${o}\n`,exitCode:1}}return s.isFile?{fullDirectory:i,entryPath:o}:{stdout:``,stderr:`serve: entry is not a file: ${o}\n`,exitCode:1}}function _je(e){return`exitCode`in e}async function vje(e){let t,n=k7();if(n)t=await n({type:`stop`,previewToken:e});else{let n=M();if(!n)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};t=await n.call(`tray-revoke-preview`,{previewToken:e})}if(!t.revoked)return{stdout:``,stderr:`serve: preview token not found or already revoked
9045
- `,exitCode:1};if(t.webhookId){let n=await j7();if(!n)return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but the preview-bridge webhook could not be cleaned up (lick manager unavailable). It is a live endpoint — delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0};try{await n.deleteWebhook(t.webhookId)}catch(n){return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but webhook cleanup failed: ${n instanceof Error?n.message:String(n)}. Delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0}}}return{stdout:`Preview revoked: ${e}\n`,stderr:``,exitCode:0}}async function yje(){let e=k7();if(e){let t=(await e({type:`list`})).previews??[];return t.length===0?{stdout:`No active previews
9044
+ `}:(n.directory=e,{skip:0})}function gje(e){let t={entry:`index.html`,bridge:!1,noBridge:!1,project:!1,list:!1,quiet:!1};for(let n=0;n<e.length;n+=1){let r=hje(e[n],e[n+1],t);if(mje(r))return{...t,error:r.error};n+=r.skip}return t}async function _je(e,t,n,r){if(!GK(t))return{stdout:``,stderr:`serve: invalid entry file: ${t}\n`,exitCode:1};let i=n.resolvePath(r,e),a;try{a=await n.stat(i)}catch{return{stdout:``,stderr:`serve: no such directory: ${e}\n`,exitCode:1}}if(!a.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${e}\n`,exitCode:1};let o=KK(i,t),s;try{s=await n.stat(o)}catch{return{stdout:``,stderr:`serve: entry file not found: ${o}\n`,exitCode:1}}return s.isFile?{fullDirectory:i,entryPath:o}:{stdout:``,stderr:`serve: entry is not a file: ${o}\n`,exitCode:1}}function vje(e){return`exitCode`in e}async function yje(e){let t,n=k7();if(n)t=await n({type:`stop`,previewToken:e});else{let n=M();if(!n)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};t=await n.call(`tray-revoke-preview`,{previewToken:e})}if(!t.revoked)return{stdout:``,stderr:`serve: preview token not found or already revoked
9045
+ `,exitCode:1};if(t.webhookId){let n=await j7();if(!n)return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but the preview-bridge webhook could not be cleaned up (lick manager unavailable). It is a live endpoint — delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0};try{await n.deleteWebhook(t.webhookId)}catch(n){return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but webhook cleanup failed: ${n instanceof Error?n.message:String(n)}. Delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0}}}return{stdout:`Preview revoked: ${e}\n`,stderr:``,exitCode:0}}async function bje(){let e=k7();if(e){let t=(await e({type:`list`})).previews??[];return t.length===0?{stdout:`No active previews
9046
9046
  `,stderr:``,exitCode:0}:{stdout:`Active previews:\n${t.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}let t=M();if(!t)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};let n=(await t.call(`tray-list-previews`,void 0)).previews??[];return n.length===0?{stdout:`No active previews
9047
- `,stderr:``,exitCode:0}:{stdout:`Active previews:\n${n.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}function N7(e){return e().catch(e=>({stdout:``,stderr:`serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}))}async function bje(e){let t=uje();if(t)return t(e);let n=M();if(!n)throw Error("no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.");return n.call(`tray-open-preview`,e)}async function xje(e,t){if(t)return t.createPage(e);typeof window<`u`&&typeof window.open==`function`&&window.open(e,`_blank`,`noopener,noreferrer`)}async function Sje(e,t){if(!e)return{ok:!0};let n=await j7();if(!n)return{ok:!1,result:{stdout:``,stderr:`${t}serve: --bridge requires an active lick manager\n`,exitCode:1}};try{return{ok:!0,webhookId:(await n.createWebhook(`preview-bridge`)).id}}catch(e){return{ok:!1,result:{stdout:``,stderr:`${t}serve: webhook creation failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}}async function Cje(e,t,n,r,i,a){let o;try{o=await bje({entryPath:n,servedRoot:t,bridge:e.bridge,noBridge:e.noBridge,maxTabs:e.maxTabs,quiet:e.quiet,webhookId:r})}catch(e){if(r){let e=await j7();e&&await e.deleteWebhook(r).catch(()=>{})}return{stdout:``,stderr:`${i}serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let s=await xje(o.url,a),c=`${o.pushed} follower${o.pushed===1?``:`s`}`,l=s?` (targetId: ${s})`:``;return{stdout:`Preview URL: ${o.url}${l}\nPushed to ${c}\n`,stderr:i,exitCode:0}}async function wje(e,t,n){if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return M7();let r=hje(e);if(r.error)return{stdout:``,stderr:r.error,exitCode:1};if(r.stop){let e=r.stop;return await N7(()=>vje(e))}if(r.list)return await N7(()=>yje());if(!r.directory)return M7();let i=await gje(r.directory,r.entry,t.fs,t.cwd);if(_je(i))return i;let{fullDirectory:a,entryPath:o}=i,s=r.project?`serve: --project is obsolete; ignored (root-absolute paths work natively under unified preview)
9048
- `:``,c=await Sje(!r.noBridge&&r.bridge,s);return c.ok?Cje(r,a,o,c.webhookId,s,n):c.result}function Tje(e,t){return SA(`serve`,(t,n)=>wje(t,n,e))}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 Eje(e){return F7()[e]}function Dje(e,t){let n=F7();n[e]=t,I7(n)}function Oje(e){let t=F7();delete t[e],I7(t)}function kje(){return F7()}function Aje(){return{stdout:`usage: sprinkle <subcommand> [args]
9047
+ `,stderr:``,exitCode:0}:{stdout:`Active previews:\n${n.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}function N7(e){return e().catch(e=>({stdout:``,stderr:`serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}))}async function xje(e){let t=dje();if(t)return t(e);let n=M();if(!n)throw Error("no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.");return n.call(`tray-open-preview`,e)}async function Sje(e,t){if(t)return t.createPage(e);typeof window<`u`&&typeof window.open==`function`&&window.open(e,`_blank`,`noopener,noreferrer`)}async function Cje(e,t){if(!e)return{ok:!0};let n=await j7();if(!n)return{ok:!1,result:{stdout:``,stderr:`${t}serve: --bridge requires an active lick manager\n`,exitCode:1}};try{return{ok:!0,webhookId:(await n.createWebhook(`preview-bridge`)).id}}catch(e){return{ok:!1,result:{stdout:``,stderr:`${t}serve: webhook creation failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}}async function wje(e,t,n,r,i,a){let o;try{o=await xje({entryPath:n,servedRoot:t,bridge:e.bridge,noBridge:e.noBridge,maxTabs:e.maxTabs,quiet:e.quiet,webhookId:r})}catch(e){if(r){let e=await j7();e&&await e.deleteWebhook(r).catch(()=>{})}return{stdout:``,stderr:`${i}serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let s=await Sje(o.url,a),c=`${o.pushed} follower${o.pushed===1?``:`s`}`,l=s?` (targetId: ${s})`:``;return{stdout:`Preview URL: ${o.url}${l}\nPushed to ${c}\n`,stderr:i,exitCode:0}}async function Tje(e,t,n){if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return M7();let r=gje(e);if(r.error)return{stdout:``,stderr:r.error,exitCode:1};if(r.stop){let e=r.stop;return await N7(()=>yje(e))}if(r.list)return await N7(()=>bje());if(!r.directory)return M7();let i=await _je(r.directory,r.entry,t.fs,t.cwd);if(vje(i))return i;let{fullDirectory:a,entryPath:o}=i,s=r.project?`serve: --project is obsolete; ignored (root-absolute paths work natively under unified preview)
9048
+ `:``,c=await Cje(!r.noBridge&&r.bridge,s);return c.ok?wje(r,a,o,c.webhookId,s,n):c.result}function Eje(e,t){return SA(`serve`,(t,n)=>Tje(t,n,e))}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 Dje(e){return F7()[e]}function Oje(e,t){let n=F7();n[e]=t,I7(n)}function kje(e){let t=F7();delete t[e],I7(t)}function Aje(){return F7()}function jje(){return{stdout:`usage: sprinkle <subcommand> [args]
9049
9049
 
9050
9050
  list List available .shtml sprinkles
9051
9051
  open <name> Open a sprinkle by name
@@ -9059,26 +9059,26 @@ Examples:
9059
9059
  chat <html> Show inline HTML in chat (Tool UI)
9060
9060
  Use data-action="name" on buttons for callbacks
9061
9061
  Pipe HTML: echo "<div>...</div>" | sprinkle chat
9062
- `,stderr:``,exitCode:0}}function jje(){return globalThis.__slicc_sprinkleManager??null}async function Mje(e,t){let n=e.slice(1).join(` `);if(!n){let e=T1(t.stdin);e&&(n=e)}if(!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
9062
+ `,stderr:``,exitCode:0}}function Mje(){return globalThis.__slicc_sprinkleManager??null}async function Nje(e,t){let n=e.slice(1).join(` `);if(!n){let e=T1(t.stdin);e&&(n=e)}if(!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
9063
9063
  `,exitCode:1};let r=await d({html:n,onAction:async(e,t)=>({action:e,data:t})});return r===null?{stdout:``,stderr:`sprinkle chat: not in tool execution context
9064
9064
  `,exitCode:1}:{stdout:JSON.stringify(r)+`
9065
- `,stderr:``,exitCode:0}}async function Nje(e){await e.refresh();let t=e.available();if(t.length===0)return{stdout:`No .shtml sprinkles found.
9065
+ `,stderr:``,exitCode:0}}async function Pje(e){await e.refresh();let t=e.available();if(t.length===0)return{stdout:`No .shtml sprinkles found.
9066
9066
  `,stderr:``,exitCode:0};let n=new Set(e.opened());return{stdout:t.map(e=>{let t=n.has(e.name)?` [open]`:``;return` ${e.name}${t} ${e.title} (${e.path})`}).join(`
9067
9067
  `)+`
9068
- `,stderr:``,exitCode:0}}async function L7(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle open: name required
9069
- `,exitCode:1};try{return await e.open(n),{stdout:`Sprinkle "${n}" opened.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function Pje(e,t){let n=t[1];return n?(e.close(n),{stdout:`Sprinkle "${n}" closed.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`sprinkle close: name required
9070
- `,exitCode:1}}async function Fje(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle reload: name required
9071
- `,exitCode:1};try{return await e.reload(n),{stdout:`Sprinkle "${n}" reloaded.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle reload: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function Ije(e){await e.refresh();let t=e.available().length;return{stdout:`Found ${t} sprinkle${t===1?``:`s`}.\n`,stderr:``,exitCode:0}}function Lje(e){let t=e[1];if(!t){let e=kje(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
9068
+ `,stderr:``,exitCode:0}}async function Fje(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle open: name required
9069
+ `,exitCode:1};try{return await e.open(n),{stdout:`Sprinkle "${n}" opened.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function Ije(e,t){let n=t[1];return n?(e.close(n),{stdout:`Sprinkle "${n}" closed.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`sprinkle close: name required
9070
+ `,exitCode:1}}async function Lje(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle reload: name required
9071
+ `,exitCode:1};try{return await e.reload(n),{stdout:`Sprinkle "${n}" reloaded.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle reload: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function Rje(e){await e.refresh();let t=e.available().length;return{stdout:`Found ${t} sprinkle${t===1?``:`s`}.\n`,stderr:``,exitCode:0}}function zje(e){let t=e[1];if(!t){let e=Aje(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
9072
9072
  `,stderr:``,exitCode:0}:{stdout:`Sprinkle routes:
9073
9073
  `+t.map(([e,t])=>` ${e} -> ${t}`).join(`
9074
9074
  `)+`
9075
- `,stderr:``,exitCode:0}}if(e.includes(`--clear`))return Oje(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=Eje(t);return e?{stdout:`${t} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${t} -> cone (default)\n`,stderr:``,exitCode:0}}return Dje(t,r),{stdout:`Sprinkle "${t}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}function Rje(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle send: name required
9075
+ `,stderr:``,exitCode:0}}if(e.includes(`--clear`))return kje(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=Dje(t);return e?{stdout:`${t} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${t} -> cone (default)\n`,stderr:``,exitCode:0}}return Oje(t,r),{stdout:`Sprinkle "${t}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}function Bje(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle send: name required
9076
9076
  `,exitCode:1};let r=t.slice(2).join(` `);if(!r)return{stdout:``,stderr:`sprinkle send: JSON data required
9077
9077
  `,exitCode:1};let i;try{i=JSON.parse(r)}catch{return{stdout:``,stderr:`sprinkle send: invalid JSON
9078
- `,exitCode:1}}return e.sendToSprinkle(n,i),{stdout:`Data sent to sprinkle "${n}".\n`,stderr:``,exitCode:0}}function zje(){return SA(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return Aje();let n=e[0];if(n===`chat`)return Mje(e,t);let r=jje();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
9079
- `,exitCode:1};switch(n){case`list`:return Nje(r);case`open`:return L7(r,e);case`close`:return Pje(r,e);case`reload`:return Fje(r,e);case`refresh`:return Ije(r);case`route`:return Lje(e);case`send`:return Rje(r,e);default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function Bje(){return{stdout:`usage: sqlite3 [database] [sql]
9080
- `,stderr:``,exitCode:0}}function R7(e=`sqlite3`){return SA(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return Bje();let r=`:memory:`,i=t;t.length>0&&!t[0].startsWith(`-`)&&(r=t[0],i=t.slice(1));let a=i.join(` `).trim()||T1(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 XK(),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(`
9081
- `)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function Vje(e={}){let{broker:t,persistGrant:n,suppressNextGate:r}=e;return SA(`sudo`,async(e,i)=>{if(e.length===0)return{stdout:``,stderr:`sudo: usage: sudo <command> [args...]
9078
+ `,exitCode:1}}return e.sendToSprinkle(n,i),{stdout:`Data sent to sprinkle "${n}".\n`,stderr:``,exitCode:0}}function L7(){return SA(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return jje();let n=e[0];if(n===`chat`)return Nje(e,t);let r=Mje();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
9079
+ `,exitCode:1};switch(n){case`list`:return Pje(r);case`open`:return Fje(r,e);case`close`:return Ije(r,e);case`reload`:return Lje(r,e);case`refresh`:return Rje(r);case`route`:return zje(e);case`send`:return Bje(r,e);default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function Vje(){return{stdout:`usage: sqlite3 [database] [sql]
9080
+ `,stderr:``,exitCode:0}}function R7(e=`sqlite3`){return SA(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return Vje();let r=`:memory:`,i=t;t.length>0&&!t[0].startsWith(`-`)&&(r=t[0],i=t.slice(1));let a=i.join(` `).trim()||T1(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 XK(),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(`
9081
+ `)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function Hje(e={}){let{broker:t,persistGrant:n,suppressNextGate:r}=e;return SA(`sudo`,async(e,i)=>{if(e.length===0)return{stdout:``,stderr:`sudo: usage: sudo <command> [args...]
9082
9082
  `,exitCode:1};if(e[0]===`--help`||e[0]===`-h`)return{stdout:`usage: sudo <command> [args...]
9083
9083
 
9084
9084
  Request human approval to run <command> with elevation. If approved, the
@@ -9093,7 +9093,7 @@ Options:
9093
9093
  `,stderr:``,exitCode:0};if(!t)return{stdout:``,stderr:`sudo: command-level approval is not configured
9094
9094
  `,exitCode:1};if(!i.exec)return{stdout:``,stderr:`sudo: cannot dispatch inner command in this context
9095
9095
  `,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
9096
- `,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 Hje=`/**
9096
+ `,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 Uje=`/**
9097
9097
  * Standalone assertions - no dependency on test runner
9098
9098
  *
9099
9099
  * Each assertion:
@@ -9281,7 +9281,7 @@ function sameMembers(a, b) {
9281
9281
  }
9282
9282
 
9283
9283
  const slice = a => (isPrimitive(a) ? a : a.slice ? a.slice() : Object.assign({}, a))
9284
- `,Uje=`/**
9284
+ `,Wje=`/**
9285
9285
  * tst - minimal test runner
9286
9286
  *
9287
9287
  * - Standalone assertions (assert.js works anywhere)
@@ -9935,27 +9935,27 @@ Install:
9935
9935
  Then \`tsc --version\` and the transpile commands above. There is no
9936
9936
  bundled binary, no CDN fallback; a missing package exits non-zero
9937
9937
  with a clear \`ipk add\` hint.
9938
- `;function Wje(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 Gje(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 Kje(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 V7={target:`ES2022`,module:`ESNext`,moduleResolution:`Bundler`,esModuleInterop:!0,allowSyntheticDefaultImports:!0,isolatedModules:!0};async function qje(e,t,n){let r=await Kje(e,n);if(!r)return{compilerOptions:{...V7}};let i;try{i=await e.readFile(r)}catch{return{compilerOptions:{...V7}}}let{config:a,error:o}=t.parseConfigFileTextToJson(r,i);if(o||!a)return{compilerOptions:{...V7}};let s=a.compilerOptions??{};return{compilerOptions:{...V7,...s}}}function H7(e,t){let n=e.flattenDiagnosticMessageText(t.messageText,`
9939
- `);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 Jje(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 U7(e,t,n,r,i){let a=e.transpileModule(t,{compilerOptions:r,fileName:n,reportDiagnostics:i});return{outputText:a.outputText,diagnostics:a.diagnostics??[]}}function Yje(e,t,n,r){let{outputText:i,diagnostics:a}=U7(e,r,`<stdin>.ts`,n.compilerOptions,!0),o=a.map(t=>H7(e,t)),s=o.length>0?`${o.join(`
9940
- `)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function Xje(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}}Jje(e,a);let{outputText:s,diagnostics:c}=U7(e,o,a,i.compilerOptions,!0),l=[];for(let t of c)l.push(`${H7(e,t)}\n`);let u=c.length>0;if(r.noEmit)return{stderr:l.join(``),hadError:u};let d=t.fs.resolvePath(t.cwd,Gje(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 Zje(e,t){let n;try{n=Wje(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:B7,stderr:``,exitCode:0}};let r;try{r=await QK(z7(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 Qje(){return SA(`tsc`,async(e,t)=>{let n=await Zje(e,t);if(`done`in n)return n.done;let{parsed:r,ts:i}=n,a=await qje(t.fs,i,t.cwd);if(r.files.length===0){let e=T1(t.stdin);return e?Yje(i,r,a,e):{stdout:B7,stderr:``,exitCode:0}}let o=[],s=!1;for(let e of r.files){let n=await Xje(i,t,e,r,a);n.stderr&&o.push(n.stderr),n.hadError&&(s=!0)}return{stdout:``,stderr:o.join(``),exitCode:+!!s}})}const $je=[`**/*.test.{js,ts}`];function eMe(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:[...$je],reporter:n,showHelp:r}}function W7(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 W7(`${r}${e}${i}`))o.push(t);return o}function tMe(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 nMe(e,t,n){let r=n.flatMap(W7).map(tMe),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 G7=null;async function rMe(e){if(G7)return G7;let t={module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,esModuleInterop:!0,isolatedModules:!1};return G7=`
9938
+ `;function Gje(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 Kje(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 qje(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 V7={target:`ES2022`,module:`ESNext`,moduleResolution:`Bundler`,esModuleInterop:!0,allowSyntheticDefaultImports:!0,isolatedModules:!0};async function Jje(e,t,n){let r=await qje(e,n);if(!r)return{compilerOptions:{...V7}};let i;try{i=await e.readFile(r)}catch{return{compilerOptions:{...V7}}}let{config:a,error:o}=t.parseConfigFileTextToJson(r,i);if(o||!a)return{compilerOptions:{...V7}};let s=a.compilerOptions??{};return{compilerOptions:{...V7,...s}}}function H7(e,t){let n=e.flattenDiagnosticMessageText(t.messageText,`
9939
+ `);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 Yje(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 U7(e,t,n,r,i){let a=e.transpileModule(t,{compilerOptions:r,fileName:n,reportDiagnostics:i});return{outputText:a.outputText,diagnostics:a.diagnostics??[]}}function Xje(e,t,n,r){let{outputText:i,diagnostics:a}=U7(e,r,`<stdin>.ts`,n.compilerOptions,!0),o=a.map(t=>H7(e,t)),s=o.length>0?`${o.join(`
9940
+ `)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function Zje(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}}Yje(e,a);let{outputText:s,diagnostics:c}=U7(e,o,a,i.compilerOptions,!0),l=[];for(let t of c)l.push(`${H7(e,t)}\n`);let u=c.length>0;if(r.noEmit)return{stderr:l.join(``),hadError:u};let d=t.fs.resolvePath(t.cwd,Kje(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 Qje(e,t){let n;try{n=Gje(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:B7,stderr:``,exitCode:0}};let r;try{r=await QK(z7(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 $je(){return SA(`tsc`,async(e,t)=>{let n=await Qje(e,t);if(`done`in n)return n.done;let{parsed:r,ts:i}=n,a=await Jje(t.fs,i,t.cwd);if(r.files.length===0){let e=T1(t.stdin);return e?Xje(i,r,a,e):{stdout:B7,stderr:``,exitCode:0}}let o=[],s=!1;for(let e of r.files){let n=await Zje(i,t,e,r,a);n.stderr&&o.push(n.stderr),n.hadError&&(s=!0)}return{stdout:``,stderr:o.join(``),exitCode:+!!s}})}const eMe=[`**/*.test.{js,ts}`];function tMe(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:[...eMe],reporter:n,showHelp:r}}function W7(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 W7(`${r}${e}${i}`))o.push(t);return o}function nMe(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 rMe(e,t,n){let r=n.flatMap(W7).map(nMe),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 G7=null;async function iMe(e){if(G7)return G7;let t={module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,esModuleInterop:!0,isolatedModules:!1};return G7=`
9941
9941
  if (typeof process !== 'undefined' && !process.versions) {
9942
9942
  try { process.versions = { node: '20.0.0' }; } catch (_) { /* readonly process.versions is fine */ }
9943
9943
  }
9944
9944
  const __tst_assert_exports = (function () {
9945
9945
  const module = { exports: {} };
9946
9946
  const exports = module.exports;
9947
- ${e.transpileModule(Hje,{compilerOptions:t,fileName:`assert.js`}).outputText}
9947
+ ${e.transpileModule(Uje,{compilerOptions:t,fileName:`assert.js`}).outputText}
9948
9948
  return module.exports;
9949
9949
  })();
9950
9950
  const __tst_module_exports = (function () {
9951
9951
  const module = { exports: {} };
9952
9952
  const exports = module.exports;
9953
- ${e.transpileModule(Uje,{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"))`)}
9953
+ ${e.transpileModule(Wje,{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"))`)}
9954
9954
  return module.exports;
9955
9955
  })();
9956
9956
  const __tst = __tst_module_exports.default || __tst_module_exports;
9957
9957
  __tst.manual = true;
9958
- `.trim(),G7}function K7(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 iMe(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 aMe(e,t,n){let r=Qe(`${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 oMe(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 iMe(r)){if(!n.startsWith(`./`)&&!n.startsWith(`../`))continue;let r=await aMe(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 sMe(e,t,n,r,i,a){let o=r===`spec`?`pretty`:`tap`,s=[];for(let[e,t]of i.entries()){let n=K7(t,a.get(e)??new Map);s.push(`${JSON.stringify(e)}: function (module, exports, require) {\n${n}\n}`)}return`"use strict";
9958
+ `.trim(),G7}function K7(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 aMe(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 oMe(e,t,n){let r=Qe(`${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 sMe(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 aMe(r)){if(!n.startsWith(`./`)&&!n.startsWith(`../`))continue;let r=await oMe(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 cMe(e,t,n,r,i,a){let o=r===`spec`?`pretty`:`tap`,s=[];for(let[e,t]of i.entries()){let n=K7(t,a.get(e)??new Map);s.push(`${JSON.stringify(e)}: function (module, exports, require) {\n${n}\n}`)}return`"use strict";
9959
9959
  ${e}
9960
9960
  const __tstReq = (id) => {
9961
9961
  if (id === "tst") return __tst_module_exports;
@@ -9987,7 +9987,7 @@ const __state = await __tst.run({ format: ${JSON.stringify(o)} });
9987
9987
  await Promise.resolve();
9988
9988
  await new Promise((resolve) => setTimeout(resolve));
9989
9989
  if (__state && __state.failed && __state.failed.length > 0) process.exit(1);
9990
- `}const cMe={esModuleInterop:!0,allowJs:!0,isolatedModules:!1};function lMe(e){return{module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,...cMe}}async function uMe(e,t){let n;try{n=eMe(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
9990
+ `}const lMe={esModuleInterop:!0,allowJs:!0,isolatedModules:!1};function uMe(e){return{module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,...lMe}}async function dMe(e,t){let n;try{n=tMe(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
9991
9991
 
9992
9992
  Usage:
9993
9993
  test [options] [glob...]
@@ -10000,7 +10000,7 @@ Notes:
10000
10000
  - Default glob: **/*.test.{js,ts}, walked from the current cwd.
10001
10001
  - .ts files are transpiled via the bundled typescript package.
10002
10002
  - Each file runs in its own realm (same engine as 'node').
10003
- `,stderr:``,exitCode:0}};let r=await nMe(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 QK(z7(t))}catch(e){return{done:{stdout:``,stderr:`test: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}let a=await rMe(i);return{parsed:n,files:r,ts:i,harness:a,userOpts:lMe(i)}}function dMe(e){return e.includes(`# fail `)||/(^|\n)not ok /.test(e)}async function fMe(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 oMe(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 D1(sMe(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||dMe(f.stdout)}}function pMe(){return SA(`test`,async(e,t)=>{let n=await uMe(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 fMe(t,n,e,r);i+=s.stdout,a+=s.stderr,s.failed&&(o=!0)}return{stdout:i,stderr:a,exitCode:+!!o}})}const q7=`usage: theme <subcommand> [args]
10003
+ `,stderr:``,exitCode:0}};let r=await rMe(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 QK(z7(t))}catch(e){return{done:{stdout:``,stderr:`test: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}let a=await iMe(i);return{parsed:n,files:r,ts:i,harness:a,userOpts:uMe(i)}}function fMe(e){return e.includes(`# fail `)||/(^|\n)not ok /.test(e)}async function pMe(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 sMe(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 D1(cMe(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||fMe(f.stdout)}}function mMe(){return SA(`test`,async(e,t)=>{let n=await dMe(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 pMe(t,n,e,r);i+=s.stdout,a+=s.stderr,s.failed&&(o=!0)}return{stdout:i,stderr:a,exitCode:+!!o}})}const q7=`usage: theme <subcommand> [args]
10004
10004
 
10005
10005
  Subcommands:
10006
10006
  list List available preset and custom themes
@@ -10009,21 +10009,21 @@ Subcommands:
10009
10009
  reset Reset to the default theme
10010
10010
  current Show the currently active theme
10011
10011
  export <id> <path> Export a theme to a VFS path
10012
- `;function mMe(){return SA(`theme`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:q7,stderr:``,exitCode:0};let n=e[0];return n===`list`?hMe():n===`current`?gMe():n===`reset`?_Me():n===`apply`?vMe(e.slice(1),t):n===`export`?yMe(e.slice(1),t):{stdout:``,stderr:`theme: unknown subcommand "${n}"\n${q7}`,exitCode:1}})}async function hMe(){let{PRESETS:e}=await import(`./theme-presets-xiOb9AFN.js`),t=[`Presets:`];for(let n of e)t.push(` ${n.id.padEnd(16)} ${n.name}`);return t.push(``),{stdout:t.join(`
10013
- `),stderr:``,exitCode:0}}async function gMe(){return{stdout:`Check the Theme settings dialog for the active theme.
10014
- `,stderr:``,exitCode:0}}async function _Me(){let e=M();return e?(await e.call(`theme-apply`,{action:`reset`}),{stdout:`Theme reset to default.
10012
+ `;function hMe(){return SA(`theme`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:q7,stderr:``,exitCode:0};let n=e[0];return n===`list`?gMe():n===`current`?_Me():n===`reset`?vMe():n===`apply`?yMe(e.slice(1),t):n===`export`?bMe(e.slice(1),t):{stdout:``,stderr:`theme: unknown subcommand "${n}"\n${q7}`,exitCode:1}})}async function gMe(){let{PRESETS:e}=await import(`./theme-presets-xiOb9AFN.js`),t=[`Presets:`];for(let n of e)t.push(` ${n.id.padEnd(16)} ${n.name}`);return t.push(``),{stdout:t.join(`
10013
+ `),stderr:``,exitCode:0}}async function _Me(){return{stdout:`Check the Theme settings dialog for the active theme.
10014
+ `,stderr:``,exitCode:0}}async function vMe(){let e=M();return e?(await e.call(`theme-apply`,{action:`reset`}),{stdout:`Theme reset to default.
10015
10015
  `,stderr:``,exitCode:0}):{stdout:``,stderr:`theme: no panel-RPC connection available
10016
- `,exitCode:1}}async function vMe(e,t){if(e.length===0)return{stdout:``,stderr:`theme apply: missing theme id or path
10016
+ `,exitCode:1}}async function yMe(e,t){if(e.length===0)return{stdout:``,stderr:`theme apply: missing theme id or path
10017
10017
  `,exitCode:1};let n=M();if(!n)return{stdout:``,stderr:`theme: no panel-RPC connection available
10018
10018
  `,exitCode:1};let r=e[0],{PRESETS:i}=await import(`./theme-presets-xiOb9AFN.js`),a=i.find(e=>e.id===r);if(a){let e=JSON.stringify(a);return await n.call(`theme-apply`,{themeJson:e,action:`apply`}),{stdout:`Applied theme: ${a.name}\n`,stderr:``,exitCode:0}}let o=t.fs.resolvePath(t.cwd,r),s;try{s=await t.fs.readFile(o)}catch{return{stdout:``,stderr:`theme apply: "${r}" is not a known preset id and file not found at ${o}\n`,exitCode:1}}try{let e=JSON.parse(s);if(!e.id||!e.name||!e.base||!e.tokens)return{stdout:``,stderr:`theme apply: invalid theme file (missing id, name, base, or tokens)
10019
10019
  `,exitCode:1}}catch{return{stdout:``,stderr:`theme apply: file is not valid JSON
10020
- `,exitCode:1}}return{stdout:`Applied theme: ${(await n.call(`theme-apply`,{themeJson:s,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function yMe(e,t){if(e.length<2)return{stdout:``,stderr:`theme export: usage: theme export <id> <path>
10021
- `,exitCode:1};let[n,r]=e,{PRESETS:i}=await import(`./theme-presets-xiOb9AFN.js`),a=i.find(e=>e.id===n);if(!a)return{stdout:``,stderr:`theme export: unknown preset id "${n}"\n`,exitCode:1};let o=t.fs.resolvePath(t.cwd,r);try{await t.fs.writeFile(o,JSON.stringify(a,null,2))}catch(e){return{stdout:``,stderr:`theme export: write failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return{stdout:`Exported "${a.name}" to ${o}\n`,stderr:``,exitCode:0}}function bMe(){return{stdout:`usage: uname
10022
- `,stderr:``,exitCode:0}}function xMe(){return SA(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return bMe();if(e.length>0)return{stdout:``,stderr:`uname: unsupported arguments
10020
+ `,exitCode:1}}return{stdout:`Applied theme: ${(await n.call(`theme-apply`,{themeJson:s,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function bMe(e,t){if(e.length<2)return{stdout:``,stderr:`theme export: usage: theme export <id> <path>
10021
+ `,exitCode:1};let[n,r]=e,{PRESETS:i}=await import(`./theme-presets-xiOb9AFN.js`),a=i.find(e=>e.id===n);if(!a)return{stdout:``,stderr:`theme export: unknown preset id "${n}"\n`,exitCode:1};let o=t.fs.resolvePath(t.cwd,r);try{await t.fs.writeFile(o,JSON.stringify(a,null,2))}catch(e){return{stdout:``,stderr:`theme export: write failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return{stdout:`Exported "${a.name}" to ${o}\n`,stderr:``,exitCode:0}}function xMe(){return{stdout:`usage: uname
10022
+ `,stderr:``,exitCode:0}}function SMe(){return SA(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return xMe();if(e.length>0)return{stdout:``,stderr:`uname: unsupported arguments
10023
10023
  `,exitCode:1};let t=globalThis.navigator?.userAgent;return typeof t!=`string`||t.length===0?{stdout:``,stderr:`uname: navigator.userAgent is unavailable
10024
- `,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function SMe(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
10025
- `,stderr:``,exitCode:0}}function CMe(){return SA(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return SMe();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
10026
- `,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=jF(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 wMe=new Set([`--vid`,`--pid`,`--class`,`--subclass`,`--protocol`,`--serial`,`--request-type`,`--recipient`,`--request`,`--value`,`--index`,`--__resolved`]);function TMe(e){return qV(e,wMe)}function J7(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 EMe(e){let t={};return e.has(`--vid`)&&(t.vendorId=J7(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=J7(e.get(`--pid`),`pid`)),e.has(`--class`)&&(t.classCode=J7(e.get(`--class`),`class`)),e.has(`--subclass`)&&(t.subclassCode=J7(e.get(`--subclass`),`subclass`)),e.has(`--protocol`)&&(t.protocolCode=J7(e.get(`--protocol`),`protocol`)),e.has(`--serial`)&&(t.serialNumber=e.get(`--serial`)),Object.keys(t).length>0?[t]:[]}const DMe=new Set([`standard`,`class`,`vendor`]),OMe=new Set([`device`,`interface`,`endpoint`,`other`]);function Y7(e){let t=e.get(`--request-type`)??`vendor`,n=e.get(`--recipient`)??`device`;if(!DMe.has(t))throw Error(`invalid --request-type: '${t}'`);if(!OMe.has(n))throw Error(`invalid --recipient: '${n}'`);return{requestType:t,recipient:n,request:J7(e.get(`--request`)??`0`,`request`),value:J7(e.get(`--value`)??`0`,`value`),index:J7(e.get(`--index`)??`0`,`index`)}}function X7(e){let t=E1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function kMe(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function Z7(e){return`0x${e.toString(16).padStart(4,`0`)}`}function Q7(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${Z7(e.vendorId)}:${Z7(e.productId)}\t${t}${n}${r}`}function $7(e){return{stdout:e,stderr:``,exitCode:0}}function e9(e){return{stdout:``,stderr:`usb: ${e}\n`,exitCode:1}}const AMe=`usb - access USB devices via WebUSB
10024
+ `,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function CMe(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
10025
+ `,stderr:``,exitCode:0}}function wMe(){return SA(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return CMe();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
10026
+ `,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=jF(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 TMe=new Set([`--vid`,`--pid`,`--class`,`--subclass`,`--protocol`,`--serial`,`--request-type`,`--recipient`,`--request`,`--value`,`--index`,`--__resolved`]);function EMe(e){return qV(e,TMe)}function J7(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 DMe(e){let t={};return e.has(`--vid`)&&(t.vendorId=J7(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=J7(e.get(`--pid`),`pid`)),e.has(`--class`)&&(t.classCode=J7(e.get(`--class`),`class`)),e.has(`--subclass`)&&(t.subclassCode=J7(e.get(`--subclass`),`subclass`)),e.has(`--protocol`)&&(t.protocolCode=J7(e.get(`--protocol`),`protocol`)),e.has(`--serial`)&&(t.serialNumber=e.get(`--serial`)),Object.keys(t).length>0?[t]:[]}const OMe=new Set([`standard`,`class`,`vendor`]),kMe=new Set([`device`,`interface`,`endpoint`,`other`]);function Y7(e){let t=e.get(`--request-type`)??`vendor`,n=e.get(`--recipient`)??`device`;if(!OMe.has(t))throw Error(`invalid --request-type: '${t}'`);if(!kMe.has(n))throw Error(`invalid --recipient: '${n}'`);return{requestType:t,recipient:n,request:J7(e.get(`--request`)??`0`,`request`),value:J7(e.get(`--value`)??`0`,`value`),index:J7(e.get(`--index`)??`0`,`index`)}}function X7(e){let t=E1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function AMe(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function Z7(e){return`0x${e.toString(16).padStart(4,`0`)}`}function Q7(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${Z7(e.vendorId)}:${Z7(e.productId)}\t${t}${n}${r}`}function $7(e){return{stdout:e,stderr:``,exitCode:0}}function e9(e){return{stdout:``,stderr:`usb: ${e}\n`,exitCode:1}}const jMe=`usb - access USB devices via WebUSB
10027
10027
 
10028
10028
  Usage: usb <subcommand> [options]
10029
10029
 
@@ -10052,9 +10052,9 @@ Options:
10052
10052
  -h, --help
10053
10053
 
10054
10054
  Transfers are capped at ${c1} bytes (4 MiB).
10055
- `;function t9(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return $7(t)}return $7(e.length?`${kMe(e)}\n`:``)}async function jMe(e){let t=await e.list();return t.length===0?$7(`no granted USB devices
10055
+ `;function t9(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return $7(t)}return $7(e.length?`${AMe(e)}\n`:``)}async function MMe(e){let t=await e.list();return t.length===0?$7(`no granted USB devices
10056
10056
  `):$7(`${t.map(Q7).join(`
10057
- `)}\n`)}async function MMe(e,t){let n=e.get(`--__resolved`);if(n)return $7(`${Q7(await t.info(n))}\n`);let r=EMe(e),i=u();if(i){let e=await g(`usb-device`,r,i);if(e.handle)return $7(`${Q7(await t.info(e.handle))}\n`);let n=e.info,a=a1();if(!a)return e9(`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?$7(`${Q7(l1(s1().register(o),o))}\n`):e9(`request: granted device could not be re-acquired`)}return $7(`${Q7(await t.request(r))}\n`)}async function NMe(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),$7(``)):e9(`${e}: handle required`)}async function PMe(e,t){let[,n,r]=e;return!n||r===void 0?e9(`select-config: handle and value required`):(await t.selectConfig(n,J7(r,`configuration`)),$7(``))}async function FMe(e,t,n){let[,r,i]=t;return!r||i===void 0?e9(`${e}: handle and interface required`):(await(e===`claim`?n.claim:n.release).call(n,r,J7(i,`interface`)),$7(``))}async function IMe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return e9(`control-in: handle and length required`);let o=J7(a,`length`);return o>4194304?e9(`control-in length exceeds 4 MiB limit`):t9((await n.controlIn(i,Y7(t),o)).bytes,r)}async function LMe(e,t,n,r){let i=e[1];if(!i)return e9(`control-out: handle required`);let a=X7(t);return a.length>4194304?e9(`control-out payload exceeds 4 MiB limit`):$7(`${(await r.controlOut(i,Y7(n),a)).bytesWritten} bytes written\n`)}async function RMe(e,t,n,r){let[,i,a,o]=e;if(!i||a===void 0||o===void 0)return e9(`transfer-in: handle, endpoint and length required`);let s=J7(o,`length`);return s>4194304?e9(`transfer-in length exceeds 4 MiB limit`):t9((await n.transferIn(i,J7(a,`endpoint`),s)).bytes,r)}async function zMe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return e9(`transfer-out: handle and endpoint required`);let o=X7(t);return o.length>4194304?e9(`transfer-out payload exceeds 4 MiB limit`):$7(`${(await r.transferOut(i,J7(a,`endpoint`),o)).bytesWritten} bytes written\n`)}async function BMe(e,t,n){let{positionals:r,flags:i,bools:a}=TMe(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return jMe(n);case`request`:return MMe(i,n);case`open`:case`close`:case`reset`:return NMe(o,r,n);case`select-config`:return PMe(r,n);case`claim`:case`release`:return FMe(o,r,n);case`control-in`:return IMe(r,i,n,s);case`control-out`:return LMe(r,t,i,n);case`transfer-in`:return RMe(r,i,n,s);case`transfer-out`:return zMe(r,t,i,n);default:return e9(`unknown subcommand '${o??``}'. Try 'usb --help'.`)}}function VMe(){return SA(`usb`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return $7(AMe);let n=h1(fe(),M());if(!n)return e9(`WebUSB is unavailable in this environment`);try{return await BMe(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?e9(`user cancelled or no device selected`):e9(t)}})}function HMe(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function n9(e,t){return`${new URL(e).origin}/webhooks/${t}`}function r9(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function UMe(){return{stdout:`usage: webhook <command> [options]
10057
+ `)}\n`)}async function NMe(e,t){let n=e.get(`--__resolved`);if(n)return $7(`${Q7(await t.info(n))}\n`);let r=DMe(e),i=u();if(i){let e=await g(`usb-device`,r,i);if(e.handle)return $7(`${Q7(await t.info(e.handle))}\n`);let n=e.info,a=a1();if(!a)return e9(`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?$7(`${Q7(l1(s1().register(o),o))}\n`):e9(`request: granted device could not be re-acquired`)}return $7(`${Q7(await t.request(r))}\n`)}async function PMe(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),$7(``)):e9(`${e}: handle required`)}async function FMe(e,t){let[,n,r]=e;return!n||r===void 0?e9(`select-config: handle and value required`):(await t.selectConfig(n,J7(r,`configuration`)),$7(``))}async function IMe(e,t,n){let[,r,i]=t;return!r||i===void 0?e9(`${e}: handle and interface required`):(await(e===`claim`?n.claim:n.release).call(n,r,J7(i,`interface`)),$7(``))}async function LMe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return e9(`control-in: handle and length required`);let o=J7(a,`length`);return o>4194304?e9(`control-in length exceeds 4 MiB limit`):t9((await n.controlIn(i,Y7(t),o)).bytes,r)}async function RMe(e,t,n,r){let i=e[1];if(!i)return e9(`control-out: handle required`);let a=X7(t);return a.length>4194304?e9(`control-out payload exceeds 4 MiB limit`):$7(`${(await r.controlOut(i,Y7(n),a)).bytesWritten} bytes written\n`)}async function zMe(e,t,n,r){let[,i,a,o]=e;if(!i||a===void 0||o===void 0)return e9(`transfer-in: handle, endpoint and length required`);let s=J7(o,`length`);return s>4194304?e9(`transfer-in length exceeds 4 MiB limit`):t9((await n.transferIn(i,J7(a,`endpoint`),s)).bytes,r)}async function BMe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return e9(`transfer-out: handle and endpoint required`);let o=X7(t);return o.length>4194304?e9(`transfer-out payload exceeds 4 MiB limit`):$7(`${(await r.transferOut(i,J7(a,`endpoint`),o)).bytesWritten} bytes written\n`)}async function VMe(e,t,n){let{positionals:r,flags:i,bools:a}=EMe(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return MMe(n);case`request`:return NMe(i,n);case`open`:case`close`:case`reset`:return PMe(o,r,n);case`select-config`:return FMe(r,n);case`claim`:case`release`:return IMe(o,r,n);case`control-in`:return LMe(r,i,n,s);case`control-out`:return RMe(r,t,i,n);case`transfer-in`:return zMe(r,i,n,s);case`transfer-out`:return BMe(r,t,i,n);default:return e9(`unknown subcommand '${o??``}'. Try 'usb --help'.`)}}function HMe(){return SA(`usb`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return $7(jMe);let n=h1(fe(),M());if(!n)return e9(`WebUSB is unavailable in this environment`);try{return await VMe(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?e9(`user cancelled or no device selected`):e9(t)}})}function UMe(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function n9(e,t){return`${new URL(e).origin}/webhooks/${t}`}function r9(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function WMe(){return{stdout:`usage: webhook <command> [options]
10058
10058
 
10059
10059
  Commands:
10060
10060
  create --scoop <name> [--name <name>] [--filter <code>] Create a new webhook endpoint
@@ -10072,16 +10072,16 @@ Examples:
10072
10072
  webhook create --scoop slack-relay --name slack --filter "(e) => ({ text: e.body.text, user: e.body.user })"
10073
10073
  webhook list
10074
10074
  webhook delete abc123
10075
- `,stderr:``,exitCode:0}}function WMe(){return globalThis.__slicc_lickManager??null}async function i9(){if(WMe())return zn().session?.webhookUrl??null;let{getTrayWebhookUrlAsync:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return await e()}function a9(e,t){return t?r9(t,e):ge()?n9(self.location.href,e):`(URL unavailable — connect a leader tray)`}function o9(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}async function GMe(e){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)
10075
+ `,stderr:``,exitCode:0}}function GMe(){return globalThis.__slicc_lickManager??null}async function i9(){if(GMe())return zn().session?.webhookUrl??null;let{getTrayWebhookUrlAsync:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return await e()}function a9(e,t){return t?r9(t,e):ge()?n9(self.location.href,e):`(URL unavailable — connect a leader tray)`}function o9(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}async function KMe(e){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)
10076
10076
  `,exitCode:1};if(!ge()&&n)return{stdout:``,stderr:`webhook create: --filter is not supported in extension mode (CSP forbids dynamic eval) — drop --filter, or use standalone CLI mode
10077
- `,exitCode:1};let s=await JMe();if(s)return s;let c=await j7();if(!c)return o9(`create`);let l=await c.createWebhook(t,r,n),u=await YMe(l.id),d=`Created webhook "${l.name}"\nID: ${l.id}\nURL: ${u}\n`;return l.scoop&&(d+=`Scoop: ${l.scoop}\n`),l.filter&&(d+=`Filter: ${l.filter}\n`),{stdout:d,stderr:``,exitCode:0}}async function KMe(){let e=await j7();if(!e)return o9(`list`);let t=await e.listWebhooks();if(t.length===0)return{stdout:`No active webhooks
10078
- `,stderr:``,exitCode:0};let{trayUrlBase:n,urlResolutionError:r}=await XMe();return{stdout:ZMe(t.map(e=>({id:e.id,name:e.name,url:a9(e.id,n),createdAt:e.createdAt,filter:e.filter,scoop:e.scoop})),n,r),stderr:``,exitCode:0}}async function qMe(e){let t=e[1];if(!t)return{stdout:``,stderr:`webhook delete: requires an ID
10079
- `,exitCode:1};let n=await j7();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}:o9(`delete`)}async function JMe(){if(ge())return null;if(!await i9()){let e=zn().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}")`)+`
10080
- `,exitCode:1}}return null}async function YMe(e){try{return a9(e,await i9())}catch(e){return`(URL resolution failed: ${e instanceof Error?e.message:String(e)})`}}async function XMe(){try{return{trayUrlBase:await i9(),urlResolutionError:null}}catch(e){return{trayUrlBase:null,urlResolutionError:e instanceof Error?e.message:String(e)}}}function ZMe(e,t,n){let r=`Active webhooks:
10077
+ `,exitCode:1};let s=await YMe();if(s)return s;let c=await j7();if(!c)return o9(`create`);let l=await c.createWebhook(t,r,n),u=await XMe(l.id),d=`Created webhook "${l.name}"\nID: ${l.id}\nURL: ${u}\n`;return l.scoop&&(d+=`Scoop: ${l.scoop}\n`),l.filter&&(d+=`Filter: ${l.filter}\n`),{stdout:d,stderr:``,exitCode:0}}async function qMe(){let e=await j7();if(!e)return o9(`list`);let t=await e.listWebhooks();if(t.length===0)return{stdout:`No active webhooks
10078
+ `,stderr:``,exitCode:0};let{trayUrlBase:n,urlResolutionError:r}=await ZMe();return{stdout:QMe(t.map(e=>({id:e.id,name:e.name,url:a9(e.id,n),createdAt:e.createdAt,filter:e.filter,scoop:e.scoop})),n,r),stderr:``,exitCode:0}}async function JMe(e){let t=e[1];if(!t)return{stdout:``,stderr:`webhook delete: requires an ID
10079
+ `,exitCode:1};let n=await j7();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}:o9(`delete`)}async function YMe(){if(ge())return null;if(!await i9()){let e=zn().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}")`)+`
10080
+ `,exitCode:1}}return null}async function XMe(e){try{return a9(e,await i9())}catch(e){return`(URL resolution failed: ${e instanceof Error?e.message:String(e)})`}}async function ZMe(){try{return{trayUrlBase:await i9(),urlResolutionError:null}}catch(e){return{trayUrlBase:null,urlResolutionError:e instanceof Error?e.message:String(e)}}}function QMe(e,t,n){let r=`Active webhooks:
10081
10081
  `;for(let t of e)r+=` ${t.id} ${t.name.padEnd(20)} ${t.url}`,t.scoop&&(r+=` -> ${t.scoop}`),t.filter&&(r+=` [filtered]`),r+=`
10082
10082
  `;return n?r+=`\nNote: webhook URL resolution failed (${n}). Try again once the tray is connected.\n`:!ge()&&!t&&(r+=`
10083
10083
  Note: webhook URLs require a leader tray. Configure one in Settings to expose POST endpoints.
10084
- `),r}function QMe(){return SA(`webhook`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return UMe();let t=e[0];try{switch(t){case`create`:return await GMe(e);case`list`:return await KMe();case`delete`:return await qMe(e);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 $Me(){return{stdout:`usage: websocat [FLAGS] [OPTIONS] <ws://URL | wss://URL>
10084
+ `),r}function $Me(){return SA(`webhook`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return WMe();let t=e[0];try{switch(t){case`create`:return await KMe(e);case`list`:return await qMe();case`delete`:return await JMe(e);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 eNe(){return{stdout:`usage: websocat [FLAGS] [OPTIONS] <ws://URL | wss://URL>
10085
10085
 
10086
10086
  Minimal websocat client. Sends stdin lines as WebSocket messages and prints
10087
10087
  received messages to stdout. Server mode and advanced specifiers (exec:, tcp:,
@@ -10123,19 +10123,19 @@ EXAMPLES:
10123
10123
  echo 'Page.navigate {"url":"https://example.com"}' \\
10124
10124
  | websocat -1 --jsonrpc --jsonrpc-omit-jsonrpc \\
10125
10125
  ws://127.0.0.1:9222/devtools/page/<id>
10126
- `,stderr:``,exitCode:0}}const s9=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 eNe(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(s9.has(i)||s9.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
10126
+ `,stderr:``,exitCode:0}}const s9=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 tNe(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(s9.has(i)||s9.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
10127
10127
  `,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
10128
10128
  `,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
10129
10129
  `,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)
10130
- `),t}function tNe(e,t){if(!e)return[];let n=t?`\0`:`
10131
- `,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function nNe(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 c9(e){let t=``;for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t)}function rNe(e){try{return new TextDecoder(`utf-8`,{fatal:!1}).decode(e)}catch{return c9(e)}}async function iNe(e,t,n={}){let r=eNe(e);if(r.showHelp)return $Me();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)
10130
+ `),t}function nNe(e,t){if(!e)return[];let n=t?`\0`:`
10131
+ `,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function rNe(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 c9(e){let t=``;for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t)}function iNe(e){try{return new TextDecoder(`utf-8`,{fatal:!1}).decode(e)}catch{return c9(e)}}async function aNe(e,t,n={}){let r=tNe(e);if(r.showHelp)return eNe();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)
10132
10132
  `,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
10133
10133
  `,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`:`
10134
- `,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?c9(t):rNe(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(`
10134
+ `,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?c9(t):iNe(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(`
10135
10135
  `)+`
10136
- `,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=tNe(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=nNe(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(`
10136
+ `,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=nNe(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=rNe(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(`
10137
10137
  `)+`
10138
- `:``,exitCode:E}}function aNe(){return SA(`websocat`,async(e,t)=>iNe(e,{stdin:T1(t.stdin)}))}function oNe(){return SA(`__wf_progress`,async()=>({stdout:``,stderr:``,exitCode:0}))}async function sNe(e){return e.scriptCatalog?e.scriptCatalog.getJshCommands():e.fs?A1(e.fs):new Map}async function cNe(e){return e.scriptCatalog?e.scriptCatalog.getWorkflowCommands():e.fs?L1(e.fs):new Map}function lNe(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 uNe(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return SA(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
10138
+ `:``,exitCode:E}}function oNe(){return SA(`websocat`,async(e,t)=>aNe(e,{stdin:T1(t.stdin)}))}function sNe(){return SA(`__wf_progress`,async()=>({stdout:``,stderr:``,exitCode:0}))}async function cNe(e){return e.scriptCatalog?e.scriptCatalog.getJshCommands():e.fs?A1(e.fs):new Map}async function lNe(e){return e.scriptCatalog?e.scriptCatalog.getWorkflowCommands():e.fs?L1(e.fs):new Map}function uNe(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 dNe(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return SA(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
10139
10139
 
10140
10140
  Usage: which <command> [command...]
10141
10141
 
@@ -10145,9 +10145,9 @@ Prints the path of the given command(s).
10145
10145
 
10146
10146
  Exit code 0 if all commands found, 1 if any not found.
10147
10147
  `,stderr:``,exitCode:0};if(e.length===0)return{stdout:``,stderr:`which: missing argument
10148
- `,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=await sNe(t),o=await cNe(t),s=typeof t.getStaticBuiltins==`function`?new Set(t.getStaticBuiltins()):i,c=[],l=!0;for(let t of e){let e=lNe(t,a.get(t),o.get(t),s,i);c.push(...e.lines),e.found||(l=!1)}return{stdout:c.length>0?c.join(`
10148
+ `,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=await cNe(t),o=await lNe(t),s=typeof t.getStaticBuiltins==`function`?new Set(t.getStaticBuiltins()):i,c=[],l=!0;for(let t of e){let e=uNe(t,a.get(t),o.get(t),s,i);c.push(...e.lines),e.found||(l=!1)}return{stdout:c.length>0?c.join(`
10149
10149
  `)+`
10150
- `:``,stderr:``,exitCode:+!l}})}const l9=i(`workflow-run-manager`),u9=`__slicc_workflows`,d9=`/shared/workflow-runs`,f9=1e3;function dNe(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){l9.warn(`observeRun handler threw`,e)}},i=t=>t===void 0?`terminal`:t===e.getConeJid()?`cone`:`scoop`,a=(e,n)=>gNe(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),mNe(t,n);let f=a(o.ctx,l),p=hNe(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=>l9.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=`${d9}/${n}.json`,l=new Date().toISOString();try{await e.sharedFs.mkdir(d9,{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);l9.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`?pNe(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){l9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function fNe(e){let t=dNe(e);return globalThis[u9]=t,l9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function pNe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function mNe(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 hNe(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 gNe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?_Ne(n,t,a?.args??[],r):e===`agent`?vNe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function _Ne(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>f9&&i.logs.splice(0,i.logs.length-f9),r()}return{stdout:``,stderr:``,exitCode:0}}async function vNe(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 yNe=String.raw`
10150
+ `:``,stderr:``,exitCode:+!l}})}const l9=i(`workflow-run-manager`),u9=`__slicc_workflows`,d9=`/shared/workflow-runs`,f9=1e3;function fNe(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){l9.warn(`observeRun handler threw`,e)}},i=t=>t===void 0?`terminal`:t===e.getConeJid()?`cone`:`scoop`,a=(e,n)=>_Ne(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),hNe(t,n);let f=a(o.ctx,l),p=gNe(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=>l9.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=`${d9}/${n}.json`,l=new Date().toISOString();try{await e.sharedFs.mkdir(d9,{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);l9.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`?mNe(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){l9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function pNe(e){let t=fNe(e);return globalThis[u9]=t,l9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function mNe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function hNe(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 gNe(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 _Ne(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?vNe(n,t,a?.args??[],r):e===`agent`?yNe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function vNe(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>f9&&i.logs.splice(0,i.logs.length-f9),r()}return{stdout:``,stderr:``,exitCode:0}}async function yNe(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 bNe=String.raw`
10151
10151
  class WorkflowError extends Error {}
10152
10152
  class WorkflowDeterminismError extends WorkflowError {}
10153
10153
  class WorkflowAgentCapError extends WorkflowError {}
@@ -10257,11 +10257,11 @@ function log(message) {
10257
10257
  }
10258
10258
  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()); } };
10259
10259
  function workflow() { throw new WorkflowNestingUnsupportedError('nested workflow() unsupported in SP1'); }
10260
- `;function p9(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function bNe(e){let t=CNe(e);return t===null?{name:null,description:null}:{name:h9(t,`name`),description:h9(t,`description`)}}function xNe(e){return e.replace(/\bexport\s+(const|let|var|function|async\s+function|class)\b/g,`$1`)}function SNe(e){return`const __emit = console.log.bind(console);
10260
+ `;function p9(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function xNe(e){let t=wNe(e);return t===null?{name:null,description:null}:{name:h9(t,`name`),description:h9(t,`description`)}}function SNe(e){return e.replace(/\bexport\s+(const|let|var|function|async\s+function|class)\b/g,`$1`)}function CNe(e){return`const __emit = console.log.bind(console);
10261
10261
  const __stringify = JSON.stringify.bind(JSON);
10262
- const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${xNe(e.body)}\n})();\n__emit(${JSON.stringify(e.sentinel)} + __stringify(__r ?? null));\n`}function m9(e,t){let n=e.split(`
10262
+ const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${SNe(e.body)}\n})();\n__emit(${JSON.stringify(e.sentinel)} + __stringify(__r ?? null));\n`}function m9(e,t){let n=e.split(`
10263
10263
  `);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(`
10264
- `).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 CNe(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 h9(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1`).exec(e);return n?n[2]:null}const g9=i(`workflow-command`);function _9(){return globalThis[u9]}function wNe(){let e=globalThis.navigator?.hardwareConcurrency??8;return Math.min(16,Math.max(8,e*4))}function TNe(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 ENe(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=wNe(),n={budget:null,cap:Math.min(8,t)};for(let r=1;r<e.length;r++){let i=TNe(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 DNe(e={}){return SA(`workflow`,async(t,n)=>{if(t[0]===`list`||t[0]===`status`||t[0]===`stop`)return MNe(t,n);if(t[0]===`save`)return jNe(t,n,e);let r=ENe(t);if(r.help)return{stdout:`usage: workflow run <file.js> [--args <json>] [--budget <n>] [--concurrency <n>] [--wait]
10264
+ `).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 wNe(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 h9(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1`).exec(e);return n?n[2]:null}const g9=i(`workflow-command`);function _9(){return globalThis[u9]}function TNe(){let e=globalThis.navigator?.hardwareConcurrency??8;return Math.min(16,Math.max(8,e*4))}function ENe(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 DNe(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=TNe(),n={budget:null,cap:Math.min(8,t)};for(let r=1;r<e.length;r++){let i=ENe(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 ONe(e={}){return SA(`workflow`,async(t,n)=>{if(t[0]===`list`||t[0]===`status`||t[0]===`stop`)return NNe(t,n);if(t[0]===`save`)return MNe(t,n,e);let r=DNe(t);if(r.help)return{stdout:`usage: workflow run <file.js> [--args <json>] [--budget <n>] [--concurrency <n>] [--wait]
10265
10265
  workflow run --script '<inline js>' [...]
10266
10266
  workflow list
10267
10267
  workflow status <runId>
@@ -10270,26 +10270,26 @@ const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (asyn
10270
10270
  Runs a Claude-Code-format dynamic workflow. Default is non-blocking (returns a run id);
10271
10271
  pass --wait to block and print the full result.
10272
10272
  `,stderr:``,exitCode:0};if(r.error)return{stdout:``,stderr:r.error+`
10273
- `,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=bNe(i);if(!o.name)return{stdout:``,stderr:`workflow: script must define a meta block with a name (description optional)
10274
- `,exitCode:1};let s=p9().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=p9(),u=SNe({prelude:yNe,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?ONe(u,a,l,o,n):kNe({code:u,source:i,name:o.name,filename:a,sentinel:l,runId:s,ctx:n,options:e})})}async function ONe(e,t,n,r,i){let a;try{a=await D1(e,[`workflow`,t],i,void 0,{filename:t})}catch(e){return g9.error(`workflow run failed`,e),{stdout:``,stderr:`workflow: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return NNe(r,a,n)}async function kNe(e){let t=_9();if(!t)return{stdout:``,stderr:`workflow: run manager not available
10275
- `,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 ANe=/^[a-z0-9][a-z0-9-]*$/,v9=`/workspace/.workflows`;async function jNe(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]
10276
- `,exitCode:1};if(!ANe.test(o))return{stdout:``,stderr:`workflow: invalid name '${o}' (use [a-z0-9][a-z0-9-]*)\n`,exitCode:1};let c=_9()?.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=`${v9}/${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(v9,{recursive:!0}),await t.fs.writeFile(l,c.source);try{await n.syncScriptCommands?.()}catch(e){g9.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 MNe(e,t){let n=_9();if(e[0]===`list`){if(!n)return{stdout:``,stderr:`workflow: run manager not available
10273
+ `,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=xNe(i);if(!o.name)return{stdout:``,stderr:`workflow: script must define a meta block with a name (description optional)
10274
+ `,exitCode:1};let s=p9().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=p9(),u=CNe({prelude:bNe,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?kNe(u,a,l,o,n):ANe({code:u,source:i,name:o.name,filename:a,sentinel:l,runId:s,ctx:n,options:e})})}async function kNe(e,t,n,r,i){let a;try{a=await D1(e,[`workflow`,t],i,void 0,{filename:t})}catch(e){return g9.error(`workflow run failed`,e),{stdout:``,stderr:`workflow: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return PNe(r,a,n)}async function ANe(e){let t=_9();if(!t)return{stdout:``,stderr:`workflow: run manager not available
10275
+ `,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 jNe=/^[a-z0-9][a-z0-9-]*$/,v9=`/workspace/.workflows`;async function MNe(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]
10276
+ `,exitCode:1};if(!jNe.test(o))return{stdout:``,stderr:`workflow: invalid name '${o}' (use [a-z0-9][a-z0-9-]*)\n`,exitCode:1};let c=_9()?.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=`${v9}/${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(v9,{recursive:!0}),await t.fs.writeFile(l,c.source);try{await n.syncScriptCommands?.()}catch(e){g9.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 NNe(e,t){let n=_9();if(e[0]===`list`){if(!n)return{stdout:``,stderr:`workflow: run manager not available
10277
10277
  `,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(`
10278
10278
  `):`(no runs)`)+`
10279
10279
  `,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(`
10280
10280
  `)+`
10281
- `,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 NNe(e,t,n){let{result:r,log:i,hadResult:a}=m9(t.stdout,n),o=e.name?`workflow: ${e.name}${e.description?` — `+e.description:``}\n`:``,s=i?PNe(i)+`
10281
+ `,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 PNe(e,t,n){let{result:r,log:i,hadResult:a}=m9(t.stdout,n),o=e.name?`workflow: ${e.name}${e.description?` — `+e.description:``}\n`:``,s=i?FNe(i)+`
10282
10282
  `:``;return t.exitCode!==0||!a?{stdout:o+s,stderr:t.stderr||(a?``:`workflow: script produced no result
10283
10283
  `),exitCode:t.exitCode||1}:{stdout:o+s+(typeof r==`string`?r:JSON.stringify(r))+`
10284
- `,stderr:t.stderr,exitCode:0}}function PNe(e){return e.split(`
10284
+ `,stderr:t.stderr,exitCode:0}}function FNe(e){return e.split(`
10285
10285
  `).map(e=>e.replace(/^WFPHASE/,`▸ `).replace(/^WFLOG/,`· `)).join(`
10286
- `)}function y9(e){return{stdout:``,stderr:`xxd: ${e}\n`,exitCode:1}}function FNe(e){if(e==null)throw Error(`missing option value`);let t=e.startsWith(`-`),n=t||e.startsWith(`+`)?e.slice(1):e,r;if(/^0x[0-9a-fA-F]+$/.test(n))r=parseInt(n.slice(2),16);else if(/^[0-9]+$/.test(n))r=parseInt(n,10);else throw Error(`invalid number: ${e}`);return t?-r:r}function b9(e,t){let n=e.toString(16).padStart(2,`0`);return t?n.toUpperCase():n}function x9(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}function INe(e){return e.replace(/[^0-9a-zA-Z]/g,`_`)}function LNe(e,t,n,r,i){let a=[];for(let o=0;o<e.length;o+=t){let s=Math.min(o+t,e.length),c=(i+o).toString(16).padStart(8,`0`),l=``;for(let i=0;i<t;i++)n>0&&i>0&&i%n===0&&(l+=` `),l+=o+i<s?b9(e[o+i],r):` `;let u=``;for(let t=o;t<s;t++)u+=e[t]>=32&&e[t]<=126?String.fromCharCode(e[t]):`.`;a.push(`${c}: ${l} ${u}`)}return a.length?a.join(`
10286
+ `)}function y9(e){return{stdout:``,stderr:`xxd: ${e}\n`,exitCode:1}}function INe(e){if(e==null)throw Error(`missing option value`);let t=e.startsWith(`-`),n=t||e.startsWith(`+`)?e.slice(1):e,r;if(/^0x[0-9a-fA-F]+$/.test(n))r=parseInt(n.slice(2),16);else if(/^[0-9]+$/.test(n))r=parseInt(n,10);else throw Error(`invalid number: ${e}`);return t?-r:r}function b9(e,t){let n=e.toString(16).padStart(2,`0`);return t?n.toUpperCase():n}function x9(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}function LNe(e){return e.replace(/[^0-9a-zA-Z]/g,`_`)}function RNe(e,t,n,r,i){let a=[];for(let o=0;o<e.length;o+=t){let s=Math.min(o+t,e.length),c=(i+o).toString(16).padStart(8,`0`),l=``;for(let i=0;i<t;i++)n>0&&i>0&&i%n===0&&(l+=` `),l+=o+i<s?b9(e[o+i],r):` `;let u=``;for(let t=o;t<s;t++)u+=e[t]>=32&&e[t]<=126?String.fromCharCode(e[t]):`.`;a.push(`${c}: ${l} ${u}`)}return a.length?a.join(`
10287
10287
  `)+`
10288
- `:``}function RNe(e,t,n){let r=``;for(let i=0;i<e.length;i+=t){let a=``;for(let r=0;r<t&&i+r<e.length;r++)a+=b9(e[i+r],n);r+=a+`
10289
- `}return r}function zNe(e,t,n,r){let i=Array.from(e,e=>`0x${b9(e,n)}`),a=[];for(let e=0;e<i.length;e+=t)a.push(` `+i.slice(e,e+t).join(`, `));let o=a.join(`,
10288
+ `:``}function zNe(e,t,n){let r=``;for(let i=0;i<e.length;i+=t){let a=``;for(let r=0;r<t&&i+r<e.length;r++)a+=b9(e[i+r],n);r+=a+`
10289
+ `}return r}function BNe(e,t,n,r){let i=Array.from(e,e=>`0x${b9(e,n)}`),a=[];for(let e=0;e<i.length;e+=t)a.push(` `+i.slice(e,e+t).join(`, `));let o=a.join(`,
10290
10290
  `);return r===null?i.length?o+`
10291
- `:``:`unsigned char ${r}[] = {\n${o}\n};\nunsigned int ${r}_len = ${e.length};\n`}function BNe(e){let t=e.replace(/[^0-9a-fA-F]/g,``),n=Math.floor(t.length/2),r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=parseInt(t.substr(e*2,2),16);return r}function VNe(e){let t=[],n=0;for(let r of e.split(`
10292
- `)){let e=r.replace(/\r$/,``),i=e.indexOf(`:`);if(i<0)continue;let a=parseInt(e.slice(0,i).trim(),16);if(Number.isNaN(a))continue;let o=e.slice(i+1),s=o.indexOf(` `);s>=0&&(o=o.slice(0,s));let c=o.replace(/[^0-9a-fA-F]/g,``),l=[];for(let e=0;e+1<c.length;e+=2)l.push(parseInt(c.substr(e,2),16));l.length&&(t.push({offset:a,bytes:l}),n=Math.max(n,a+l.length))}if(!t.length)return new Uint8Array;let r=new Uint8Array(n);for(let e of t)for(let t=0;t<e.bytes.length;t++)r[e.offset+t]=e.bytes[t];return r}const HNe={"-u":`upper`,"-p":`plain`,"-ps":`plain`,"-postscript":`plain`,"-i":`include`,"-include":`include`,"-r":`revert`,"-revert":`revert`},UNe=[{key:`cols`,exact:[`-c`,`-cols`],attached:/^-c(0x)?[0-9]/},{key:`group`,exact:[`-g`,`-groupsize`],attached:/^-g(0x)?[0-9]/},{key:`length`,exact:[`-l`,`-len`],attached:/^-l(0x)?[0-9]/},{key:`seek`,exact:[`-s`,`-seek`],attached:/^-s[+-]?(0x)?[0-9]/}];function WNe(e){let t={upper:!1,plain:!1,include:!1,revert:!1,positional:[]};for(let n=0;n<e.length;n++){let r=e[n],i=HNe[r];if(i){t[i]=!0;continue}let a=UNe.find(e=>e.exact.includes(r)||e.attached.test(r));if(a){t[a.key]=FNe(a.exact.includes(r)?e[++n]:r.slice(2));continue}if(r!==`-`&&r.startsWith(`-`)&&r.length>1)throw Error(`invalid option ${r}`);t.positional.push(r)}return t}function GNe(e){return e.includes(`-h`)||e.includes(`--help`)||e.includes(`-help`)}async function KNe(e,t,n){if(!n&&t)return e.fs.readFileBuffer(e.fs.resolvePath(e.cwd,t));let r=E1(e.stdin),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e)&255;return i}function qNe(e,t,n,r,i){let a=e.cols&&e.cols>0?e.cols:e.plain?30:e.include?12:16;return e.plain?RNe(t,a,e.upper):e.include?zNe(t,a,e.upper,i?null:INe(r??``)):LNe(t,a,e.group!=null&&e.group>=0?e.group:2,e.upper,n)}function JNe(e,t){let n=0,r=t;return e.seek!==void 0&&(n=e.seek<0?Math.max(0,r.length+e.seek):Math.min(e.seek,r.length),r=r.subarray(n)),e.length!==void 0&&(r=r.subarray(0,Math.max(0,e.length))),{data:r,base:n}}function YNe(){return SA(`xxd`,async(e,t)=>{if(GNe(e))return{stdout:`usage: xxd [options] [infile [outfile]]
10291
+ `:``:`unsigned char ${r}[] = {\n${o}\n};\nunsigned int ${r}_len = ${e.length};\n`}function VNe(e){let t=e.replace(/[^0-9a-fA-F]/g,``),n=Math.floor(t.length/2),r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=parseInt(t.substr(e*2,2),16);return r}function HNe(e){let t=[],n=0;for(let r of e.split(`
10292
+ `)){let e=r.replace(/\r$/,``),i=e.indexOf(`:`);if(i<0)continue;let a=parseInt(e.slice(0,i).trim(),16);if(Number.isNaN(a))continue;let o=e.slice(i+1),s=o.indexOf(` `);s>=0&&(o=o.slice(0,s));let c=o.replace(/[^0-9a-fA-F]/g,``),l=[];for(let e=0;e+1<c.length;e+=2)l.push(parseInt(c.substr(e,2),16));l.length&&(t.push({offset:a,bytes:l}),n=Math.max(n,a+l.length))}if(!t.length)return new Uint8Array;let r=new Uint8Array(n);for(let e of t)for(let t=0;t<e.bytes.length;t++)r[e.offset+t]=e.bytes[t];return r}const UNe={"-u":`upper`,"-p":`plain`,"-ps":`plain`,"-postscript":`plain`,"-i":`include`,"-include":`include`,"-r":`revert`,"-revert":`revert`},WNe=[{key:`cols`,exact:[`-c`,`-cols`],attached:/^-c(0x)?[0-9]/},{key:`group`,exact:[`-g`,`-groupsize`],attached:/^-g(0x)?[0-9]/},{key:`length`,exact:[`-l`,`-len`],attached:/^-l(0x)?[0-9]/},{key:`seek`,exact:[`-s`,`-seek`],attached:/^-s[+-]?(0x)?[0-9]/}];function GNe(e){let t={upper:!1,plain:!1,include:!1,revert:!1,positional:[]};for(let n=0;n<e.length;n++){let r=e[n],i=UNe[r];if(i){t[i]=!0;continue}let a=WNe.find(e=>e.exact.includes(r)||e.attached.test(r));if(a){t[a.key]=INe(a.exact.includes(r)?e[++n]:r.slice(2));continue}if(r!==`-`&&r.startsWith(`-`)&&r.length>1)throw Error(`invalid option ${r}`);t.positional.push(r)}return t}function KNe(e){return e.includes(`-h`)||e.includes(`--help`)||e.includes(`-help`)}async function qNe(e,t,n){if(!n&&t)return e.fs.readFileBuffer(e.fs.resolvePath(e.cwd,t));let r=E1(e.stdin),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e)&255;return i}function JNe(e,t,n,r,i){let a=e.cols&&e.cols>0?e.cols:e.plain?30:e.include?12:16;return e.plain?zNe(t,a,e.upper):e.include?BNe(t,a,e.upper,i?null:LNe(r??``)):RNe(t,a,e.group!=null&&e.group>=0?e.group:2,e.upper,n)}function YNe(e,t){let n=0,r=t;return e.seek!==void 0&&(n=e.seek<0?Math.max(0,r.length+e.seek):Math.min(e.seek,r.length),r=r.subarray(n)),e.length!==void 0&&(r=r.subarray(0,Math.max(0,e.length))),{data:r,base:n}}function XNe(){return SA(`xxd`,async(e,t)=>{if(KNe(e))return{stdout:`usage: xxd [options] [infile [outfile]]
10293
10293
  -c cols number of octets per line (default 16; 30 for -p; 12 for -i)
10294
10294
  -g bytes number of octets per group (default 2; 0 disables grouping)
10295
10295
  -l len stop after len octets
@@ -10299,11 +10299,11 @@ pass --wait to block and print the full result.
10299
10299
  -i output in C include style
10300
10300
  -r reverse: convert a hex dump back to binary (-r -p for plain)
10301
10301
  -h show this help
10302
- `,stderr:``,exitCode:0};let n;try{n=WNe(e)}catch(e){return y9(e.message)}let r=n.positional[0],i=n.positional[1],a=!r||r===`-`,o;try{o=await KNe(t,r,a)}catch{return y9(`${r}: No such file or directory`)}if(n.revert){let e=x9(o),r=n.plain?BNe(e):VNe(e);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),r),{stdout:``,stderr:``,exitCode:0}):{stdout:x9(r),stderr:``,exitCode:0}}let{data:s,base:c}=JNe(n,o),l=qNe(n,s,c,r,a);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),l),{stdout:``,stderr:``,exitCode:0}):{stdout:l,stderr:``,exitCode:0}})}async function S9(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 S9(e,i,s,r)}return a}function XNe(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
10303
- `,stderr:``,exitCode:0}}function ZNe(){return SA(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return XNe();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
10302
+ `,stderr:``,exitCode:0};let n;try{n=GNe(e)}catch(e){return y9(e.message)}let r=n.positional[0],i=n.positional[1],a=!r||r===`-`,o;try{o=await qNe(t,r,a)}catch{return y9(`${r}: No such file or directory`)}if(n.revert){let e=x9(o),r=n.plain?VNe(e):HNe(e);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),r),{stdout:``,stderr:``,exitCode:0}):{stdout:x9(r),stderr:``,exitCode:0}}let{data:s,base:c}=YNe(n,o),l=JNe(n,s,c,r,a);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),l),{stdout:``,stderr:``,exitCode:0}):{stdout:l,stderr:``,exitCode:0}})}async function S9(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 S9(e,i,s,r)}return a}function ZNe(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
10303
+ `,stderr:``,exitCode:0}}function QNe(){return SA(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return ZNe();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
10304
10304
  `,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 S9(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
10305
- `,exitCode:1};let c=Bue(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function QNe(e={}){let t=[UEe({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),ybe(),Tje(e.browserAPI,e.fs),Lke(e.browserAPI),vDe(e),ZNe(),CMe(),YNe(),R7(`sqlite3`),R7(`sqllite`),Qje(),pMe(),FSe(),ube(),dke({buildProcessConfig:e.buildProcessConfig}),a7(`python3`,{buildProcessConfig:e.buildProcessConfig}),a7(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[e5(`ipk`,{fs:e.fs,fetch:e.fetch}),e5(`npm`,{fs:e.fs,fetch:e.fetch}),e5(`i`,{fs:e.fs,fetch:e.fetch}),c5(`ipx`,{fs:e.fs,fetch:e.fetch}),c5(`npx`,{fs:e.fs,fetch:e.fetch}),P3(`di`,{fs:e.fs,fetch:e.fetch}),P3(`uv`,{fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[eDe({fetch:e.fetch})]:[],nwe(),QMe(),aNe(),Wxe(),DOe({fs:e.fs,scriptCatalog:e.scriptCatalog}),_we(),zje(),r7(`pdftk`),r7(`pdf`),_3(`convert`),_3(`magick`),uNe({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins}),mMe(),xMe(),xOe(),bSe(),_ke(),hke(),vOe(),lje({setEnv:e.setEnv}),xAe({fs:e.fs}),RAe(),Ibe(),Lbe(),n2(`xclip`),n2(`xsel`),NAe(),Ewe(),wye(),Tye(),cke(e.fs),ZN(),pke(),Hye({getParentJid:e.getParentJid}),ESe(),Uke({processManager:e.processManager}),rOe({processManager:e.processManager}),VMe(),gDe(),lCe(),gCe(),Mbe({registry:e.cherryRuntimeRegistry}),Yxe(),$xe({fs:e.fs}),eSe({fs:e.fs}),Vje(e.sudoCommand),DNe({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),oNe()];return e.fs&&t.push(...y6.map(t=>BEe(t,e.browserAPI,e.fs))),t}const $Ne=Reflect.get(Hee,`DefenseInDepthBox`);var ePe=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=$Ne?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=Qe(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=Qe(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=Qe(e);if(typeof t==`string`){let e=ee(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=Qe(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new b(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof b&&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 b&&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=Qe(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=Qe(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=Qe(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(Qe(e),t)})}async readdir(e){return this.trusted(async()=>{let t=Qe(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=Qe(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(Qe(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=Qe(e),i=Qe(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new b(`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=$e(e,r.name),i=$e(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(Qe(e),Qe(t))})}resolvePath(e,t){return t.startsWith(`/`)?Qe(t):Qe($e(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,Qe(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(Qe(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(Qe(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function C9(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?C9(e.getUnderlyingFS?.()):null}var w9=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 ePe(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 EW({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new vde({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=C9(i)??C9(a);this.scriptCatalog=t.scriptCatalog??new K1({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=A(),l=QNe({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(),tye(t.fs),bye(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...hA(),...gA()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new WN({fs:this.vfsAdapter,cwd:n,env:r,fetch:c,commands:f,customCommands:u}),this.allowedCommands!==null){let e=this.bash;for(let t of gA())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 p=u.map(e=>e.name),m=f??[...hA(),...gA()];this.builtinCommandNames=new Set([...m,...p]),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 sve(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){wr(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 Ave(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=sP(e);if(!n)return;let r=`${eP}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch{a=``}let o=a&&!a.endsWith(`
10306
- `)?`${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 D1(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=Tve(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 SA(`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 SA(`mount`,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}})}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?dve(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 D1(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 T9(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 tPe=class extends w9{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-Dwh1I9AE.js`),{FitAddon:r}=await import(`./addon-fit-Crogpbda.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
10305
+ `,exitCode:1};let c=Bue(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function $Ne(e={}){let t=[UEe({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),ybe(),Eje(e.browserAPI,e.fs),Rke(e.browserAPI),vDe(e),QNe(),wMe(),XNe(),R7(`sqlite3`),R7(`sqllite`),$je(),mMe(),FSe(),ube(),dke({buildProcessConfig:e.buildProcessConfig}),a7(`python3`,{buildProcessConfig:e.buildProcessConfig}),a7(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[e5(`ipk`,{fs:e.fs,fetch:e.fetch}),e5(`npm`,{fs:e.fs,fetch:e.fetch}),e5(`i`,{fs:e.fs,fetch:e.fetch}),c5(`ipx`,{fs:e.fs,fetch:e.fetch}),c5(`npx`,{fs:e.fs,fetch:e.fetch}),P3(`di`,{fs:e.fs,fetch:e.fetch}),P3(`uv`,{fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[eDe({fetch:e.fetch})]:[],nwe(),$Me(),oNe(),Wxe(),DOe({fs:e.fs,scriptCatalog:e.scriptCatalog}),_we(),L7(),r7(`pdftk`),r7(`pdf`),_3(`convert`),_3(`magick`),dNe({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins}),hMe(),SMe(),xOe(),bSe(),vke(),gke(),vOe(),uje({setEnv:e.setEnv}),SAe({fs:e.fs}),zAe(),Ibe(),Lbe(),n2(`xclip`),n2(`xsel`),PAe(),Ewe(),wye(),Tye(),cke(e.fs),ZN(),mke(),Hye({getParentJid:e.getParentJid}),ESe(),Wke({processManager:e.processManager}),rOe({processManager:e.processManager}),HMe(),gDe(),lCe(),gCe(),Mbe({registry:e.cherryRuntimeRegistry}),Yxe(),$xe({fs:e.fs}),eSe({fs:e.fs}),Hje(e.sudoCommand),ONe({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),sNe()];return e.fs&&t.push(...y6.map(t=>BEe(t,e.browserAPI,e.fs))),t}const ePe=Reflect.get(Hee,`DefenseInDepthBox`);var tPe=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=ePe?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=Qe(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=Qe(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=Qe(e);if(typeof t==`string`){let e=ee(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=Qe(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new b(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof b&&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 b&&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=Qe(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=Qe(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=Qe(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(Qe(e),t)})}async readdir(e){return this.trusted(async()=>{let t=Qe(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=Qe(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(Qe(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=Qe(e),i=Qe(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new b(`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=$e(e,r.name),i=$e(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(Qe(e),Qe(t))})}resolvePath(e,t){return t.startsWith(`/`)?Qe(t):Qe($e(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,Qe(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(Qe(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(Qe(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function C9(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?C9(e.getUnderlyingFS?.()):null}var w9=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 tPe(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 EW({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new vde({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=C9(i)??C9(a);this.scriptCatalog=t.scriptCatalog??new K1({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=A(),l=$Ne({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(),tye(t.fs),bye(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...hA(),...gA()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new WN({fs:this.vfsAdapter,cwd:n,env:r,fetch:c,commands:f,customCommands:u}),this.allowedCommands!==null){let e=this.bash;for(let t of gA())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 p=u.map(e=>e.name),m=f??[...hA(),...gA()];this.builtinCommandNames=new Set([...m,...p]),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 sve(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){wr(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 Ave(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=sP(e);if(!n)return;let r=`${eP}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch{a=``}let o=a&&!a.endsWith(`
10306
+ `)?`${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 D1(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=Tve(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 SA(`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 SA(`mount`,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}})}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?dve(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 D1(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 T9(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 nPe=class extends w9{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-Dwh1I9AE.js`),{FitAddon:r}=await import(`./addon-fit-Crogpbda.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
10307
10307
  `),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
10308
10308
  `,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(`
10309
10309
  `).entries()){if(e+n.length>=this.cursorPos)return t;e+=n.length+1}return 0}positionTerminalCursor(){let e=this.currentLine.split(`
@@ -10318,15 +10318,15 @@ pass --wait to block and print the full result.
10318
10318
  `,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(`
10319
10319
  `).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(`
10320
10320
  `);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+`
10321
- `+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=`${T9(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=T9(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 E9=i(`tool:bash`),nPe=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function rPe(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 iPe(e){let t=rPe(e);return(t[t.length-1]??``).trim()}function aPe(e,t,n){return t!==1||n.trim()?!1:nPe.test(iPe(e))}function oPe(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;E9.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);E9.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&&!aPe(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}const D9=i(`tool:fs`);function sPe(e){return[cPe(e),lPe(e),uPe(e)]}function cPe(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;D9.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
10321
+ `+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=`${T9(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=T9(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 E9=i(`tool:bash`),rPe=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function iPe(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 aPe(e){let t=iPe(e);return(t[t.length-1]??``).trim()}function oPe(e,t,n){return t!==1||n.trim()?!1:rPe.test(aPe(e))}function sPe(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;E9.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);E9.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&&!oPe(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}const D9=i(`tool:fs`);function cPe(e){return[lPe(e),uPe(e),dPe(e)]}function lPe(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;D9.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
10322
10322
  `),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(`
10323
- `)}}catch(e){let t=e instanceof Error?e.message:String(e);return D9.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function lPe(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;D9.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 D9.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function uPe(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;D9.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 D9.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}i(`tool:search`);const O9=i(`scoop-management-tools`);function k9(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 A9=[`command`,`read`,`write`,`secret`];function dPe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`}function fPe(e){return e===void 0?{ok:!0}:xi(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${bi.join(`, `)}.`,isError:!0}}function j9(e,t){return{content:`Scoop "${e}" not found. Available: ${t().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0}}function pPe(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 mPe(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),O9.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function hPe(e){let{kind:t,detail:n,suggested_pattern:r}=e;return A9.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: ${A9.join(`, `)}.`,isError:!0}}}function gPe(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(`
10324
- `)}async function _Pe(e,t){let n=hPe(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return O9.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:gPe(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function vPe(e,t){let{scoop_name:n,prompt:r}=e,i=t.getScoops().find(e=>e.folder===n||e.name===n);if(!i)return j9(n,t.getScoops);if(i.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await t.onFeedScoop(i.jid,r),O9.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 yPe(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>pPe(t,e.getScoopTabState)).join(`
10325
- `)}`}}function bPe(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 xPe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return O9.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 SPe(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c}=e,l=fPe(c);if(!l.ok)return{content:l.content,isError:l.isError};let u=dPe(n);try{let e=bPe(n,u,r,a,o,s,l.level),c=await t.onScoopScoop(e);return O9.info(`Scoop created`,{name:n,folder:u}),i&&t.onFeedScoop?xPe(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 CPe(e,t){let{scoop_name:n}=e,r=t.getScoops().find(e=>e.folder===n||e.name===n);if(!r)return j9(n,t.getScoops);if(r.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await t.onDropScoop(r.jid),O9.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 M9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function N9(e){return{content:`No matching scoops found. Unknown: ${e.join(`, `)}`,isError:!0}}async function wPe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return M9();let{resolved:r,unknown:i}=k9(n,t.getScoops);return r.length===0?N9(i):(t.onMuteScoops(r.map(e=>e.jid)),O9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function TPe(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 EPe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return M9();let{resolved:r,unknown:i}=k9(n,t.getScoops);if(r.length===0)return N9(i);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);O9.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(...TPe(s,o)),{content:c.join(`
10326
- `)}}function DPe(e,t){return!Array.isArray(e)||e.length===0?M9():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 OPe(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 kPe(e,t){let{scoop_names:n,timeout_ms:r}=e,i=DPe(n,r);if(i)return i;let{resolved:a,unknown:o}=k9(n,t.getScoops);if(a.length===0)return N9(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 O9.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:OPe(u,o,d,r)}}function APe(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 jPe(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?(O9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:APe(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 MPe(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?(O9.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 NPe(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(`
10327
- `)}`}}async function PPe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),O9.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 FPe(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=>mPe(t,e)}}function IPe(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:[...A9],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=>_Pe(t,e)}}function LPe(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=>vPe(t,e)}}function RPe(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>yPe(e)}}function zPe(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:[...bi],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=>SPe(t,e)}}function BPe(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=>CPe(t,e)}}function VPe(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=>wPe(t,e)}}function HPe(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=>EPe(t,e)}}function UPe(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=>kPe(t,e)}}function WPe(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=>jPe(t,e)}}function GPe(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=>MPe(t,e)}}function KPe(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:()=>NPe(e)}}function qPe(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=>PPe(t,e)}}function JPe(e){let t=[],n=e.scoop.isCone;return n||(t.push(FPe(e)),e.onSudoRequest&&t.push(IPe(e))),n&&(e.onFeedScoop&&t.push(LPe(e)),t.push(RPe(e)),e.onScoopScoop&&t.push(zPe(e)),e.onDropScoop&&t.push(BPe(e)),e.onMuteScoops&&t.push(VPe(e)),e.onUnmuteScoops&&t.push(HPe(e)),e.onScheduleScoopWait&&t.push(UPe(e)),e.onSudoResolve&&(t.push(WPe(e)),t.push(GPe(e))),e.onListSudoRequests&&t.push(KPe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(qPe(e))),t}const P9=i(`scoop-context`);function F9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!tt(t).includes(`xhigh`)?`high`:e}function YPe(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 XPe(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 I9(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 L9(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 ZPe=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;activeEffortOverride;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 LF(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await _de(),i=this.buildSudoWiring(),a=i?Qce(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new tPe({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}),P9.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await IF(n,this.skillsDir)}}async buildTools(e){let t=JPe({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=[...sPe(e),oPe(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:Ce()};return this.processManager?Ie(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):Ie(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=be(e.messages);return this.sessionCreatedAt=e.createdAt,P9.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){P9.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 nle(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?it(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):it(e,n,a)},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:Be()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:N({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>Be()??void 0,headers:r,onMemoryUpdates:i,onCompactionStateChange:this.callbacks.onCompactionStateChange})}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);P9.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(!Be()){P9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?ye(this.scoop.config.modelId):I(),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=F9(this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel,a);this.activeEffortOverride=this.scoop.config?.effortOverride,this.agent=new Xe({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>Be()??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`),P9.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);P9.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=Ke()}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?(P9.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 XPe(e)?(P9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),vr(`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}handleStaleAssetError(e){return dr(e)?(P9.error(`Stale-asset import failure; requesting page reload`,{folder:this.scoop.folder,error:e}),mr(this.scoop.isCone),vr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" hit a stale build after a deploy; reloading to recover.`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!I9(e)||t>=n)return!1;let a=r*2**(t-1);return P9.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await L9(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;P9.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),vr(`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.handleStaleAssetError(a)||this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(P9.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:I9(a)}),!!(t<n&&(await L9(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?ye(this.scoop.config.modelId):I();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=I();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=F9(t,e),this.activeEffortOverride=e.reasoning?this.scoop.config?.effortOverride:void 0,P9.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 IF(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,P9.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e,t){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=F9(e,this.agent.state.model);return this.agent.state.thinkingLevel=n,n}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(bi.includes(e))return e;P9.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}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(`
10323
+ `)}}catch(e){let t=e instanceof Error?e.message:String(e);return D9.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function uPe(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;D9.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 D9.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function dPe(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;D9.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 D9.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}i(`tool:search`);const O9=i(`scoop-management-tools`);function k9(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 A9=[`command`,`read`,`write`,`secret`];function fPe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`}function pPe(e){return e===void 0?{ok:!0}:xi(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${bi.join(`, `)}.`,isError:!0}}function j9(e,t){return{content:`Scoop "${e}" not found. Available: ${t().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0}}function mPe(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 hPe(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),O9.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function gPe(e){let{kind:t,detail:n,suggested_pattern:r}=e;return A9.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: ${A9.join(`, `)}.`,isError:!0}}}function _Pe(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(`
10324
+ `)}async function vPe(e,t){let n=gPe(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return O9.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:_Pe(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function yPe(e,t){let{scoop_name:n,prompt:r}=e,i=t.getScoops().find(e=>e.folder===n||e.name===n);if(!i)return j9(n,t.getScoops);if(i.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await t.onFeedScoop(i.jid,r),O9.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 bPe(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>mPe(t,e.getScoopTabState)).join(`
10325
+ `)}`}}function xPe(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 SPe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return O9.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 CPe(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c}=e,l=pPe(c);if(!l.ok)return{content:l.content,isError:l.isError};let u=fPe(n);try{let e=xPe(n,u,r,a,o,s,l.level),c=await t.onScoopScoop(e);return O9.info(`Scoop created`,{name:n,folder:u}),i&&t.onFeedScoop?SPe(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 wPe(e,t){let{scoop_name:n}=e,r=t.getScoops().find(e=>e.folder===n||e.name===n);if(!r)return j9(n,t.getScoops);if(r.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await t.onDropScoop(r.jid),O9.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 M9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function N9(e){return{content:`No matching scoops found. Unknown: ${e.join(`, `)}`,isError:!0}}async function TPe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return M9();let{resolved:r,unknown:i}=k9(n,t.getScoops);return r.length===0?N9(i):(t.onMuteScoops(r.map(e=>e.jid)),O9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function EPe(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 DPe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return M9();let{resolved:r,unknown:i}=k9(n,t.getScoops);if(r.length===0)return N9(i);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);O9.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(...EPe(s,o)),{content:c.join(`
10326
+ `)}}function OPe(e,t){return!Array.isArray(e)||e.length===0?M9():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 kPe(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 APe(e,t){let{scoop_names:n,timeout_ms:r}=e,i=OPe(n,r);if(i)return i;let{resolved:a,unknown:o}=k9(n,t.getScoops);if(a.length===0)return N9(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 O9.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:kPe(u,o,d,r)}}function jPe(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 MPe(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?(O9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:jPe(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 NPe(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?(O9.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 PPe(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(`
10327
+ `)}`}}async function FPe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),O9.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 IPe(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=>hPe(t,e)}}function LPe(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:[...A9],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=>vPe(t,e)}}function RPe(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=>yPe(t,e)}}function zPe(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>bPe(e)}}function BPe(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:[...bi],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=>CPe(t,e)}}function VPe(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=>wPe(t,e)}}function HPe(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=>TPe(t,e)}}function UPe(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=>DPe(t,e)}}function WPe(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=>APe(t,e)}}function GPe(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=>MPe(t,e)}}function KPe(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=>NPe(t,e)}}function qPe(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:()=>PPe(e)}}function JPe(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=>FPe(t,e)}}function YPe(e){let t=[],n=e.scoop.isCone;return n||(t.push(IPe(e)),e.onSudoRequest&&t.push(LPe(e))),n&&(e.onFeedScoop&&t.push(RPe(e)),t.push(zPe(e)),e.onScoopScoop&&t.push(BPe(e)),e.onDropScoop&&t.push(VPe(e)),e.onMuteScoops&&t.push(HPe(e)),e.onUnmuteScoops&&t.push(UPe(e)),e.onScheduleScoopWait&&t.push(WPe(e)),e.onSudoResolve&&(t.push(GPe(e)),t.push(KPe(e))),e.onListSudoRequests&&t.push(qPe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(JPe(e))),t}const P9=i(`scoop-context`);function F9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!tt(t).includes(`xhigh`)?`high`:e}function XPe(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 ZPe(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 I9(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 L9(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 QPe=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;activeEffortOverride;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 LF(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await _de(),i=this.buildSudoWiring(),a=i?Qce(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new nPe({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}),P9.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await IF(n,this.skillsDir)}}async buildTools(e){let t=YPe({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=[...cPe(e),sPe(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:Ce()};return this.processManager?Ie(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):Ie(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=be(e.messages);return this.sessionCreatedAt=e.createdAt,P9.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){P9.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 nle(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?it(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):it(e,n,a)},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:Be()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:N({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>Be()??void 0,headers:r,onMemoryUpdates:i,onCompactionStateChange:this.callbacks.onCompactionStateChange})}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);P9.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(!Be()){P9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?ye(this.scoop.config.modelId):I(),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=F9(this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel,a);this.activeEffortOverride=this.scoop.config?.effortOverride,this.agent=new Xe({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>Be()??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`),P9.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);P9.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=Ke()}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?(P9.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 ZPe(e)?(P9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),vr(`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}handleStaleAssetError(e){return dr(e)?(P9.error(`Stale-asset import failure; requesting page reload`,{folder:this.scoop.folder,error:e}),mr(this.scoop.isCone),vr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" hit a stale build after a deploy; reloading to recover.`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!I9(e)||t>=n)return!1;let a=r*2**(t-1);return P9.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await L9(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;P9.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),vr(`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.handleStaleAssetError(a)||this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(P9.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:I9(a)}),!!(t<n&&(await L9(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?ye(this.scoop.config.modelId):I();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=I();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=F9(t,e),this.activeEffortOverride=e.reasoning?this.scoop.config?.effortOverride:void 0,P9.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 IF(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,P9.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e,t){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=F9(e,this.agent.state.model);return this.agent.state.thinkingLevel=n,n}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(bi.includes(e))return e;P9.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}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(`
10328
10328
  `);if(e.isError){let t=n.filter(e=>!e.startsWith(`<img:`)).join(`
10329
- `);vr(`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&&YPe(n)){this.recoverFromImageError(e);return}if(!this.isRecovering&&yi(t)){this.recoverFromOverflow(e);return}if(!this.isRecovering&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=n;return}this.isRecovering=!1,vr(`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=>{P9.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++,P9.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){P9.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=>{P9.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){P9.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){P9.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=>{P9.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){P9.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
10329
+ `);vr(`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&&XPe(n)){this.recoverFromImageError(e);return}if(!this.isRecovering&&yi(t)){this.recoverFromOverflow(e);return}if(!this.isRecovering&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=n;return}this.isRecovering=!1,vr(`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=>{P9.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++,P9.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){P9.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=>{P9.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){P9.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){P9.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=>{P9.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){P9.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
10330
10330
 
10331
10331
  ${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
10332
10332
  Folder: ${this.scoop.folder}
@@ -10407,14 +10407,14 @@ ${e}
10407
10407
  ---
10408
10408
  ${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
10409
10409
  ${t}
10410
- ---`);let a=Jue(n);return a&&(i+=a),i}};const R9=i(`scoop-lifecycle-manager`);var QPe=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){R9.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){R9.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`)R9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{R9.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 L(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 ZPe(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),R9.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),R9.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 R9.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(R9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){R9.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){R9.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`)),R9.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),R9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||xr(`spawn`,e.folder)}catch(n){R9.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){R9.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=>{R9.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=>{R9.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=>{R9.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&&R9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),R9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){R9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();R9.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=>{R9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),R9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){R9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();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)),xr(`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);R9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),xr(`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){R9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{R9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const z9=i(`scoop-message-router`);var $Pe=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(z9.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){z9.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}`);xr(`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),z9.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);z9.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){z9.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)){z9.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(z9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){z9.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{z9.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){z9.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){z9.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(z9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){z9.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}: ${xe(e.content,e.attachments)}`).join(`
10411
- `),c=o.flatMap(e=>Te(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);z9.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=>{z9.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=>{z9.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,[]),z9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{z9.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(),z9.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 B9=i(`orchestrator`);var eFe=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Zue({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new gde({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new hde({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new fde({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 lde({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>hn(e),saveMessage:e=>pn(e)});lickRegistry=new sde({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 $Pe({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=>pn(e),deleteMessage:e=>mn(e),clearMessagesForScoop:e=>fn(e),clearAllMessages:()=>dn(),getMessagesSince:(e,t,n)=>gn(e,t,n),setState:(e,t)=>Sn(e,t)},isExternalLickChannel:Tt});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new QPe({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=>cn(e),deleteScoop:e=>un(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>rI(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 Cn(),this.sharedFs=await ut.create({dbName:`slicc-fs`}),this.sessionStore=new Se,this.fsWatcher=new ct,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new TP({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await ln();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 xn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new cde({onTaskRun:async(e,t)=>{B9.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(),B9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())await this.createScoopTab(e.jid);JN(()=>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()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){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 ut.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await LF(this.sharedFs).catch(e=>{B9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new TP({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),B9.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 hn(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,n){return this.lifecycle.setThinkingLevel(e,t,n)}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&&B9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,B9.info(`Orchestrator shutdown`)}},tFe=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=H9(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=U9(t[0]);if(n===null||!this.pidExists(n))throw new b(`ENOENT`,`no such file or directory`,e);return V9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new b(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=H9(e);if(t.length!==2)throw new b(`EISDIR`,`is a directory`,e);let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new b(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new b(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new b(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=H9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new b(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new b(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new b(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new b(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new b(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new b(`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 b(`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 sFe(t);let n=this.pm.get(e);switch(t){case`status`:return nFe(n);case`cmdline`:return rFe(n);case`cwd`:return iFe(n);case`stat`:return aFe(n)}}};const V9=[`status`,`cmdline`,`cwd`,`stat`];function H9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function U9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function nFe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${W9(e.status)} (${e.status})`,`Owner:\t${oFe(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(`
10410
+ ---`);let a=Jue(n);return a&&(i+=a),i}};const R9=i(`scoop-lifecycle-manager`);var $Pe=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){R9.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){R9.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`)R9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{R9.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 L(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 QPe(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),R9.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),R9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}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 R9.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(R9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){R9.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){R9.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`)),R9.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),R9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||xr(`spawn`,e.folder)}catch(n){R9.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){R9.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=>{R9.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=>{R9.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=>{R9.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&&R9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),R9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){R9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();R9.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=>{R9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),R9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){R9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();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)),xr(`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);R9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),xr(`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){R9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{R9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const z9=i(`scoop-message-router`);var eFe=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(z9.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){z9.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}`);xr(`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),z9.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);z9.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){z9.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)){z9.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(z9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){z9.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{z9.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){z9.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){z9.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(z9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){z9.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}: ${xe(e.content,e.attachments)}`).join(`
10411
+ `),c=o.flatMap(e=>Te(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);z9.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=>{z9.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=>{z9.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,[]),z9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{z9.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(),z9.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 B9=i(`orchestrator`);var tFe=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Zue({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new gde({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new hde({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new fde({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 lde({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>hn(e),saveMessage:e=>pn(e)});lickRegistry=new sde({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 eFe({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=>pn(e),deleteMessage:e=>mn(e),clearMessagesForScoop:e=>fn(e),clearAllMessages:()=>dn(),getMessagesSince:(e,t,n)=>gn(e,t,n),setState:(e,t)=>Sn(e,t)},isExternalLickChannel:Tt});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new $Pe({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=>cn(e),deleteScoop:e=>un(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>rI(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 Cn(),this.sharedFs=await ut.create({dbName:`slicc-fs`}),this.sessionStore=new Se,this.fsWatcher=new ct,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new TP({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await ln();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 xn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new cde({onTaskRun:async(e,t)=>{B9.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(),B9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);B9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}JN(()=>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()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){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 ut.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await LF(this.sharedFs).catch(e=>{B9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new TP({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),B9.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 hn(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,n){return this.lifecycle.setThinkingLevel(e,t,n)}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&&B9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,B9.info(`Orchestrator shutdown`)}},nFe=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=H9(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=U9(t[0]);if(n===null||!this.pidExists(n))throw new b(`ENOENT`,`no such file or directory`,e);return V9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new b(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=H9(e);if(t.length!==2)throw new b(`EISDIR`,`is a directory`,e);let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new b(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new b(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new b(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=H9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new b(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new b(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new b(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new b(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new b(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new b(`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 b(`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 cFe(t);let n=this.pm.get(e);switch(t){case`status`:return rFe(n);case`cmdline`:return iFe(n);case`cwd`:return aFe(n);case`stat`:return oFe(n)}}};const V9=[`status`,`cmdline`,`cwd`,`stat`];function H9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function U9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function rFe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${W9(e.status)} (${e.status})`,`Owner:\t${sFe(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(`
10412
10412
  `)+`
10413
- `}function rFe(e){return e.argv.join(`\0`)+`\0`}function iFe(e){return e.cwd+`
10414
- `}function aFe(e){return[e.pid,`(${e.kind})`,W9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
10415
- `}function W9(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function oFe(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function sFe(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
10413
+ `}function iFe(e){return e.argv.join(`\0`)+`\0`}function aFe(e){return e.cwd+`
10414
+ `}function oFe(e){return[e.pid,`(${e.kind})`,W9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
10415
+ `}function W9(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function sFe(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function cFe(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
10416
10416
  `)+`
10417
10417
  `;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
10418
10418
  `;case`stat`:return`1 (kernel-host) R 0 - 0 -
10419
- `}}function cFe(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`preview`:return e.previewOrigin??`preview`;default:return e.cronName}}function lFe(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;default:return e.cronId}}function uFe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}dFe(e,t)}function dFe(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=Lt(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=cFe(e),a=lFe(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 fFe(e,t,n,r){let i=new MW,a=new eFe(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=Vn(()=>n.emitTrayRuntimeStatus()),s=Yt(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function pFe(e,t,n){let{registerSessionCostsProvider:r}=await Promise.resolve().then(()=>Fce);r(()=>e.getSessionCosts());let{getLickManager:i}=await Promise.resolve().then(()=>rde),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??uFe,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function mFe(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 hFe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;fNe({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>D1(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>p9().slice(10,22),splitResult:(e,t)=>m9(e,t)})}async function gFe(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))+`
10420
- `,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 _Fe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-BzYGVgks.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 vFe(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 gi(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 yFe(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-s20mtVA3.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>yt),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 bFe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-CBbp183e.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 xFe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await Promise.resolve().then(()=>Dve),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function SFe(){return ge()}async function CFe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await fFe(t,n,r,i);if(d?Mi(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new tFe(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await pFe(c,e,o);d&&hFe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await gFe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;SFe()&&(h=await _Fe(f,o,e.localLickWsUrl??null));let g=vFe(n,f,o);d&&yFe(d,f,o),a||await mFe(c),d&&bFe(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await xFe(d,n,o));let y=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){y||(y=!0,await wFe({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function wFe(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)}TFe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function TFe(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[u9]}const G9=`x-bypass-llm-proxy`;function EFe(e,t,n){return t?(r,i)=>{if(!DFe(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 DFe(e,t,n){if(kFe(e,t))return!0;let r=n?.()??null;return r?OFe(e,r,t):!1}function OFe(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.startsWith(`/api/`)}function kFe(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 AFe(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 jFe=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(!MFe(e)||e.source!==`panel`)return;let t=e.payload;NFe(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 MFe(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 NFe(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 PFe=class extends w9{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 FFe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new jFe({transport:t,processManager:i,createShell:(e,a)=>new PFe(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 IFe(e){let t=new LFe(e);return t.start(),{stop:()=>t.dispose()}}var LFe=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(!RFe(e)||e.source!==`panel`)return;let t=e.payload;if(zFe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(BFe(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 b(`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 b(`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(VFe(e.type),e.requestId,new b(`EACCES`,`vfs-rpc-host has no writable backend wired`),HFe(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 b(`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 b(`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 RFe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function zFe(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 BFe(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 VFe(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 HFe(e){return e.type===`vfs-flush`?``:e.path}function J9(e,t){return e instanceof b?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function UFe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=EFe(e.bind(globalThis),t,WFe)}function WFe(){let e=ne();if(!e)return null;try{return new URL(e).origin}catch{return null}}function GFe(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 KFe=AFe(e=>qFe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&KFe.handle(e.data)});async function qFe(e){pr(e.instanceId);try{UFe(),k(e.localApiBaseUrl??null),ae(e.bridgeToken??null),O(e.extensionDelegateId??null),GFe(e.localStorageSeed??{}),Nr().catch(()=>{}),await me();let t=Gr(e.kernelPort),n=new qn(t),r=qn.createCallbacks(n),i=new Kr(e.cdpPort);await i.connect();let a=new rr(i);Y9=await CFe({container:{},browser:a,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:o}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),s=o({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=s;let c=Y9.sharedFs?.getWatcher();if(c){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)c.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)s.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:l}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=l({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,a.setTrayTargetProvider(lr(M));let u=await JFe({host:Y9,transport:t,browser:a,instanceId:e.instanceId});u&&(X9=u.stopTerminalHost,Z9=u.stopVfsRpcHost,Q9=u.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw hr(e),e}}async function JFe(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=FFe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=IFe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await YFe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function YFe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-BjFLbrTH.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CMT-jCdn.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{xn as C,vt as D,Bt as E,Mn as S,zt as T,yI as _,Y8 as a,Rn as b,_Ce as c,sQ as d,VK as f,bI as g,UV as h,u5 as i,Txe as l,IH as m,r9 as n,y8 as o,WK as p,n9 as r,_8 as s,HMe as t,fme as u,mP as v,Sn as w,Pn as x,zn as y};
10419
+ `}}function lFe(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`preview`:return e.previewOrigin??`preview`;default:return e.cronName}}function uFe(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;default:return e.cronId}}function dFe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}fFe(e,t)}function fFe(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=Lt(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=lFe(e),a=uFe(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 pFe(e,t,n,r){let i=new MW,a=new tFe(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=Vn(()=>n.emitTrayRuntimeStatus()),s=Yt(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function mFe(e,t,n){let{registerSessionCostsProvider:r}=await Promise.resolve().then(()=>Fce);r(()=>e.getSessionCosts());let{getLickManager:i}=await Promise.resolve().then(()=>rde),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??dFe,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function hFe(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 gFe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;pNe({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>D1(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>p9().slice(10,22),splitResult:(e,t)=>m9(e,t)})}async function _Fe(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))+`
10420
+ `,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 vFe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-CQSyrpuD.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 yFe(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 gi(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 bFe(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-s20mtVA3.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>yt),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 xFe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-BrSe-3a9.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 SFe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await Promise.resolve().then(()=>Dve),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function CFe(){return ge()}async function wFe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await pFe(t,n,r,i);if(d?Mi(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new nFe(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await mFe(c,e,o);d&&gFe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await _Fe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;CFe()&&(h=await vFe(f,o,e.localLickWsUrl??null));let g=yFe(n,f,o);d&&bFe(d,f,o),a||await hFe(c),d&&xFe(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await SFe(d,n,o));let y=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){y||(y=!0,await TFe({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function TFe(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)}EFe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function EFe(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[u9]}const G9=`x-bypass-llm-proxy`;function DFe(e,t,n){return t?(r,i)=>{if(!OFe(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 OFe(e,t,n){if(AFe(e,t))return!0;let r=n?.()??null;return r?kFe(e,r,t):!1}function kFe(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.startsWith(`/api/`)}function AFe(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 jFe(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 MFe=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(!NFe(e)||e.source!==`panel`)return;let t=e.payload;PFe(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 NFe(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 PFe(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 FFe=class extends w9{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 IFe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new MFe({transport:t,processManager:i,createShell:(e,a)=>new FFe(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 LFe(e){let t=new RFe(e);return t.start(),{stop:()=>t.dispose()}}var RFe=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(!zFe(e)||e.source!==`panel`)return;let t=e.payload;if(BFe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(VFe(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 b(`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 b(`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(HFe(e.type),e.requestId,new b(`EACCES`,`vfs-rpc-host has no writable backend wired`),UFe(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 b(`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 b(`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 zFe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function BFe(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 VFe(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 HFe(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 UFe(e){return e.type===`vfs-flush`?``:e.path}function J9(e,t){return e instanceof b?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function WFe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=DFe(e.bind(globalThis),t,GFe)}function GFe(){let e=ne();if(!e)return null;try{return new URL(e).origin}catch{return null}}function KFe(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 qFe=jFe(e=>JFe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&qFe.handle(e.data)});async function JFe(e){pr(e.instanceId);try{WFe(),k(e.localApiBaseUrl??null),ae(e.bridgeToken??null),O(e.extensionDelegateId??null),KFe(e.localStorageSeed??{}),Nr().catch(()=>{}),await me();let t=Gr(e.kernelPort),n=new qn(t),r=qn.createCallbacks(n),i=new Kr(e.cdpPort);await i.connect();let a=new rr(i);Y9=await wFe({container:{},browser:a,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:o}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),s=o({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=s;let c=Y9.sharedFs?.getWatcher();if(c){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)c.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)s.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:l}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=l({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,a.setTrayTargetProvider(lr(M));let u=await YFe({host:Y9,transport:t,browser:a,instanceId:e.instanceId});u&&(X9=u.stopTerminalHost,Z9=u.stopVfsRpcHost,Q9=u.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw hr(e),e}}async function YFe(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=IFe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=LFe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await XFe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function XFe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-BUJcf-hE.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CMT-jCdn.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{xn as C,vt as D,Bt as E,Mn as S,zt as T,yI as _,Y8 as a,Rn as b,_Ce as c,sQ as d,VK as f,bI as g,UV as h,u5 as i,Txe as l,IH as m,r9 as n,y8 as o,WK as p,n9 as r,_8 as s,UMe as t,fme as u,mP as v,Sn as w,Pn as x,zn as y};