sliccy 5.40.0 → 5.40.1
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.
- package/dist/ui/assets/{account-store-hXYe6llx.js → account-store-DnfeinGB.js} +1 -1
- package/dist/ui/assets/account-store-GtFnwH-H.js +103 -0
- package/dist/ui/assets/adobe-Czhfxi0p.js +1 -0
- package/dist/ui/assets/adobe-DMK4xEaO.js +2 -0
- package/dist/ui/assets/{adobe-oauth-state-DW-IwDjB.js → adobe-oauth-state-DyQZzetd.js} +1 -1
- package/dist/ui/assets/{agent-message-to-chat-BDP4kUxn.js → agent-message-to-chat-Cxc2ezE3.js} +1 -1
- package/dist/ui/assets/anthropic-messages-BP_xL8Mh.js +39 -0
- package/dist/ui/assets/anthropic-messages-BwBPoNP0.js +39 -0
- package/dist/ui/assets/{apps-rQgl-cpB.js → apps-ClA05CCZ.js} +1 -1
- package/dist/ui/assets/{azure-openai-BGD2kY_f.js → azure-openai-BLtYWDqq.js} +1 -1
- package/dist/ui/assets/{azure-openai-Dw-PBopQ.js → azure-openai-BvCVBwdH.js} +1 -1
- package/dist/ui/assets/azure-openai-responses-BXDkTtSH.js +1 -0
- package/dist/ui/assets/azure-openai-responses-De9pJjBR.js +1 -0
- package/dist/ui/assets/bedrock-camp-CZFsedRI.js +1 -0
- package/dist/ui/assets/bedrock-camp-Czep_VHL.js +1 -0
- package/dist/ui/assets/{cerebras-kLjh5Y4m.js → cerebras-CGfTW8cv.js} +1 -1
- package/dist/ui/assets/{cerebras-DlQY_TSV.js → cerebras-DFlg7DL9.js} +1 -1
- package/dist/ui/assets/compat-FrhC6T45.js +2 -0
- package/dist/ui/assets/{connect-surface-B9fZF0bW.js → connect-surface-DxFQNDWS.js} +1 -1
- package/dist/ui/assets/{context-compaction-DaxQExZG.js → context-compaction-LYFtS2_f.js} +1 -1
- package/dist/ui/assets/dip-BjEsG-Hy.js +1 -0
- package/dist/ui/assets/{dist-C4rnF_u9.js → dist-C4FoRFNu.js} +1 -1
- package/dist/ui/assets/{dist-SCTbiXRc.js → dist-xJPdMGJR.js} +1 -1
- package/dist/ui/assets/{ensure-speech-assets-C8wT1Kva.js → ensure-speech-assets-DN2tBkA3.js} +1 -1
- package/dist/ui/assets/error-body-C0EnfbdK.js +1 -0
- package/dist/ui/assets/esp8266-X1cHLEke.js +1 -0
- package/dist/ui/assets/{esptool-operations-D0PMNTBy.js → esptool-operations-CSixDQRB.js} +2 -2
- package/dist/ui/assets/{fs-C9drMRXK.js → fs-B80Ome53.js} +1 -1
- package/dist/ui/assets/{fs-DJdIY3mI.js → fs-CLbTXqU7.js} +2 -2
- package/dist/ui/assets/{github-DRGaGMIq.js → github-CDGV9LOr.js} +1 -1
- package/dist/ui/assets/{github-Dr0PBLdJ.js → github-CF0ypnjs.js} +2 -2
- package/dist/ui/assets/{github-copilot-B5MsC-Mh.js → github-copilot-1jO5YhBA.js} +1 -1
- package/dist/ui/assets/{github-copilot-DTMNK2iN.js → github-copilot-CKMgyVP3.js} +1 -1
- package/dist/ui/assets/google-generative-ai-C58ldv83.js +1 -0
- package/dist/ui/assets/google-generative-ai-Eq6eGS5h.js +1 -0
- package/dist/ui/assets/{google-shared-mehyRjje.js → google-shared-DQbld86Z.js} +1 -1
- package/dist/ui/assets/{google-shared-0Fg2dFO2.js → google-shared-DwCjfFnw.js} +1 -1
- package/dist/ui/assets/google-vertex-C18Xl3dV.js +1 -0
- package/dist/ui/assets/google-vertex-CkkAgSFr.js +1 -0
- package/dist/ui/assets/{hear-CtbSNbmL.js → hear-BA7LmzBZ.js} +1 -1
- package/dist/ui/assets/{kernel-worker-M4OSUjLe.js → kernel-worker-BFPqa_y4.js} +22 -22
- package/dist/ui/assets/{kokoro-engine-CHDadqXT.js → kokoro-engine-DmKFV5gN.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-BNbPpvx4.js → lick-ws-bridge-BWokgV-S.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-HfRG1D9a.js → lick-ws-bridge-Dvo0A29q.js} +1 -1
- package/dist/ui/assets/{local-llm-DMeLZ6lb.js → local-llm-CHb97cbD.js} +1 -1
- package/dist/ui/assets/{main-C_E1hhV6.js → main-CMLc_YHL.js} +4 -4
- package/dist/ui/assets/{mistral-conversations-CoropYyn.js → mistral-conversations-DKqvekSA.js} +2 -2
- package/dist/ui/assets/{mistral-conversations-BD1LHG49.js → mistral-conversations-szVW8BsU.js} +2 -2
- package/dist/ui/assets/{mount-DKLuOjhC.js → mount-B7EzmUC0.js} +2 -2
- package/dist/ui/assets/{mount-DTRYDdBi.js → mount-BvBmQ0-0.js} +1 -1
- package/dist/ui/assets/{new-session-D9geKvL4.js → new-session-DGwIj1BV.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-pcB_o7_p.js → oauth-bootstrap-2pqa5H30.js} +2 -2
- package/dist/ui/assets/{openai-codex-Bm1P7I1P.js → openai-codex-CN1uYxxv.js} +1 -1
- package/dist/ui/assets/{openai-codex-B-tq0InW.js → openai-codex-PE2VxSOv.js} +1 -1
- package/dist/ui/assets/openai-codex-responses-BDYh8ojD.js +7 -0
- package/dist/ui/assets/openai-codex-responses-C7QnNmC0.js +7 -0
- package/dist/ui/assets/openai-completions-BnAjXzgN.js +5 -0
- package/dist/ui/assets/openai-completions-t-glszMQ.js +5 -0
- package/dist/ui/assets/openai-responses-BofM6cmY.js +1 -0
- package/dist/ui/assets/openai-responses-o9_kr7GP.js +1 -0
- package/dist/ui/assets/openai-responses-shared-79gch22X.js +10 -0
- package/dist/ui/assets/openai-responses-shared-DKPwc9Eh.js +10 -0
- package/dist/ui/assets/openrouter-images-D0dgD5eX.js +1 -0
- package/dist/ui/assets/openrouter-images-PT0FZmkM.js +1 -0
- package/dist/ui/assets/{page-follower-tray-CB-5guCo.js → page-follower-tray-fj4kD6LU.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-Bw3OaUZN.js → panel-rpc-handlers-BvcCKs0_.js} +2 -2
- package/dist/ui/assets/{provider-BLHkVFKJ.js → provider-C5S_5LXL.js} +1 -1
- package/dist/ui/assets/{provider-CpPdfI7j.js → provider-CjYJAk12.js} +2 -2
- package/dist/ui/assets/provider-store-access-DbX-7uoI.js +1 -0
- package/dist/ui/assets/provider-store-access-vQAeypVR.js +1 -0
- package/dist/ui/assets/{providers-BeDyVcSi.js → providers-BLSeI6gZ.js} +1 -1
- package/dist/ui/assets/{providers-ekTC5xpd.js → providers-EOfV9vdZ.js} +2 -2
- package/dist/ui/assets/{quick-llm-crEbkH6q.js → quick-llm-CvbElujR.js} +1 -1
- package/dist/ui/assets/session-freezer-CKE1FQU0.js +1 -0
- package/dist/ui/assets/{speak-BKhMmu0q.js → speak-CeaHsGEi.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-DJEGpbEL.js → sprinkle-manager-D17pd_PU.js} +1 -1
- package/dist/ui/assets/{store-SugE11kf.js → store-C1dmcd_Z.js} +1 -1
- package/dist/ui/assets/{sudo-8FlHSwPf.js → sudo-BaZeZrKO.js} +1 -1
- package/dist/ui/assets/transform-messages-DwI5R8if.js +1 -0
- package/dist/ui/assets/{transform-messages-CQuDksPz.js → transform-messages-ZX8cvJiJ.js} +1 -1
- package/dist/ui/assets/{transformers-env-Dm6KYkFB.js → transformers-env-BtZiU9Zy.js} +1 -1
- package/dist/ui/assets/{tray-leader-BEuWSPjO.js → tray-leader-DySjWLR-.js} +1 -1
- package/dist/ui/assets/{tray-leave-runtime-xQpmmvcJ.js → tray-leave-runtime-BTy8ZdNr.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-BmINZ5Oh.js → upgrade-detection-D1RzsLJG.js} +1 -1
- package/dist/ui/assets/{voice-reply-BVSzlCQd.js → voice-reply-DLFM5K98.js} +1 -1
- package/dist/ui/assets/{wc-attach-zuw07y30.js → wc-attach-COndISMH.js} +2 -2
- package/dist/ui/assets/{wc-extension-DkFWiXyA.js → wc-extension-DqsWFOzt.js} +2 -2
- package/dist/ui/assets/{wc-follower-BpVE8bZM.js → wc-follower-8V6fEQ4R.js} +3 -3
- package/dist/ui/assets/{wc-live-DsVoxwUC.js → wc-live-CWjluHxO.js} +5 -5
- package/dist/ui/assets/{wc-nav-D76G_K-8.js → wc-nav-CXUL4V4Y.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-C6hoCgyi.js → wc-onboarding-D9584JBU.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-CCAMhCT0.js → wc-placeholder-WEW27YLe.js} +3 -3
- package/dist/ui/assets/{wc-settings-Ds_UySgO.js → wc-settings-DuuwHWSv.js} +3 -3
- package/dist/ui/assets/{wc-shell-ChVfRkDg.js → wc-shell-BRXA9i_k.js} +3 -3
- package/dist/ui/assets/{wc-sprinkles-ZlT4-gI3.js → wc-sprinkles-C14qdDwd.js} +2 -2
- package/dist/ui/assets/wc-tray-C9VyD3aS.js +2 -0
- package/dist/ui/assets/{whisper-engine-Dq-ISOvb.js → whisper-engine-DT9tB6ou.js} +1 -1
- package/dist/ui/assets/{xai-grok-BeVMpO7i.js → xai-grok-B2ak-_nc.js} +1 -1
- package/dist/ui/assets/{xai-grok-DpCU3Vf9.js → xai-grok-iwV6WbVP.js} +1 -1
- package/dist/ui/index.html +7 -7
- package/dist/ui/packages/webapp/index.html +7 -7
- package/package.json +1 -1
- package/dist/ui/assets/account-store-CEtbM5ni.js +0 -103
- package/dist/ui/assets/adobe-DGmDeCd3.js +0 -2
- package/dist/ui/assets/adobe-cPrvHbnb.js +0 -1
- package/dist/ui/assets/anthropic-messages-DP3-Xd3J.js +0 -39
- package/dist/ui/assets/anthropic-messages-DSmP2_-Q.js +0 -39
- package/dist/ui/assets/azure-openai-responses-CEEm6_Xn.js +0 -1
- package/dist/ui/assets/azure-openai-responses-YO8iO-Ch.js +0 -1
- package/dist/ui/assets/bedrock-camp-DVKDCEuf.js +0 -1
- package/dist/ui/assets/bedrock-camp-DbZ6Mjym.js +0 -1
- package/dist/ui/assets/compat-DADQxxLV.js +0 -2
- package/dist/ui/assets/dip-DLGbA_M8.js +0 -1
- package/dist/ui/assets/esp8266-BhWeHRu0.js +0 -1
- package/dist/ui/assets/google-generative-ai-Cz3VHJVe.js +0 -1
- package/dist/ui/assets/google-generative-ai-DRLjqQHr.js +0 -1
- package/dist/ui/assets/google-vertex-C8F4Q-3-.js +0 -1
- package/dist/ui/assets/google-vertex-DI_ybVGc.js +0 -1
- package/dist/ui/assets/openai-codex-responses-DUWTsNB0.js +0 -7
- package/dist/ui/assets/openai-codex-responses-DcE8b3Us.js +0 -7
- package/dist/ui/assets/openai-completions-2m5htnw8.js +0 -5
- package/dist/ui/assets/openai-completions-CPxuOo6h.js +0 -5
- package/dist/ui/assets/openai-responses-BIaF8Olv.js +0 -1
- package/dist/ui/assets/openai-responses-D3YJWUR5.js +0 -1
- package/dist/ui/assets/openai-responses-shared-1KvKQf-4.js +0 -12
- package/dist/ui/assets/openai-responses-shared-CEQMR7Nx.js +0 -12
- package/dist/ui/assets/openrouter-images-CHaqAs_0.js +0 -1
- package/dist/ui/assets/openrouter-images-CIagBWVL.js +0 -1
- package/dist/ui/assets/provider-store-access-BGivQpbO.js +0 -1
- package/dist/ui/assets/provider-store-access-C4gvtXXH.js +0 -1
- package/dist/ui/assets/session-freezer-2cCjCk93.js +0 -1
- package/dist/ui/assets/transform-messages-D7OsqBmU.js +0 -1
- package/dist/ui/assets/wc-tray-3cfbfVP2.js +0 -2
|
@@ -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,d as o,f as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v,y}from"./proxied-fetch-CEtAlRgC.js";import{n as b,o as x,s as S}from"./tool-ui-t6ocn6AG.js";import{a as C,i as w,n as T,o as E,r as D,t as O}from"./backend-local-Xd3x-KgI.js";import{t as k}from"./runtime-env-byAg9ij-.js";import{t as A}from"./types-idfTVsM8.js";import{n as ee,t as j}from"./mime-types-BqLkKWa7.js";import{a as te,i as ne,n as re,r as ie}from"./mount-
|
|
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,d as o,f as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v,y}from"./proxied-fetch-CEtAlRgC.js";import{n as b,o as x,s as S}from"./tool-ui-t6ocn6AG.js";import{a as C,i as w,n as T,o as E,r as D,t as O}from"./backend-local-Xd3x-KgI.js";import{t as k}from"./runtime-env-byAg9ij-.js";import{t as A}from"./types-idfTVsM8.js";import{n as ee,t as j}from"./mime-types-BqLkKWa7.js";import{a as te,i as ne,n as re,r as ie}from"./mount-BvBmQ0-0.js";import{t as ae}from"./mount-id-nJcx05eu.js";import{n as oe,r as se,t as ce}from"./fetch-body-DDu_AU5I.js";import{t as le}from"./remote-cache-D59F5FOx.js";import{n as ue}from"./mount-table-store-s20mtVA3.js";import{n as M,r as de,t as fe}from"./panel-rpc-CjFVE0nK.js";import{a as pe}from"./providers-BLSeI6gZ.js";import{A as me,B as he,C as ge,D as _e,E as ve,F as ye,I as N,L as be,M as xe,N as Se,O as Ce,P as we,R as P,S as Te,T as F,V as I,_ as Ee,a as De,b as Oe,c as ke,d as Ae,f as je,g as Me,h as Ne,i as Pe,j as Fe,k as Ie,l as Le,m as Re,o as ze,p as Be,r as Ve,s as He,t as Ue,u as We,v as Ge,w as Ke,x as qe,y as Je,z as Ye}from"./account-store-GtFnwH-H.js";import{i as Xe,n as Ze,t as Qe}from"./path-utils-DU6QhF_k.js";import{p as $e,u as et}from"./transform-messages-ZX8cvJiJ.js";import{_ as tt,l as nt,m as rt,p as it,x as at}from"./bedrock-camp-Czep_VHL.js";import{t as ot}from"./__vite-browser-external-SwrSgYTf.js";import{i as st,n as ct,r as lt}from"./fs-B80Ome53.js";const ut=`__slicc_binary__`;function L(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[ut]===`b64`&&typeof t.data==`string`}function dt(e){if(e instanceof Uint8Array)return{[ut]:`b64`,data:y(e)};if(Array.isArray(e))return e.map(dt);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=dt(r);return t}return e}function ft(e){if(L(e))return v(e.data);if(Array.isArray(e))return e.map(ft);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=ft(r);return t}return e}const pt=i(`panel-transport`);function mt(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function ht(){return{onMessage:e=>{let t=(t,n,r)=>(mt(t)&&e(ft(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=dt(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||pt.error(`Offscreen → panel transport send failed`,{error:t})})}}}const gt=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]);var _t=t({formatMountRecoveryPrompt:()=>xt,mdInlineCode:()=>bt,recoverMounts:()=>vt,shellQuote:()=>yt});async function vt(e,t,n){let r=[],i=[];for(let a of e){let{targetPath:e,descriptor:o}=a;if(o.kind===`local`){let a=await ue(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=O.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 le({mountId:o.mountId,ttlMs:3e4}),a=new ne({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:ie(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 le({mountId:o.mountId,ttlMs:3e4}),a=new te({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:re()});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 yt(e){return`'${e.replace(/'/g,`'\\''`)}'`}function bt(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 xt(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 ${bt(t)})`:``;return`- ${bt(e)}${n}`}),i=r.map(({path:e})=>` mount ${yt(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 ${yt(n)}`,a=`mount --source ${yt(t)}${i} ${yt(e)}`;return`- ${bt(e)} (${bt(t)}, profile ${bt(n)}) — ${r}\n Retry: ${bt(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 St=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`sudo-request`,`preview`]);function Ct(e){return e!=null&&St.has(e)}const wt={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 Tt(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 Et(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=xt(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=Mt(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 Dt(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 Ot(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 kt(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function At(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 jt(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 Mt(e,t){let n=Tt(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 Nt(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Mt(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 Pt(e,t){let n=Mt(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 Ft(e){let t=wt[e.type];return e.type===`session-reload`?Et(e,t):e.type===`upgrade`?Dt(e,t):e.type===`cherry`?Ot(e,t):e.type===`preview`?kt(e,t):e.type===`workflow`?At(e,t):e.type===`sudo-request`?jt(e,t):e.type===`navigate`?Pt(e,t):e.type===`webhook`?Nt(e,t):Mt(e,t)}const It=64*1024;function Lt(e,t=It){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${Ht(t)} of ${Ht(e.length)} — the agent received the full output]`}function Rt(e,t=It,n=4){if(typeof e==`string`)return Lt(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=Rt(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=Rt(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}const zt=()=>/<img:data:image\/[^>]+>/g;function Bt(e,t=It){if(!e)return e;if(!zt().test(e))return Lt(e,t);let n=Lt(e.replace(zt(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function Vt(e,t=It){if(e.length<=t)return e;if(!zt().test(e))return Lt(e,t);let n=[],r=0;for(let i of e.matchAll(zt()))n.push(Lt(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(Lt(e.slice(r),t)),n.join(``)}function Ht(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}let Ut={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Wt(){return{...Ut}}function Gt(){let e=Wt();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 Kt=new Set;function qt(e){return Kt.add(e),()=>{Kt.delete(e)}}const Jt={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Yt=null;function Xt(e){if(!e.objectStoreNames.contains(Jt.MESSAGES)){let t=e.createObjectStore(Jt.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(Jt.SESSIONS)||e.createObjectStore(Jt.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(Jt.TASKS)||e.createObjectStore(Jt.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(Jt.STATE)||e.createObjectStore(Jt.STATE,{keyPath:`key`})}function Zt(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 Qt(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(Jt.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);for(let t of e)r.put(Zt(t))};return}t.objectStoreNames.contains(Jt.SCOOPS)||t.createObjectStore(Jt.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function $t(e){e.objectStoreNames.contains(Jt.WEBHOOKS)||e.createObjectStore(Jt.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(Jt.CRONTASKS)||e.createObjectStore(Jt.CRONTASKS,{keyPath:`id`})}function en(e){let t=e.target.result,n=e.oldVersion;n<1&&Xt(t),n<2&&Qt(e,t),n<3&&$t(t)}function tn(){if(!Yt)return null;let e=Object.values(Jt).every(e=>Yt.objectStoreNames.contains(e));return Yt.version===3&&e?Yt:(Yt.close(),Yt=null,null)}function nn(e){e.onversionchange=()=>{e.close(),Yt===e&&(Yt=null)},e.onclose=()=>{Yt===e&&(Yt=null)}}async function rn(){return tn()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=en,n.onsuccess=()=>{let t=n.result;nn(t),Yt=t,e(t)},n.onerror=()=>t(n.error)})}async function an(e,t=`readonly`){return(await rn()).transaction(e,t).objectStore(e)}async function on(e){let t=await an(Jt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function sn(){let e=await an(Jt.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 cn(e){let t=await an(Jt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ln(){let e=await an(Jt.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function un(e){let t=(await an(Jt.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 dn(e){let t=await an(Jt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function fn(e){let t=await an(Jt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function pn(e){let t=(await an(Jt.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 mn(e,t,n){let r=(await an(Jt.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 hn(e){let t=await an(Jt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function gn(e){let t=await an(Jt.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function _n(){let e=await an(Jt.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function vn(e){let t=await an(Jt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function yn(e){let t=await an(Jt.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 bn(e,t){let n=await an(Jt.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 xn(){await rn()}async function Sn(e){let t=await an(Jt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Cn(){try{let e=await an(Jt.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function wn(e){let t=await an(Jt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Tn(e){let t=await an(Jt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function En(){try{let e=await an(Jt.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Dn(e){let t=await an(Jt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}function On(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 kn(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=On(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}const An=`slicc.trayWorkerBaseUrl`,jn=`slicc.trayJoinUrl`,Mn=`https://www.sliccy.ai`;function Nn(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 kn(t.toString());let i=On(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function Pn(e){let t=Nn(e);return t?.joinUrl?t:null}i(`tray-leader`);let Fn={state:`inactive`,session:null,error:null};function In(){return{...Fn,session:Fn.session?{...Fn.session}:null}}function Ln(){let e=In();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 Rn=new Set;function zn(e){return Rn.add(e),()=>{Rn.delete(e)}}const Bn=`sessions`;function Vn(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Bn)||e.createObjectStore(Bn,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Hn=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Vn();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(Bn,`readwrite`);i.objectStore(Bn).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(Bn,`readonly`).objectStore(Bn).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(Bn,`readonly`).objectStore(Bn).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(Bn,`readwrite`);i.objectStore(Bn).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 Un=i(`offscreen-bridge`);function Wn(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 Gn=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||=ht(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Hn;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-${Kn()}`;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)=>{gt.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{gt.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=Rt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Kn(),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=Bt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Vt(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=In(),t=Wt();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}-${Kn()}`,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){Un.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=Wn(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=Ft({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=>{Un.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-BDP4kUxn.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){Un.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:qn(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-BDP4kUxn.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:qn(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){Un.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}-${Kn()}`,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)}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`){S.markMounted(t);return}try{await S.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}),S.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 Kn(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function qn(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 Mt(e,t){let n=Tt(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 Nt(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Mt(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 Pt(e,t){let n=Mt(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 Ft(e){let t=wt[e.type];return e.type===`session-reload`?Et(e,t):e.type===`upgrade`?Dt(e,t):e.type===`cherry`?Ot(e,t):e.type===`preview`?kt(e,t):e.type===`workflow`?At(e,t):e.type===`sudo-request`?jt(e,t):e.type===`navigate`?Pt(e,t):e.type===`webhook`?Nt(e,t):Mt(e,t)}const It=64*1024;function Lt(e,t=It){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${Ht(t)} of ${Ht(e.length)} — the agent received the full output]`}function Rt(e,t=It,n=4){if(typeof e==`string`)return Lt(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=Rt(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=Rt(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}const zt=()=>/<img:data:image\/[^>]+>/g;function Bt(e,t=It){if(!e)return e;if(!zt().test(e))return Lt(e,t);let n=Lt(e.replace(zt(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function Vt(e,t=It){if(e.length<=t)return e;if(!zt().test(e))return Lt(e,t);let n=[],r=0;for(let i of e.matchAll(zt()))n.push(Lt(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(Lt(e.slice(r),t)),n.join(``)}function Ht(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}let Ut={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Wt(){return{...Ut}}function Gt(){let e=Wt();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 Kt=new Set;function qt(e){return Kt.add(e),()=>{Kt.delete(e)}}const Jt={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Yt=null;function Xt(e){if(!e.objectStoreNames.contains(Jt.MESSAGES)){let t=e.createObjectStore(Jt.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(Jt.SESSIONS)||e.createObjectStore(Jt.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(Jt.TASKS)||e.createObjectStore(Jt.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(Jt.STATE)||e.createObjectStore(Jt.STATE,{keyPath:`key`})}function Zt(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 Qt(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(Jt.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);for(let t of e)r.put(Zt(t))};return}t.objectStoreNames.contains(Jt.SCOOPS)||t.createObjectStore(Jt.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function $t(e){e.objectStoreNames.contains(Jt.WEBHOOKS)||e.createObjectStore(Jt.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(Jt.CRONTASKS)||e.createObjectStore(Jt.CRONTASKS,{keyPath:`id`})}function en(e){let t=e.target.result,n=e.oldVersion;n<1&&Xt(t),n<2&&Qt(e,t),n<3&&$t(t)}function tn(){if(!Yt)return null;let e=Object.values(Jt).every(e=>Yt.objectStoreNames.contains(e));return Yt.version===3&&e?Yt:(Yt.close(),Yt=null,null)}function nn(e){e.onversionchange=()=>{e.close(),Yt===e&&(Yt=null)},e.onclose=()=>{Yt===e&&(Yt=null)}}async function rn(){return tn()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=en,n.onsuccess=()=>{let t=n.result;nn(t),Yt=t,e(t)},n.onerror=()=>t(n.error)})}async function an(e,t=`readonly`){return(await rn()).transaction(e,t).objectStore(e)}async function on(e){let t=await an(Jt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function sn(){let e=await an(Jt.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 cn(e){let t=await an(Jt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ln(){let e=await an(Jt.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function un(e){let t=(await an(Jt.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 dn(e){let t=await an(Jt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function fn(e){let t=await an(Jt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function pn(e){let t=(await an(Jt.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 mn(e,t,n){let r=(await an(Jt.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 hn(e){let t=await an(Jt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function gn(e){let t=await an(Jt.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function _n(){let e=await an(Jt.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function vn(e){let t=await an(Jt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function yn(e){let t=await an(Jt.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 bn(e,t){let n=await an(Jt.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 xn(){await rn()}async function Sn(e){let t=await an(Jt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Cn(){try{let e=await an(Jt.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function wn(e){let t=await an(Jt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Tn(e){let t=await an(Jt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function En(){try{let e=await an(Jt.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function Dn(e){let t=await an(Jt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}function On(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 kn(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=On(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}const An=`slicc.trayWorkerBaseUrl`,jn=`slicc.trayJoinUrl`,Mn=`https://www.sliccy.ai`;function Nn(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 kn(t.toString());let i=On(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function Pn(e){let t=Nn(e);return t?.joinUrl?t:null}i(`tray-leader`);let Fn={state:`inactive`,session:null,error:null};function In(){return{...Fn,session:Fn.session?{...Fn.session}:null}}function Ln(){let e=In();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 Rn=new Set;function zn(e){return Rn.add(e),()=>{Rn.delete(e)}}const Bn=`sessions`;function Vn(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Bn)||e.createObjectStore(Bn,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Hn=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await Vn();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(Bn,`readwrite`);i.objectStore(Bn).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(Bn,`readonly`).objectStore(Bn).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(Bn,`readonly`).objectStore(Bn).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(Bn,`readwrite`);i.objectStore(Bn).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 Un=i(`offscreen-bridge`);function Wn(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 Gn=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||=ht(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Hn;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-${Kn()}`;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)=>{gt.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{gt.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=Rt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Kn(),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=Bt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Vt(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=In(),t=Wt();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}-${Kn()}`,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){Un.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=Wn(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=Ft({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=>{Un.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-Cxc2ezE3.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){Un.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:qn(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-Cxc2ezE3.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:qn(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){Un.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}-${Kn()}`,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`){S.markMounted(t);return}try{await S.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}),S.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 Kn(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function qn(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 Jn=i(`cdp`);var Yn=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,Jn.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Jn.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(),Jn.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),Jn.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;Jn.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Jn.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;Jn.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,Jn.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Jn.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 Xn=`(function() {
|
|
7
7
|
'use strict';
|
|
8
8
|
|
|
@@ -7667,7 +7667,7 @@ Install:
|
|
|
7667
7667
|
`,fxe=new Set([`iife`,`cjs`,`esm`]),H3=new Set([`linked`,`inline`,`external`,`both`]),pxe={"-h":`showHelp`,"--help":`showHelp`,"-v":`showVersion`,"--version":`showVersion`,"--bundle":`bundle`,"--transform":`transform`,"--minify":`minify`};function mxe(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 U3(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 hxe(e,t,n,r){if(t.inlineValue!==null){if(!H3.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`&&H3.has(i)?(e.sourcemap=i,1):(e.sourcemap=!0,0)}function gxe(e,t,n,r){if(t.key===`--outfile`){let{value:i,advance:a}=U3(t,n,r);return e.outfile=i,a}if(t.key===`--format`){let{value:i,advance:a}=U3(t,n,r);if(!fxe.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}=U3(t,n,r);return e.target=i.split(`,`).map(e=>e.trim()).filter(Boolean),a}if(t.key===`--loader`){let{value:i,advance:a}=U3(t,n,r);return e.loader=i,a}return-1}function _xe(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=pxe[r];if(i){t[i]=!0;continue}let a=mxe(r);if(a.key===`--sourcemap`){n+=hxe(t,a,e,n);continue}let o=gxe(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 vxe(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(`/`)?uK(r.importer):t;return{path:await yxe(e,e.resolvePath(n,r.path))}}let i=r.importer?.startsWith(`/`)?uK(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:W3(t.path),resolveDir:uK(t.path)})}}}function W3(e){let t=lK(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 yxe(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=dK(t,`index${r}`);if(await e.exists(n))return n}return t}async function G3(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 bxe(){return EA(`esbuild`,async(e,t)=>{let n;try{n=_xe(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:V3,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)
|
|
7668
7668
|
`,exitCode:2};let r;try{r=await M$({ipk:B3(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?xxe(n,t,r):Sxe(n,t,r)})}async function xxe(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=k1(t.stdin),!r)return{stdout:V3,stderr:``,exitCode:0};let a={loader:e.loader??W3(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 G3(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 G3(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function Sxe(e,t,n){if(e.entries.length===0)return{stdout:``,stderr:`esbuild: --bundle requires at least one entry point
|
|
7669
7669
|
`,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:[vxe(t.fs,t.cwd,B3(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 G3(n.formatMessages,r.errors,r.warnings),o=r.outputFiles??[];if(e.outfile){if(o.length===0)return{stdout:``,stderr:`esbuild: build produced no output
|
|
7670
|
-
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e.outfile);await t.fs.writeFile(n,o[0].text);let r=uK(n);for(let e=1;e<o.length;e++){let n=o[e],i=dK(r,lK(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 G3(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function Cxe(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var wxe=class{ops(){return import(`./esptool-operations-
|
|
7670
|
+
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e.outfile);await t.fs.writeFile(n,o[0].text);let r=uK(n);for(let e=1;e<o.length;e++){let n=o[e],i=dK(r,lK(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 G3(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function Cxe(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var wxe=class{ops(){return import(`./esptool-operations-CSixDQRB.js`)}registry(){if(!e1())throw Error(`Web Serial is unavailable in this browser`);return n1()}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)}},Txe=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:Cxe(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 Exe(e,t){return e&&e1()?new wxe:t?new Txe(t):null}const Dxe=new Set([`--vid`,`--pid`,`--baud`,`--data-bits`,`--stop-bits`,`--parity`,`--flow-control`,`--buffer-size`,`--bytes`,`--until`,`--timeout-ms`,`--dtr`,`--rts`,`--break`,`--__resolved`]);function Oxe(e){return lH(e,Dxe)}function K3(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 kxe(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 q3(e){let t={};return e.has(`--vid`)&&(t.usbVendorId=K3(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.usbProductId=K3(e.get(`--pid`),`pid`)),Object.keys(t).length>0?[t]:[]}const Axe=new Set([`none`,`even`,`odd`]),jxe=new Set([`none`,`hardware`]);function Mxe(e){let t={baudRate:e.has(`--baud`)?K3(e.get(`--baud`),`baud`):9600};if(e.has(`--data-bits`)&&(t.dataBits=K3(e.get(`--data-bits`),`data-bits`)),e.has(`--stop-bits`)&&(t.stopBits=K3(e.get(`--stop-bits`),`stop-bits`)),e.has(`--parity`)){let n=e.get(`--parity`);if(!Axe.has(n))throw Error(`invalid --parity: '${n}'`);t.parity=n}if(e.has(`--flow-control`)){let n=e.get(`--flow-control`);if(!jxe.has(n))throw Error(`invalid --flow-control: '${n}'`);t.flowControl=n}return e.has(`--buffer-size`)&&(t.bufferSize=K3(e.get(`--buffer-size`),`buffer-size`)),t}function Nxe(e){let t={};return e.has(`--bytes`)&&(t.maxBytes=K3(e.get(`--bytes`),`bytes`)),e.has(`--until`)&&(t.until=kxe(e.get(`--until`))),e.has(`--timeout-ms`)&&(t.timeoutMs=K3(e.get(`--timeout-ms`),`timeout-ms`)),t}function J3(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 Pxe(e){let t={};return e.has(`--dtr`)&&(t.dataTerminalReady=J3(e.get(`--dtr`),`dtr`)),e.has(`--rts`)&&(t.requestToSend=J3(e.get(`--rts`),`rts`)),e.has(`--break`)&&(t.break=J3(e.get(`--break`),`break`)),t}function Fxe(e){let t=A1(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function Ixe(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function Y3(e){return`0x${e.toString(16).padStart(4,`0`)}`}function X3(e){let t=e.usbVendorId!==void 0||e.usbProductId!==void 0?`${Y3(e.usbVendorId??0)}:${Y3(e.usbProductId??0)}`:`(native serial)`,n=e.opened?` [open]`:``;return`${e.handle}\t${t}${n}`}function Lxe(e){return`cts=${+!!e.clearToSend} dcd=${+!!e.dataCarrierDetect} dsr=${+!!e.dataSetReady} ri=${+!!e.ringIndicator}\n`}function Z3(e){return{stdout:e,stderr:``,exitCode:0}}function Q3(e){return{stdout:``,stderr:`serial: ${e}\n`,exitCode:1}}const Rxe=`serial - access serial ports via Web Serial
|
|
7671
7671
|
|
|
7672
7672
|
Usage: serial <subcommand> [options]
|
|
7673
7673
|
|
|
@@ -7820,8 +7820,8 @@ Options:
|
|
|
7820
7820
|
`;case`idle`:return`enhanced engine: not downloaded (run hear --warmup)
|
|
7821
7821
|
`;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 y6(e){return{stdout:``,stderr:`hear: ${e}\n`,exitCode:1}}function b6(e){return e instanceof Error?e.message:String(e)}function x6(e){let t=e.map((e,t)=>`${e.deviceId}\t${e.label||`Microphone ${t+1}`}`);return t.join(`
|
|
7822
7822
|
`)+(t.length?`
|
|
7823
|
-
`:``)}async function sCe(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:x6((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:y6(`device enumeration unavailable`):{stdout:x6((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return y6(b6(e))}}async function cCe(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-
|
|
7824
|
-
`,stderr:``,exitCode:0}}catch(e){return y6(`transcription failed: ${b6(e)}`)}}async function uCe(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-
|
|
7823
|
+
`:``)}async function sCe(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:x6((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:y6(`device enumeration unavailable`):{stdout:x6((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return y6(b6(e))}}async function cCe(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-BA7LmzBZ.js`);return{stdout:v6(t?n():e()),stderr:``,exitCode:0}}return{stdout:v6(t?await e.panelRpc.call(`hear-warmup`,void 0):await e.panelRpc.call(`hear-status`,void 0)),stderr:``,exitCode:0}}catch(e){return y6(b6(e))}}async function lCe(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 y6(`cannot open ${r}: No such file`)}let o=gK(i);if(!o.startsWith(`audio/`)&&!o.startsWith(`video/`))return y6(`${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-BA7LmzBZ.js`)).hearTranscribe(s,t.lang):await e.panelRpc.call(`hear-transcribe`,{bytes:s,lang:t.lang},{timeoutMs:6e5})).transcript+`
|
|
7824
|
+
`,stderr:``,exitCode:0}}catch(e){return y6(`transcription failed: ${b6(e)}`)}}async function uCe(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-BA7LmzBZ.js`)).hearCapture(r):await e.panelRpc.call(`hear-capture`,r,{timeoutMs:n+3e4});return i.transcript?{stdout:i.transcript+`
|
|
7825
7825
|
`,stderr:``,exitCode:0}:{stdout:``,stderr:`hear: no speech detected
|
|
7826
7826
|
`,exitCode:1}}catch(e){return y6(b6(e))}}function dCe(){return EA(`hear`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return rCe();let n=oCe(e);if(`exitCode`in n)return n;let r={local:de(),panelRpc:M()};return!r.local&&!r.panelRpc?y6(`speech recognition unavailable in this environment`):n.devices?sCe(r):n.status||n.warmup?cCe(r,n.warmup):n.inputFile?lCe(r,n,t):uCe(r,n)})}const S6=[`playwright-cli`,`playwright`,`puppeteer`],C6=new WeakMap;function fCe(e,t){let n=C6.get(e);n||(n=new WeakMap,C6.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 w6(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}const T6=v,pCe=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`,`drop`]);function E6(e){return e.toISOString().replace(/:/g,`-`)}function mCe(e){return e instanceof A||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}const D6=`function(text) {
|
|
7827
7827
|
const el = this;
|
|
@@ -8466,7 +8466,7 @@ Examples:
|
|
|
8466
8466
|
kill -STOP 1024 pause; \`kill -CONT 1024\` resumes
|
|
8467
8467
|
kill -s SIGKILL 1024 explicit signal name
|
|
8468
8468
|
`,stderr:``,exitCode:0}}var p5=t({config:()=>g5,detectRuntime:()=>S5,discoverModels:()=>x5,originOf:()=>b5,register:()=>ZEe,verifyConnection:()=>eDe});const KEe=i(`local-llm`),m5=`local-llm`,h5=`${m5}-unconfigured`,g5={id:m5,name:`Local LLM (OpenAI-compatible)`,description:[`Connect to any OpenAI-compatible local model server.`,``,`Common base URLs:`,` • Ollama http://localhost:11434/v1`,` • LM Studio http://localhost:1234/v1`,` • llama.cpp http://localhost:8080/v1`,` • vLLM http://localhost:8000/v1`,` • mlx_lm http://localhost:8080/v1`,` • Jan http://localhost:1337/v1`,``,`Ollama needs OLLAMA_ORIGINS=* (or chrome-extension://*) so the`,`browser can reach it. macOS: launchctl setenv OLLAMA_ORIGINS "*".`].join(`
|
|
8469
|
-
`),requiresApiKey:!1,optionalApiKey:!0,apiKeyPlaceholder:`Leave empty for local servers, or paste a key for hosted endpoints`,apiKeyEnvVar:`LOCAL_LLM_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`http://localhost:11434/v1`,baseUrlDescription:`Ollama: 11434 • LM Studio: 1234 • llama.cpp/mlx: 8080 • vLLM: 8000 • Jan: 1337. Trailing /v1 required.`,requiresDeployment:!0,deploymentPlaceholder:`llama3.1:8b, qwen2.5-coder:14b`,deploymentDescription:`Comma-separated model IDs from your server. List them with: curl <baseUrl>/models | jq -r .data[].id`,getModelIds:()=>{let e=qEe(Ae(m5));return e.length===0?[{id:h5,name:`Local LLM (set base URL + model IDs in Settings)`,api:`openai`}]:e.map(e=>({id:e,name:e,api:`openai`,input:[`text`],context_window:32e3,max_tokens:4096}))}};function qEe(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const JEe=`${m5}-openai`;function _5(e){return{...e,api:`openai-completions`}}function v5(e){let t=e??{};return!t.apiKey||t.apiKey.length===0?{...t,apiKey:`local`}:t}const YEe=(e,t,n={})=>e.id===h5?y5(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?
|
|
8469
|
+
`),requiresApiKey:!1,optionalApiKey:!0,apiKeyPlaceholder:`Leave empty for local servers, or paste a key for hosted endpoints`,apiKeyEnvVar:`LOCAL_LLM_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`http://localhost:11434/v1`,baseUrlDescription:`Ollama: 11434 • LM Studio: 1234 • llama.cpp/mlx: 8080 • vLLM: 8000 • Jan: 1337. Trailing /v1 required.`,requiresDeployment:!0,deploymentPlaceholder:`llama3.1:8b, qwen2.5-coder:14b`,deploymentDescription:`Comma-separated model IDs from your server. List them with: curl <baseUrl>/models | jq -r .data[].id`,getModelIds:()=>{let e=qEe(Ae(m5));return e.length===0?[{id:h5,name:`Local LLM (set base URL + model IDs in Settings)`,api:`openai`}]:e.map(e=>({id:e,name:e,api:`openai`,input:[`text`],context_window:32e3,max_tokens:4096}))}};function qEe(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const JEe=`${m5}-openai`;function _5(e){return{...e,api:`openai-completions`}}function v5(e){let t=e??{};return!t.apiKey||t.apiKey.length===0?{...t,apiKey:`local`}:t}const YEe=(e,t,n={})=>e.id===h5?y5(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?tt(_5(e),t,v5(n)):y5(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`),XEe=(e,t,n)=>e.id===h5?y5(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?at(_5(e),t,v5(n)):y5(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`);function y5(e,t){let n=$e(),r={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t,timestamp:Date.now()};return queueMicrotask(()=>{n.push({type:`error`,reason:`error`,error:r}),n.end()}),n}function ZEe(){it({api:JEe,stream:YEe,streamSimple:XEe})}function b5(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e.replace(/\/v1\/?$/,``).replace(/\/+$/,``)}}function QEe(e){let t=e.replace(/\/+$/,``);try{let e=new URL(t);if(e.pathname===``||e.pathname===`/`)return`${t}/v1`}catch{}return t}async function x5(e,t,n){let r=`${QEe(e)}/models`,i={Accept:`application/json`};t&&t.length>0&&(i.Authorization=`Bearer ${t}`);let a=await fetch(r,{method:`GET`,headers:i,signal:n});if(!a.ok)throw Error(`GET ${r} -> ${a.status} ${a.statusText}`);let o=await a.json();return Array.isArray(o.data)?o.data.map(e=>e.id??``).filter(e=>e.length>0):[]}async function S5(e,t){let n=b5(e),r=await C5(`${n}/api/version`,t);if(r&&typeof r.version==`string`)return{kind:`ollama`,version:r.version};let i=await C5(`${n}/api/v0/models`,t);if(i&&i.object===`list`)return{kind:`lmstudio`};let a=await C5(`${n}/props`,t);if(a&&`build_info`in a)return{kind:`llamacpp`,version:a.build_info?.version};let o=$Ee(e);return o===`11434`?{kind:`ollama`}:o===`1234`?{kind:`lmstudio`}:o===`8000`?{kind:`vllm`}:o===`1337`?{kind:`jan`}:{kind:`unknown`}}function $Ee(e){try{return new URL(e).port||null}catch{return null}}async function C5(e,t){try{let n=await fetch(e,{method:`GET`,signal:t});return n.ok?await n.json():null}catch{return null}}async function eDe(e,t,n){let r={kind:`unknown`};try{r=await S5(e,n)}catch{}try{let i=await x5(e,t,n);return{ok:!0,runtime:r,models:i}}catch(t){let n=t instanceof Error?t.message:String(t),i=tDe(n,r.kind);return KEe.warn(`verifyConnection failed`,{baseUrl:e,runtime:r.kind,message:n}),{ok:!1,runtime:r,models:[],error:i}}}function tDe(e,t){let n=e.toLowerCase();return n.includes(`failed to fetch`)||n.includes(`networkerror`)?t===`ollama`?{kind:`cors`,message:e,hint:'Ollama rejects requests from non-localhost origins by default. Set OLLAMA_ORIGINS=* (or chrome-extension://*) and restart Ollama. macOS: `launchctl setenv OLLAMA_ORIGINS "*"` then quit and relaunch the Ollama app.'}:{kind:`connection`,message:e,hint:`Server unreachable. Check the URL and that the server is running.`}:n.includes(` 401`)||n.includes(` 403`)?{kind:`auth`,message:e,hint:`Server returned an auth error. If your endpoint requires a key, set it in Settings.`}:/-> \d{3} /.test(e)?{kind:`http`,message:e}:{kind:`unknown`,message:e}}const w5=g5.id;function nDe(){return`local-llm — inspect and configure the Local LLM provider
|
|
8470
8470
|
|
|
8471
8471
|
Usage:
|
|
8472
8472
|
local-llm Show current config + verify connection
|
|
@@ -8532,20 +8532,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
8532
8532
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
8533
8533
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
8534
8534
|
short name resolves on the PATH.
|
|
8535
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return P5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return P5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return P5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
8535
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return P5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return P5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return P5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-C1dmcd_Z.js`).then(e=>e.r);if(await a(i,t.fs))return P5(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>T5),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await mDe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>R5(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 PDe(i,t);let m=await V5(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-C5S_5LXL.js`);e({name:i,serverUrl:r,auth:u})}return N5([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${M5}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
8536
8536
|
`)+`
|
|
8537
8537
|
`)}async function mDe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await Promise.resolve().then(()=>r6),c=await MDe(r.oauthFetchImpl),l=r.oauthLauncher??await z5(),u=await i(e,n,c);j5.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await jDe(),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 hDe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return N5(`usage: mcp list
|
|
8538
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
8538
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-C5S_5LXL.js`);await n();let{listServers:r}=await import(`./store-C1dmcd_Z.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return N5("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 N5(F5(o))}function F5(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(`
|
|
8539
8539
|
`)+`
|
|
8540
8540
|
`}async function gDe(e,t){if(e[0]===`--help`||e[0]===`-h`)return N5(`usage: mcp search <query>
|
|
8541
8541
|
|
|
8542
8542
|
Case-insensitive substring search across the cached tools of every
|
|
8543
8543
|
registered MCP server. Matches tool name OR description and prints a
|
|
8544
8544
|
table of (server, tool, description, match-field) rows.
|
|
8545
|
-
`);if(e.length===0)return P5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
8546
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
8545
|
+
`);if(e.length===0)return P5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-C5S_5LXL.js`);await i();let{listServers:a}=await import(`./store-C1dmcd_Z.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return N5("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 N5(`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,_De(e.description),e.match]);return N5(F5(l))}function _De(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function vDe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?P5(`mcp delete: expected <name>`):N5(`usage: mcp delete <name>
|
|
8546
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-C5S_5LXL.js`);await r(n);let{deleteServer:a}=await import(`./store-C1dmcd_Z.js`).then(e=>e.r),o=await a(n,t.fs);await FDe(n,t),await IDe(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await Promise.resolve().then(()=>r6);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){j5.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?P5(`mcp delete: no server, alias, or account found for "${n}"`):N5([`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(`
|
|
8547
8547
|
`)+`
|
|
8548
|
-
`)}async function yDe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?P5(`mcp invoke: expected <name>`):N5(xDe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
8548
|
+
`)}async function yDe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?P5(`mcp invoke: expected <name>`):N5(xDe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-C5S_5LXL.js`);await i(n);let{getServer:a}=await import(`./store-C1dmcd_Z.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return P5(`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 N5(SDe(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return P5(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=bDe(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return N5(CDe(n,l));let p=wDe(d,l.inputSchema);if(!p.ok)return P5(`mcp invoke: ${p.error}`);let{McpClient:m}=await Promise.resolve().then(()=>T5),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>R5(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=ODe(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function bDe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=I5(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=I5(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 I5(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 xDe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
8549
8549
|
|
|
8550
8550
|
mcp invoke <name> List tools on <name>.
|
|
8551
8551
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -8575,7 +8575,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
8575
8575
|
|
|
8576
8576
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
8577
8577
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
8578
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
8578
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-C5S_5LXL.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-C1dmcd_Z.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return P5(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>T5),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>R5(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return P5(`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 V5(n,d,t);return N5(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function ADe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return N5(`usage: mcp auth <name> [--silent | --interactive]
|
|
8579
8579
|
|
|
8580
8580
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
8581
8581
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -8587,7 +8587,7 @@ Options:
|
|
|
8587
8587
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
8588
8588
|
directly. Use after revoking a refresh token or
|
|
8589
8589
|
when the AS no longer accepts the cached one.
|
|
8590
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return P5(`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 P5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
8590
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return P5(`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 P5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-C5S_5LXL.js`),s=await o(r),{getServer:c}=await import(`./store-C1dmcd_Z.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return P5(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return P5(`mcp auth: server "${r}" does not use OAuth`);if(!s)return P5(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-BLSeI6gZ.js`).then(e=>e.r),f=d(u);if(!f)return P5(`mcp auth: provider "${u}" is not registered`);if(a)return await L5(r,f,t);if(!f.onSilentRenew)return i?P5(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await L5(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 P5(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);j5.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?N5(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?P5(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await L5(r,f,t)}async function L5(e,t,n){if(!t.onOAuthLogin)return P5(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await z5(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?N5(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):P5(`mcp auth: interactive login for "${e}" did not complete`)}async function R5(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await Promise.resolve().then(()=>r6),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-BLSeI6gZ.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){j5.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function z5(){let{createOAuthLauncher:e}=await import(`./oauth-service-8X2UrjIV.js`);return e()}async function jDe(){if(k()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-8X2UrjIV.js`),{origin:t}=await e();return`${t}/auth/callback`}async function MDe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-CEtAlRgC.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 B5(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-B80Ome53.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await Promise.resolve().then(()=>iH);return await t.create({dbName:n})}function NDe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
8591
8591
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
8592
8592
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
8593
8593
|
const escape = (s) => {
|
|
@@ -8601,7 +8601,7 @@ const r = await exec(cmd);
|
|
|
8601
8601
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
8602
8602
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
8603
8603
|
process.exit(r.exitCode || 0);
|
|
8604
|
-
`}async function PDe(e,t){let n=await B5(t.fs);await n.mkdir(M5,{recursive:!0}),await n.writeFile(`${M5}/${e}.jsh`,NDe(e)),t.scriptCatalog?.invalidateJsh()}async function FDe(e,t){let n=await B5(t.fs),r=`${M5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){j5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function IDe(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
8604
|
+
`}async function PDe(e,t){let n=await B5(t.fs);await n.mkdir(M5,{recursive:!0}),await n.writeFile(`${M5}/${e}.jsh`,NDe(e)),t.scriptCatalog?.invalidateJsh()}async function FDe(e,t){let n=await B5(t.fs),r=`${M5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){j5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function IDe(e,t){let{removeAppSprinkles:n}=await import(`./apps-ClA05CCZ.js`);await n(e,t.fs)}async function V5(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-ClA05CCZ.js`);return(await r(e,t,n.fs)).length}catch(t){return j5.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const H5=`/.cache/artificial-analysis.json`;async function LDe(e,t=!1){if(e&&!t)try{let t=await e.readFile(H5),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=d(),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(H5,JSON.stringify(t))}catch{}}return s}function U5(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function RDe(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=U5(e),a=t.find(e=>U5(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 zDe(){return`models - list available LLM models
|
|
8605
8605
|
|
|
8606
8606
|
Usage: models [options]
|
|
8607
8607
|
|
|
@@ -8714,11 +8714,11 @@ Examples:
|
|
|
8714
8714
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
8715
8715
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
8716
8716
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
8717
|
-
`}function nOe(){return EA(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await Promise.resolve().then(()=>r6),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-
|
|
8717
|
+
`}function nOe(){return EA(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await Promise.resolve().then(()=>r6),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-BLSeI6gZ.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:tOe(),stderr:``,exitCode:0};if(e.includes(`--list`))return aOe(i,o,a,n);if(e.includes(`--renew`))return rOe(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return iOe(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
|
|
8718
8718
|
`,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
|
|
8719
8719
|
`,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
|
|
8720
8720
|
`,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-8X2UrjIV.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-8X2UrjIV.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
|
|
8721
|
-
`,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 rOe(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await Promise.resolve().then(()=>r6),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-
|
|
8721
|
+
`,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 rOe(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await Promise.resolve().then(()=>r6),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-BLSeI6gZ.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 J5(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return J5(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return J5(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${K5(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: ${K5(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(`
|
|
8722
8722
|
`)+`
|
|
8723
8723
|
`,stderr:``,exitCode:+!u}}function K5(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 iOe(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-8X2UrjIV.js`),i,a=e.indexOf(`--from-file`);if(a>=0){let n=e[a+1];if(!n)return J5(`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 J5(`oauth-token: failed to read ${n}: ${e instanceof Error?e.message:String(e)}`)}}else{let t=q5(e,`--authorize-url`),n=q5(e,`--redirect-pattern`);if(!t)return J5(`oauth-token: --authorize-url is required`);if(!n)return J5(`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 J5(`oauth-token: --rewrite requires a value`);let i=n.split(`=`);if(i.length<3)return J5(`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 J5(`oauth-token: invalid intercept config: ${o.error}`);let s=await r();if(!s)return J5(`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}:J5(`oauth-token: intercept timed out or was cancelled`)}function q5(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function J5(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function aOe(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
8724
8724
|
`,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(`
|
|
@@ -8862,11 +8862,11 @@ Examples:
|
|
|
8862
8862
|
`,stderr:``,exitCode:0}}function _7(e){switch(e.state){case`ready`:return`voice engine: ready
|
|
8863
8863
|
`;case`failed`:return`voice engine: failed (re-run say --warmup to retry)
|
|
8864
8864
|
`;case`idle`:return`voice engine: not downloaded (run say --warmup)
|
|
8865
|
-
`;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 v7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function y7(e){return e instanceof Error?e.message:String(e)}let b7=!1,x7=null;function S7(){return b7?Promise.resolve(speechSynthesis.getVoices()):(x7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){b7=!0,e(t);return}let n=()=>{b7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),b7=!0,e(speechSynthesis.getVoices())},1e3)}),x7)}const C7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function ske(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 cke(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 C7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return v7(`${i} requires ${C7[i]}`);let a=ske(t,i,n);if(a)return v7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return v7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function w7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function lke(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-
|
|
8865
|
+
`;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 v7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function y7(e){return e instanceof Error?e.message:String(e)}let b7=!1,x7=null;function S7(){return b7?Promise.resolve(speechSynthesis.getVoices()):(x7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){b7=!0,e(t);return}let n=()=>{b7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),b7=!0,e(speechSynthesis.getVoices())},1e3)}),x7)}const C7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function ske(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 cke(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 C7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return v7(`${i} requires ${C7[i]}`);let a=ske(t,i,n);if(a)return v7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return v7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function w7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function lke(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-CeaHsGEi.js`),t=e().map(e=>w7({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await S7()).map(e=>w7({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
|
|
8866
8866
|
`)+`
|
|
8867
8867
|
`,stderr:``,exitCode:0}}try{return{stdout:(await e.panelRpc.call(`list-voices`,void 0)).voices.map(e=>w7(e)).join(`
|
|
8868
8868
|
`)+`
|
|
8869
|
-
`,stderr:``,exitCode:0}}catch(e){return v7(y7(e))}}async function uke(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-
|
|
8869
|
+
`,stderr:``,exitCode:0}}catch(e){return v7(y7(e))}}async function uke(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-CeaHsGEi.js`),n=t().map(e=>({name:e.id})),r=(await S7()).map(e=>({name:e.name}));return[...n,...r]}async function dke(e,t){let n=(await uke(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:v7(`voice "${t}" not found. Use --list to see available voices.`)}}async function T7(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speak-CeaHsGEi.js`);return{stdout:_7(t?n():e()),stderr:``,exitCode:0}}return{stdout:_7(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return v7(y7(e))}}async function fke(e,t){return t.includes(`--list`)?lke(e):t.includes(`--status`)?T7(e,!1):t.includes(`--warmup`)?T7(e,!0):null}async function pke(e){try{let{speak:t}=await import(`./speak-CeaHsGEi.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return v7(`speech synthesis error: ${y7(e)}`)}}async function mke(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(e){return v7(y7(e))}}async function hke(e){let{synthesizeToWav:t}=await import(`./speak-CeaHsGEi.js`);try{return{bytes:await t(e)}}catch(e){return v7(y7(e))}}async function gke(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 v7(y7(e))}}async function _ke(e,t,n,r){let i=e.local?await hke(r):await gke(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 v7(`failed to write ${n}: ${y7(e)}`)}return{stdout:`wrote ${Math.max(1,Math.round(i.bytes.byteLength/1024))} KB to ${a}\n`,stderr:``,exitCode:0}}function vke(){return EA(`say`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return g7();let n={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:M()};if(!n.local&&!n.panelRpc)return v7(`Web Speech API unavailable in this environment`);let r=await fke(n,e);if(r)return r;let i=cke(e);if(`exitCode`in i)return i;if(!i.text)return g7();if(!i.lang)return v7(`-l language tag is required`);let a;if(i.voiceName){let{resolved:e,error:t}=await dke(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?_ke(n,t,i.outFile,o):n.local?pke(o):mke(n,o)})}function yke(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
|
|
8870
8870
|
|
|
8871
8871
|
Usage: screencapture [options] <output-file>
|
|
8872
8872
|
|
|
@@ -10230,7 +10230,7 @@ pass --wait to block and print the full result.
|
|
|
10230
10230
|
`)}async function VMe(e,t){let n=zMe(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:BMe(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function HMe(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 UMe(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>LMe(t,e.getScoopTabState)).join(`
|
|
10231
10231
|
`)}`}}function WMe(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 GMe(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 KMe(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c}=e,l=IMe(c);if(!l.ok)return{content:l.content,isError:l.isError};let u=FMe(n);try{let e=WMe(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?GMe(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 qMe(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 JMe(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 YMe(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 XMe(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(...YMe(s,o)),{content:c.join(`
|
|
10232
10232
|
`)}}function ZMe(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 QMe(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 $Me(e,t){let{scoop_names:n,timeout_ms:r}=e,i=ZMe(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:QMe(u,o,d,r)}}function eNe(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 tNe(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:eNe(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 nNe(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 rNe(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(`
|
|
10233
|
-
`)}`}}async function iNe(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 aNe(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=>RMe(t,e)}}function oNe(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=>VMe(t,e)}}function sNe(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=>HMe(t,e)}}function cNe(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>UMe(e)}}function lNe(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:[...li],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=>KMe(t,e)}}function uNe(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=>qMe(t,e)}}function dNe(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=>JMe(t,e)}}function fNe(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=>XMe(t,e)}}function pNe(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=>$Me(t,e)}}function mNe(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=>tNe(t,e)}}function hNe(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=>nNe(t,e)}}function gNe(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:()=>rNe(e)}}function _Ne(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=>iNe(t,e)}}function vNe(e){let t=[],n=e.scoop.isCone;return n||(t.push(aNe(e)),e.onSudoRequest&&t.push(oNe(e))),n&&(e.onFeedScoop&&t.push(sNe(e)),t.push(cNe(e)),e.onScoopScoop&&t.push(lNe(e)),e.onDropScoop&&t.push(uNe(e)),e.onMuteScoops&&t.push(dNe(e)),e.onUnmuteScoops&&t.push(fNe(e)),e.onScheduleScoopWait&&t.push(pNe(e)),e.onSudoResolve&&(t.push(mNe(e)),t.push(hNe(e))),e.onListSudoRequests&&t.push(gNe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(_Ne(e))),t}const P9=i(`scoop-context`);function F9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!et(t).includes(`xhigh`)?`high`:e}function yNe(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 bNe(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 xNe=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;coneJid;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,t=this.scoop.isCone,n=this.scoop.folder,r=this.callbacks.onSudoRequest,i=t||!r?e.getBroker():{requestApproval:e=>r(e)},a=t?()=>e.getPolicy():()=>e.getPolicyForScoop(n),o=t?`allow`:`require-approval`,s=e.getShellConfig(),c=t?s.persistCommandGrant:async()=>{};return{broker:i,getPolicy:a,defaultDisposition:o,shellConfig:{...s,broker:i,getPolicy:a,defaultDisposition:o,persistCommandGrant:c}}}async initShellAndSkills(){let e=this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await ZF(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await Gue(),i=this.buildSudoWiring(),a=i?Ece(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new TMe({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 XF(n,this.skillsDir)}}async buildTools(e){let t=vNe({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=[...jMe(e),AMe(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:Se()};return this.processManager?Fe(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):Fe(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=N(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 Ace(this.scoop,this.coneJid),n=(e,n,r)=>e.provider===`adobe`?at(e,n,{...r,headers:{...r?.headers,"X-Session-Id":t}}):at(e,n,r),r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=this.scoop.isCone&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:ze()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:ye({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>ze()??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(!ze()){P9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?ve(this.scoop.config.modelId):F(),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.agent=new Ye({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>ze()??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=Ge()}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 bNe(e)?(P9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),ur(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!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}),ur(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{return await e.prompt(t,n),this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(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?ve(this.scoop.config.modelId):F();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=F();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=F9(t,e),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 XF(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){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;let t=F9(e,this.agent.state.model);return this.agent.state.thinkingLevel=t,t}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(li.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(`
|
|
10233
|
+
`)}`}}async function iNe(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 aNe(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=>RMe(t,e)}}function oNe(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=>VMe(t,e)}}function sNe(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=>HMe(t,e)}}function cNe(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>UMe(e)}}function lNe(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:[...li],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=>KMe(t,e)}}function uNe(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=>qMe(t,e)}}function dNe(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=>JMe(t,e)}}function fNe(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=>XMe(t,e)}}function pNe(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=>$Me(t,e)}}function mNe(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=>tNe(t,e)}}function hNe(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=>nNe(t,e)}}function gNe(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:()=>rNe(e)}}function _Ne(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=>iNe(t,e)}}function vNe(e){let t=[],n=e.scoop.isCone;return n||(t.push(aNe(e)),e.onSudoRequest&&t.push(oNe(e))),n&&(e.onFeedScoop&&t.push(sNe(e)),t.push(cNe(e)),e.onScoopScoop&&t.push(lNe(e)),e.onDropScoop&&t.push(uNe(e)),e.onMuteScoops&&t.push(dNe(e)),e.onUnmuteScoops&&t.push(fNe(e)),e.onScheduleScoopWait&&t.push(pNe(e)),e.onSudoResolve&&(t.push(mNe(e)),t.push(hNe(e))),e.onListSudoRequests&&t.push(gNe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(_Ne(e))),t}const P9=i(`scoop-context`);function F9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!et(t).includes(`xhigh`)?`high`:e}function yNe(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 bNe(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 xNe=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 ZF(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await Gue(),i=this.buildSudoWiring(),a=i?Ece(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new TMe({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 XF(n,this.skillsDir)}}async buildTools(e){let t=vNe({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=[...jMe(e),AMe(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:Se()};return this.processManager?Fe(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):Fe(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=N(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 Ace(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?rt(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):rt(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:ze()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:ye({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>ze()??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(!ze()){P9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?ve(this.scoop.config.modelId):F(),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 Ye({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>ze()??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=Ge()}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 bNe(e)?(P9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),ur(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!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}),ur(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{return await e.prompt(t,n),this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(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?ve(this.scoop.config.modelId):F();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=F();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 XF(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(li.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(`
|
|
10234
10234
|
`);if(e.isError){let t=n.filter(e=>!e.startsWith(`<img:`)).join(`
|
|
10235
10235
|
`);ur(`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&&yNe(n)){this.recoverFromImageError(e);return}if(!this.isRecovering&&ci(t)){this.recoverFromOverflow(e);return}if(!this.isRecovering&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=n;return}this.isRecovering=!1,ur(`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
|
|
10236
10236
|
|
|
@@ -10313,8 +10313,8 @@ ${e}
|
|
|
10313
10313
|
---
|
|
10314
10314
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
10315
10315
|
${t}
|
|
10316
|
-
---`);let a=Sue(n);return a&&(i+=a),i}};const R9=i(`scoop-lifecycle-manager`);var SNe=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 lt(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 xNe(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||pr(`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){let n=this.deps.getScoops().get(e);if(!n)return null;let r=this.contexts.get(e),i=r?r.setThinkingLevel(t):null;if(t===void 0){if(n.config&&n.config.thinkingLevel!==void 0){let{thinkingLevel:e,...t}=n.config;n.config=t}}else n.config={...n.config??{},thinkingLevel:t};try{await this.deps.db.saveScoop(n)}catch(t){R9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return i}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),pr(`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}),pr(`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 CNe=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}`);pr(`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}: ${be(e.content,e.attachments)}`).join(`
|
|
10317
|
-
`),c=o.flatMap(e=>P(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 wNe=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Tue({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new Wue({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Uue({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Bue({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 Lue({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>pn(e),saveMessage:e=>dn(e)});lickRegistry=new Fue({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 CNe({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=>dn(e),deleteMessage:e=>fn(e),clearMessagesForScoop:e=>un(e),clearAllMessages:()=>ln(),getMessagesSince:(e,t,n)=>mn(e,t,n),setState:(e,t)=>bn(e,t)},isExternalLickChannel:Ct});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new SNe({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=>on(e),deleteScoop:e=>cn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>_I(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 xn(),this.sharedFs=await ct.create({dbName:`slicc-fs`}),this.sessionStore=new xe,this.fsWatcher=new st,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new zP({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await sn();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 yn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Iue({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);cP(()=>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 ct.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await ZF(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 zP({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 pn(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t){return this.lifecycle.setThinkingLevel(e,t)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&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`)}},TNe=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 A(`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 A(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=H9(e);if(t.length!==2)throw new A(`EISDIR`,`is a directory`,e);let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new A(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new A(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=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 A(`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 A(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new A(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new A(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new A(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new A(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new A(`EBADF`,`mount closed`,e)}pidExists(e){return e===1?!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 jNe(t);let n=this.pm.get(e);switch(t){case`status`:return ENe(n);case`cmdline`:return DNe(n);case`cwd`:return ONe(n);case`stat`:return kNe(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 ENe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${W9(e.status)} (${e.status})`,`Owner:\t${ANe(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(`
|
|
10316
|
+
---`);let a=Sue(n);return a&&(i+=a),i}};const R9=i(`scoop-lifecycle-manager`);var SNe=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 lt(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 xNe(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||pr(`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)),pr(`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}),pr(`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 CNe=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}`);pr(`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}: ${be(e.content,e.attachments)}`).join(`
|
|
10317
|
+
`),c=o.flatMap(e=>P(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 wNe=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Tue({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new Wue({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Uue({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Bue({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 Lue({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>pn(e),saveMessage:e=>dn(e)});lickRegistry=new Fue({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 CNe({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=>dn(e),deleteMessage:e=>fn(e),clearMessagesForScoop:e=>un(e),clearAllMessages:()=>ln(),getMessagesSince:(e,t,n)=>mn(e,t,n),setState:(e,t)=>bn(e,t)},isExternalLickChannel:Ct});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new SNe({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=>on(e),deleteScoop:e=>cn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>_I(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 xn(),this.sharedFs=await ct.create({dbName:`slicc-fs`}),this.sessionStore=new xe,this.fsWatcher=new st,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new zP({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await sn();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 yn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Iue({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);cP(()=>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 ct.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await ZF(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 zP({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 pn(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`)}},TNe=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 A(`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 A(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=H9(e);if(t.length!==2)throw new A(`EISDIR`,`is a directory`,e);let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new A(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new A(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new A(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=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 A(`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 A(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new A(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new A(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new A(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new A(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new A(`EBADF`,`mount closed`,e)}pidExists(e){return e===1?!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 jNe(t);let n=this.pm.get(e);switch(t){case`status`:return ENe(n);case`cmdline`:return DNe(n);case`cwd`:return ONe(n);case`stat`:return kNe(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 ENe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${W9(e.status)} (${e.status})`,`Owner:\t${ANe(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(`
|
|
10318
10318
|
`)+`
|
|
10319
10319
|
`}function DNe(e){return e.argv.join(`\0`)+`\0`}function ONe(e){return e.cwd+`
|
|
10320
10320
|
`}function kNe(e){return[e.pid,`(${e.kind})`,W9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
@@ -10323,4 +10323,4 @@ ${t}
|
|
|
10323
10323
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
10324
10324
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
10325
10325
|
`}}function MNe(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 NNe(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 PNe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}FNe(e,t)}function FNe(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=Ft(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=MNe(e),a=NNe(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 INe(e,t,n,r){let i=new sW,a=new wNe(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=zn(()=>n.emitTrayRuntimeStatus()),s=qt(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function LNe(e,t,n){let{registerSessionCostsProvider:r}=await Promise.resolve().then(()=>uce);r(()=>e.getSessionCosts());let{getLickManager:i}=await Promise.resolve().then(()=>jue),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??PNe,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function RNe(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 zNe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;Zje({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>j1(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>g9().slice(10,22),splitResult:(e,t)=>_9(e,t)})}async function BNe(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))+`
|
|
10326
|
-
`,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 VNe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-HfRG1D9a.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 HNe(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 ai(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 UNe(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(()=>_t),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 WNe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-BmINZ5Oh.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 GNe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await Promise.resolve().then(()=>v_e),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 KNe(){return he()}async function qNe(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 INe(t,n,r,i);if(d?xi(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new TNe(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await LNe(c,e,o);d&&zNe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await BNe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;KNe()&&(h=await VNe(f,o,e.localLickWsUrl??null));let g=HNe(n,f,o);d&&UNe(d,f,o),a||await RNe(c),d&&WNe(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await GNe(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 JNe({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 JNe(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)}YNe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function YNe(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[p9]}const G9=`x-bypass-llm-proxy`;function XNe(e,t,n){return t?(r,i)=>{if(!ZNe(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 ZNe(e,t,n){if($Ne(e,t))return!0;let r=n?.()??null;return r?QNe(e,r,t):!1}function QNe(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 $Ne(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 ePe(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 tPe=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(!nPe(e)||e.source!==`panel`)return;let t=e.payload;rPe(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 nPe(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 rPe(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 iPe=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 aPe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new tPe({transport:t,processManager:i,createShell:(e,a)=>new iPe(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 oPe(e){let t=new sPe(e);return t.start(),{stop:()=>t.dispose()}}var sPe=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(!cPe(e)||e.source!==`panel`)return;let t=e.payload;if(lPe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(uPe(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 A(`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 A(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async 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(dPe(e.type),e.requestId,new A(`EACCES`,`vfs-rpc-host has no writable backend wired`),fPe(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 A(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new A(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}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 cPe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function lPe(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 uPe(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 dPe(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 fPe(e){return e.type===`vfs-flush`?``:e.path}function J9(e,t){return e instanceof A?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function pPe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=XNe(e.bind(globalThis),t,mPe)}function mPe(){let e=c();if(!e)return null;try{return new URL(e).origin}catch{return null}}function hPe(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 gPe=ePe(e=>_Pe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&gPe.handle(e.data)});async function _Pe(e){pPe(),l(e.localApiBaseUrl??null),h(e.bridgeToken??null),a(e.extensionDelegateId??null),hPe(e.localStorageSeed??{}),Tr().catch(()=>{}),await pe();let t=Lr(e.kernelPort),n=new Gn(t),r=Gn.createCallbacks(n),i=new Rr(e.cdpPort);await i.connect();let o=new tr(i);Y9=await qNe({container:{},browser:o,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:s}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),c=s({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=c;let u=Y9.sharedFs?.getWatcher();if(u){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)u.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)c.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider(sr(M));let f=await vPe({host:Y9,transport:t,browser:o,instanceId:e.instanceId});f&&(X9=f.stopTerminalHost,Z9=f.stopVfsRpcHost,Q9=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}async function vPe(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=aPe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=oPe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await yPe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function yPe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-C8wT1Kva.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CEtAlRgC.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{yn as C,gt as D,Rt as E,An as S,Lt as T,NI as _,Q8 as a,In as b,nSe as c,dQ as d,gK as f,PI as g,aH as h,p5 as i,ube as l,LH as m,o9 as n,S8 as o,yK as p,a9 as r,b8 as s,Dje as t,rpe as u,OP as v,bn as w,Mn as x,Ln as y};
|
|
10326
|
+
`,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 VNe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-Dvo0A29q.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 HNe(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 ai(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 UNe(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(()=>_t),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 WNe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-D1RzsLJG.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 GNe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await Promise.resolve().then(()=>v_e),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 KNe(){return he()}async function qNe(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 INe(t,n,r,i);if(d?xi(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new TNe(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await LNe(c,e,o);d&&zNe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await BNe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;KNe()&&(h=await VNe(f,o,e.localLickWsUrl??null));let g=HNe(n,f,o);d&&UNe(d,f,o),a||await RNe(c),d&&WNe(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await GNe(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 JNe({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 JNe(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)}YNe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function YNe(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[p9]}const G9=`x-bypass-llm-proxy`;function XNe(e,t,n){return t?(r,i)=>{if(!ZNe(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 ZNe(e,t,n){if($Ne(e,t))return!0;let r=n?.()??null;return r?QNe(e,r,t):!1}function QNe(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 $Ne(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 ePe(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 tPe=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(!nPe(e)||e.source!==`panel`)return;let t=e.payload;rPe(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 nPe(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 rPe(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 iPe=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 aPe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new tPe({transport:t,processManager:i,createShell:(e,a)=>new iPe(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 oPe(e){let t=new sPe(e);return t.start(),{stop:()=>t.dispose()}}var sPe=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(!cPe(e)||e.source!==`panel`)return;let t=e.payload;if(lPe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(uPe(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 A(`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 A(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async 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(dPe(e.type),e.requestId,new A(`EACCES`,`vfs-rpc-host has no writable backend wired`),fPe(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 A(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new A(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}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 cPe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function lPe(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 uPe(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 dPe(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 fPe(e){return e.type===`vfs-flush`?``:e.path}function J9(e,t){return e instanceof A?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function pPe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=XNe(e.bind(globalThis),t,mPe)}function mPe(){let e=c();if(!e)return null;try{return new URL(e).origin}catch{return null}}function hPe(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 gPe=ePe(e=>_Pe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&gPe.handle(e.data)});async function _Pe(e){pPe(),l(e.localApiBaseUrl??null),h(e.bridgeToken??null),a(e.extensionDelegateId??null),hPe(e.localStorageSeed??{}),Tr().catch(()=>{}),await pe();let t=Lr(e.kernelPort),n=new Gn(t),r=Gn.createCallbacks(n),i=new Rr(e.cdpPort);await i.connect();let o=new tr(i);Y9=await qNe({container:{},browser:o,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:s}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),c=s({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=c;let u=Y9.sharedFs?.getWatcher();if(u){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)u.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)c.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider(sr(M));let f=await vPe({host:Y9,transport:t,browser:o,instanceId:e.instanceId});f&&(X9=f.stopTerminalHost,Z9=f.stopVfsRpcHost,Q9=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}async function vPe(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=aPe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=oPe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await yPe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function yPe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DN2tBkA3.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CEtAlRgC.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{yn as C,gt as D,Rt as E,An as S,Lt as T,NI as _,Q8 as a,In as b,nSe as c,dQ as d,gK as f,PI as g,aH as h,p5 as i,ube as l,LH as m,o9 as n,S8 as o,yK as p,a9 as r,b8 as s,Dje as t,rpe as u,OP as v,bn as w,Mn as x,Ln as y};
|