sliccy 2.50.1 → 2.50.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/node-server/chrome-launch.d.ts +57 -0
  2. package/dist/node-server/chrome-launch.js +74 -1
  3. package/dist/node-server/index.js +26 -5
  4. package/dist/ui/assets/{adobe-Lb2H770K.js → adobe-DUtaWS08.js} +1 -1
  5. package/dist/ui/assets/{adobe-B6ZzdYYn.js → adobe-DyivPKeZ.js} +1 -1
  6. package/dist/ui/assets/{agent-bridge-B8Wt0_SR.js → agent-bridge-CwcUwWSd.js} +1 -1
  7. package/dist/ui/assets/{agent-message-to-chat-B43li_Kr.js → agent-message-to-chat-CImm2vOT.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-DCwrMJpF.js → azure-openai-CWUoVLgB.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-CqPJtB1j.js → azure-openai-iR8v3vNp.js} +1 -1
  10. package/dist/ui/assets/{cdp-DoCAWJnr.js → cdp-BqE7lRro.js} +3 -3
  11. package/dist/ui/assets/cost-command-DbyN_w4x.js +1 -0
  12. package/dist/ui/assets/{es-BhhLePsi.js → es-Dn0gWvf2.js} +1 -1
  13. package/dist/ui/assets/{fs-2sT7KQgc.js → fs-BHjUDaPI.js} +1 -1
  14. package/dist/ui/assets/{fs-D66OodlB.js → fs-DR9Kg_gg.js} +2 -2
  15. package/dist/ui/assets/{github-Ci5CeNMP.js → github-C4yRzqy8.js} +1 -1
  16. package/dist/ui/assets/{github-Co3G1bcS.js → github-_05uBVE2.js} +2 -2
  17. package/dist/ui/assets/{index-Bq4R2DIC.js → index-BbIDJNZM.js} +5 -5
  18. package/dist/ui/assets/{kernel-worker-HRJvl7xM.js → kernel-worker-iLIRf2UW.js} +9 -9
  19. package/dist/ui/assets/{local-llm-BMOoTlOp.js → local-llm-DDeUXsOw.js} +1 -1
  20. package/dist/ui/assets/{local-llm-BlJ8NcSI.js → local-llm-DQTKwWew.js} +1 -1
  21. package/dist/ui/assets/{magick-wasm-BU1WL1Qf.js → magick-wasm-Bxy887fy.js} +1 -1
  22. package/dist/ui/assets/{mount-BC9F6LaZ.js → mount-BlPJ6Tdt.js} +1 -1
  23. package/dist/ui/assets/{mount-BFAEJSOk.js → mount-XZ9QStv8.js} +2 -2
  24. package/dist/ui/assets/{nuke-command-_5HS9UZu.js → nuke-command-DRPb3203.js} +1 -1
  25. package/dist/ui/assets/{oauth-bootstrap-BBwF_o-P.js → oauth-bootstrap-BcPvzxBK.js} +1 -1
  26. package/dist/ui/assets/{oauth-service-DDqMLBsS.js → oauth-service-CfvA2rAX.js} +1 -1
  27. package/dist/ui/assets/{offscreen-client-Cs8p2QtE.js → offscreen-client-D-QLFw1K.js} +1 -1
  28. package/dist/ui/assets/{onboarding-orchestrator-Dabb2uEJ.js → onboarding-orchestrator-C9pDcsCa.js} +1 -1
  29. package/dist/ui/assets/{provider-settings-DbAAu75J.js → provider-settings-B_lSRZ0U.js} +1 -1
  30. package/dist/ui/assets/{provider-settings-BCl4HZqa.js → provider-settings-DGXqU1Yt.js} +3 -3
  31. package/dist/ui/assets/{providers-hylnGcn1.js → providers-B3LV-JEw.js} +1 -1
  32. package/dist/ui/assets/{spawn-CksrpU9U.js → spawn-CGCJ3d87.js} +1 -1
  33. package/dist/ui/assets/{upgrade-detection-BNmWyZeI.js → upgrade-detection-BWEeiTSq.js} +1 -1
  34. package/dist/ui/index.html +4 -4
  35. package/dist/ui/packages/webapp/index.html +4 -4
  36. package/package.json +1 -1
  37. package/dist/ui/assets/cost-command-Ba-NeOIy.js +0 -1
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,r as n,t as r}from"./chunk-jRWAZmH_.js";import{t as i}from"./logger-BHrAkMIS.js";import{S as a,_ as o,a as s,b as c,c as l,d as u,f as d,g as f,h as p,i as m,l as h,m as g,n as _,o as v,p as y,r as b,s as x,t as S,u as C,v as w,x as T,y as E}from"./db-DPvmo9md.js";import{C as D,S as O,_ as ee,b as te,c as ne,d as k,g as re,h as ie,m as ae,n as oe,p as se,r as ce,u as le,v as ue,x as de,y as fe}from"./provider-settings-DbAAu75J.js";import{a as A,o as pe,t as me}from"./tool-ui-D9h6SJkp.js";import{i as he,n as ge,r as _e}from"./fs-2sT7KQgc.js";import{i as ve,n as ye,r as be,t as xe}from"./backend-local-P05Hg6Af.js";import{n as j,t as Se}from"./path-utils-CgbXfwyO.js";import{t as Ce}from"./mount-id-Ccy4_G8i.js";import{n as we}from"./mount-table-store-BDnU4NqG.js";import{a as Te,i as Ee,r as M,t as De}from"./git-config-CxvDN7N3.js";import{n as N,t as P}from"./mime-types-DVkB7Eq7.js";import{_ as Oe,a as ke,c as Ae,d as je,f as Me,g as Ne,h as Pe,i as Fe,l as Ie,m as Le,o as Re,p as ze,r as Be,s as Ve,t as He,u as Ue,v as We}from"./magick-wasm-CTqVspRN.js";import{c as Ge,o as Ke}from"./bedrock-camp-9aDiXDk5.js";import{f as qe}from"./transform-messages-uhk4b6os.js";import{i as Je}from"./providers-hylnGcn1.js";import{t as Ye}from"./local-llm-BlJ8NcSI.js";import{a as Xe,i as Ze,n as Qe,r as $e}from"./mount-BC9F6LaZ.js";import{t as et}from"./remote-cache-DdfqyJ2A.js";const tt=i(`cdp`);var nt=class{ws=null;nextId=1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}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}=e;return this._state=`connecting`,new Promise((e,r)=>{let i=setTimeout(()=>{this.cleanup(),r(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=new WebSocket(t)}catch(e){clearTimeout(i),this._state=`disconnected`,r(e);return}this.ws.onopen=()=>{clearTimeout(i),this._state=`connected`,tt.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(i),this._state===`connecting`&&(tt.error(`Connection failed`,{url:t}),this.cleanup(),r(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=()=>{this.handleClose()}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this.cleanup(),tt.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),tt.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;tt.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(tt.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;tt.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(){tt.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});for(let[,e]of this.pending)e.reject(Error(`CDP connection closed`));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};function rt(e,t=``){if(e==null)return t;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)??t}catch{return String(e)}}const it=`(function() {
1
+ import{i as e,o as t,r as n,t as r}from"./chunk-jRWAZmH_.js";import{t as i}from"./logger-BHrAkMIS.js";import{S as a,_ as o,a as s,b as c,c as l,d as u,f as d,g as f,h as p,i as m,l as h,m as g,n as _,o as v,p as y,r as b,s as x,t as S,u as C,v as w,x as T,y as E}from"./db-DPvmo9md.js";import{C as D,S as O,_ as ee,b as te,c as ne,d as k,g as re,h as ie,m as ae,n as oe,p as se,r as ce,u as le,v as ue,x as de,y as fe}from"./provider-settings-B_lSRZ0U.js";import{a as A,o as pe,t as me}from"./tool-ui-D9h6SJkp.js";import{i as he,n as ge,r as _e}from"./fs-BHjUDaPI.js";import{i as ve,n as ye,r as be,t as xe}from"./backend-local-P05Hg6Af.js";import{n as j,t as Se}from"./path-utils-CgbXfwyO.js";import{t as Ce}from"./mount-id-Ccy4_G8i.js";import{n as we}from"./mount-table-store-BDnU4NqG.js";import{a as Te,i as Ee,r as M,t as De}from"./git-config-CxvDN7N3.js";import{n as N,t as P}from"./mime-types-DVkB7Eq7.js";import{_ as Oe,a as ke,c as Ae,d as je,f as Me,g as Ne,h as Pe,i as Fe,l as Ie,m as Le,o as Re,p as ze,r as Be,s as Ve,t as He,u as Ue,v as We}from"./magick-wasm-CTqVspRN.js";import{c as Ge,o as Ke}from"./bedrock-camp-9aDiXDk5.js";import{f as qe}from"./transform-messages-uhk4b6os.js";import{i as Je}from"./providers-B3LV-JEw.js";import{t as Ye}from"./local-llm-DQTKwWew.js";import{a as Xe,i as Ze,n as Qe,r as $e}from"./mount-BlPJ6Tdt.js";import{t as et}from"./remote-cache-DdfqyJ2A.js";const tt=i(`cdp`);var nt=class{ws=null;nextId=1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}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}=e;return this._state=`connecting`,new Promise((e,r)=>{let i=setTimeout(()=>{this.cleanup(),r(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=new WebSocket(t)}catch(e){clearTimeout(i),this._state=`disconnected`,r(e);return}this.ws.onopen=()=>{clearTimeout(i),this._state=`connected`,tt.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(i),this._state===`connecting`&&(tt.error(`Connection failed`,{url:t}),this.cleanup(),r(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=()=>{this.handleClose()}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this.cleanup(),tt.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),tt.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;tt.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(tt.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;tt.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(){tt.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});for(let[,e]of this.pending)e.reject(Error(`CDP connection closed`));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};function rt(e,t=``){if(e==null)return t;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)??t}catch{return String(e)}}const it=`(function() {
2
2
  'use strict';
3
3
 
4
4
  // ===== DOM Utilities =====
@@ -876,7 +876,7 @@ import{i as e,o as t,r as n,t as r}from"./chunk-jRWAZmH_.js";import{t as i}from"
876
876
  this.scrollIntoView({ block: 'center', inline: 'center' });
877
877
  const r = this.getBoundingClientRect();
878
878
  return { x: r.x, y: r.y, width: r.width, height: r.height };
879
- }`,returnByValue:!0},this.sessionId)).result?.value;if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async ensureLocalConnected(){this.localClient.state===`disconnected`&&await this.localClient.connect({url:ot()})}async ensureConnected(){this.client.state===`disconnected`&&(this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null,this.client.state===`disconnected`&&await this.connect())}ensureAttached(){if(!this.sessionId)throw Error(`Not attached to a page. Call attachToPage(targetId) first.`)}addDialogListener(e){e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}removeDialogListener(e){e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}setClient(e){this.client!==e&&(this.removeDialogListener(this.client),this.client=e,this.addDialogListener(this.client))}async boundingBox(e){await this.client.send(`DOM.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.getDocument`,{depth:0},this.sessionId)).root.nodeId,n;try{n=(await this.client.send(`DOM.querySelector`,{nodeId:t,selector:e},this.sessionId)).nodeId}catch{return null}if(!n)return null;let r=(await this.client.send(`DOM.getBoxModel`,{nodeId:n},this.sessionId)).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function ct(e){let t={role:rt(e.role,`unknown`),name:rt(e.name)},n=rt(e.value);n!==``&&(t.value=n);let r=rt(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>ct(e)).filter(e=>e.role!==`unknown`)),t}function lt(e){return e.headers.get(`x-proxy-error`)===`1`}async function ut(e){let t=`Proxy error ${e.status}`,n;try{n=await e.text()}catch{return t}return dt(n,t)}function dt(e,t){let n;try{n=JSON.parse(e)}catch{return t}if(!n||typeof n!=`object`)return t;let r=n.error;if(typeof r==`string`&&r.length>0)return r;if(r&&typeof r==`object`){let e=r.message;if(typeof e==`string`&&e.length>0)return e;try{return JSON.stringify(r)}catch{return t}}return t}i(`tray-leader`);let ft={state:`inactive`,session:null,error:null};function pt(){return{...ft,session:ft.session?{...ft.session}:null}}const mt=new Set;function ht(e){return mt.add(e),()=>{mt.delete(e)}}const gt=new Set([`send_message`,`list_scoops`,`list_tasks`]),_t=`sessions`;function vt(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(_t)||e.createObjectStore(_t,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var yt=class{db=null;async init(){this.db=await vt()}ensureDb(){if(!this.db)throw Error(`SessionStore not initialized. Call init() first.`);return this.db}async save(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(_t,`readwrite`);i.objectStore(_t).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(_t,`readonly`).objectStore(_t).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=this.ensureDb();return new Promise((t,n)=>{let r=e.transaction(_t,`readonly`).objectStore(_t).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=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(_t,`readwrite`);i.objectStore(_t).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)}};i(`panel-transport`);function bt(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function xt(){return{onMessage:e=>{let t=(t,n,r)=>(bt(t)&&e(t),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:e=>{chrome.runtime.sendMessage({source:`offscreen`,payload:e}).catch(()=>{})}}}var St=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=xt(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new yt;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-${Ct()}`;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)=>{if(gt.has(n))return;let i=e.getOrCreateAssistantMsg(t);i.toolCalls||=[],i.toolCalls.push({id:Ct(),name:n,input:r}),e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:n,toolInput:r})},onToolEnd:(t,n,r,i)=>{if(gt.has(n))return;let a=e.currentMessageId.get(t);if(a){let o=e.getBuffer(t).find(e=>e.id===a);if(o?.toolCalls){let e=[...o.toolCalls].reverse().find(e=>e.name===n&&e.result===void 0);e&&(e.result=r,e.isError=i)}}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:n,toolResult:r,isError: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)=>{let r={id:n.id,role:`user`,content:n.channel===`delegation`?`**[Instructions from sliccy]**\n\n${n.content}`:n.content,attachments:n.attachments,timestamp:new Date(n.timestamp).getTime(),source:n.channel===`delegation`?`delegation`:void 0,channel:n.channel};e.getBuffer(t).push(r),e.persistScoop(t),e.emit({type:`incoming-message`,scoopJid:t,message:{id:n.id,content:n.content,attachments:n.attachments,channel:n.channel,senderName:n.senderName,fromAssistant:n.fromAssistant,timestamp:n.timestamp}})}}}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))??[];return{type:`state-snapshot`,scoops:e,activeScoopJid:e.find(e=>e.isCone)?.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=pt(),t=O();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}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.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{console.warn(`[offscreen-bridge] applyFollowerSnapshot persist failed:`,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 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=this.orchestrator.getScoopContext(e);if(r){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-B43li_Kr.js`),i=r.getAgentMessages();if(i.length>0){let r=n(i,{source:t.isCone?`cone`:t.name??t.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}));this.messageBuffers.set(e,r),this.currentMessageId.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.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){console.warn(`[offscreen-bridge] sessionStore load failed:`,n,e)}}}persistScoop(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);!r||r.length===0||this.sessionStore.saveMessages(n,r).catch(e=>{console.warn(`[offscreen-bridge] persistScoop failed:`,n,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}-${Ct()}`,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-8PgiiiqE.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`:{if(this.followerSync){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.sendMessage(e.text,e.messageId,e.attachments);break}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`};this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),await this.orchestrator.handleMessage(t),this.orchestrator.createScoopTab(e.scoopJid);break}case`cone-create`:{let t={jid:`cone_${Date.now()}`,name:e.name,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)});break}case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:{let t=this.orchestrator.getScoops().find(t=>t.jid===e.scoopJid);if(await this.orchestrator.unregisterScoop(e.scoopJid),this.messageBuffers.delete(e.scoopJid),this.currentMessageId.delete(e.scoopJid),this.scoopStatuses.delete(e.scoopJid),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();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`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`clear-chat`:{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.emit({type:`clear-chat-ack`,requestId:e.requestId});break}case`clear-filesystem`:try{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`:{let t=this.orchestrator.getScoops(),n=e,r=n.targetScoop?t.find(e=>e.name===n.targetScoop||e.folder===n.targetScoop||e.folder===`${n.targetScoop}-scoop`):void 0;if(r||=t.find(e=>e.isCone),r){let e=`sprinkle-${n.sprinkleName}-${Date.now()}`,t=`[Sprinkle Event: ${n.sprinkleName}]\n\`\`\`json\n${JSON.stringify(n.body,null,2)}\n\`\`\``,i={id:e,chatJid:r.jid,senderId:`sprinkle`,senderName:`sprinkle:${n.sprinkleName}`,content:t,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(r.jid).push({id:e,role:`user`,content:t,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(r.jid),await this.orchestrator.handleMessage(i)}break}case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[offscreen-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:{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`});break}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)})}break}case`tool-ui-action`:{let{requestId:t,action:n,data:r}=e;try{await pe.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}),pe.cancel(t,`Action failed: ${r}`)}break}case`local-storage-set`:try{globalThis.localStorage?.setItem(e.key,e.value)}catch(e){console.warn(`[offscreen-bridge] local-storage-set failed:`,e)}break;case`local-storage-remove`:try{globalThis.localStorage?.removeItem(e.key)}catch(e){console.warn(`[offscreen-bridge] local-storage-remove failed:`,e)}break;case`local-storage-clear`:try{globalThis.localStorage?.clear()}catch(e){console.warn(`[offscreen-bridge] local-storage-clear failed:`,e)}break}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e)}};function Ct(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}const wt=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function Tt(e){return typeof e==`string`&&wt.includes(e)}var Et=r((e=>{(function(){var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function n(e){return i(o(e),arguments)}function r(e,t){return n.apply(null,[e].concat(t||[]))}function i(e,r){var i=1,a=e.length,o,s=``,c,l,u,d,f,p,m,h;for(c=0;c<a;c++)if(typeof e[c]==`string`)s+=e[c];else if(typeof e[c]==`object`){if(u=e[c],u.keys)for(o=r[i],l=0;l<u.keys.length;l++){if(o==null)throw Error(n(`[sprintf] Cannot access property "%s" of undefined value "%s"`,u.keys[l],u.keys[l-1]));o=o[u.keys[l]]}else o=u.param_no?r[u.param_no]:r[i++];if(t.not_type.test(u.type)&&t.not_primitive.test(u.type)&&o instanceof Function&&(o=o()),t.numeric_arg.test(u.type)&&typeof o!=`number`&&isNaN(o))throw TypeError(n(`[sprintf] expecting number but found %T`,o));switch(t.number.test(u.type)&&(m=o>=0),u.type){case`b`:o=parseInt(o,10).toString(2);break;case`c`:o=String.fromCharCode(parseInt(o,10));break;case`d`:case`i`:o=parseInt(o,10);break;case`j`:o=JSON.stringify(o,null,u.width?parseInt(u.width):0);break;case`e`:o=u.precision?parseFloat(o).toExponential(u.precision):parseFloat(o).toExponential();break;case`f`:o=u.precision?parseFloat(o).toFixed(u.precision):parseFloat(o);break;case`g`:o=u.precision?String(Number(o.toPrecision(u.precision))):parseFloat(o);break;case`o`:o=(parseInt(o,10)>>>0).toString(8);break;case`s`:o=String(o),o=u.precision?o.substring(0,u.precision):o;break;case`t`:o=String(!!o),o=u.precision?o.substring(0,u.precision):o;break;case`T`:o=Object.prototype.toString.call(o).slice(8,-1).toLowerCase(),o=u.precision?o.substring(0,u.precision):o;break;case`u`:o=parseInt(o,10)>>>0;break;case`v`:o=o.valueOf(),o=u.precision?o.substring(0,u.precision):o;break;case`x`:o=(parseInt(o,10)>>>0).toString(16);break;case`X`:o=(parseInt(o,10)>>>0).toString(16).toUpperCase();break}t.json.test(u.type)?s+=o:(t.number.test(u.type)&&(!m||u.sign)?(h=m?`+`:`-`,o=o.toString().replace(t.sign,``)):h=``,f=u.pad_char?u.pad_char===`0`?`0`:u.pad_char.charAt(1):` `,p=u.width-(h+o).length,d=u.width&&p>0?f.repeat(p):``,s+=u.align?h+o+d:f===`0`?h+d+o:d+h+o)}return s}var a=Object.create(null);function o(e){if(a[e])return a[e];for(var n=e,r,i=[],o=0;n;){if((r=t.text.exec(n))!==null)i.push(r[0]);else if((r=t.modulo.exec(n))!==null)i.push(`%`);else if((r=t.placeholder.exec(n))!==null){if(r[2]){o|=1;var s=[],c=r[2],l=[];if((l=t.key.exec(c))!==null)for(s.push(l[1]);(c=c.substring(l[0].length))!==``;)if((l=t.key_access.exec(c))!==null)s.push(l[1]);else if((l=t.index_access.exec(c))!==null)s.push(l[1]);else throw SyntaxError(`[sprintf] failed to parse named argument key`);else throw SyntaxError(`[sprintf] failed to parse named argument key`);r[2]=s}else o|=2;if(o===3)throw Error(`[sprintf] mixing positional and named placeholders is not (yet) supported`);i.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}else throw SyntaxError(`[sprintf] unexpected placeholder`);n=n.substring(r[0].length)}return a[e]=i}e!==void 0&&(e.sprintf=n,e.vsprintf=r),typeof window<`u`&&(window.sprintf=n,window.vsprintf=r,typeof define==`function`&&define.amd&&define(function(){return{sprintf:n,vsprintf:r}}))})()}))();const Dt=(e,t,n)=>{let r=e instanceof RegExp?Ot(e,n):e,i=t instanceof RegExp?Ot(t,n):t,a=r!==null&&i!=null&&kt(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},Ot=(e,t)=>{let n=t.match(e);return n?n[0]:null},kt=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},At=`\0SLASH`+Math.random()+`\0`,jt=`\0OPEN`+Math.random()+`\0`,Mt=`\0CLOSE`+Math.random()+`\0`,Nt=`\0COMMA`+Math.random()+`\0`,Pt=`\0PERIOD`+Math.random()+`\0`,Ft=new RegExp(At,`g`),It=new RegExp(jt,`g`),Lt=new RegExp(Mt,`g`),Rt=new RegExp(Nt,`g`),zt=new RegExp(Pt,`g`),Bt=/\\\\/g,Vt=/\\{/g,Ht=/\\}/g,Ut=/\\,/g,Wt=/\\\./g;function Gt(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Kt(e){return e.replace(Bt,At).replace(Vt,jt).replace(Ht,Mt).replace(Ut,Nt).replace(Wt,Pt)}function qt(e){return e.replace(Ft,`\\`).replace(It,`{`).replace(Lt,`}`).replace(Rt,`,`).replace(zt,`.`)}function Jt(e){if(!e)return[``];let t=[],n=Dt(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=Jt(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function Yt(e,t={}){if(!e)return[];let{max:n=1e5}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),en(Kt(e),n,!0).map(qt)}function Xt(e){return`{`+e+`}`}function Zt(e){return/^-?0\d/.test(e)}function Qt(e,t){return e<=t}function $t(e,t){return e>=t}function en(e,t,n){let r=[],i=Dt(`{`,`}`,e);if(!i)return[e];let a=i.pre,o=i.post.length?en(i.post,t,!1):[``];if(/\$$/.test(i.pre))for(let e=0;e<o.length&&e<t;e++){let t=a+`{`+i.body+`}`+o[e];r.push(t)}else{let s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),l=s||c,u=i.body.indexOf(`,`)>=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+`{`+i.body+Mt+i.post,en(e,t,!0)):[e];let d;if(l)d=i.body.split(/\.\./);else if(d=Jt(i.body),d.length===1&&d[0]!==void 0&&(d=en(d[0],t,!1).map(Xt),d.length===1))return o.map(e=>i.pre+d[0]+e);let f;if(l&&d[0]!==void 0&&d[1]!==void 0){let e=Gt(d[0]),t=Gt(d[1]),n=Math.max(d[0].length,d[1].length),r=d.length===3&&d[2]!==void 0?Math.abs(Gt(d[2])):1,i=Qt;t<e&&(r*=-1,i=$t);let a=d.some(Zt);f=[];for(let o=e;i(o,t);o+=r){let e;if(c)e=String.fromCharCode(o),e===`\\`&&(e=``);else if(e=String(o),a){let t=n-e.length;if(t>0){let n=Array(t+1).join(`0`);e=o<0?`-`+n+e.slice(1):n+e}}f.push(e)}}else{f=[];for(let e=0;e<d.length;e++)f.push.apply(f,en(d[e],t,!1))}for(let e=0;e<f.length;e++)for(let i=0;i<o.length&&r.length<t;i++){let t=a+f[e]+o[i];(!n||l||t)&&r.push(t)}}return r}const tn=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},nn={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},rn=e=>e.replace(/[[\]\\-]/g,`\\$&`),an=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),on=e=>e.join(``),sn=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(nn))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue WHILE}}if(c=!1,d){t>d?r.push(rn(d)+`-`+rn(t)):t===d&&r.push(rn(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(rn(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(rn(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l)return[an(r[0].length===2?r[0].slice(-1):r[0]),!1,u-n,!1];let f=`[`+(l?`^`:``)+on(r)+`]`,p=`[`+(l?``:`^`)+on(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},cn=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^\/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,`$1$2`).replace(/\\([^\/])/g,`$1`):t?e.replace(/\[([^\/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,`$1$2`).replace(/\\([^\/{}])/g,`$1`);var ln;const un=new Set([`!`,`?`,`+`,`*`,`@`]),dn=e=>un.has(e),fn=e=>dn(e.type),pn=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),mn=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),hn=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),gn=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),_n=`(?!\\.)`,vn=new Set([`[`,`.`]),yn=new Set([`..`,`.`]),bn=new Set(`().*{}+?[]^$\\!`),xn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Sn=`[^/]`,Cn=Sn+`*?`,wn=Sn+`+?`;let Tn=0;var En=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++Tn;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.type?this.#l=this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#l=this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==``){if(typeof t!=`string`&&!(t instanceof ln&&t.#i===this))throw Error(`invalid part: `+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;t<this.#a;t++){let n=e.#r[t];if(!(n instanceof ln&&n.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(e){let t=new ln(this.type,e);for(let e of this.#r)t.copyIn(e);return t}static#f(e,t,n,r,i){let a=r.maxExtglobRecursion??2,o=!1,s=!1,c=-1,l=!1;if(t.type===null){let u=n,d=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,d+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),d+=n;continue}else if(n===`[`){s=!0,c=u,l=!1,d+=n;continue}if(!r.noext&&dn(n)&&e.charAt(u)===`(`&&i<=a){t.push(d),d=``;let a=new ln(n,t);u=ln.#f(e,a,u,r,i+1),t.push(a);continue}d+=n}return t.push(d),u}let u=n+1,d=new ln(null,t),f=[],p=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,p+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),p+=n;continue}else if(n===`[`){s=!0,c=u,l=!1,p+=n;continue}if(!r.noext&&dn(n)&&e.charAt(u)===`(`&&(i<=a||t&&t.#h(n))){let a=t&&t.#h(n)?0:1;d.push(p),p=``;let o=new ln(n,d);d.push(o),u=ln.#f(e,o,u,r,i+a);continue}if(n===`|`){d.push(p),p=``,f.push(d),d=new ln(null,t);continue}if(n===`)`)return p===``&&t.#r.length===0&&(t.#u=!0),d.push(p),p=``,t.push(...f,d),u;p+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],u}#p(e){return this.#m(e,mn)}#m(e,t=pn){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null)return!1;let n=e.#r[0];return!n||typeof n!=`object`||n.type===null?!1:this.#h(n.type,t)}#h(e,t=hn){return!!t.get(this.type)?.includes(e)}#g(e,t){let n=e.#r[0],r=new ln(null,n,this.options);r.#r.push(``),n.push(r),this.#_(e,t)}#_(e,t){let n=e.#r[0];this.#r.splice(t,1,...n.#r);for(let e of n.#r)typeof e==`object`&&(e.#i=this);this.#l=void 0}#v(e){return!!gn.get(this.type)?.has(e)}#y(e){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let t=e.#r[0];return!t||typeof t!=`object`||t.type===null?!1:this.#v(t.type)}#b(e){let t=gn.get(this.type),n=e.#r[0],r=t?.get(n.type);if(!r)return!1;this.#r=n.#r;for(let e of this.#r)typeof e==`object`&&(e.#i=this);this.type=r,this.#l=void 0,this.#u=!1}static fromGlob(e,t={}){let n=new ln(null,void 0,t);return ln.#f(e,n,0,t,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(e){let t=e??!!this.#c.dot;if(this.#e===this&&(this.#x(),this.#d()),!fn(this)){let n=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?ln.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&yn.has(this.#r[0]))){let n=vn,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?_n:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,cn(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,cn(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?_n:``)+wn;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?_n:``)+Cn+`)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,cn(i),this.#t=!!this.#t,this.#n]}#x(){if(fn(this)){let e=0,t=!1;do{t=!0;for(let e=0;e<this.#r.length;e++){let n=this.#r[e];typeof n==`object`&&(n.#x(),this.#m(n)?(t=!1,this.#_(n,e)):this.#p(n)?(t=!1,this.#g(n,e)):this.#y(n)&&(t=!1,this.#b(n)))}}while(!t&&++e<10)}else for(let e of this.#r)typeof e==`object`&&e.#x();this.#l=void 0}#S(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(bn.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?wn:Cn,t=!0;continue}else o=!1;if(c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=sn(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=Sn,t=!0;continue}i+=xn(c)}return[i,cn(e),!!t,a]}};ln=En;const Dn=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),On=(e,t,n={})=>(tn(t),!n.nocomment&&t.charAt(0)===`#`?!1:new nr(t,n).match(e)),kn=/^\*+([^+@!?\*\[\(]*)$/,An=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),jn=e=>t=>t.endsWith(e),Mn=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),Nn=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Pn=/^\*+\.\*+$/,Fn=e=>!e.startsWith(`.`)&&e.includes(`.`),In=e=>e!==`.`&&e!==`..`&&e.includes(`.`),Ln=/^\.\*+$/,Rn=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),zn=/^\*+$/,Bn=e=>e.length!==0&&!e.startsWith(`.`),Vn=e=>e.length!==0&&e!==`.`&&e!==`..`,Hn=/^\?+([^+@!?\*\[\(]*)?$/,Un=([e,t=``])=>{let n=qn([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Wn=([e,t=``])=>{let n=Jn([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Gn=([e,t=``])=>{let n=Jn([e]);return t?e=>n(e)&&e.endsWith(t):n},Kn=([e,t=``])=>{let n=qn([e]);return t?e=>n(e)&&e.endsWith(t):n},qn=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},Jn=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},Yn=typeof process==`object`&&process?{}.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,Xn={win32:{sep:`\\`},posix:{sep:`/`}};On.sep=Yn===`win32`?Xn.win32.sep:Xn.posix.sep;const Zn=Symbol(`globstar **`);On.GLOBSTAR=Zn,On.filter=(e,t={})=>n=>On(n,e,t);const Qn=(e,t={})=>Object.assign({},e,t);On.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return On;let t=On;return Object.assign((n,r,i={})=>t(n,r,Qn(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,Qn(e,n))}static defaults(n){return t.defaults(Qn(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,Qn(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,Qn(e,r))}},unescape:(n,r={})=>t.unescape(n,Qn(e,r)),escape:(n,r={})=>t.escape(n,Qn(e,r)),filter:(n,r={})=>t.filter(n,Qn(e,r)),defaults:n=>t.defaults(Qn(e,n)),makeRe:(n,r={})=>t.makeRe(n,Qn(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,Qn(e,r)),match:(n,r,i={})=>t.match(n,r,Qn(e,i)),sep:t.sep,GLOBSTAR:Zn})};const $n=(e,t={})=>(tn(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Yt(e,{max:t.braceExpandMax}));On.braceExpand=$n,On.makeRe=(e,t={})=>new nr(e,t).makeRe(),On.match=(e,t,n={})=>{let r=new nr(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const er=/[?*]|[+@!]\(.*?\)|\[|\]/,tr=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var nr=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){tn(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||Yn,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!er.test(e[2]))&&!er.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)e[t][n]===`**`&&(e[t][n]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===``&&e[0]===``||(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];e===1&&r===``&&n[0]===``||(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=0,i=0;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),a=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),o=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),s=!o&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),c=a?3:n?0:void 0,l=s?3:o?0:void 0;if(typeof c==`number`&&typeof l==`number`){let[n,a]=[e[c],t[l]];n.toLowerCase()===a.toLowerCase()&&(t[l]=n,i=l,r=c)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(Zn)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(Zn,i),o=t.lastIndexOf(Zn),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n<e.length-u;n++){let r=String(e[n]);if(t=!0,r===`.`||r===`..`||!this.options.dot&&r.startsWith(`.`))return!1}return n||t}let d=[[[],0]],f=d[0],p=0,m=[0];for(let e of c)e===Zn?(m.push(p),f=[[],0],d.push(f)):(f[0].push(e),p++);let h=d.length-1,g=e.length-u;for(let e of d)e[1]=g-(m[h--]+e[0].length);return!!this.#t(e,d,r,0,n,0,!!u)}#t(e,t,n,r,i,a,o){let s=t[r];if(!s){for(let t=n;t<e.length;t++){o=!0;let n=e[t];if(n===`.`||n===`..`||!this.options.dot&&n.startsWith(`.`))return!1}return o}let[c,l]=s;for(;n<=l;){if(this.#n(e.slice(0,n+c.length),c,i,n,0)&&a<this.maxGlobstarRecursion){let s=this.#t(e,t,n+c.length,r+1,i,a+1,o);if(s!==!1)return s}let s=e[n];if(s===`.`||s===`..`||!this.options.dot&&s.startsWith(`.`))return!1;n++}return i||null}#n(e,t,n,r,i){let a,o,s,c;for(a=r,o=i,c=e.length,s=t.length;a<c&&o<s;a++,o++){this.debug(`matchOne loop`);let n=t[o],r=e[a];if(this.debug(t,n,r),n===!1||n===Zn)return!1;let i;if(typeof n==`string`?(i=r===n,this.debug(`string match`,n,r,i)):(i=n.test(r),this.debug(`pattern match`,n,r,i)),!i)return!1}if(a===c&&o===s)return!0;if(a===c)return n;if(o===s)return a===c-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return $n(this.pattern,this.options)}parse(e){tn(e);let t=this.options;if(e===`**`)return Zn;if(e===``)return``;let n,r=null;(n=e.match(zn))?r=t.dot?Vn:Bn:(n=e.match(kn))?r=(t.nocase?t.dot?Nn:Mn:t.dot?jn:An)(n[1]):(n=e.match(Hn))?r=(t.nocase?t.dot?Wn:Un:t.dot?Gn:Kn)(n):(n=e.match(Pn))?r=t.dot?In:Fn:(n=e.match(Ln))&&(r=Rn);let i=En.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,`test`,{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?`[^/]*?`:t.dot?`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`:`(?:(?!(?:\\/|^)\\.).)*?`,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?tr(e):e===Zn?Zn:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e!==Zn||a===Zn||(a===void 0?i!==void 0&&i!==Zn?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==Zn&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=Zn))});let i=t.filter(e=>e!==Zn);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^\/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e=0;e<i.length;e++){let o=i[e],s=r;if(n.matchBase&&o.length===1&&(s=[a]),this.matchOne(s,o,t))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return On.defaults(e).Minimatch}};On.AST=En,On.Minimatch=nr,On.escape=Dn,On.unescape=cn;const rr={};function ir(){throw Error(`gunzipSync is not available in the browser`)}function ar(){throw Error(`gzipSync is not available in the browser`)}var or=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends or{};function sr(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function cr(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function lr(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function ur(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function dr(e,t){return lr(e,t,``)}function fr(e,t){return ur(e,t,``)}function pr(e,t){return t.slice(0,mr(e,t))}function mr(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function hr(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function gr(e){let t=e.match(/^\s*/);return t?t[0]:``}const _r=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,vr=RegExp(`[${_r}]+|\\s+|[^${_r}]`,`ug`);new class extends or{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=[];for(let t of Array.from(r.segment(e))){let e=t.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}}else n=e.match(vr)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&yr(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&yr(n,i,r,null),e}};function yr(e,t,n,r){if(t&&n){let i=gr(t.value),a=hr(t.value),o=gr(n.value),s=hr(n.value);if(e){let r=sr(i,o);e.value=ur(e.value,o,r),t.value=dr(t.value,r),n.value=dr(n.value,r)}if(r){let e=cr(a,s);r.value=lr(r.value,s,e),t.value=fr(t.value,e),n.value=fr(n.value,e)}}else if(n){if(e){let e=gr(n.value);n.value=n.value.substring(e.length)}if(r){let e=gr(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=gr(r.value),i=gr(t.value),a=hr(t.value),o=sr(n,i);t.value=dr(t.value,o);let s=cr(dr(n,o),a);t.value=fr(t.value,s),r.value=lr(r.value,n,s),e.value=ur(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=gr(r.value),n=pr(hr(t.value),e);t.value=fr(t.value,n)}else if(e){let n=pr(hr(e.value),gr(t.value));t.value=dr(t.value,n)}}new class extends or{tokenize(e){let t=RegExp(`(\\r?\\n)|[${_r}]+|[^\\S\\n\\r]+|[^${_r}]`,`ug`);return e.match(t)||[]}};const br=new class extends or{constructor(){super(...arguments),this.tokenize=Sr}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
879
+ }`,returnByValue:!0},this.sessionId)).result?.value;if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async ensureLocalConnected(){this.localClient.state===`disconnected`&&await this.localClient.connect({url:ot()})}async ensureConnected(){this.client.state===`disconnected`&&(this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null,this.client.state===`disconnected`&&await this.connect())}ensureAttached(){if(!this.sessionId)throw Error(`Not attached to a page. Call attachToPage(targetId) first.`)}addDialogListener(e){e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}removeDialogListener(e){e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}setClient(e){this.client!==e&&(this.removeDialogListener(this.client),this.client=e,this.addDialogListener(this.client))}async boundingBox(e){await this.client.send(`DOM.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.getDocument`,{depth:0},this.sessionId)).root.nodeId,n;try{n=(await this.client.send(`DOM.querySelector`,{nodeId:t,selector:e},this.sessionId)).nodeId}catch{return null}if(!n)return null;let r=(await this.client.send(`DOM.getBoxModel`,{nodeId:n},this.sessionId)).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function ct(e){let t={role:rt(e.role,`unknown`),name:rt(e.name)},n=rt(e.value);n!==``&&(t.value=n);let r=rt(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>ct(e)).filter(e=>e.role!==`unknown`)),t}function lt(e){return e.headers.get(`x-proxy-error`)===`1`}async function ut(e){let t=`Proxy error ${e.status}`,n;try{n=await e.text()}catch{return t}return dt(n,t)}function dt(e,t){let n;try{n=JSON.parse(e)}catch{return t}if(!n||typeof n!=`object`)return t;let r=n.error;if(typeof r==`string`&&r.length>0)return r;if(r&&typeof r==`object`){let e=r.message;if(typeof e==`string`&&e.length>0)return e;try{return JSON.stringify(r)}catch{return t}}return t}i(`tray-leader`);let ft={state:`inactive`,session:null,error:null};function pt(){return{...ft,session:ft.session?{...ft.session}:null}}const mt=new Set;function ht(e){return mt.add(e),()=>{mt.delete(e)}}const gt=new Set([`send_message`,`list_scoops`,`list_tasks`]),_t=`sessions`;function vt(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(_t)||e.createObjectStore(_t,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var yt=class{db=null;async init(){this.db=await vt()}ensureDb(){if(!this.db)throw Error(`SessionStore not initialized. Call init() first.`);return this.db}async save(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(_t,`readwrite`);i.objectStore(_t).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(_t,`readonly`).objectStore(_t).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=this.ensureDb();return new Promise((t,n)=>{let r=e.transaction(_t,`readonly`).objectStore(_t).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=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(_t,`readwrite`);i.objectStore(_t).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)}};i(`panel-transport`);function bt(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function xt(){return{onMessage:e=>{let t=(t,n,r)=>(bt(t)&&e(t),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:e=>{chrome.runtime.sendMessage({source:`offscreen`,payload:e}).catch(()=>{})}}}var St=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=xt(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new yt;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-${Ct()}`;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)=>{if(gt.has(n))return;let i=e.getOrCreateAssistantMsg(t);i.toolCalls||=[],i.toolCalls.push({id:Ct(),name:n,input:r}),e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:n,toolInput:r})},onToolEnd:(t,n,r,i)=>{if(gt.has(n))return;let a=e.currentMessageId.get(t);if(a){let o=e.getBuffer(t).find(e=>e.id===a);if(o?.toolCalls){let e=[...o.toolCalls].reverse().find(e=>e.name===n&&e.result===void 0);e&&(e.result=r,e.isError=i)}}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:n,toolResult:r,isError: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)=>{let r={id:n.id,role:`user`,content:n.channel===`delegation`?`**[Instructions from sliccy]**\n\n${n.content}`:n.content,attachments:n.attachments,timestamp:new Date(n.timestamp).getTime(),source:n.channel===`delegation`?`delegation`:void 0,channel:n.channel};e.getBuffer(t).push(r),e.persistScoop(t),e.emit({type:`incoming-message`,scoopJid:t,message:{id:n.id,content:n.content,attachments:n.attachments,channel:n.channel,senderName:n.senderName,fromAssistant:n.fromAssistant,timestamp:n.timestamp}})}}}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))??[];return{type:`state-snapshot`,scoops:e,activeScoopJid:e.find(e=>e.isCone)?.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=pt(),t=O();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}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.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{console.warn(`[offscreen-bridge] applyFollowerSnapshot persist failed:`,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 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=this.orchestrator.getScoopContext(e);if(r){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-CImm2vOT.js`),i=r.getAgentMessages();if(i.length>0){let r=n(i,{source:t.isCone?`cone`:t.name??t.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}));this.messageBuffers.set(e,r),this.currentMessageId.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.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){console.warn(`[offscreen-bridge] sessionStore load failed:`,n,e)}}}persistScoop(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);!r||r.length===0||this.sessionStore.saveMessages(n,r).catch(e=>{console.warn(`[offscreen-bridge] persistScoop failed:`,n,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}-${Ct()}`,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-8PgiiiqE.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`:{if(this.followerSync){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.sendMessage(e.text,e.messageId,e.attachments);break}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`};this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),await this.orchestrator.handleMessage(t),this.orchestrator.createScoopTab(e.scoopJid);break}case`cone-create`:{let t={jid:`cone_${Date.now()}`,name:e.name,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)});break}case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:{let t=this.orchestrator.getScoops().find(t=>t.jid===e.scoopJid);if(await this.orchestrator.unregisterScoop(e.scoopJid),this.messageBuffers.delete(e.scoopJid),this.currentMessageId.delete(e.scoopJid),this.scoopStatuses.delete(e.scoopJid),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();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`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`clear-chat`:{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.emit({type:`clear-chat-ack`,requestId:e.requestId});break}case`clear-filesystem`:try{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`:{let t=this.orchestrator.getScoops(),n=e,r=n.targetScoop?t.find(e=>e.name===n.targetScoop||e.folder===n.targetScoop||e.folder===`${n.targetScoop}-scoop`):void 0;if(r||=t.find(e=>e.isCone),r){let e=`sprinkle-${n.sprinkleName}-${Date.now()}`,t=`[Sprinkle Event: ${n.sprinkleName}]\n\`\`\`json\n${JSON.stringify(n.body,null,2)}\n\`\`\``,i={id:e,chatJid:r.jid,senderId:`sprinkle`,senderName:`sprinkle:${n.sprinkleName}`,content:t,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(r.jid).push({id:e,role:`user`,content:t,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(r.jid),await this.orchestrator.handleMessage(i)}break}case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[offscreen-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:{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`});break}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)})}break}case`tool-ui-action`:{let{requestId:t,action:n,data:r}=e;try{await pe.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}),pe.cancel(t,`Action failed: ${r}`)}break}case`local-storage-set`:try{globalThis.localStorage?.setItem(e.key,e.value)}catch(e){console.warn(`[offscreen-bridge] local-storage-set failed:`,e)}break;case`local-storage-remove`:try{globalThis.localStorage?.removeItem(e.key)}catch(e){console.warn(`[offscreen-bridge] local-storage-remove failed:`,e)}break;case`local-storage-clear`:try{globalThis.localStorage?.clear()}catch(e){console.warn(`[offscreen-bridge] local-storage-clear failed:`,e)}break}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e)}};function Ct(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}const wt=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function Tt(e){return typeof e==`string`&&wt.includes(e)}var Et=r((e=>{(function(){var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function n(e){return i(o(e),arguments)}function r(e,t){return n.apply(null,[e].concat(t||[]))}function i(e,r){var i=1,a=e.length,o,s=``,c,l,u,d,f,p,m,h;for(c=0;c<a;c++)if(typeof e[c]==`string`)s+=e[c];else if(typeof e[c]==`object`){if(u=e[c],u.keys)for(o=r[i],l=0;l<u.keys.length;l++){if(o==null)throw Error(n(`[sprintf] Cannot access property "%s" of undefined value "%s"`,u.keys[l],u.keys[l-1]));o=o[u.keys[l]]}else o=u.param_no?r[u.param_no]:r[i++];if(t.not_type.test(u.type)&&t.not_primitive.test(u.type)&&o instanceof Function&&(o=o()),t.numeric_arg.test(u.type)&&typeof o!=`number`&&isNaN(o))throw TypeError(n(`[sprintf] expecting number but found %T`,o));switch(t.number.test(u.type)&&(m=o>=0),u.type){case`b`:o=parseInt(o,10).toString(2);break;case`c`:o=String.fromCharCode(parseInt(o,10));break;case`d`:case`i`:o=parseInt(o,10);break;case`j`:o=JSON.stringify(o,null,u.width?parseInt(u.width):0);break;case`e`:o=u.precision?parseFloat(o).toExponential(u.precision):parseFloat(o).toExponential();break;case`f`:o=u.precision?parseFloat(o).toFixed(u.precision):parseFloat(o);break;case`g`:o=u.precision?String(Number(o.toPrecision(u.precision))):parseFloat(o);break;case`o`:o=(parseInt(o,10)>>>0).toString(8);break;case`s`:o=String(o),o=u.precision?o.substring(0,u.precision):o;break;case`t`:o=String(!!o),o=u.precision?o.substring(0,u.precision):o;break;case`T`:o=Object.prototype.toString.call(o).slice(8,-1).toLowerCase(),o=u.precision?o.substring(0,u.precision):o;break;case`u`:o=parseInt(o,10)>>>0;break;case`v`:o=o.valueOf(),o=u.precision?o.substring(0,u.precision):o;break;case`x`:o=(parseInt(o,10)>>>0).toString(16);break;case`X`:o=(parseInt(o,10)>>>0).toString(16).toUpperCase();break}t.json.test(u.type)?s+=o:(t.number.test(u.type)&&(!m||u.sign)?(h=m?`+`:`-`,o=o.toString().replace(t.sign,``)):h=``,f=u.pad_char?u.pad_char===`0`?`0`:u.pad_char.charAt(1):` `,p=u.width-(h+o).length,d=u.width&&p>0?f.repeat(p):``,s+=u.align?h+o+d:f===`0`?h+d+o:d+h+o)}return s}var a=Object.create(null);function o(e){if(a[e])return a[e];for(var n=e,r,i=[],o=0;n;){if((r=t.text.exec(n))!==null)i.push(r[0]);else if((r=t.modulo.exec(n))!==null)i.push(`%`);else if((r=t.placeholder.exec(n))!==null){if(r[2]){o|=1;var s=[],c=r[2],l=[];if((l=t.key.exec(c))!==null)for(s.push(l[1]);(c=c.substring(l[0].length))!==``;)if((l=t.key_access.exec(c))!==null)s.push(l[1]);else if((l=t.index_access.exec(c))!==null)s.push(l[1]);else throw SyntaxError(`[sprintf] failed to parse named argument key`);else throw SyntaxError(`[sprintf] failed to parse named argument key`);r[2]=s}else o|=2;if(o===3)throw Error(`[sprintf] mixing positional and named placeholders is not (yet) supported`);i.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}else throw SyntaxError(`[sprintf] unexpected placeholder`);n=n.substring(r[0].length)}return a[e]=i}e!==void 0&&(e.sprintf=n,e.vsprintf=r),typeof window<`u`&&(window.sprintf=n,window.vsprintf=r,typeof define==`function`&&define.amd&&define(function(){return{sprintf:n,vsprintf:r}}))})()}))();const Dt=(e,t,n)=>{let r=e instanceof RegExp?Ot(e,n):e,i=t instanceof RegExp?Ot(t,n):t,a=r!==null&&i!=null&&kt(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},Ot=(e,t)=>{let n=t.match(e);return n?n[0]:null},kt=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},At=`\0SLASH`+Math.random()+`\0`,jt=`\0OPEN`+Math.random()+`\0`,Mt=`\0CLOSE`+Math.random()+`\0`,Nt=`\0COMMA`+Math.random()+`\0`,Pt=`\0PERIOD`+Math.random()+`\0`,Ft=new RegExp(At,`g`),It=new RegExp(jt,`g`),Lt=new RegExp(Mt,`g`),Rt=new RegExp(Nt,`g`),zt=new RegExp(Pt,`g`),Bt=/\\\\/g,Vt=/\\{/g,Ht=/\\}/g,Ut=/\\,/g,Wt=/\\\./g;function Gt(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Kt(e){return e.replace(Bt,At).replace(Vt,jt).replace(Ht,Mt).replace(Ut,Nt).replace(Wt,Pt)}function qt(e){return e.replace(Ft,`\\`).replace(It,`{`).replace(Lt,`}`).replace(Rt,`,`).replace(zt,`.`)}function Jt(e){if(!e)return[``];let t=[],n=Dt(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=Jt(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function Yt(e,t={}){if(!e)return[];let{max:n=1e5}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),en(Kt(e),n,!0).map(qt)}function Xt(e){return`{`+e+`}`}function Zt(e){return/^-?0\d/.test(e)}function Qt(e,t){return e<=t}function $t(e,t){return e>=t}function en(e,t,n){let r=[],i=Dt(`{`,`}`,e);if(!i)return[e];let a=i.pre,o=i.post.length?en(i.post,t,!1):[``];if(/\$$/.test(i.pre))for(let e=0;e<o.length&&e<t;e++){let t=a+`{`+i.body+`}`+o[e];r.push(t)}else{let s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),l=s||c,u=i.body.indexOf(`,`)>=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+`{`+i.body+Mt+i.post,en(e,t,!0)):[e];let d;if(l)d=i.body.split(/\.\./);else if(d=Jt(i.body),d.length===1&&d[0]!==void 0&&(d=en(d[0],t,!1).map(Xt),d.length===1))return o.map(e=>i.pre+d[0]+e);let f;if(l&&d[0]!==void 0&&d[1]!==void 0){let e=Gt(d[0]),t=Gt(d[1]),n=Math.max(d[0].length,d[1].length),r=d.length===3&&d[2]!==void 0?Math.abs(Gt(d[2])):1,i=Qt;t<e&&(r*=-1,i=$t);let a=d.some(Zt);f=[];for(let o=e;i(o,t);o+=r){let e;if(c)e=String.fromCharCode(o),e===`\\`&&(e=``);else if(e=String(o),a){let t=n-e.length;if(t>0){let n=Array(t+1).join(`0`);e=o<0?`-`+n+e.slice(1):n+e}}f.push(e)}}else{f=[];for(let e=0;e<d.length;e++)f.push.apply(f,en(d[e],t,!1))}for(let e=0;e<f.length;e++)for(let i=0;i<o.length&&r.length<t;i++){let t=a+f[e]+o[i];(!n||l||t)&&r.push(t)}}return r}const tn=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},nn={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},rn=e=>e.replace(/[[\]\\-]/g,`\\$&`),an=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),on=e=>e.join(``),sn=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(nn))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue WHILE}}if(c=!1,d){t>d?r.push(rn(d)+`-`+rn(t)):t===d&&r.push(rn(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(rn(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(rn(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l)return[an(r[0].length===2?r[0].slice(-1):r[0]),!1,u-n,!1];let f=`[`+(l?`^`:``)+on(r)+`]`,p=`[`+(l?``:`^`)+on(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},cn=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^\/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,`$1$2`).replace(/\\([^\/])/g,`$1`):t?e.replace(/\[([^\/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,`$1$2`).replace(/\\([^\/{}])/g,`$1`);var ln;const un=new Set([`!`,`?`,`+`,`*`,`@`]),dn=e=>un.has(e),fn=e=>dn(e.type),pn=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),mn=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),hn=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),gn=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),_n=`(?!\\.)`,vn=new Set([`[`,`.`]),yn=new Set([`..`,`.`]),bn=new Set(`().*{}+?[]^$\\!`),xn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Sn=`[^/]`,Cn=Sn+`*?`,wn=Sn+`+?`;let Tn=0;var En=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++Tn;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.type?this.#l=this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#l=this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==``){if(typeof t!=`string`&&!(t instanceof ln&&t.#i===this))throw Error(`invalid part: `+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;t<this.#a;t++){let n=e.#r[t];if(!(n instanceof ln&&n.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(e){let t=new ln(this.type,e);for(let e of this.#r)t.copyIn(e);return t}static#f(e,t,n,r,i){let a=r.maxExtglobRecursion??2,o=!1,s=!1,c=-1,l=!1;if(t.type===null){let u=n,d=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,d+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),d+=n;continue}else if(n===`[`){s=!0,c=u,l=!1,d+=n;continue}if(!r.noext&&dn(n)&&e.charAt(u)===`(`&&i<=a){t.push(d),d=``;let a=new ln(n,t);u=ln.#f(e,a,u,r,i+1),t.push(a);continue}d+=n}return t.push(d),u}let u=n+1,d=new ln(null,t),f=[],p=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,p+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),p+=n;continue}else if(n===`[`){s=!0,c=u,l=!1,p+=n;continue}if(!r.noext&&dn(n)&&e.charAt(u)===`(`&&(i<=a||t&&t.#h(n))){let a=t&&t.#h(n)?0:1;d.push(p),p=``;let o=new ln(n,d);d.push(o),u=ln.#f(e,o,u,r,i+a);continue}if(n===`|`){d.push(p),p=``,f.push(d),d=new ln(null,t);continue}if(n===`)`)return p===``&&t.#r.length===0&&(t.#u=!0),d.push(p),p=``,t.push(...f,d),u;p+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],u}#p(e){return this.#m(e,mn)}#m(e,t=pn){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null)return!1;let n=e.#r[0];return!n||typeof n!=`object`||n.type===null?!1:this.#h(n.type,t)}#h(e,t=hn){return!!t.get(this.type)?.includes(e)}#g(e,t){let n=e.#r[0],r=new ln(null,n,this.options);r.#r.push(``),n.push(r),this.#_(e,t)}#_(e,t){let n=e.#r[0];this.#r.splice(t,1,...n.#r);for(let e of n.#r)typeof e==`object`&&(e.#i=this);this.#l=void 0}#v(e){return!!gn.get(this.type)?.has(e)}#y(e){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let t=e.#r[0];return!t||typeof t!=`object`||t.type===null?!1:this.#v(t.type)}#b(e){let t=gn.get(this.type),n=e.#r[0],r=t?.get(n.type);if(!r)return!1;this.#r=n.#r;for(let e of this.#r)typeof e==`object`&&(e.#i=this);this.type=r,this.#l=void 0,this.#u=!1}static fromGlob(e,t={}){let n=new ln(null,void 0,t);return ln.#f(e,n,0,t,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(e){let t=e??!!this.#c.dot;if(this.#e===this&&(this.#x(),this.#d()),!fn(this)){let n=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?ln.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&yn.has(this.#r[0]))){let n=vn,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?_n:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,cn(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,cn(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?_n:``)+wn;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?_n:``)+Cn+`)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,cn(i),this.#t=!!this.#t,this.#n]}#x(){if(fn(this)){let e=0,t=!1;do{t=!0;for(let e=0;e<this.#r.length;e++){let n=this.#r[e];typeof n==`object`&&(n.#x(),this.#m(n)?(t=!1,this.#_(n,e)):this.#p(n)?(t=!1,this.#g(n,e)):this.#y(n)&&(t=!1,this.#b(n)))}}while(!t&&++e<10)}else for(let e of this.#r)typeof e==`object`&&e.#x();this.#l=void 0}#S(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(bn.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?wn:Cn,t=!0;continue}else o=!1;if(c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=sn(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=Sn,t=!0;continue}i+=xn(c)}return[i,cn(e),!!t,a]}};ln=En;const Dn=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),On=(e,t,n={})=>(tn(t),!n.nocomment&&t.charAt(0)===`#`?!1:new nr(t,n).match(e)),kn=/^\*+([^+@!?\*\[\(]*)$/,An=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),jn=e=>t=>t.endsWith(e),Mn=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),Nn=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Pn=/^\*+\.\*+$/,Fn=e=>!e.startsWith(`.`)&&e.includes(`.`),In=e=>e!==`.`&&e!==`..`&&e.includes(`.`),Ln=/^\.\*+$/,Rn=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),zn=/^\*+$/,Bn=e=>e.length!==0&&!e.startsWith(`.`),Vn=e=>e.length!==0&&e!==`.`&&e!==`..`,Hn=/^\?+([^+@!?\*\[\(]*)?$/,Un=([e,t=``])=>{let n=qn([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Wn=([e,t=``])=>{let n=Jn([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Gn=([e,t=``])=>{let n=Jn([e]);return t?e=>n(e)&&e.endsWith(t):n},Kn=([e,t=``])=>{let n=qn([e]);return t?e=>n(e)&&e.endsWith(t):n},qn=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},Jn=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},Yn=typeof process==`object`&&process?{}.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,Xn={win32:{sep:`\\`},posix:{sep:`/`}};On.sep=Yn===`win32`?Xn.win32.sep:Xn.posix.sep;const Zn=Symbol(`globstar **`);On.GLOBSTAR=Zn,On.filter=(e,t={})=>n=>On(n,e,t);const Qn=(e,t={})=>Object.assign({},e,t);On.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return On;let t=On;return Object.assign((n,r,i={})=>t(n,r,Qn(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,Qn(e,n))}static defaults(n){return t.defaults(Qn(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,Qn(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,Qn(e,r))}},unescape:(n,r={})=>t.unescape(n,Qn(e,r)),escape:(n,r={})=>t.escape(n,Qn(e,r)),filter:(n,r={})=>t.filter(n,Qn(e,r)),defaults:n=>t.defaults(Qn(e,n)),makeRe:(n,r={})=>t.makeRe(n,Qn(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,Qn(e,r)),match:(n,r,i={})=>t.match(n,r,Qn(e,i)),sep:t.sep,GLOBSTAR:Zn})};const $n=(e,t={})=>(tn(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Yt(e,{max:t.braceExpandMax}));On.braceExpand=$n,On.makeRe=(e,t={})=>new nr(e,t).makeRe(),On.match=(e,t,n={})=>{let r=new nr(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const er=/[?*]|[+@!]\(.*?\)|\[|\]/,tr=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var nr=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){tn(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||Yn,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!er.test(e[2]))&&!er.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)e[t][n]===`**`&&(e[t][n]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===``&&e[0]===``||(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];e===1&&r===``&&n[0]===``||(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=0,i=0;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),a=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),o=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),s=!o&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),c=a?3:n?0:void 0,l=s?3:o?0:void 0;if(typeof c==`number`&&typeof l==`number`){let[n,a]=[e[c],t[l]];n.toLowerCase()===a.toLowerCase()&&(t[l]=n,i=l,r=c)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(Zn)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(Zn,i),o=t.lastIndexOf(Zn),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n<e.length-u;n++){let r=String(e[n]);if(t=!0,r===`.`||r===`..`||!this.options.dot&&r.startsWith(`.`))return!1}return n||t}let d=[[[],0]],f=d[0],p=0,m=[0];for(let e of c)e===Zn?(m.push(p),f=[[],0],d.push(f)):(f[0].push(e),p++);let h=d.length-1,g=e.length-u;for(let e of d)e[1]=g-(m[h--]+e[0].length);return!!this.#t(e,d,r,0,n,0,!!u)}#t(e,t,n,r,i,a,o){let s=t[r];if(!s){for(let t=n;t<e.length;t++){o=!0;let n=e[t];if(n===`.`||n===`..`||!this.options.dot&&n.startsWith(`.`))return!1}return o}let[c,l]=s;for(;n<=l;){if(this.#n(e.slice(0,n+c.length),c,i,n,0)&&a<this.maxGlobstarRecursion){let s=this.#t(e,t,n+c.length,r+1,i,a+1,o);if(s!==!1)return s}let s=e[n];if(s===`.`||s===`..`||!this.options.dot&&s.startsWith(`.`))return!1;n++}return i||null}#n(e,t,n,r,i){let a,o,s,c;for(a=r,o=i,c=e.length,s=t.length;a<c&&o<s;a++,o++){this.debug(`matchOne loop`);let n=t[o],r=e[a];if(this.debug(t,n,r),n===!1||n===Zn)return!1;let i;if(typeof n==`string`?(i=r===n,this.debug(`string match`,n,r,i)):(i=n.test(r),this.debug(`pattern match`,n,r,i)),!i)return!1}if(a===c&&o===s)return!0;if(a===c)return n;if(o===s)return a===c-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return $n(this.pattern,this.options)}parse(e){tn(e);let t=this.options;if(e===`**`)return Zn;if(e===``)return``;let n,r=null;(n=e.match(zn))?r=t.dot?Vn:Bn:(n=e.match(kn))?r=(t.nocase?t.dot?Nn:Mn:t.dot?jn:An)(n[1]):(n=e.match(Hn))?r=(t.nocase?t.dot?Wn:Un:t.dot?Gn:Kn)(n):(n=e.match(Pn))?r=t.dot?In:Fn:(n=e.match(Ln))&&(r=Rn);let i=En.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,`test`,{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?`[^/]*?`:t.dot?`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`:`(?:(?!(?:\\/|^)\\.).)*?`,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?tr(e):e===Zn?Zn:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e!==Zn||a===Zn||(a===void 0?i!==void 0&&i!==Zn?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==Zn&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=Zn))});let i=t.filter(e=>e!==Zn);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^\/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e=0;e<i.length;e++){let o=i[e],s=r;if(n.matchBase&&o.length===1&&(s=[a]),this.matchOne(s,o,t))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return On.defaults(e).Minimatch}};On.AST=En,On.Minimatch=nr,On.escape=Dn,On.unescape=cn;const rr={};function ir(){throw Error(`gunzipSync is not available in the browser`)}function ar(){throw Error(`gzipSync is not available in the browser`)}var or=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends or{};function sr(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function cr(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function lr(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function ur(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function dr(e,t){return lr(e,t,``)}function fr(e,t){return ur(e,t,``)}function pr(e,t){return t.slice(0,mr(e,t))}function mr(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function hr(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function gr(e){let t=e.match(/^\s*/);return t?t[0]:``}const _r=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,vr=RegExp(`[${_r}]+|\\s+|[^${_r}]`,`ug`);new class extends or{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=[];for(let t of Array.from(r.segment(e))){let e=t.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}}else n=e.match(vr)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&yr(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&yr(n,i,r,null),e}};function yr(e,t,n,r){if(t&&n){let i=gr(t.value),a=hr(t.value),o=gr(n.value),s=hr(n.value);if(e){let r=sr(i,o);e.value=ur(e.value,o,r),t.value=dr(t.value,r),n.value=dr(n.value,r)}if(r){let e=cr(a,s);r.value=lr(r.value,s,e),t.value=fr(t.value,e),n.value=fr(n.value,e)}}else if(n){if(e){let e=gr(n.value);n.value=n.value.substring(e.length)}if(r){let e=gr(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=gr(r.value),i=gr(t.value),a=hr(t.value),o=sr(n,i);t.value=dr(t.value,o);let s=cr(dr(n,o),a);t.value=fr(t.value,s),r.value=lr(r.value,n,s),e.value=ur(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=gr(r.value),n=pr(hr(t.value),e);t.value=fr(t.value,n)}else if(e){let n=pr(hr(e.value),gr(t.value));t.value=dr(t.value,n)}}new class extends or{tokenize(e){let t=RegExp(`(\\r?\\n)|[${_r}]+|[^\\S\\n\\r]+|[^${_r}]`,`ug`);return e.match(t)||[]}};const br=new class extends or{constructor(){super(...arguments),this.tokenize=Sr}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
880
880
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
881
881
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
882
882
  `)&&(e=e.slice(0,-1)),t.endsWith(`
@@ -3028,7 +3028,7 @@ except BaseException:
3028
3028
  `,exitCode:1};let n;try{n=await t.fs.stat(i)}catch{return{stdout:``,stderr:`open: no such file: ${e}\n`,exitCode:1}}if(!n.isFile)return{stdout:``,stderr:`open: not a file: ${e}\n`,exitCode:1};let r;try{r=await t.fs.readFileBuffer(i)}catch{return{stdout:``,stderr:`open: failed to read: ${e}\n`,exitCode:1}}let a=new Uint8Array(r.byteLength);a.set(r);let s=new Blob([a.buffer],{type:ke(i)}),c=URL.createObjectURL(s),l=document.createElement(`a`);l.href=c,l.download=Fe(i)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),u.push(`downloaded ${i}`)}else{if(!c)return{stdout:``,stderr:`open: browser APIs are unavailable in this environment
3029
3029
  `,exitCode:1};let e=We(i);try{await l(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}u.push(`opened ${i} → ${e}`)}}return{stdout:u.join(`
3030
3030
  `)+`
3031
- `,stderr:``,exitCode:0}})}let mY=null,hY=null;async function gY(){return mY||=import(`./es-BhhLePsi.js`),mY}async function _Y(){return hY||=import(`./dist-Nvn9jT7s.js`),hY}function vY(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function yY(e){let{range:t,rotation:n}=vY(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function bY(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function xY(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
3031
+ `,stderr:``,exitCode:0}})}let mY=null,hY=null;async function gY(){return mY||=import(`./es-Dn0gWvf2.js`),mY}async function _Y(){return hY||=import(`./dist-Nvn9jT7s.js`),hY}function vY(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function yY(e){let{range:t,rotation:n}=vY(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function bY(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function xY(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
3032
3032
 
3033
3033
  Operations:
3034
3034
  dump_data Print metadata (page count, title, author, etc.)
@@ -3267,10 +3267,10 @@ Examples:
3267
3267
  oauth-token adobe
3268
3268
  oauth-token github --scope "repo,models:read"
3269
3269
  curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
3270
- `}function MZ(){return MM(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await import(`./provider-settings-DbAAu75J.js`).then(e=>e.l),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-hylnGcn1.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:jZ(),stderr:``,exitCode:0};if(e.includes(`--list`))return NZ(r,a,i,t);let o,s=e.indexOf(`--scope`);if(s>=0){if(o=e[s+1]?.trim(),!o||o.startsWith(`-`))return{stdout:``,stderr:`oauth-token: --scope requires a value
3270
+ `}function MZ(){return MM(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await import(`./provider-settings-B_lSRZ0U.js`).then(e=>e.l),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-B3LV-JEw.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:jZ(),stderr:``,exitCode:0};if(e.includes(`--list`))return NZ(r,a,i,t);let o,s=e.indexOf(`--scope`);if(s>=0){if(o=e[s+1]?.trim(),!o||o.startsWith(`-`))return{stdout:``,stderr:`oauth-token: --scope requires a value
3271
3271
  `,exitCode:1};e.splice(s,2)}let c,l=e.indexOf(`--provider`);if(l>=0){if(c=e[l+1],!c)return{stdout:``,stderr:`oauth-token: --provider requires a value
3272
3272
  `,exitCode:1}}else if(e.length>0)c=e[0];else{let e=n(),t=i(e);if(t?.isOAuth&&t.onOAuthLogin)c=e;else if(c=a().find(e=>{let t=i(e);return t?.isOAuth&&t.onOAuthLogin}),!c)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
3273
- `,exitCode:1}}let u=i(c);if(!u)return{stdout:``,stderr:`oauth-token: unknown provider "${c}"\n`,exitCode:1};if(!u.isOAuth||!u.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${c}" is not an OAuth provider\n`,exitCode:1};if(!o){let e=t(c);if(e&&!e.expired){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${c} (try logging in again)\n`,exitCode:1}}}try{let{createOAuthLauncher:e}=await import(`./oauth-service-DDqMLBsS.js`),n=e();await u.onOAuthLogin(n,()=>{},o?{scopes:o}:void 0);let r=t(c);if(r&&r.token){let e=r.maskedValue;return e?{stdout:`${e}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${c} (try logging in again)\n`,exitCode:1}}return console.error(`[oauth-token] Provider ${c}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
3273
+ `,exitCode:1}}let u=i(c);if(!u)return{stdout:``,stderr:`oauth-token: unknown provider "${c}"\n`,exitCode:1};if(!u.isOAuth||!u.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${c}" is not an OAuth provider\n`,exitCode:1};if(!o){let e=t(c);if(e&&!e.expired){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${c} (try logging in again)\n`,exitCode:1}}}try{let{createOAuthLauncher:e}=await import(`./oauth-service-CfvA2rAX.js`),n=e();await u.onOAuthLogin(n,()=>{},o?{scopes:o}:void 0);let r=t(c);if(r&&r.token){let e=r.maskedValue;return e?{stdout:`${e}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${c} (try logging in again)\n`,exitCode:1}}return console.error(`[oauth-token] Provider ${c}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
3274
3274
  `,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${c}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function NZ(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
3275
3275
  `,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(`
3276
3276
  `)+`
@@ -3293,7 +3293,7 @@ Common base URLs:
3293
3293
  llama.cpp http://localhost:8080/v1
3294
3294
  vLLM http://localhost:8000/v1
3295
3295
  Jan http://localhost:1337/v1
3296
- `}function IZ(){return MM(PZ,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:FZ(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-DbAAu75J.js`).then(e=>e.l),{verifyConnection:a}=await import(`./local-llm-BlJ8NcSI.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(PZ);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
3296
+ `}function IZ(){return MM(PZ,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:FZ(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-B_lSRZ0U.js`).then(e=>e.l),{verifyConnection:a}=await import(`./local-llm-DQTKwWew.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(PZ);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
3297
3297
  `,exitCode:1};let c=await a(s,t(PZ)??void 0);if(!c.ok){let e=[`✗ Could not reach ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` error: ${c.error?.message??`unknown`}`];return c.error?.hint&&e.push(` hint: ${c.error.hint}`),{stdout:``,stderr:e.join(`
3298
3298
  `)+`
3299
3299
  `,exitCode:1}}return o===`discover`?(i(PZ,n(PZ)??``,s,c.models.join(`, `)),{stdout:[`✓ ${s} (${c.runtime.kind}${c.runtime.version?` ${c.runtime.version}`:``})`,` Saved ${c.models.length} model${c.models.length===1?``:`s`} to Settings:`,...c.models.map(e=>` • ${e}`)].join(`
@@ -3370,7 +3370,7 @@ Examples:
3370
3370
  oauth-domain add adobe '*.da.live'
3371
3371
  oauth-domain list adobe
3372
3372
  oauth-domain remove adobe admin.da.live
3373
- `}function JZ(){return MM(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:qZ(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomains:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-DbAAu75J.js`).then(e=>e.l),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
3373
+ `}function JZ(){return MM(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:qZ(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomains:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-B_lSRZ0U.js`).then(e=>e.l),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
3374
3374
  `)+`
3375
3375
  `,stderr:``,exitCode:0}}let e=r(),n=Object.entries(e).filter(([,e])=>e.length>0);return n.length===0?{stdout:`(no extra OAuth domains configured)
3376
3376
  `,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
@@ -3499,7 +3499,7 @@ Options:
3499
3499
  -h, --help Show this help message
3500
3500
  `}function XQ(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function ZQ(e){return`$${e.toFixed(2)}`}const QQ=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function $Q(e){let t=`${e.id} ${e.name??``}`;return!QQ.test(t)}function e$(e){let t=e.toLowerCase();t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``);let n=t.match(/^(claude-(?:opus|sonnet|haiku))/);if(n)return n[1];let r=t.match(/^(gpt-\d+)(?:\.\d+)?(-[a-z][-a-z]*)?$/);if(r)return r[1]+(r[2]??``);let i=t.match(/^gemini-[\d.]+-(.+)$/);if(i)return`gemini-${i[1]}`;let a=t.match(/^gemini-(\d+)-(.+)$/);if(a)return`gemini-${a[2]}`;let o=t.match(/^grok-[\d.]+-([\w-]+)$/);if(o)return`grok-${o[1]}`;if(t.match(/^(grok)-[\d.]+$/))return`grok`;let s=t.match(/^(o\d+(?:-[a-z]+)?)(?:-\d.*)?$/);return s?s[1]:t.replace(/-[\d.]+$/,``)}function t$(e){let t=new Map;for(let n of e){let e=e$(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function n$(e,t,n,r,i){let a=i?JQ(e.id,i):void 0,o={id:e.id,name:e.name,provider:t,cost:e.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??0,maxTokens:e.maxTokens??0,reasoning:!!e.reasoning,input:e.input??[`text`],selected:e.id===n&&t===r};return a?.intelligence_index!=null&&(o.intelligence=a.intelligence_index),a?.coding_index!=null&&(o.codingScore=a.coding_index),a?.speed_tps!=null&&(o.speed=a.speed_tps),o}function r$(e,t,n,r){let i=[];i.push(`Models for "${e}" (${t}):\n`);for(let e of n){let t=e.selected?` ► `:` `,n=e.id.padEnd(30),r=`${ZQ(e.cost.input)} / ${ZQ(e.cost.output)}`,a=`${XQ(e.contextWindow)} ctx`,o=e.intelligence==null?``:`IQ:${e.intelligence}`,s=e.speed==null?``:`${Math.round(e.speed)} t/s`,c=e.reasoning?`reasoning`:``,l=o||s?`${o.padEnd(6)} ${s.padEnd(8)}`:``;i.push(`${t}${n} ${r.padEnd(16)} ${a.padEnd(10)} ${l} ${c}`)}let a=n.find(e=>e.selected);return i.push(`\n ${n.length} model${n.length===1?``:`s`} available.${a?` Currently using: ${a.id}`:``}`),r&&i.push(` Intelligence data: artificialanalysis.ai`),i.join(`
3501
3501
  `)+`
3502
- `}function i$(e){return MM(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await import(`./provider-settings-DbAAu75J.js`).then(e=>e.l);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:YQ(),stderr:``,exitCode:0};let c=t.includes(`--json`),l=t.includes(`--all`),u=t.includes(`--all-versions`),d=t.includes(`--refresh`),f=t.includes(`--no-benchmarks`),p=t.indexOf(`--provider`),m=p>=0?t[p+1]:void 0,h=o(),g=s(),_=n();if(_.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
3502
+ `}function i$(e){return MM(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await import(`./provider-settings-B_lSRZ0U.js`).then(e=>e.l);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:YQ(),stderr:``,exitCode:0};let c=t.includes(`--json`),l=t.includes(`--all`),u=t.includes(`--all-versions`),d=t.includes(`--refresh`),f=t.includes(`--no-benchmarks`),p=t.indexOf(`--provider`),m=p>=0?t[p+1]:void 0,h=o(),g=s(),_=n();if(_.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
3503
3503
  `,exitCode:1};let v;f||(v=await KQ(e,d),v.length===0&&(v=void 0));let y;if(m){let e=r();if(!e.includes(m))return{stdout:``,stderr:`Unknown provider: ${m}. Available: ${e.join(`, `)}\n`,exitCode:1};y=[m]}else y=l?[...new Set(_.map(e=>e.providerId))]:[h];let b=[],x=[];for(let e of y){let t=a(e).filter($Q);if(t.length===0){if(!l)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>n$(t,e,g,h,v)).sort((e,t)=>t.cost.input-e.cost.input);if(u||(n=t$(n)),b.push(...n),!c){let t=i(e);x.push(r$(t.name,e,n,!!v))}}return c?{stdout:JSON.stringify(b,null,2)+`
3504
3504
  `,stderr:``,exitCode:0}:(!u&&!c&&x.push(`Showing latest versions only. Use --all-versions to see all.
3505
3505
  `),{stdout:x.join(`
@@ -7031,4 +7031,4 @@ ${t}
7031
7031
  `;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
7032
7032
  `;case`stat`:return`1 (kernel-host) R 0 - 0 -
7033
7033
  `}}var E4=n({formatMountRecoveryPrompt:()=>A4,mdInlineCode:()=>k4,recoverMounts:()=>D4,shellQuote:()=>O4});async function D4(e,t,n){let r=[],i=[];for(let a of e){let{targetPath:e,descriptor:o}=a;if(o.kind===`local`){let a=await we(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=xe.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 et({mountId:o.mountId,ttlMs:3e4}),a=new Xe({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:$e(o.profile)});await t.mount(e,a),n?.info?.(`Restored S3 mount from previous session`,{path:e,source:o.source}),r.push({kind:`s3`,path:e,source:o.source,profile:o.profile,reason:``})}catch(t){let r=t instanceof Error?t.message:String(t);n?.warn?.(`Failed to restore S3 mount`,{path:e,error:r}),i.push({kind:`s3`,path:e,source:o.source,profile:o.profile,reason:r})}continue}if(o.kind===`da`){try{let i=new et({mountId:o.mountId,ttlMs:3e4}),a=new Ze({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:Qe()});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})}continue}}return{restored:r,needsRecovery:i}}function O4(e){return`'${e.replace(/'/g,`'\\''`)}'`}function k4(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 A4(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 ${k4(t)})`:``;return`- ${k4(e)}${n}`}),i=r.map(({path:e})=>` mount ${O4(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 ${O4(n)}`,a=`mount --source ${O4(t)}${i} ${O4(e)}`;return`- ${k4(e)} (${k4(t)}, profile ${k4(n)}) — ${r}\n Retry: ${k4(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(`
7034
- `)}function j4(e){let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=e.type===`navigate`,o=e.type===`upgrade`,s=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`mount-recovery`:a?e.navigateUrl:o?`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`:e.cronName,c=t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:a?`Navigate Event`:o?`Upgrade Event`:`Cron Event`;if(i){let t=e.body;if(t?.reason===`mount-recovery`){let e=A4(t.mounts??[]);return e===null?null:{label:c,content:e}}}if(o){let t=e.upgradeFromVersion??`unknown`,n=e.upgradeToVersion??`unknown`,r=e.body?.releasedAt??null;return{label:c,content:`[${c}: ${t}→${n}]\n\nSLICC was upgraded from \`${t}\` to \`${n}\`.${r?`\nReleased: ${r}`:``}\n\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to:\n- Show the user the changelog between these tags from GitHub\n- Offer to merge new bundled vfs-root content into their workspace (three-way merge: bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}}return{label:c,content:`[${c}: ${s}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function M4(e,{orchestrator:t,log:n}){let r=j4(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=e.type===`webhook`,a=e.type===`sprinkle`,o=e.type===`fswatch`,s=e.type===`navigate`,c=e.type===`upgrade`,l=e.type===`session-reload`,u=i?e.webhookName:a?e.sprinkleName:o?e.fswatchName:s?e.navigateUrl:c?`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`:l?`mount-recovery`:e.cronName,d=i?e.webhookId:a?e.sprinkleName:o?e.fswatchId:s?e.navigateUrl:c?`upgrade-${e.upgradeToVersion??`unknown`}`:l?`session-reload-${e.timestamp}`:e.cronId,f=e.type,p=t.getScoops(),m;if(m=e.targetScoop?p.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):p.find(e=>e.isCone),!m){n.warn(`Lick target scoop not found`,e.targetScoop);return}let h={id:`${f}-${d}-${Date.now()}`,chatJid:m.jid,senderId:f,senderName:`${f}:${u}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:f};t.handleMessage(h)}async function N4(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=new lJ,c=new e4(t,{...i,getBrowserAPI:()=>n});c.setProcessManager(s),globalThis.__slicc_pm=s,await r.bind(c,n);let l=ht(()=>r.emitTrayRuntimeStatus()),u=D(()=>r.emitTrayRuntimeStatus());await c.init();let d=c.getSharedFS();if(d?r4(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new h4(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let{registerSessionCostsProvider:f}=await Promise.resolve().then(()=>a$);f(()=>c.getSessionCosts());let{getLickManager:p}=await Promise.resolve().then(()=>G2),m=p();await m.init(),c.setLickManager(m);let h=e.lickEventHandler??M4,g={orchestrator:c,lickManager:m,log:o};m.setEventHandler(e=>h(e,g)),globalThis.__slicc_lickManager=m,d&&(async()=>{try{let{getAllMountEntries:e}=await import(`./mount-table-store-BDnU4NqG.js`).then(e=>e.r),{recoverMounts:t}=await Promise.resolve().then(()=>E4),n=await e();if(n.length===0)return;let{needsRecovery:r}=await t(n,d,o);if(r.length===0)return;m.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:r}})}catch(e){o.warn(`mount recovery failed`,e)}})(),a||c.getScoops().some(e=>e.isCone)||await c.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()}),d&&(async()=>{try{let{detectUpgrade:e,recordVersionSeen:t}=await import(`./upgrade-detection-BNmWyZeI.js`),n=await e();if(!n.isUpgrade||n.lastSeen===null)return;m.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:n.lastSeen,upgradeToVersion:n.bundled.version,body:{from:n.lastSeen,to:n.bundled.version,releasedAt:n.bundled.releasedAt}}),await t(n.bundled.version)}catch(e){o.warn(`Upgrade detection failed`,e)}})();let _=null,v=null;if(d)try{let{BshWatchdog:e}=await import(`./bsh-watchdog-D59Tbl5E.js`),{ScriptCatalog:t}=await Promise.resolve().then(()=>r0),r=new t({jshFs:d,bshFs:d,watcher:d.getWatcher()}),i=new e({browserAPI:n,scriptCatalog:r,fs:d});i.start(),_=()=>i.stop(),v=()=>r.dispose()}catch(e){o.warn(`Failed to start BSH watchdog`,e)}let y=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:m,sharedFs:d??null,processManager:s,async dispose(){if(!y){if(y=!0,l?.(),u?.(),_?.(),v?.(),d)try{await d.unmountInternal(`/proc`)}catch{}P4({processManager:s,lickManager:m})}}}}function P4(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager}function F4(e){let t=!1,n=()=>{t||(t=!0,typeof e.start==`function`&&e.start())};return{onMessage:t=>{let r=e=>{t(e.data)};return e.addEventListener(`message`,r),n(),()=>{e.removeEventListener(`message`,r)}},send:t=>{e.postMessage(t)}}}function I4(e){let t=F4(e);return{onMessage:e=>t.onMessage(e),send:e=>{t.send({source:`offscreen`,payload:e})}}}var L4=class extends LK{constructor(e){let t=F4(e);super({label:`WorkerCdpProxy`,buildCommandEnvelope:(e,t,n,r)=>({type:`cdp-cmd`,id:e,method:t,params:n,sessionId:r}),sendEnvelope:e=>(t.send(e),Promise.resolve()),subscribeIncoming:e=>t.onMessage(e),parseResponse:e=>{let t=e;if(t?.type!==`cdp-response`)return null;if(typeof t.id!=`number`||!Number.isFinite(t.id))return console.warn(`[WorkerCdpProxy] dropping cdp-response with invalid id`,t),null;let n=e;return{id:n.id,result:n.result,error:n.error}},parseEvent:e=>{let t=e;if(t?.type!==`cdp-event`)return null;if(typeof t.method!=`string`)return console.warn(`[WorkerCdpProxy] dropping cdp-event with invalid method`,t),null;let n=e;return{method:n.method,params:n.params}},onSubscribeEvent:e=>{t.send({type:`cdp-subscribe`,event:e})},onUnsubscribeEvent:e=>{t.send({type:`cdp-unsubscribe`,event:e})}})}},R4=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(!z4(e)||e.source!==`panel`)return;let t=e.payload;V4(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`))}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:127}),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode: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),a=n.signal.aborted?130:i.exitCode;n.signal.aborted||(r&&await r.gate.wait(),i.stdout&&this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:`stdout`,data:i.stdout}),i.stderr&&this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:`stderr`,data:i.stderr})),this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:a}),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:i.exitCode)}catch(t){if(n.signal.aborted){let t=B4(r?.terminatedBy??`SIGINT`);this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t}),r&&this.pm&&this.pm.exit(r.pid,null)}else{let n=t instanceof Error?t.message:String(t);this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:`stderr`,data:`Error: ${n}\n`}),this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:1}),r&&this.pm&&this.pm.exit(r.pid,1)}}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}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 z4(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function B4(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function V4(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`}function H4(e){let{transport:t,fs:n,browser:r,processManager:i}=e,a=new R4({transport:t,processManager:i,createShell:(e,t)=>new f0({fs:n,cwd:t.cwd,env:t.env,browserAPI:r,processManager:i,processOwner:{kind:`system`}}),logger:e.logger??console});return{host:a,stop:a.start()}}function U4(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}const W4=`x-bypass-llm-proxy`;function G4(e,t){return t?(n,r)=>{if(!K4(n,t))return e(n,r);let i=new Headers(r?.headers);return i.has(W4)||i.set(W4,`1`),e(n,{...r,headers:i})}:e}function K4(e,t){let n;n=typeof e==`string`?e:e instanceof URL?e.href:e.url;try{return new URL(n,t).origin===t}catch{return!0}}function q4(){let e=globalThis.fetch;if(!e)return;let t=typeof self<`u`&&self.location?self.location.origin:void 0;globalThis.fetch=G4(e.bind(globalThis),t)}function J4(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 Y4=null,X4=null,Z4=null;const Q4=U4(e=>$4(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Q4.handle(e.data)});async function $4(e){q4(),J4(e.localStorageSeed??{}),await Je();let t=I4(e.kernelPort),n=new St(t),r=St.createCallbacks(n),i=new L4(e.cdpPort);await i.connect();let a=new st(i);Y4=await N4({container:{},browser:a,bridge:n,callbacks:r,logger:console});let{createSprinkleManagerProxyOverChannel:o}=await import(`./sprinkle-bridge-channel-CHgv5aYx.js`);globalThis.__slicc_sprinkleManager=o({instanceId:e.instanceId});let{createPanelRpcClient:s}=await Promise.resolve().then(()=>BK);Z4=s({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=Z4;let c=Y4.processManager,l=Y4.sharedFs;l?X4=H4({transport:t,fs:l,browser:a,processManager:c,logger:console}).stop:console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),e.kernelPort.postMessage({type:`kernel-worker-ready`})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X4?.(),X4=null,Z4?.dispose(),Z4=null,Y4?.dispose())});export{gt as i,cK as n,yB as r,GK as t};
7034
+ `)}function j4(e){let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=e.type===`navigate`,o=e.type===`upgrade`,s=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`mount-recovery`:a?e.navigateUrl:o?`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`:e.cronName,c=t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:a?`Navigate Event`:o?`Upgrade Event`:`Cron Event`;if(i){let t=e.body;if(t?.reason===`mount-recovery`){let e=A4(t.mounts??[]);return e===null?null:{label:c,content:e}}}if(o){let t=e.upgradeFromVersion??`unknown`,n=e.upgradeToVersion??`unknown`,r=e.body?.releasedAt??null;return{label:c,content:`[${c}: ${t}→${n}]\n\nSLICC was upgraded from \`${t}\` to \`${n}\`.${r?`\nReleased: ${r}`:``}\n\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to:\n- Show the user the changelog between these tags from GitHub\n- Offer to merge new bundled vfs-root content into their workspace (three-way merge: bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}}return{label:c,content:`[${c}: ${s}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function M4(e,{orchestrator:t,log:n}){let r=j4(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=e.type===`webhook`,a=e.type===`sprinkle`,o=e.type===`fswatch`,s=e.type===`navigate`,c=e.type===`upgrade`,l=e.type===`session-reload`,u=i?e.webhookName:a?e.sprinkleName:o?e.fswatchName:s?e.navigateUrl:c?`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`:l?`mount-recovery`:e.cronName,d=i?e.webhookId:a?e.sprinkleName:o?e.fswatchId:s?e.navigateUrl:c?`upgrade-${e.upgradeToVersion??`unknown`}`:l?`session-reload-${e.timestamp}`:e.cronId,f=e.type,p=t.getScoops(),m;if(m=e.targetScoop?p.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):p.find(e=>e.isCone),!m){n.warn(`Lick target scoop not found`,e.targetScoop);return}let h={id:`${f}-${d}-${Date.now()}`,chatJid:m.jid,senderId:f,senderName:`${f}:${u}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:f};t.handleMessage(h)}async function N4(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=new lJ,c=new e4(t,{...i,getBrowserAPI:()=>n});c.setProcessManager(s),globalThis.__slicc_pm=s,await r.bind(c,n);let l=ht(()=>r.emitTrayRuntimeStatus()),u=D(()=>r.emitTrayRuntimeStatus());await c.init();let d=c.getSharedFS();if(d?r4(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new h4(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let{registerSessionCostsProvider:f}=await Promise.resolve().then(()=>a$);f(()=>c.getSessionCosts());let{getLickManager:p}=await Promise.resolve().then(()=>G2),m=p();await m.init(),c.setLickManager(m);let h=e.lickEventHandler??M4,g={orchestrator:c,lickManager:m,log:o};m.setEventHandler(e=>h(e,g)),globalThis.__slicc_lickManager=m,d&&(async()=>{try{let{getAllMountEntries:e}=await import(`./mount-table-store-BDnU4NqG.js`).then(e=>e.r),{recoverMounts:t}=await Promise.resolve().then(()=>E4),n=await e();if(n.length===0)return;let{needsRecovery:r}=await t(n,d,o);if(r.length===0)return;m.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:r}})}catch(e){o.warn(`mount recovery failed`,e)}})(),a||c.getScoops().some(e=>e.isCone)||await c.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()}),d&&(async()=>{try{let{detectUpgrade:e,recordVersionSeen:t}=await import(`./upgrade-detection-BWEeiTSq.js`),n=await e();if(!n.isUpgrade||n.lastSeen===null)return;m.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:n.lastSeen,upgradeToVersion:n.bundled.version,body:{from:n.lastSeen,to:n.bundled.version,releasedAt:n.bundled.releasedAt}}),await t(n.bundled.version)}catch(e){o.warn(`Upgrade detection failed`,e)}})();let _=null,v=null;if(d)try{let{BshWatchdog:e}=await import(`./bsh-watchdog-D59Tbl5E.js`),{ScriptCatalog:t}=await Promise.resolve().then(()=>r0),r=new t({jshFs:d,bshFs:d,watcher:d.getWatcher()}),i=new e({browserAPI:n,scriptCatalog:r,fs:d});i.start(),_=()=>i.stop(),v=()=>r.dispose()}catch(e){o.warn(`Failed to start BSH watchdog`,e)}let y=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:m,sharedFs:d??null,processManager:s,async dispose(){if(!y){if(y=!0,l?.(),u?.(),_?.(),v?.(),d)try{await d.unmountInternal(`/proc`)}catch{}P4({processManager:s,lickManager:m})}}}}function P4(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager}function F4(e){let t=!1,n=()=>{t||(t=!0,typeof e.start==`function`&&e.start())};return{onMessage:t=>{let r=e=>{t(e.data)};return e.addEventListener(`message`,r),n(),()=>{e.removeEventListener(`message`,r)}},send:t=>{e.postMessage(t)}}}function I4(e){let t=F4(e);return{onMessage:e=>t.onMessage(e),send:e=>{t.send({source:`offscreen`,payload:e})}}}var L4=class extends LK{constructor(e){let t=F4(e);super({label:`WorkerCdpProxy`,buildCommandEnvelope:(e,t,n,r)=>({type:`cdp-cmd`,id:e,method:t,params:n,sessionId:r}),sendEnvelope:e=>(t.send(e),Promise.resolve()),subscribeIncoming:e=>t.onMessage(e),parseResponse:e=>{let t=e;if(t?.type!==`cdp-response`)return null;if(typeof t.id!=`number`||!Number.isFinite(t.id))return console.warn(`[WorkerCdpProxy] dropping cdp-response with invalid id`,t),null;let n=e;return{id:n.id,result:n.result,error:n.error}},parseEvent:e=>{let t=e;if(t?.type!==`cdp-event`)return null;if(typeof t.method!=`string`)return console.warn(`[WorkerCdpProxy] dropping cdp-event with invalid method`,t),null;let n=e;return{method:n.method,params:n.params}},onSubscribeEvent:e=>{t.send({type:`cdp-subscribe`,event:e})},onUnsubscribeEvent:e=>{t.send({type:`cdp-unsubscribe`,event:e})}})}},R4=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(!z4(e)||e.source!==`panel`)return;let t=e.payload;V4(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`))}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:127}),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode: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),a=n.signal.aborted?130:i.exitCode;n.signal.aborted||(r&&await r.gate.wait(),i.stdout&&this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:`stdout`,data:i.stdout}),i.stderr&&this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:`stderr`,data:i.stderr})),this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:a}),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:i.exitCode)}catch(t){if(n.signal.aborted){let t=B4(r?.terminatedBy??`SIGINT`);this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t}),r&&this.pm&&this.pm.exit(r.pid,null)}else{let n=t instanceof Error?t.message:String(t);this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:`stderr`,data:`Error: ${n}\n`}),this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:1}),r&&this.pm&&this.pm.exit(r.pid,1)}}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}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 z4(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function B4(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function V4(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`}function H4(e){let{transport:t,fs:n,browser:r,processManager:i}=e,a=new R4({transport:t,processManager:i,createShell:(e,t)=>new f0({fs:n,cwd:t.cwd,env:t.env,browserAPI:r,processManager:i,processOwner:{kind:`system`}}),logger:e.logger??console});return{host:a,stop:a.start()}}function U4(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}const W4=`x-bypass-llm-proxy`;function G4(e,t){return t?(n,r)=>{if(!K4(n,t))return e(n,r);let i=new Headers(r?.headers);return i.has(W4)||i.set(W4,`1`),e(n,{...r,headers:i})}:e}function K4(e,t){let n;n=typeof e==`string`?e:e instanceof URL?e.href:e.url;try{return new URL(n,t).origin===t}catch{return!0}}function q4(){let e=globalThis.fetch;if(!e)return;let t=typeof self<`u`&&self.location?self.location.origin:void 0;globalThis.fetch=G4(e.bind(globalThis),t)}function J4(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 Y4=null,X4=null,Z4=null;const Q4=U4(e=>$4(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Q4.handle(e.data)});async function $4(e){q4(),J4(e.localStorageSeed??{}),await Je();let t=I4(e.kernelPort),n=new St(t),r=St.createCallbacks(n),i=new L4(e.cdpPort);await i.connect();let a=new st(i);Y4=await N4({container:{},browser:a,bridge:n,callbacks:r,logger:console});let{createSprinkleManagerProxyOverChannel:o}=await import(`./sprinkle-bridge-channel-CHgv5aYx.js`);globalThis.__slicc_sprinkleManager=o({instanceId:e.instanceId});let{createPanelRpcClient:s}=await Promise.resolve().then(()=>BK);Z4=s({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=Z4;let c=Y4.processManager,l=Y4.sharedFs;l?X4=H4({transport:t,fs:l,browser:a,processManager:c,logger:console}).stop:console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),e.kernelPort.postMessage({type:`kernel-worker-ready`})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X4?.(),X4=null,Z4?.dispose(),Z4=null,Y4?.dispose())});export{gt as i,cK as n,yB as r,GK as t};
@@ -1,2 +1,2 @@
1
- import{t as e}from"./logger-B-No_qN_.js";import{c as t}from"./provider-settings-BCl4HZqa.js";import{u as n}from"./bedrock-camp-CqXHYC67.js";import{o as r}from"./simple-options-imi_RHvn.js";import{streamOpenAICompletions as i,streamSimpleOpenAICompletions as a}from"./openai-completions-D5rB4vsV.js";var o=e(`local-llm`),s=`local-llm`,c=`local`,l=`${s}-unconfigured`,u={id:s,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(`
1
+ import{t as e}from"./logger-B-No_qN_.js";import{c as t}from"./provider-settings-DGXqU1Yt.js";import{u as n}from"./bedrock-camp-CqXHYC67.js";import{o as r}from"./simple-options-imi_RHvn.js";import{streamOpenAICompletions as i,streamSimpleOpenAICompletions as a}from"./openai-completions-D5rB4vsV.js";var o=e(`local-llm`),s=`local-llm`,c=`local`,l=`${s}-unconfigured`,u={id:s,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(`
2
2
  `),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=d(t(s));return e.length===0?[{id:l,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 d(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}var f=`openai-completions`,p=`${s}-openai`;function m(e){return{...e,api:f}}function h(e){let t=e??{};return!t.apiKey||t.apiKey.length===0?{...t,apiKey:c}:t}var g=(e,t,n={})=>e.id===l?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?i(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`),_=(e,t,n)=>e.id===l?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?a(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`);function v(e,t){let n=r(),i={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:i}),n.end()}),n}function y(){n({api:p,stream:g,streamSimple:_})}function b(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e.replace(/\/v1\/?$/,``).replace(/\/+$/,``)}}function x(e){let t=e.replace(/\/+$/,``);try{let e=new URL(t);if(e.pathname===``||e.pathname===`/`)return`${t}/v1`}catch{}return t}async function S(e,t,n){let r=`${x(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 C(e,t){let n=b(e),r=await T(`${n}/api/version`,t);if(r&&typeof r.version==`string`)return{kind:`ollama`,version:r.version};let i=await T(`${n}/api/v0/models`,t);if(i&&i.object===`list`)return{kind:`lmstudio`};let a=await T(`${n}/props`,t);if(a&&`build_info`in a)return{kind:`llamacpp`,version:a.build_info?.version};let o=w(e);return o===`11434`?{kind:`ollama`}:o===`1234`?{kind:`lmstudio`}:o===`8000`?{kind:`vllm`}:o===`1337`?{kind:`jan`}:{kind:`unknown`}}function w(e){try{return new URL(e).port||null}catch{return null}}async function T(e,t){try{let n=await fetch(e,{method:`GET`,signal:t});return n.ok?await n.json():null}catch{return null}}async function E(e,t,n){let r={kind:`unknown`};try{r=await C(e,n)}catch{}try{let i=await S(e,t,n);return{ok:!0,runtime:r,models:i}}catch(t){let n=t instanceof Error?t.message:String(t),i=D(n,r.kind);return o.warn(`verifyConnection failed`,{baseUrl:e,runtime:r.kind,message:n}),{ok:!1,runtime:r,models:[],error:i}}}function D(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}}export{u as config,C as detectRuntime,S as discoverModels,b as originOf,y as register,E as verifyConnection};
@@ -1,2 +1,2 @@
1
- import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./logger-BHrAkMIS.js";import{o as n}from"./provider-settings-DbAAu75J.js";import{p as r}from"./bedrock-camp-9aDiXDk5.js";import{o as i}from"./transform-messages-uhk4b6os.js";import{n as a,r as o}from"./openai-completions-ytvpg3gQ.js";var s=e({config:()=>d,detectRuntime:()=>C,discoverModels:()=>S,originOf:()=>b,register:()=>y,verifyConnection:()=>E});const c=t(`local-llm`),l=`local-llm`,u=`${l}-unconfigured`,d={id:l,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(`
1
+ import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./logger-BHrAkMIS.js";import{o as n}from"./provider-settings-B_lSRZ0U.js";import{p as r}from"./bedrock-camp-9aDiXDk5.js";import{o as i}from"./transform-messages-uhk4b6os.js";import{n as a,r as o}from"./openai-completions-ytvpg3gQ.js";var s=e({config:()=>d,detectRuntime:()=>C,discoverModels:()=>S,originOf:()=>b,register:()=>y,verifyConnection:()=>E});const c=t(`local-llm`),l=`local-llm`,u=`${l}-unconfigured`,d={id:l,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(`
2
2
  `),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=f(n(l));return e.length===0?[{id:u,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 f(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const p=`${l}-openai`;function m(e){return{...e,api:`openai-completions`}}function h(e){let t=e??{};return!t.apiKey||t.apiKey.length===0?{...t,apiKey:`local`}:t}const g=(e,t,n={})=>e.id===u?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?a(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`),_=(e,t,n)=>e.id===u?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?o(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`);function v(e,t){let n=i(),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 y(){r({api:p,stream:g,streamSimple:_})}function b(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e.replace(/\/v1\/?$/,``).replace(/\/+$/,``)}}function x(e){let t=e.replace(/\/+$/,``);try{let e=new URL(t);if(e.pathname===``||e.pathname===`/`)return`${t}/v1`}catch{}return t}async function S(e,t,n){let r=`${x(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 C(e,t){let n=b(e),r=await T(`${n}/api/version`,t);if(r&&typeof r.version==`string`)return{kind:`ollama`,version:r.version};let i=await T(`${n}/api/v0/models`,t);if(i&&i.object===`list`)return{kind:`lmstudio`};let a=await T(`${n}/props`,t);if(a&&`build_info`in a)return{kind:`llamacpp`,version:a.build_info?.version};let o=w(e);return o===`11434`?{kind:`ollama`}:o===`1234`?{kind:`lmstudio`}:o===`8000`?{kind:`vllm`}:o===`1337`?{kind:`jan`}:{kind:`unknown`}}function w(e){try{return new URL(e).port||null}catch{return null}}async function T(e,t){try{let n=await fetch(e,{method:`GET`,signal:t});return n.ok?await n.json():null}catch{return null}}async function E(e,t,n){let r={kind:`unknown`};try{r=await C(e,n)}catch{}try{let i=await S(e,t,n);return{ok:!0,runtime:r,models:i}}catch(t){let n=t instanceof Error?t.message:String(t),i=D(n,r.kind);return c.warn(`verifyConnection failed`,{baseUrl:e,runtime:r.kind,message:n}),{ok:!1,runtime:r,models:[],error:i}}}function D(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}}export{s as n,d as t};
@@ -1 +1 @@
1
- import{t as e}from"./preload-helper-ca-nBW7U.js";import{n as t}from"./index-Bq4R2DIC.js";var n={"image/jpeg":`JPEG`,"image/png":`PNG`,"image/gif":`GIF`,"image/webp":`WEBP`,"image/bmp":`BMP`,"image/tiff":`TIFF`,"image/avif":`AVIF`},r=null,i=`https://cdn.jsdelivr.net/npm/@imagemagick/magick-wasm@0.0.38/dist/`,a=typeof chrome<`u`&&!!chrome?.runtime?.id;async function o(){return r||=(async()=>{try{let n=await e(()=>import(`./dist-DNQ3u_NS.js`),[]);if(a){let e=chrome.runtime.getURL(`magick.wasm`),t=await fetch(e);if(!t.ok)throw Error(`Failed to fetch magick.wasm: ${t.status} ${t.statusText}`);let r=new Uint8Array(await t.arrayBuffer());await n.initializeImageMagick(r)}else{let e=t()?new URL(`/assets/index-BeMnZBAU.js`,``+import.meta.url).toString():i,r=new URL(`magick.wasm`,e);await n.initializeImageMagick(r)}return n}catch(e){throw r=null,e}})(),r}export{i as MAGICK_WASM_CDN,n as MIME_TO_MAGICK_FORMAT,o as getMagick,a as isExtension};
1
+ import{t as e}from"./preload-helper-ca-nBW7U.js";import{n as t}from"./index-BbIDJNZM.js";var n={"image/jpeg":`JPEG`,"image/png":`PNG`,"image/gif":`GIF`,"image/webp":`WEBP`,"image/bmp":`BMP`,"image/tiff":`TIFF`,"image/avif":`AVIF`},r=null,i=`https://cdn.jsdelivr.net/npm/@imagemagick/magick-wasm@0.0.38/dist/`,a=typeof chrome<`u`&&!!chrome?.runtime?.id;async function o(){return r||=(async()=>{try{let n=await e(()=>import(`./dist-DNQ3u_NS.js`),[]);if(a){let e=chrome.runtime.getURL(`magick.wasm`),t=await fetch(e);if(!t.ok)throw Error(`Failed to fetch magick.wasm: ${t.status} ${t.statusText}`);let r=new Uint8Array(await t.arrayBuffer());await n.initializeImageMagick(r)}else{let e=t()?new URL(`/assets/index-BeMnZBAU.js`,``+import.meta.url).toString():i,r=new URL(`magick.wasm`,e);await n.initializeImageMagick(r)}return n}catch(e){throw r=null,e}})(),r}export{i as MAGICK_WASM_CDN,n as MIME_TO_MAGICK_FORMAT,o as getMagick,a as isExtension};
@@ -1 +1 @@
1
- import{r as e}from"./chunk-jRWAZmH_.js";import{i as t}from"./backend-local-P05Hg6Af.js";import{t as n}from"./mime-types-DVkB7Eq7.js";import{t as r}from"./remote-cache-DdfqyJ2A.js";function i(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var a=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=i(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new t(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r&&!this.cache.isStale(r.cachedAt))return r.body;let i={};r&&(i[`if-none-match`]=r.etag);let a=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i});if(a.status===304&&r)return await this.cache.putBody(n,r.body,r.etag),r.body;if(a.status===404)throw await this.cache.invalidateBody(n),new t(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new t(`EACCES`,`s3 access denied`,e);if(a.status>=400)throw new t(`EIO`,`s3 readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(n,c,l),c}async writeFile(e,n){this.assertOpen(e);let r=this.toMountRelative(e);if(n.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=await this.cache.getBody(r),a={"content-type":`application/octet-stream`,"content-length":String(n.byteLength)};i?a[`if-match`]=i.etag:a[`if-none-match`]=`*`;let o=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(r),headers:a,body:n}),s,c=1;try{s=await o()}catch{c=2,s=await o()}if(s.status===412){if(c===2){let i=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(r)});if(i.status>=400)throw new t(`EIO`,`s3 reconcile HEAD failed: ${i.status}`,e);let a=i.headers.get(`etag`)??``;await this.cache.putBody(r,n,a);let o=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new t(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new t(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new t(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(r,n,l);let u=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],n;do{let r={"list-type":`2`};this.parsed.prefix&&(r.prefix=`${this.parsed.prefix}/`),n&&(r[`continuation-token`]=n);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:r});if(i.status>=400)throw new t(`EIO`,`s3 list failed: ${i.status}`,`/`);let a=await i.text(),o=this.parseListingXml(a);e.push(...o.contents),n=o.nextContinuationToken}while(n);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r)return{kind:`file`,size:r.body.byteLength,mtime:r.cachedAt,etag:r.etag};let i=n.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let n=s.entries.find(e=>e.name===a);if(n?.kind===`file`&&n.size!==void 0)return{kind:`file`,size:n.size,mtime:n.lastModified??s.cachedAt,etag:n.etag??``};if(n?.kind===`directory`)return{kind:`directory`,size:0,mtime:n.lastModified??s.cachedAt};if(!n)throw new t(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let r=await this.cache.getListing(n);if(r)return{kind:`directory`,size:0,mtime:r.cachedAt};throw new t(`ENOENT`,`no such file or directory`,e)}throw new t(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,n){this.assertOpen(e);let r=this.toMountRelative(e);if(n?.recursive)throw new t(`EINVAL`,`recursive remove not yet supported on S3`,e);let i=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(r)});if(i.status===404)throw new t(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new t(`EACCES`,`s3 delete denied`,e);if(i.status>=400)throw new t(`EIO`,`s3 delete failed: ${i.status}`,e);await this.cache.invalidateBody(r);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function o(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function s(e){return e.split(`/`).pop()||`data`}function c(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var l=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=c(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new t(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r&&!this.cache.isStale(r.cachedAt))return r.body;let i={};r&&(i[`if-none-match`]=r.etag);let a=await this.transport({method:`GET`,path:this.toSourcePath(n),headers:i});if(a.status===304&&r)return await this.cache.putBody(n,r.body,r.etag),r.body;if(a.status===404)throw await this.cache.invalidateBody(n),new t(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new t(`EACCES`,`da access denied`,e);if(a.status>=400)throw new t(`EIO`,`da readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(n,c,l),c}async writeFile(e,r){if(this.assertOpen(e),r.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=this.toMountRelative(e),a=await this.cache.getBody(i),c=o(s(e),n(e),r),l={"content-type":c.contentType,"content-length":String(c.body.byteLength)};a&&a.etag?l[`if-match`]=a.etag:a||(l[`if-none-match`]=`*`);let u=()=>this.transport({method:`POST`,path:this.toSourcePath(i),headers:l,body:c.body}),d,f=1;try{d=await u()}catch{f=2,d=await u()}if(d.status===412){if(f===2){let n=await this.transport({method:`HEAD`,path:this.toSourcePath(i)});if(n.status>=400)throw new t(`EIO`,`da reconcile HEAD failed: ${n.status}`,e);let a=n.headers.get(`etag`)??``;await this.cache.putBody(i,r,a);let o=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(i);try{await this.readFile(e)}catch{}throw new t(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(d.status===401||d.status===403)throw new t(`EACCES`,`da write denied`,e);if(d.status>=400)throw new t(`EIO`,`da writeFile failed: ${d.status}`,e);let p=d.headers.get(`etag`)??``;await this.cache.putBody(i,r,p);let m=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let n=this.toMountRelative(e).replace(/\/+$/,``),r=await this.cache.getListing(n);if(r&&!this.cache.isStale(r.cachedAt))return r.entries;let i=await this.transport({method:`GET`,path:this.toListPath(n)});if(i.status===404)throw new t(`ENOENT`,`no such directory`,e);if(i.status>=400)throw new t(`EIO`,`da list failed: ${i.status}`,e);let a=(await i.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(n,a),a}async stat(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r)return{kind:`file`,size:r.size,mtime:r.cachedAt,etag:r.etag};let i=n.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let n=s.entries.find(e=>e.name===a);if(n?.kind===`file`&&n.size!==void 0)return{kind:`file`,size:n.size,mtime:n.lastModified??s.cachedAt,etag:n.etag??``};if(n?.kind===`directory`)return{kind:`directory`,size:0,mtime:n.lastModified??s.cachedAt};if(!n)throw new t(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===a&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(o,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let r=await this.cache.getListing(n);if(r)return{kind:`directory`,size:0,mtime:r.cachedAt};throw new t(`ENOENT`,`no such file or directory`,e)}throw new t(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.transport({method:`DELETE`,path:this.toSourcePath(n)});if(r.status===404)throw new t(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new t(`EACCES`,`da delete denied`,e);if(r.status>=400)throw new t(`EIO`,`da delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});continue}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified});let i=await this.cache.getBody(n);i?r.etag&&i.etag!==r.etag?(await this.cache.invalidateBody(n),t.changed.push(n)):t.unchanged++:t.added.push(n)}else{a.push({name:r.name,kind:`directory`});let t=e?`${e}/${r.name}`:r.name;n.push(t)}await this.cache.putListing(e,a)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}if(e?.bodies)for(let e of t.changed)try{await this.readFile(e)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}return t}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},u=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function d(){let{getAccounts:e}=await import(`./provider-settings-DbAAu75J.js`).then(e=>e.l),t=e().find(e=>e.providerId===`adobe`);if(!t||!t.accessToken)throw new u(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}function f(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function p(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function m(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}const h=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),g=new Set([101,103,204,205,304]);function _(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new t(`EACCES`,e.error):e.errorCode===`invalid_request`?new t(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||h.has(String(e.errorCode))?new t(`EIO`,e.error):new t(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let n;try{n=p(e.bodyBase64)}catch(e){throw new t(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let r=g.has(e.status)?null:n;return new Response(r,{status:e.status,headers:new Headers(e.headers)})}async function v(e,n){let r;try{r=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}catch(e){throw new t(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await r.json()}catch(e){throw new t(`EIO`,`mount transport: response is not a JSON envelope (status ${r.status}): ${e instanceof Error?e.message:String(e)}`)}}async function y(e,n){try{return await chrome.runtime.sendMessage({type:e,envelope:n})}catch(e){throw new t(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}function b(e){return async t=>{let n={profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?m(t.body):void 0};return _(f()?await y(`mount.s3-sign-and-forward`,n):await v(`/api/s3-sign-and-forward`,n))}}function x(e){let n=e?.getImsToken??(async()=>(await d()).getBearerToken());return async e=>{let r;try{r=await n()}catch(e){throw new t(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}let i={imsToken:r,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?m(e.body):void 0};return _(f()?await y(`mount.da-sign-and-forward`,i):await v(`/api/da-sign-and-forward`,i))}}var S=e({DaMountBackend:()=>l,RemoteMountCache:()=>r,S3MountBackend:()=>a,makeSignedFetchDa:()=>x,makeSignedFetchS3:()=>b});export{a,l as i,x as n,b as r,S as t};
1
+ import{r as e}from"./chunk-jRWAZmH_.js";import{i as t}from"./backend-local-P05Hg6Af.js";import{t as n}from"./mime-types-DVkB7Eq7.js";import{t as r}from"./remote-cache-DdfqyJ2A.js";function i(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var a=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=i(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new t(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r&&!this.cache.isStale(r.cachedAt))return r.body;let i={};r&&(i[`if-none-match`]=r.etag);let a=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i});if(a.status===304&&r)return await this.cache.putBody(n,r.body,r.etag),r.body;if(a.status===404)throw await this.cache.invalidateBody(n),new t(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new t(`EACCES`,`s3 access denied`,e);if(a.status>=400)throw new t(`EIO`,`s3 readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(n,c,l),c}async writeFile(e,n){this.assertOpen(e);let r=this.toMountRelative(e);if(n.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=await this.cache.getBody(r),a={"content-type":`application/octet-stream`,"content-length":String(n.byteLength)};i?a[`if-match`]=i.etag:a[`if-none-match`]=`*`;let o=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(r),headers:a,body:n}),s,c=1;try{s=await o()}catch{c=2,s=await o()}if(s.status===412){if(c===2){let i=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(r)});if(i.status>=400)throw new t(`EIO`,`s3 reconcile HEAD failed: ${i.status}`,e);let a=i.headers.get(`etag`)??``;await this.cache.putBody(r,n,a);let o=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new t(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new t(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new t(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(r,n,l);let u=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],n;do{let r={"list-type":`2`};this.parsed.prefix&&(r.prefix=`${this.parsed.prefix}/`),n&&(r[`continuation-token`]=n);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:r});if(i.status>=400)throw new t(`EIO`,`s3 list failed: ${i.status}`,`/`);let a=await i.text(),o=this.parseListingXml(a);e.push(...o.contents),n=o.nextContinuationToken}while(n);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r)return{kind:`file`,size:r.body.byteLength,mtime:r.cachedAt,etag:r.etag};let i=n.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let n=s.entries.find(e=>e.name===a);if(n?.kind===`file`&&n.size!==void 0)return{kind:`file`,size:n.size,mtime:n.lastModified??s.cachedAt,etag:n.etag??``};if(n?.kind===`directory`)return{kind:`directory`,size:0,mtime:n.lastModified??s.cachedAt};if(!n)throw new t(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let r=await this.cache.getListing(n);if(r)return{kind:`directory`,size:0,mtime:r.cachedAt};throw new t(`ENOENT`,`no such file or directory`,e)}throw new t(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,n){this.assertOpen(e);let r=this.toMountRelative(e);if(n?.recursive)throw new t(`EINVAL`,`recursive remove not yet supported on S3`,e);let i=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(r)});if(i.status===404)throw new t(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new t(`EACCES`,`s3 delete denied`,e);if(i.status>=400)throw new t(`EIO`,`s3 delete failed: ${i.status}`,e);await this.cache.invalidateBody(r);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function o(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function s(e){return e.split(`/`).pop()||`data`}function c(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var l=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=c(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new t(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r&&!this.cache.isStale(r.cachedAt))return r.body;let i={};r&&(i[`if-none-match`]=r.etag);let a=await this.transport({method:`GET`,path:this.toSourcePath(n),headers:i});if(a.status===304&&r)return await this.cache.putBody(n,r.body,r.etag),r.body;if(a.status===404)throw await this.cache.invalidateBody(n),new t(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new t(`EACCES`,`da access denied`,e);if(a.status>=400)throw new t(`EIO`,`da readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(n,c,l),c}async writeFile(e,r){if(this.assertOpen(e),r.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=this.toMountRelative(e),a=await this.cache.getBody(i),c=o(s(e),n(e),r),l={"content-type":c.contentType,"content-length":String(c.body.byteLength)};a&&a.etag?l[`if-match`]=a.etag:a||(l[`if-none-match`]=`*`);let u=()=>this.transport({method:`POST`,path:this.toSourcePath(i),headers:l,body:c.body}),d,f=1;try{d=await u()}catch{f=2,d=await u()}if(d.status===412){if(f===2){let n=await this.transport({method:`HEAD`,path:this.toSourcePath(i)});if(n.status>=400)throw new t(`EIO`,`da reconcile HEAD failed: ${n.status}`,e);let a=n.headers.get(`etag`)??``;await this.cache.putBody(i,r,a);let o=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(i);try{await this.readFile(e)}catch{}throw new t(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(d.status===401||d.status===403)throw new t(`EACCES`,`da write denied`,e);if(d.status>=400)throw new t(`EIO`,`da writeFile failed: ${d.status}`,e);let p=d.headers.get(`etag`)??``;await this.cache.putBody(i,r,p);let m=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let n=this.toMountRelative(e).replace(/\/+$/,``),r=await this.cache.getListing(n);if(r&&!this.cache.isStale(r.cachedAt))return r.entries;let i=await this.transport({method:`GET`,path:this.toListPath(n)});if(i.status===404)throw new t(`ENOENT`,`no such directory`,e);if(i.status>=400)throw new t(`EIO`,`da list failed: ${i.status}`,e);let a=(await i.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(n,a),a}async stat(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r)return{kind:`file`,size:r.size,mtime:r.cachedAt,etag:r.etag};let i=n.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let n=s.entries.find(e=>e.name===a);if(n?.kind===`file`&&n.size!==void 0)return{kind:`file`,size:n.size,mtime:n.lastModified??s.cachedAt,etag:n.etag??``};if(n?.kind===`directory`)return{kind:`directory`,size:0,mtime:n.lastModified??s.cachedAt};if(!n)throw new t(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===a&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(o,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let r=await this.cache.getListing(n);if(r)return{kind:`directory`,size:0,mtime:r.cachedAt};throw new t(`ENOENT`,`no such file or directory`,e)}throw new t(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.transport({method:`DELETE`,path:this.toSourcePath(n)});if(r.status===404)throw new t(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new t(`EACCES`,`da delete denied`,e);if(r.status>=400)throw new t(`EIO`,`da delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});continue}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified});let i=await this.cache.getBody(n);i?r.etag&&i.etag!==r.etag?(await this.cache.invalidateBody(n),t.changed.push(n)):t.unchanged++:t.added.push(n)}else{a.push({name:r.name,kind:`directory`});let t=e?`${e}/${r.name}`:r.name;n.push(t)}await this.cache.putListing(e,a)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}if(e?.bodies)for(let e of t.changed)try{await this.readFile(e)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}return t}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},u=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function d(){let{getAccounts:e}=await import(`./provider-settings-B_lSRZ0U.js`).then(e=>e.l),t=e().find(e=>e.providerId===`adobe`);if(!t||!t.accessToken)throw new u(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}function f(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function p(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function m(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}const h=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),g=new Set([101,103,204,205,304]);function _(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new t(`EACCES`,e.error):e.errorCode===`invalid_request`?new t(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||h.has(String(e.errorCode))?new t(`EIO`,e.error):new t(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let n;try{n=p(e.bodyBase64)}catch(e){throw new t(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let r=g.has(e.status)?null:n;return new Response(r,{status:e.status,headers:new Headers(e.headers)})}async function v(e,n){let r;try{r=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}catch(e){throw new t(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await r.json()}catch(e){throw new t(`EIO`,`mount transport: response is not a JSON envelope (status ${r.status}): ${e instanceof Error?e.message:String(e)}`)}}async function y(e,n){try{return await chrome.runtime.sendMessage({type:e,envelope:n})}catch(e){throw new t(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}function b(e){return async t=>{let n={profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?m(t.body):void 0};return _(f()?await y(`mount.s3-sign-and-forward`,n):await v(`/api/s3-sign-and-forward`,n))}}function x(e){let n=e?.getImsToken??(async()=>(await d()).getBearerToken());return async e=>{let r;try{r=await n()}catch(e){throw new t(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}let i={imsToken:r,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?m(e.body):void 0};return _(f()?await y(`mount.da-sign-and-forward`,i):await v(`/api/da-sign-and-forward`,i))}}var S=e({DaMountBackend:()=>l,RemoteMountCache:()=>r,S3MountBackend:()=>a,makeSignedFetchDa:()=>x,makeSignedFetchS3:()=>b});export{a,l as i,x as n,b as r,S as t};