sliccy 1.57.0 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -236,7 +236,7 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
236
236
  </style>
237
237
  <script>${li}<\/script>
238
238
  </head>
239
- <body class="sprinkle-inline">${t}</body></html>`;if(ci)return pi(e,r,n);let i=document.createElement(`iframe`);i.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),i.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,i.srcdoc=r,e.appendChild(i);let a=e=>{if(e.source!==i.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(i.style.height=t.height+`px`))};return window.addEventListener(`message`,a),{dispose(){window.removeEventListener(`message`,a),i.remove()}}}function di(e,t){let n=e.querySelectorAll(`pre > code.language-shtml`);if(n.length===0)return[];let r=[];for(let e of n){let n=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__inline-sprinkle`,n.replaceWith(a),r.push(ui(a,i,t))}return r}function fi(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function pi(e,t,n){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,e.appendChild(r);let i=e=>{if(e.source!==r.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(r.style.height=t.height+`px`))};return window.addEventListener(`message`,i),r.addEventListener(`load`,()=>{r.contentWindow?.postMessage({type:`inline-sprinkle-render`,srcdoc:t},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,i),r.remove()}}}var mi=n(`tool-ui-renderer`),hi=typeof chrome<`u`&&!!chrome?.runtime?.id,gi=class{container;iframe=null;inlineSprinkle=null;messageHandler=null;requestId;nonce;constructor(e,t){this.container=e,this.requestId=t,this.nonce=crypto.randomUUID()}async render(e){hi?await this.renderInSandbox(e):this.renderWithInlineSprinkle(e)}async renderInSandbox(e){let t=document.createElement(`iframe`);t.src=chrome.runtime.getURL(`tool-ui-sandbox.html`),t.style.cssText=`width: 100%; border: none; min-height: 60px;`,this.iframe=t,await new Promise((e,n)=>{let r=setTimeout(()=>{mi.error(`Tool UI iframe load timed out`),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe load timed out`))},5e3);t.addEventListener(`load`,()=>{clearTimeout(r),e()},{once:!0}),t.addEventListener(`error`,()=>{clearTimeout(r),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(t)}),this.messageHandler=e=>{if(e.source!==t.contentWindow)return;let n=e.data;if(n?.type){if(n.nonce!==this.nonce){mi.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(mi.info(`Tool UI action received`,{id:n.id,action:n.action}),_.handleAction(n.id,{action:n.action,data:n.data})):n.type===`tool-ui-rendered`&&n.id===this.requestId?n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`):n.type===`tool-ui-resize`&&n.id===this.requestId&&n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`)}},window.addEventListener(`message`,this.messageHandler);let{collectThemeCSS:n}=await v(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-CTvH_7GK.js`);return{collectThemeCSS:e}},[]),r=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:r},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=ui(t,e,(e,t)=>{mi.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),_.handleAction(this.requestId,{action:e,data:t})})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.inlineSprinkle&&=(this.inlineSprinkle.dispose(),null)}},_i=new Map;function vi(e,t,n){let r=_i.get(t);r&&r.dispose();let i=new gi(e,t);return _i.set(t,i),i.render(n).catch(e=>{mi.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function yi(e){let t=_i.get(e);t&&(t.dispose(),_i.delete(e))}var bi=n(`chat-panel`);function xi(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Si={bash:`$`,browser:`B`,read_file:`R`,write_file:`W`,edit_file:`E`,javascript:`JS`,delegate_to_scoop:`D`,send_message:`M`,schedule_task:`T`,list_scoops:`LS`,list_tasks:`LT`,register_scoop:`RS`,update_global_memory:`GM`};function Ci(e){return Si[e]??`?`}function wi(e){return e.role===`assistant`?Wr(e.content):Ur(e.content)}var Ti=class{container;messagesEl;messagesInner;inputArea;textarea;sendBtn;stopBtn;micBtn;voiceInput=null;voiceMode=!1;keydownListener=null;messages=[];agent=null;unsubscribe=null;isStreaming=!1;currentStreamId=null;sessionStore;sessionId;readOnly=!1;terminalOutputCallback=null;currentScoopName=null;autoScrollAttached=!0;lastScrollTop=0;jumpPill;onDeleteQueuedMessage=null;pendingDeltaText=``;streamingRafId=null;inlineSprinkles=new Map;onInlineSprinkleLick;modelSelectorEl;handoffsEl;pendingHandoffs=[];onAcceptPendingHandoff=null;onDismissPendingHandoff=null;onModelChange;constructor(e){this.container=e,this.sessionStore=new Xr,this.sessionId=`default`,this.render()}setAgent(e){this.unsubscribe?.(),this.agent=e,this.unsubscribe=e.onEvent(e=>this.handleAgentEvent(e))}onTerminalOutput(e){this.terminalOutputCallback=e}setDeleteQueuedMessageCallback(e){this.onDeleteQueuedMessage=e}async initSession(e){await this.sessionStore.init(),this.sessionId=e??`default`;let t=await this.sessionStore.load(this.sessionId);t&&t.messages.length>0&&(this.messages=t.messages.map(e=>({...e,isStreaming:!1})),this.renderMessages())}async clearSession(){this.messages=[],this.renderMessages(),await this.sessionStore.delete(this.sessionId)}async deleteSessionById(e){await this.sessionStore.delete(e)}async switchToContext(e,t,n){await this.persistSessionAsync(),this.setStreamingState(!1),this.currentStreamId=null,this.cancelPendingDelta(),this.sessionId=e,this.currentScoopName=n??null,this.setReadOnly(t);let r=await this.sessionStore.load(this.sessionId);r&&r.messages.length>0?this.messages=r.messages.map(e=>({...e,isStreaming:!1})):this.messages=[],this.renderMessages()}setReadOnly(e){this.readOnly=e,this.inputArea&&(this.inputArea.style.display=e?`none`:``)}async persistSessionAsync(){try{await this.sessionStore.saveMessages(this.sessionId,this.messages)}catch{}}setProcessing(e){e?this.setStreamingState(!0):this.setStreamingState(!1)}addSystemMessage(e){let t={id:xi(),role:`assistant`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t),this.persistSession()}addLickMessage(e,t,n){let r={id:e,role:`user`,content:t,timestamp:Date.now(),source:`lick`,channel:n};this.messages.push(r),this.appendMessageEl(r),this.persistSession()}getMessages(){return[...this.messages]}loadMessages(e){this.messages=e.map(e=>({...e,isStreaming:!1})),this.renderMessages(),this.persistSession(),this.renderModelSelector()}clear(){this.messages=[],this.renderMessages(),this.renderModelSelector()}setPendingHandoffs(e){this.pendingHandoffs=[...e],this.renderPendingHandoffs()}setPendingHandoffActions(e){this.onAcceptPendingHandoff=e.onAccept,this.onDismissPendingHandoff=e.onDismiss,this.renderPendingHandoffs()}addUserMessage(e){let t={id:xi(),role:`user`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}deleteQueuedMessage(e){let t=this.messages.findIndex(t=>t.id===e);if(t===-1)return;this.messages.splice(t,1);let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);n&&n.remove(),this.persistSession(),this.onDeleteQueuedMessage?.(e)}render(){this.container.innerHTML=``,this.container.classList.add(`chat`),this.messagesEl=document.createElement(`div`),this.messagesEl.className=`chat__messages`,this.messagesInner=document.createElement(`div`),this.messagesInner.className=`chat__messages-inner`,this.messagesEl.appendChild(this.messagesInner),this.handoffsEl=document.createElement(`div`),this.handoffsEl.className=`chat__handoffs`,this.handoffsEl.hidden=!0,this.messagesEl.appendChild(this.handoffsEl),this.container.appendChild(this.messagesEl),this.renderPendingHandoffs(),this.messagesEl.addEventListener(`scroll`,()=>{let{scrollTop:e,scrollHeight:t,clientHeight:n}=this.messagesEl;t-e-n<=250?(this.autoScrollAttached=!0,this.hideJumpPill()):e<this.lastScrollTop&&(this.autoScrollAttached=!1),this.lastScrollTop=e},{passive:!0}),this.inputArea=document.createElement(`div`);let e=this.inputArea;e.className=`chat__input-area`;let t=document.createElement(`div`);t.className=`chat__input-area-inner`,this.textarea=document.createElement(`textarea`),this.textarea.className=`chat__textarea`,this.textarea.placeholder=`What shall we build?`,this.textarea.rows=1,this.sendBtn=document.createElement(`button`),this.sendBtn.className=`chat__send-btn`,this.sendBtn.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M10 1.25C5.167 1.25 1.25 5.167 1.25 10s3.917 8.75 8.75 8.75 8.75-3.918 8.75-8.75S14.833 1.25 10 1.25zm3.527 8.284a.75.75 0 0 1-1.06 0L10.75 7.82v6.172a.75.75 0 0 1-1.5 0V7.812L7.527 9.534a.75.75 0 1 1-1.06-1.06l2.998-2.998a.75.75 0 0 1 1.06-.001l3.002 2.998a.75.75 0 0 1 0 1.061z"/></svg>`,this.sendBtn.dataset.tooltip=`Send message`,this.sendBtn.dataset.tooltipPos=`top`,this.stopBtn=document.createElement(`button`),this.stopBtn.className=`chat__stop-btn`,this.stopBtn.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M13.75 4H6.25A2.25 2.25 0 0 0 4 6.25v7.5A2.25 2.25 0 0 0 6.25 16h7.5A2.25 2.25 0 0 0 16 13.75v-7.5A2.25 2.25 0 0 0 13.75 4z"/></svg>`,this.stopBtn.dataset.tooltip=`Stop generation`,this.stopBtn.style.display=`none`,this.micBtn=document.createElement(`button`),this.micBtn.className=`chat__mic-btn`;let n=`http://www.w3.org/2000/svg`,r=document.createElementNS(n,`svg`);r.setAttribute(`width`,`16`),r.setAttribute(`height`,`16`),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`2`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`);let i=document.createElementNS(n,`path`);i.setAttribute(`d`,`M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z`);let a=document.createElementNS(n,`path`);a.setAttribute(`d`,`M19 10v2a7 7 0 0 1-14 0v-2`);let o=document.createElementNS(n,`line`);o.setAttribute(`x1`,`12`),o.setAttribute(`y1`,`19`),o.setAttribute(`x2`,`12`),o.setAttribute(`y2`,`23`);let s=document.createElementNS(n,`line`);s.setAttribute(`x1`,`8`),s.setAttribute(`y1`,`23`),s.setAttribute(`x2`,`16`),s.setAttribute(`y2`,`23`),r.append(i,a,o,s),this.micBtn.appendChild(r),this.micBtn.dataset.tooltip=`Voice (Ctrl+Shift+V)`;let c=document.createElement(`div`);c.className=`chat__input-wrapper`,c.appendChild(this.textarea);let l=document.createElement(`div`);l.className=`chat__action-bar`;let u=document.createElement(`div`);u.className=`chat__action-bar-left`,u.appendChild(this.micBtn),l.appendChild(u),this.modelSelectorEl=document.createElement(`div`),this.modelSelectorEl.className=`chat__model-selector`,this.renderModelSelector(),l.appendChild(this.modelSelectorEl);let d=document.createElement(`div`);d.className=`chat__action-bar-right`,d.appendChild(this.sendBtn),d.appendChild(this.stopBtn),l.appendChild(d),c.appendChild(l),t.appendChild(c),e.appendChild(t),this.container.appendChild(e),this.jumpPill=document.createElement(`button`),this.jumpPill.className=`chat__jump-pill`,this.jumpPill.textContent=`↓ New activity`,this.jumpPill.addEventListener(`click`,()=>{this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}),this.container.appendChild(this.jumpPill),this.textarea.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.sendMessage())}),this.textarea.addEventListener(`input`,()=>{this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`}),this.sendBtn.addEventListener(`click`,()=>this.sendMessage()),this.stopBtn.addEventListener(`click`,()=>{this.agent?.stop();for(let e of this.messages)e.queued&&(e.queued=!1,this.updateMessageEl(e.id));this.setStreamingState(!1)}),this.voiceInput=new ei({onTranscript:(e,t)=>{this.textarea.value=e,this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`},onStateChange:e=>{e===`error`?(this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`)):this.voiceMode?e===`listening`&&this.micBtn.classList.add(`chat__mic-btn--listening`):this.micBtn.classList.toggle(`chat__mic-btn--listening`,e===`listening`)},onError:e=>{bi.debug(`Voice input error`,{error:e}),!(this.voiceMode&&e.includes(`No speech detected`))&&this.addSystemMessage(e)},autoSend:!0,onAutoSend:e=>{this.textarea.value=e,this.sendMessage()},onAutoDisable:()=>{this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`),this.addSystemMessage(`Voice mode disabled after 2 minutes of inactivity.`)},lang:ni()}),this.micBtn.addEventListener(`click`,()=>{this.toggleVoiceMode()}),this.keydownListener=e=>{e.shiftKey&&(e.ctrlKey||e.metaKey)&&e.key===`V`&&(e.preventDefault(),this.toggleVoiceMode())},document.addEventListener(`keydown`,this.keydownListener)}renderPendingHandoffs(){if(!this.handoffsEl)return;if(this.pendingHandoffs.length===0){this.handoffsEl.hidden=!0,this.handoffsEl.innerHTML=``;return}let e=this.pendingHandoffs.length===1?`1 pending handoff`:`${this.pendingHandoffs.length} pending handoffs`;this.handoffsEl.hidden=!1,this.handoffsEl.innerHTML=`
239
+ <body class="sprinkle-inline">${t}</body></html>`;if(ci)return pi(e,r,n);let i=document.createElement(`iframe`);i.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),i.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,i.srcdoc=r,e.appendChild(i);let a=e=>{if(e.source!==i.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(i.style.height=t.height+`px`))};return window.addEventListener(`message`,a),{dispose(){window.removeEventListener(`message`,a),i.remove()}}}function di(e,t){let n=e.querySelectorAll(`pre > code.language-shtml`);if(n.length===0)return[];let r=[];for(let e of n){let n=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__inline-sprinkle`,n.replaceWith(a),r.push(ui(a,i,t))}return r}function fi(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function pi(e,t,n){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,e.appendChild(r);let i=e=>{if(e.source!==r.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(r.style.height=t.height+`px`))};return window.addEventListener(`message`,i),r.addEventListener(`load`,()=>{r.contentWindow?.postMessage({type:`inline-sprinkle-render`,srcdoc:t},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,i),r.remove()}}}var mi=n(`tool-ui-renderer`),hi=typeof chrome<`u`&&!!chrome?.runtime?.id,gi=class{container;iframe=null;inlineSprinkle=null;messageHandler=null;requestId;nonce;constructor(e,t){this.container=e,this.requestId=t,this.nonce=crypto.randomUUID()}async render(e){hi?await this.renderInSandbox(e):this.renderWithInlineSprinkle(e)}async renderInSandbox(e){let t=document.createElement(`iframe`);t.src=chrome.runtime.getURL(`tool-ui-sandbox.html`),t.style.cssText=`width: 100%; border: none; min-height: 60px;`,this.iframe=t,await new Promise((e,n)=>{let r=setTimeout(()=>{mi.error(`Tool UI iframe load timed out`),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe load timed out`))},5e3);t.addEventListener(`load`,()=>{clearTimeout(r),e()},{once:!0}),t.addEventListener(`error`,()=>{clearTimeout(r),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(t)}),this.messageHandler=e=>{if(e.source!==t.contentWindow)return;let n=e.data;if(n?.type){if(n.nonce!==this.nonce){mi.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(mi.info(`Tool UI action received`,{id:n.id,action:n.action}),_.handleAction(n.id,{action:n.action,data:n.data})):n.type===`tool-ui-rendered`&&n.id===this.requestId?n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`):n.type===`tool-ui-resize`&&n.id===this.requestId&&n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`)}},window.addEventListener(`message`,this.messageHandler);let{collectThemeCSS:n}=await v(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-Dnz_l3xR.js`);return{collectThemeCSS:e}},[]),r=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:r},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=ui(t,e,(e,t)=>{mi.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),_.handleAction(this.requestId,{action:e,data:t})})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.inlineSprinkle&&=(this.inlineSprinkle.dispose(),null)}},_i=new Map;function vi(e,t,n){let r=_i.get(t);r&&r.dispose();let i=new gi(e,t);return _i.set(t,i),i.render(n).catch(e=>{mi.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function yi(e){let t=_i.get(e);t&&(t.dispose(),_i.delete(e))}var bi=n(`chat-panel`);function xi(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Si={bash:`$`,browser:`B`,read_file:`R`,write_file:`W`,edit_file:`E`,javascript:`JS`,delegate_to_scoop:`D`,send_message:`M`,schedule_task:`T`,list_scoops:`LS`,list_tasks:`LT`,register_scoop:`RS`,update_global_memory:`GM`};function Ci(e){return Si[e]??`?`}function wi(e){return e.role===`assistant`?Wr(e.content):Ur(e.content)}var Ti=class{container;messagesEl;messagesInner;inputArea;textarea;sendBtn;stopBtn;micBtn;voiceInput=null;voiceMode=!1;keydownListener=null;messages=[];agent=null;unsubscribe=null;isStreaming=!1;currentStreamId=null;sessionStore;sessionId;readOnly=!1;terminalOutputCallback=null;currentScoopName=null;autoScrollAttached=!0;lastScrollTop=0;jumpPill;onDeleteQueuedMessage=null;pendingDeltaText=``;streamingRafId=null;inlineSprinkles=new Map;onInlineSprinkleLick;modelSelectorEl;handoffsEl;pendingHandoffs=[];onAcceptPendingHandoff=null;onDismissPendingHandoff=null;onModelChange;constructor(e){this.container=e,this.sessionStore=new Xr,this.sessionId=`default`,this.render()}setAgent(e){this.unsubscribe?.(),this.agent=e,this.unsubscribe=e.onEvent(e=>this.handleAgentEvent(e))}onTerminalOutput(e){this.terminalOutputCallback=e}setDeleteQueuedMessageCallback(e){this.onDeleteQueuedMessage=e}async initSession(e){await this.sessionStore.init(),this.sessionId=e??`default`;let t=await this.sessionStore.load(this.sessionId);t&&t.messages.length>0&&(this.messages=t.messages.map(e=>({...e,isStreaming:!1})),this.renderMessages())}async clearSession(){this.messages=[],this.renderMessages(),await this.sessionStore.delete(this.sessionId)}async deleteSessionById(e){await this.sessionStore.delete(e)}async switchToContext(e,t,n){await this.persistSessionAsync(),this.setStreamingState(!1),this.currentStreamId=null,this.cancelPendingDelta(),this.sessionId=e,this.currentScoopName=n??null,this.setReadOnly(t);let r=await this.sessionStore.load(this.sessionId);r&&r.messages.length>0?this.messages=r.messages.map(e=>({...e,isStreaming:!1})):this.messages=[],this.renderMessages()}setReadOnly(e){this.readOnly=e,this.inputArea&&(this.inputArea.style.display=e?`none`:``)}async persistSessionAsync(){try{await this.sessionStore.saveMessages(this.sessionId,this.messages)}catch{}}setProcessing(e){e?this.setStreamingState(!0):this.setStreamingState(!1)}addSystemMessage(e){let t={id:xi(),role:`assistant`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t),this.persistSession()}addLickMessage(e,t,n){let r={id:e,role:`user`,content:t,timestamp:Date.now(),source:`lick`,channel:n};this.messages.push(r),this.appendMessageEl(r),this.persistSession()}getMessages(){return[...this.messages]}loadMessages(e){this.messages=e.map(e=>({...e,isStreaming:!1})),this.renderMessages(),this.persistSession(),this.renderModelSelector()}clear(){this.messages=[],this.renderMessages(),this.renderModelSelector()}setPendingHandoffs(e){this.pendingHandoffs=[...e],this.renderPendingHandoffs()}setPendingHandoffActions(e){this.onAcceptPendingHandoff=e.onAccept,this.onDismissPendingHandoff=e.onDismiss,this.renderPendingHandoffs()}addUserMessage(e){let t={id:xi(),role:`user`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}deleteQueuedMessage(e){let t=this.messages.findIndex(t=>t.id===e);if(t===-1)return;this.messages.splice(t,1);let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);n&&n.remove(),this.persistSession(),this.onDeleteQueuedMessage?.(e)}render(){this.container.innerHTML=``,this.container.classList.add(`chat`),this.messagesEl=document.createElement(`div`),this.messagesEl.className=`chat__messages`,this.messagesInner=document.createElement(`div`),this.messagesInner.className=`chat__messages-inner`,this.messagesEl.appendChild(this.messagesInner),this.handoffsEl=document.createElement(`div`),this.handoffsEl.className=`chat__handoffs`,this.handoffsEl.hidden=!0,this.messagesEl.appendChild(this.handoffsEl),this.container.appendChild(this.messagesEl),this.renderPendingHandoffs(),this.messagesEl.addEventListener(`scroll`,()=>{let{scrollTop:e,scrollHeight:t,clientHeight:n}=this.messagesEl;t-e-n<=250?(this.autoScrollAttached=!0,this.hideJumpPill()):e<this.lastScrollTop&&(this.autoScrollAttached=!1),this.lastScrollTop=e},{passive:!0}),this.inputArea=document.createElement(`div`);let e=this.inputArea;e.className=`chat__input-area`;let t=document.createElement(`div`);t.className=`chat__input-area-inner`,this.textarea=document.createElement(`textarea`),this.textarea.className=`chat__textarea`,this.textarea.placeholder=`What shall we build?`,this.textarea.rows=1,this.sendBtn=document.createElement(`button`),this.sendBtn.className=`chat__send-btn`,this.sendBtn.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M10 1.25C5.167 1.25 1.25 5.167 1.25 10s3.917 8.75 8.75 8.75 8.75-3.918 8.75-8.75S14.833 1.25 10 1.25zm3.527 8.284a.75.75 0 0 1-1.06 0L10.75 7.82v6.172a.75.75 0 0 1-1.5 0V7.812L7.527 9.534a.75.75 0 1 1-1.06-1.06l2.998-2.998a.75.75 0 0 1 1.06-.001l3.002 2.998a.75.75 0 0 1 0 1.061z"/></svg>`,this.sendBtn.dataset.tooltip=`Send message`,this.sendBtn.dataset.tooltipPos=`top`,this.stopBtn=document.createElement(`button`),this.stopBtn.className=`chat__stop-btn`,this.stopBtn.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M13.75 4H6.25A2.25 2.25 0 0 0 4 6.25v7.5A2.25 2.25 0 0 0 6.25 16h7.5A2.25 2.25 0 0 0 16 13.75v-7.5A2.25 2.25 0 0 0 13.75 4z"/></svg>`,this.stopBtn.dataset.tooltip=`Stop generation`,this.stopBtn.style.display=`none`,this.micBtn=document.createElement(`button`),this.micBtn.className=`chat__mic-btn`;let n=`http://www.w3.org/2000/svg`,r=document.createElementNS(n,`svg`);r.setAttribute(`width`,`16`),r.setAttribute(`height`,`16`),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`2`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`);let i=document.createElementNS(n,`path`);i.setAttribute(`d`,`M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z`);let a=document.createElementNS(n,`path`);a.setAttribute(`d`,`M19 10v2a7 7 0 0 1-14 0v-2`);let o=document.createElementNS(n,`line`);o.setAttribute(`x1`,`12`),o.setAttribute(`y1`,`19`),o.setAttribute(`x2`,`12`),o.setAttribute(`y2`,`23`);let s=document.createElementNS(n,`line`);s.setAttribute(`x1`,`8`),s.setAttribute(`y1`,`23`),s.setAttribute(`x2`,`16`),s.setAttribute(`y2`,`23`),r.append(i,a,o,s),this.micBtn.appendChild(r),this.micBtn.dataset.tooltip=`Voice (Ctrl+Shift+V)`;let c=document.createElement(`div`);c.className=`chat__input-wrapper`,c.appendChild(this.textarea);let l=document.createElement(`div`);l.className=`chat__action-bar`;let u=document.createElement(`div`);u.className=`chat__action-bar-left`,u.appendChild(this.micBtn),l.appendChild(u),this.modelSelectorEl=document.createElement(`div`),this.modelSelectorEl.className=`chat__model-selector`,this.renderModelSelector(),l.appendChild(this.modelSelectorEl);let d=document.createElement(`div`);d.className=`chat__action-bar-right`,d.appendChild(this.sendBtn),d.appendChild(this.stopBtn),l.appendChild(d),c.appendChild(l),t.appendChild(c),e.appendChild(t),this.container.appendChild(e),this.jumpPill=document.createElement(`button`),this.jumpPill.className=`chat__jump-pill`,this.jumpPill.textContent=`↓ New activity`,this.jumpPill.addEventListener(`click`,()=>{this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}),this.container.appendChild(this.jumpPill),this.textarea.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.sendMessage())}),this.textarea.addEventListener(`input`,()=>{this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`}),this.sendBtn.addEventListener(`click`,()=>this.sendMessage()),this.stopBtn.addEventListener(`click`,()=>{this.agent?.stop();for(let e of this.messages)e.queued&&(e.queued=!1,this.updateMessageEl(e.id));this.setStreamingState(!1)}),this.voiceInput=new ei({onTranscript:(e,t)=>{this.textarea.value=e,this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`},onStateChange:e=>{e===`error`?(this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`)):this.voiceMode?e===`listening`&&this.micBtn.classList.add(`chat__mic-btn--listening`):this.micBtn.classList.toggle(`chat__mic-btn--listening`,e===`listening`)},onError:e=>{bi.debug(`Voice input error`,{error:e}),!(this.voiceMode&&e.includes(`No speech detected`))&&this.addSystemMessage(e)},autoSend:!0,onAutoSend:e=>{this.textarea.value=e,this.sendMessage()},onAutoDisable:()=>{this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`),this.addSystemMessage(`Voice mode disabled after 2 minutes of inactivity.`)},lang:ni()}),this.micBtn.addEventListener(`click`,()=>{this.toggleVoiceMode()}),this.keydownListener=e=>{e.shiftKey&&(e.ctrlKey||e.metaKey)&&e.key===`V`&&(e.preventDefault(),this.toggleVoiceMode())},document.addEventListener(`keydown`,this.keydownListener)}renderPendingHandoffs(){if(!this.handoffsEl)return;if(this.pendingHandoffs.length===0){this.handoffsEl.hidden=!0,this.handoffsEl.innerHTML=``;return}let e=this.pendingHandoffs.length===1?`1 pending handoff`:`${this.pendingHandoffs.length} pending handoffs`;this.handoffsEl.hidden=!1,this.handoffsEl.innerHTML=`
240
240
  <div class="chat__handoffs-inner">
241
241
  <div class="chat__handoffs-header">${jr(e)}</div>
242
242
  ${this.pendingHandoffs.map(e=>this.renderPendingHandoffCard(e)).join(``)}
@@ -722,21 +722,21 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
722
722
  50% { transform: scale(1.3); }
723
723
  100% { transform: scale(1); }
724
724
  }
725
- `,document.head.appendChild(e)}},zi=[{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}],Bi=`slicc-hidden-tabs`,Vi=[`terminal`,`memory`];function Hi(){try{let e=localStorage.getItem(Bi);return e?new Set(JSON.parse(e)):new Set(Vi)}catch{return new Set(Vi)}}function Ui(e){let t=e.filter(e=>e!==`chat`);localStorage.setItem(Bi,JSON.stringify(t))}var Wi=zi.filter(e=>!Hi().has(e.id)),Gi=`chat`,Ki=new Set(zi.map(e=>e.id));function qi(e){return Ki.has(e)}var Ji=class{zoneId;tabBar;contentArea;tabs=new Map;activeTabId=null;callbacks;addBtn=null;fullpageBtn=null;isFullpage=!1;separator=null;scrollArea=null;storageKey;classPrefix;constructor(e,t,n,r={},i={}){this.tabBar=e,this.contentArea=t,this.zoneId=n,this.callbacks=r,this.storageKey=`slicc-${n}-tab`,this.classPrefix=i.classPrefix??`mini-tabs`}addTab(e){if(this.tabs.has(e.id))return;let t=document.createElement(`button`);if(t.dataset.tabId=e.id,e.pinned&&e.icon){t.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--icon ${this.classPrefix}__tab--dimmed`,t.innerHTML=e.icon,t.setAttribute(`aria-label`,e.label),t.dataset.tooltip=e.label,t.dataset.tooltipPos=`top`;let n=this.separator||this.findFirstNonPinnedBtn()||this.addBtn;if(n?this.tabBar.insertBefore(t,n):this.tabBar.appendChild(t),!this.separator){this.separator=document.createElement(`div`),this.separator.className=`${this.classPrefix}__separator`,this.scrollArea=document.createElement(`div`),this.scrollArea.className=`${this.classPrefix}__scroll`;let e=this.addBtn||this.fullpageBtn;e?(this.tabBar.insertBefore(this.separator,e),this.tabBar.insertBefore(this.scrollArea,e)):(this.tabBar.appendChild(this.separator),this.tabBar.appendChild(this.scrollArea))}t.addEventListener(`click`,()=>{let t=this.tabs.get(e.id);t&&!t.mounted&&this.enablePinnedTab(e.id),this.activateTab(e.id)}),this.tabs.set(e.id,{btn:t,container:e.element,tab:e,mounted:!1})}else{if(t.className=`${this.classPrefix}__tab`,t.appendChild(document.createTextNode(e.label)),e.closable){let n=document.createElement(`span`);n.className=`${this.classPrefix}__tab-close`,n.title=`Close panel`,n.textContent=`×`,n.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onTabClose?.(e.id)}),t.appendChild(n)}t.addEventListener(`click`,()=>this.activateTab(e.id)),this.scrollArea?this.scrollArea.appendChild(t):this.addBtn?this.tabBar.insertBefore(t,this.addBtn):this.tabBar.appendChild(t);let n=e.element;n.style.display=`none`,this.contentArea.appendChild(n),this.tabs.set(e.id,{btn:t,container:n,tab:e,mounted:!0}),(!this.activeTabId||!this.tabs.get(this.activeTabId)?.mounted)&&this.activateTab(e.id)}}removeTab(e){let t=this.tabs.get(e);if(t&&(t.btn.remove(),t.mounted&&t.container.remove(),this.tabs.delete(e),this.activeTabId===e)){let e=Array.from(this.tabs.entries()).find(([,e])=>e.mounted);e?this.activateTab(e[0]):this.activeTabId=null}}enablePinnedTab(e){let t=this.tabs.get(e);!t||t.mounted||(t.mounted=!0,t.btn.classList.remove(`${this.classPrefix}__tab--dimmed`),t.container.style.display=`none`,this.contentArea.appendChild(t.container))}isPinnedTabEnabled(e){return this.tabs.get(e)?.mounted??!1}activateTab(e){let t=this.tabs.get(e);if(!(!t||!t.mounted)){this.activeTabId=e;for(let[t,{btn:n,container:r,mounted:i}]of this.tabs){let a=t===e;n.classList.toggle(`${this.classPrefix}__tab--active`,a),i&&(r.style.display=a?`flex`:`none`)}try{localStorage.setItem(this.storageKey,e)}catch{}t.tab.onActivate?.(),this.callbacks.onTabActivate?.(e)}}getActiveTabId(){return this.activeTabId}getTabIds(){return Array.from(this.tabs.keys())}hasTab(e){return this.tabs.has(e)}setTabBadge(e,t){let n=this.tabs.get(e);if(!n)return;let r=n.btn.querySelector(`.${this.classPrefix}__tab-badge`);if(!t||t<=0){r?.remove();return}let i=r instanceof HTMLSpanElement?r:document.createElement(`span`);if(i.className=`${this.classPrefix}__tab-badge`,i.textContent=t>99?`99+`:String(t),i.setAttribute(`aria-label`,`${t} notifications`),!r){let e=n.btn.querySelector(`.${this.classPrefix}__tab-close`);e?n.btn.insertBefore(i,e):n.btn.appendChild(i)}}get tabCount(){return this.tabs.size}enableAddButton(){this.addBtn||(this.addBtn=document.createElement(`button`),this.addBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--add`,this.addBtn.textContent=`+`,this.addBtn.dataset.tooltip=`Open panel`,this.addBtn.dataset.tooltipPos=`top`,this.addBtn.setAttribute(`aria-label`,`Open panel`),this.addBtn.addEventListener(`click`,()=>this.callbacks.onAddClick?.()),this.tabBar.appendChild(this.addBtn))}setAddButtonEnabled(e){this.addBtn&&(this.addBtn.disabled=!e)}enableFullpageButton(){this.fullpageBtn||(this.fullpageBtn=document.createElement(`button`),this.fullpageBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--fullpage`,this.fullpageBtn.dataset.tooltip=`Full page`,this.fullpageBtn.dataset.tooltipPos=`top`,this.fullpageBtn.setAttribute(`aria-label`,`Toggle full page`),this.fullpageBtn.innerHTML=`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>`,this.fullpageBtn.addEventListener(`click`,()=>{this.isFullpage=!this.isFullpage,this.fullpageBtn.classList.toggle(`${this.classPrefix}__tab--active`,this.isFullpage),this.fullpageBtn.innerHTML=this.isFullpage?`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 6h-4V2"/><path d="M2 10h4v4"/><path d="M10 6l4.5-4.5"/><path d="M6 10L1.5 14.5"/></svg>`:`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>`,this.fullpageBtn.dataset.tooltip=this.isFullpage?`Exit full page`:`Full page`,this.callbacks.onFullpageToggle?.(this.isFullpage)}),this.tabBar.appendChild(this.fullpageBtn))}restoreActiveTab(){try{let e=localStorage.getItem(this.storageKey);if(e&&this.tabs.has(e)&&this.tabs.get(e).mounted)return this.activateTab(e),e}catch{}return null}findFirstNonPinnedBtn(){for(let[,e]of this.tabs)if(!e.tab.pinned)return e.btn;return null}},Yi=class{entries=new Map;listeners=new Set;register(e){this.entries.set(e.id,{descriptor:e}),this.notify()}unregister(e){this.entries.delete(e),this.notify()}get(e){return this.entries.get(e)}getByZone(e){let t=[];for(let n of this.entries.values())n.descriptor.zone===e&&t.push(n.descriptor);return t}getClosed(){let e=[];for(let t of this.entries.values())t.descriptor.zone===null&&e.push(t.descriptor);return e}setZone(e,t){let n=this.entries.get(e);n&&(n.descriptor.zone=t,this.notify())}ids(){return Array.from(this.entries.keys())}has(e){return this.entries.has(e)}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(let e of this.listeners)e()}};function Xi(e,t,n){let r=document.querySelector(`.sprinkle-picker`);if(r){r.remove();return}let{registry:i,callbacks:a,getAvailableSprinkles:o}=n,s=i.getClosed(),c=o?.()??[];if(s.length===0&&c.length===0)return;let l=document.createElement(`div`);l.className=`sprinkle-picker`,l.style.cssText=`position: absolute; min-width: 160px; max-height: 300px; overflow-y: auto; background: var(--s2-bg-layer-2); border: 1px solid var(--s2-border-default); border-radius: var(--s2-radius-l); padding: 4px 0; box-shadow: var(--s2-shadow-elevated); z-index: 1000;`;let u=()=>{l.remove(),document.removeEventListener(`pointerdown`,f,!0),document.removeEventListener(`keydown`,p,!0)};for(let e of s){let n=Zi(e.label,()=>{a.onSelectPanel(e.id,t),u()});l.appendChild(n)}if(s.length>0&&c.length>0){let e=document.createElement(`div`);e.style.cssText=`height: 1px; background: var(--s2-border-default); margin: 4px 0;`,l.appendChild(e)}for(let e of c){let n=Zi(e.title,()=>{a.onSelectSprinkle(e.name,t),u()});l.appendChild(n)}let d=e.getBoundingClientRect();l.style.top=`${d.bottom+4}px`,l.style.left=`${d.left}px`,document.body.appendChild(l);let f=e=>{l.contains(e.target)||u()},p=e=>{e.key===`Escape`&&u()};requestAnimationFrame(()=>{document.addEventListener(`pointerdown`,f,!0),document.addEventListener(`keydown`,p,!0)})}function Zi(e,t){let n=document.createElement(`div`);return n.className=`sprinkle-picker__item`,n.style.cssText=`padding: 6px 12px; cursor: pointer; font-size: 12px; color: var(--s2-content-default); border-radius: var(--s2-radius-s); margin: 0 4px; transition: background 130ms ease;`,n.textContent=e,n.addEventListener(`mouseenter`,()=>{n.style.background=`var(--s2-bg-elevated)`}),n.addEventListener(`mouseleave`,()=>{n.style.background=``}),n.addEventListener(`click`,t),n}var Qi=class e{root;isExtension;scoopsEl;leftEl;rightEl;verticalDivider;terminalContainer;iframeContainer;threadHeaderEl;threadHeaderName;primaryZoneEl;primaryZone;get drawerZone(){return this.primaryZone}get drawerZoneEl(){return this.primaryZoneEl}tabContainers=new Map;activeTab=`chat`;debugTabContainers=null;scoopSwitcher=null;scoopSwitcherEl=null;avatarEl;logoSvg=null;logoImg=null;logoScoopCount=-1;headerHamburger=null;panels;registry=new Yi;onModelChange;refreshModels;onScoopSelect;onClearChat;onClearFilesystem;onSprinkleClose;getAvailableSprinkles;onOpenSprinkle;constructor(e,t=!1){this.root=e,this.isExtension=t,t?this.buildTabbedLayout():this.buildSplitLayout()}setScoopSwitcherOrchestrator(e){this.scoopSwitcher?.setOrchestrator(e)}updateScoopSwitcherStatus(e,t){this.scoopSwitcher?.updateStatus(e,t)}setScoopSwitcherSelected(e){this.scoopSwitcher?.setSelected(e)}refreshScoopSwitcher(){this.scoopSwitcher?.refresh()}setActiveTab(e){this.isExtension&&this.extensionZone?.activateTab(e)}getActiveTab(){return this.activeTab}setPendingHandoffCount(e){this.isExtension&&this.extensionZone.setTabBadge(`chat`,e>0?e:null)}isTerminalOpen(){return this.isExtension?!0:this.primaryZone.isPinnedTabEnabled(`terminal`)}setAgentProcessing(e){this.threadHeaderEl?.classList.toggle(`thread-header--processing`,e)}openTerminal(){if(this.isExtension)return;this.primaryZone.isPinnedTabEnabled(`terminal`)||this.primaryZone.enablePinnedTab(`terminal`);let e=this.primaryZone.getActiveTabId();e&&e.startsWith(`sprinkle-`)||this.primaryZone.activateTab(`terminal`)}setDebugTabs(e){if(!this.isExtension||!this.debugTabContainers)return;let t=[{id:`terminal`,label:`Terminal`,container:this.debugTabContainers.terminal,onActivate:()=>this.panels?.terminal?.refit?.()},{id:`memory`,label:`Memory`,container:this.debugTabContainers.memory,onActivate:()=>this.panels?.memory?.refresh()}];for(let{id:n,label:r,container:i,onActivate:a}of t)e&&!this.extensionZone.hasTab(n)?(this.extensionZone.addTab({id:n,label:r,closable:!1,element:i,onActivate:a}),this.tabContainers.set(n,i)):!e&&this.extensionZone.hasTab(n)&&(this.extensionZone.removeTab(n),this.tabContainers.delete(n));Ui(e?[]:[`terminal`,`memory`])}buildHeader(e){let t=document.createElement(`div`);t.className=`header`;let n=()=>{if(te())return;let e=j();for(let t of e)if(t.models.length>0){let{defaultModelId:e}=E(t.providerId),n=(e?t.models.find(t=>t.id.toLowerCase().includes(e.toLowerCase())):void 0)??t.models[0];ne(`${t.providerId}:${n.id}`);return}};n(),this.refreshModels=()=>{n(),this.panels?.chat?.refreshModelSelector(),this.refreshAvatar()};let r=document.createElement(`div`);r.className=`header__row`;let i=document.createElement(`div`);if(i.className=`header__brand`,this.isExtension){let e=this.sliccLogo(24);i.appendChild(e)}else{let e=document.createElement(`button`);e.className=`scoops-hamburger`,e.dataset.tooltip=`Toggle navigation`,e.dataset.tooltipPos=`right`,e.setAttribute(`aria-label`,`Toggle navigation`),e.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.61805 16.2451C9.31922 15.958 9.30945 15.4834 9.59754 15.1855L14.5839 10.002L9.58485 4.80469C9.29677 4.50684 9.30653 4.03223 9.60536 3.74512C9.90223 3.45801 10.3778 3.4668 10.6649 3.76563L16.1649 9.48243C16.4452 9.77247 16.4452 10.2315 16.1649 10.5215L10.6776 16.2246C10.5311 16.3779 10.3339 16.4551 10.1376 16.4551C9.95008 16.4551 9.76258 16.3857 9.61805 16.2451Z"/><path d="M3.86805 16.2451C3.56922 15.958 3.55945 15.4834 3.84754 15.1855L8.83387 10.002L3.83485 4.80469C3.54677 4.50684 3.55653 4.03223 3.85536 3.74512C4.15223 3.45801 4.62782 3.4668 4.91493 3.76563L10.4149 9.48243C10.6952 9.77247 10.6952 10.2315 10.4149 10.5215L4.92763 16.2246C4.78114 16.3779 4.58388 16.4551 4.38759 16.4551C4.20008 16.4551 4.01258 16.3857 3.86805 16.2451Z"/></svg>`,this.headerHamburger=e,e.addEventListener(`click`,()=>{this.panels?.scoops?.toggleExpanded(),e.innerHTML=this.scoopsEl?.classList.contains(`layout__scoops--expanded`)?`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.86241 16.4551C9.66612 16.4551 9.46886 16.3779 9.32237 16.2246L3.83507 10.5215C3.5548 10.2315 3.5548 9.77247 3.83507 9.48243L9.33507 3.76563C9.62218 3.4668 10.0978 3.45801 10.3946 3.74512C10.6935 4.03223 10.7032 4.50684 10.4151 4.80469L5.41613 10.002L10.4025 15.1855C10.6906 15.4834 10.6808 15.958 10.382 16.2451C10.2374 16.3857 10.0499 16.4551 9.86241 16.4551Z"/><path d="M15.6124 16.4551C15.4161 16.4551 15.2189 16.3779 15.0724 16.2246L9.58507 10.5215C9.3048 10.2315 9.3048 9.77247 9.58507 9.48243L15.0851 3.76563C15.3722 3.4668 15.8478 3.45801 16.1446 3.74512C16.4435 4.03223 16.4532 4.50684 16.1652 4.80469L11.1661 10.002L16.1525 15.1855C16.4406 15.4834 16.4308 15.958 16.132 16.2451C15.9874 16.3857 15.7999 16.4551 15.6124 16.4551Z"/></svg>`:`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.61805 16.2451C9.31922 15.958 9.30945 15.4834 9.59754 15.1855L14.5839 10.002L9.58485 4.80469C9.29677 4.50684 9.30653 4.03223 9.60536 3.74512C9.90223 3.45801 10.3778 3.4668 10.6649 3.76563L16.1649 9.48243C16.4452 9.77247 16.4452 10.2315 16.1649 10.5215L10.6776 16.2246C10.5311 16.3779 10.3339 16.4551 10.1376 16.4551C9.95008 16.4551 9.76258 16.3857 9.61805 16.2451Z"/><path d="M3.86805 16.2451C3.56922 15.958 3.55945 15.4834 3.84754 15.1855L8.83387 10.002L3.83485 4.80469C3.54677 4.50684 3.55653 4.03223 3.85536 3.74512C4.15223 3.45801 4.62782 3.4668 4.91493 3.76563L10.4149 9.48243C10.6952 9.77247 10.6952 10.2315 10.4149 10.5215L4.92763 16.2246C4.78114 16.3779 4.58388 16.4551 4.38759 16.4551C4.20008 16.4551 4.01258 16.3857 3.86805 16.2451Z"/></svg>`}),i.appendChild(e)}let a=document.createElement(`div`);a.className=`header__title`,a.textContent=`slicc`,i.appendChild(a),r.appendChild(i),this.isExtension&&(this.scoopSwitcherEl=document.createElement(`div`),this.scoopSwitcherEl.className=`scoop-switcher`,this.scoopSwitcher=new Ri(this.scoopSwitcherEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onDeleteScoop:e=>{this.panels?.scoops?.deleteScoop?.(e)}}),r.appendChild(this.scoopSwitcherEl));let o=document.createElement(`div`);o.className=`header__spacer`,r.appendChild(o),this.avatarEl=this.buildUserAvatar(),r.appendChild(this.avatarEl),t.appendChild(r),e.appendChild(t)}static SCOOP_COLORS=[`#f000a0`,`#00f0f0`,`#90f000`,`#15d675`,`#e68619`];sliccLogo(e=22){let t=document.createElement(`img`);return t.width=e,t.height=e,t.src=`/logos/sliccy-color-0scoops-128x128.png`,t.alt=`slicc`,t.classList.add(`header__logo`),t.style.objectFit=`contain`,this.logoImg=t,t}static SCOOP_R=5;static SCOOP_SPACING=8.5;static ROW_STEP=7.5;pyramidLayout(t){if(t===0)return[];let{SCOOP_SPACING:n,ROW_STEP:r}=e,i=1;for(;i*(i+1)/2<t;)i++;let a=[],o=t,s=i;for(;o>0;){let e=Math.min(o,s);a.push(e),o-=e,s--}let c=[],l=19-e.SCOOP_R;for(let e of a){let t=16-(e-1)*n/2;for(let r=0;r<e;r++)c.push({cx:t+r*n,cy:l});l-=r}return c}updateLogoScoops(e){let t=e.filter(e=>!e.isCone),n=this.logoScoopCount;if(n===t.length&&n>=0)return;this.logoScoopCount=t.length;let r=Math.min(Math.max(t.length,0),10);this.logoImg&&(this.logoImg.src=`/logos/sliccy-color-${r}scoops-128x128.png`),this.updateFaviconForScoops(t.length)}updateFaviconForScoops(e){let t=Math.min(Math.max(e,0),10),n=document.querySelector(`link[rel="icon"]`);n&&(n.href=`/logos/sliccy-color-${t}scoops-32x32.png`);let r=typeof chrome<`u`?chrome:null;r?.action?.setIcon&&r.action.setIcon({path:{16:`logos/sliccy-color-${t}scoops-16x16.png`,32:`logos/sliccy-color-${t}scoops-32x32.png`,48:`logos/sliccy-color-${t}scoops-48x48.png`,128:`logos/sliccy-color-${t}scoops-128x128.png`}}).catch(()=>{})}getInitials(e){let t=e.trim().split(/\s+/);return t.length>=2?(t[0][0]+t[t.length-1][0]).toUpperCase():e.slice(0,2).toUpperCase()}buildUserAvatar(){let e=document.createElement(`div`);e.className=`header__avatar`,e.setAttribute(`aria-label`,`Account`),e.dataset.tooltip=`Account`;let t=ee().find(e=>e.userName||e.userAvatar);if(t?.userAvatar){let n=document.createElement(`img`);n.src=t.userAvatar,n.alt=t.userName??`User`,n.addEventListener(`error`,()=>{e.removeChild(n),t.userName&&(e.classList.add(`header__avatar--initials`),e.textContent=this.getInitials(t.userName))}),e.appendChild(n)}else t?.userName?(e.classList.add(`header__avatar--initials`),e.textContent=this.getInitials(t.userName)):(e.classList.add(`header__avatar--placeholder`),e.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M10 10c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4z"/></svg>`);return e.addEventListener(`click`,()=>this.showAvatarPopover()),e}refreshAvatar(){if(!this.avatarEl)return;let e=this.avatarEl.parentElement;if(!e)return;let t=this.buildUserAvatar();e.replaceChild(t,this.avatarEl),this.avatarEl=t}showAvatarPopover(){let e=document.querySelector(`.avatar-popover`);if(e){e.remove();return}let t=document.createElement(`div`);t.className=`avatar-popover`;let n=ee(),r=n.find(e=>e.userName||e.accessToken||e.apiKey);if(r){let e=document.createElement(`div`);e.className=`avatar-popover__user`;let n=document.createElement(`div`);n.className=`avatar-popover__name`,n.textContent=r.userName||`Logged in`,e.appendChild(n);let i=document.createElement(`div`);i.className=`avatar-popover__provider`,i.textContent=E(r.providerId).name,e.appendChild(i),t.appendChild(e);let a=document.createElement(`button`);a.className=`avatar-popover__item`,a.textContent=`Sign out`,a.addEventListener(`click`,()=>{w(r.providerId),t.remove(),this.refreshAvatar(),this.refreshModels?.()}),t.appendChild(a)}if(n.length>0){let e=document.createElement(`div`);e.className=`avatar-popover__separator`,t.appendChild(e);let n=document.createElement(`button`);n.className=`avatar-popover__item avatar-popover__item--danger`,n.textContent=`Clear all accounts`,n.addEventListener(`click`,()=>{A(),t.remove(),this.refreshAvatar(),this.refreshModels?.()}),t.appendChild(n)}let i=document.createElement(`div`);i.className=`avatar-popover__separator`,t.appendChild(i);let a=document.createElement(`button`);a.className=`avatar-popover__item avatar-popover__item--danger`,a.textContent=`Clear chat`,a.addEventListener(`click`,async()=>{t.remove(),await this.panels?.chat?.clearSession(),await this.onClearChat?.(),location.reload()}),t.appendChild(a);let o=document.createElement(`div`);o.className=`avatar-popover__separator`,t.appendChild(o);let s=document.createElement(`button`);s.className=`avatar-popover__item`,s.textContent=`Account settings…`,s.addEventListener(`click`,async()=>{t.remove(),T()||A(),await C()&&(this.refreshAvatar(),this.refreshModels?.())}),t.appendChild(s),document.body.appendChild(t);let c=this.avatarEl.getBoundingClientRect();t.style.top=`${c.bottom+4}px`,t.style.right=`${window.innerWidth-c.right}px`;let l=e=>{if(e instanceof KeyboardEvent){if(e.key!==`Escape`)return}else if(t.contains(e.target)||this.avatarEl.contains(e.target))return;t.remove(),document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,l)};requestAnimationFrame(()=>{document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,l)})}extensionZone;buildTabbedLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);let e=document.createElement(`div`);e.className=`tab-bar`,this.root.appendChild(e);let t=document.createElement(`div`);t.className=`tab-content`,this.root.appendChild(t),this.extensionZone=new Ji(e,t,`primary`,{onTabActivate:e=>{this.activeTab=e,e===`terminal`&&this.panels?.terminal?.refit?.(),e===`memory`&&this.panels?.memory?.refresh()},onTabClose:e=>{let t=e.startsWith(`sprinkle-`)?e.slice(9):e;this.onSprinkleClose?.(t)},onAddClick:()=>this.showExtensionPicker(e)},{classPrefix:`tab-bar`});let n=document.createElement(`div`);n.className=`tab-content__panel`;let r=document.createElement(`div`);r.className=`tab-content__panel`;let i=document.createElement(`div`);i.className=`tab-content__panel`;let a=document.createElement(`div`);a.className=`tab-content__panel`;for(let{id:e,label:t}of Wi){let o=e===`chat`?n:e===`terminal`?r:e===`files`?i:a;this.extensionZone.addTab({id:e,label:t,closable:!1,element:o,onActivate:e===`terminal`?()=>this.panels?.terminal?.refit?.():e===`memory`?()=>this.panels?.memory?.refresh():void 0}),this.tabContainers.set(e,o)}this.debugTabContainers={terminal:r,memory:a},this.extensionZone.enableAddButton(),this.iframeContainer=document.createElement(`div`),this.iframeContainer.id=`scoop-iframes`,this.iframeContainer.style.display=`none`,this.root.appendChild(this.iframeContainer),this.scoopsEl=document.createElement(`div`),this.scoopsEl.style.display=`none`,this.root.appendChild(this.scoopsEl),this.panels={chat:new Ti(n),terminal:new Ei(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new Pi(i,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.extensionZone.activateTab(`terminal`)}}),memory:new Fi(a),scoops:new Li(this.scoopsEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onSendMessage:()=>{},onScoopsChanged:e=>this.updateLogoScoops(e)})},this.panels.chat.onModelChange=e=>this.onModelChange?.(e)}showExtensionPicker(e){let t=this.getAvailableSprinkles?.()??[],n=new Set(this.extensionZone.getTabIds()),r=t.filter(e=>!n.has(`sprinkle-${e.name}`));r.length!==0&&Xi(e,`primary`,{registry:this.registry,callbacks:{onSelectPanel:()=>{},onSelectSprinkle:e=>{this.onOpenSprinkle?.(e)}},getAvailableSprinkles:()=>r})}switchTab(e){this.extensionZone&&this.extensionZone.activateTab(e)}buildSplitLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);let e=document.createElement(`div`);e.className=`layout`,this.scoopsEl=document.createElement(`div`),this.scoopsEl.className=`layout__scoops`,e.appendChild(this.scoopsEl),this.leftEl=document.createElement(`div`),this.leftEl.className=`layout__left`,this.threadHeaderEl=document.createElement(`div`),this.threadHeaderEl.className=`thread-header`;let t=document.createElement(`div`);t.className=`thread-header__title`;let n=document.createElement(`span`);n.className=`thread-header__icon`,n.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4h14a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H7l-4 3V5a1 1 0 0 1 1-1z"/><path d="M7 8h6"/><path d="M7 11h3"/></svg>`,t.appendChild(n),this.threadHeaderName=document.createElement(`span`),this.threadHeaderName.className=`thread-header__name`,this.threadHeaderName.textContent=`sliccy`,t.appendChild(this.threadHeaderName),this.threadHeaderEl.appendChild(t);let r=document.createElement(`button`);r.className=`thread-header__panel-toggle thread-header__panel-toggle--right`,r.dataset.tooltip=`Toggle panel`,r.setAttribute(`aria-label`,`Toggle panel`),r.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M12 3v14"/></svg>`,r.addEventListener(`click`,()=>{this.rightEl.classList.toggle(`layout__right--open`)});let i=document.createElement(`button`);i.className=`thread-header__panel-toggle`,i.dataset.tooltip=`Clear Chat`,i.setAttribute(`aria-label`,`Clear Chat`),i.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>`,i.addEventListener(`click`,async()=>{await this.panels.chat.clearSession(),await this.onClearChat?.(),location.reload()});let a=document.createElement(`div`);a.className=`thread-header__actions`,a.appendChild(i),a.appendChild(r),this.threadHeaderEl.appendChild(a),this.leftEl.appendChild(this.threadHeaderEl);let o=document.createElement(`div`);o.style.cssText=`display: flex; flex-direction: column; flex: 1; min-height: 0;`,this.leftEl.appendChild(o),e.appendChild(this.leftEl),this.verticalDivider=document.createElement(`div`),this.verticalDivider.className=`layout__divider layout__divider--vertical`,e.appendChild(this.verticalDivider),this.rightEl=document.createElement(`div`),this.rightEl.className=`layout__right`,this.primaryZoneEl=document.createElement(`div`),this.primaryZoneEl.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let s=document.createElement(`div`);s.className=`mini-tabs`;let c=document.createElement(`button`);c.className=`thread-header__panel-toggle thread-header__panel-toggle--right`,c.dataset.tooltip=`Close panel`,c.setAttribute(`aria-label`,`Close panel`),c.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v14"/><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>`,c.addEventListener(`click`,()=>{this.rightEl.classList.remove(`layout__right--open`)}),s.appendChild(c),this.primaryZoneEl.appendChild(s);let l=document.createElement(`div`);l.style.cssText=`flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden;`,this.primaryZoneEl.appendChild(l),this.primaryZone=new Ji(s,l,`primary`,{onTabActivate:e=>{e===`terminal`&&this.panels?.terminal?.refit(),e===`memory`&&this.panels?.memory?.refresh()},onTabClose:e=>{let t=e.startsWith(`sprinkle-`)?e.slice(9):e;this.onSprinkleClose?.(t)},onAddClick:()=>this.showPickerForZone(`primary`,s),onFullpageToggle:e=>{this.leftEl.classList.toggle(`layout__left--fullpage-hidden`,e),this.verticalDivider.classList.toggle(`layout__divider--fullpage-hidden`,e),this.scoopsEl.classList.toggle(`layout__scoops--fullpage-hidden`,e),this.rightEl.classList.toggle(`layout__right--fullpage`,e)}}),this.terminalContainer=document.createElement(`div`),this.terminalContainer.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let u=document.createElement(`div`);u.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let d=document.createElement(`div`);d.style.cssText=`display: flex; flex-direction: column; min-height: 0; flex: 1;`;let f=e=>`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">${e}</svg>`;this.primaryZone.addTab({id:`terminal`,label:`Terminal`,closable:!1,element:this.terminalContainer,pinned:!0,icon:f(`<path d="M5.5 14.5C5.30762 14.5 5.11621 14.4268 4.96973 14.2803L1.21973 10.5303C0.92676 10.2373 0.92676 9.76269 1.21973 9.46972L4.96973 5.71972C5.2627 5.42675 5.73731 5.42675 6.03028 5.71972C6.32325 6.01269 6.32325 6.4873 6.03028 6.78027L2.81055 10L6.03028 13.2197C6.32325 13.5127 6.32325 13.9873 6.03028 14.2803C5.8838 14.4268 5.69238 14.5 5.5 14.5Z" fill="currentColor"/><path d="M14.5 14.5C14.3076 14.5 14.1162 14.4268 13.9697 14.2803C13.6768 13.9873 13.6768 13.5127 13.9697 13.2197L17.1895 9.99999L13.9697 6.78026C13.6768 6.48729 13.6768 6.01268 13.9697 5.71971C14.2627 5.42674 14.7373 5.42674 15.0303 5.71971L18.7803 9.46971C19.0732 9.76268 19.0732 10.2373 18.7803 10.5303L15.0303 14.2803C14.8838 14.4267 14.6924 14.5 14.5 14.5Z" fill="currentColor"/><path d="M8.22852 18C8.16993 18 8.11036 17.9932 8.05176 17.9795C7.64844 17.8818 7.40137 17.4766 7.49805 17.0742L10.998 2.57422C11.0957 2.1709 11.5078 1.92871 11.9033 2.02051C12.3066 2.11817 12.5537 2.52344 12.457 2.92578L8.95703 17.4258C8.87402 17.7695 8.56642 18 8.22852 18Z" fill="currentColor"/>`),onActivate:()=>this.panels?.terminal?.refit()}),this.primaryZone.addTab({id:`files`,label:`Files`,closable:!1,element:u,pinned:!0,icon:f(`<path d="M18 4.75C18 2.61621 13.9756 1.5 10 1.5C6.02441 1.5 2 2.61621 2 4.75C2 4.81714 2.01538 4.88037 2.02325 4.94556C2.01696 4.98462 2 5.01978 2 5.06055V15C2 17.0615 6.14697 18 10 18C13.853 18 18 17.0615 18 15V5.06055C18 5.01978 17.983 4.98462 17.9767 4.94556C17.9846 4.88037 18 4.81714 18 4.75ZM16.5002 9.99451C16.4084 10.4097 14.2719 11.5 10 11.5C5.72705 11.5 3.59033 10.4092 3.5 10V6.72449C5.02985 7.56665 7.52393 8 10 8C12.4761 8 14.9701 7.56665 16.5001 6.72437L16.5002 9.99451ZM10 3C14.2886 3 16.5 4.22656 16.5 4.75C16.5 5.27344 14.2886 6.5 10 6.5C5.71143 6.5 3.5 5.27344 3.5 4.75C3.5 4.22656 5.71143 3 10 3ZM10 16.5C5.72705 16.5 3.59033 15.4092 3.5 15V11.8464C5.05219 12.6304 7.58337 13 10 13C12.4168 13 14.9482 12.6304 16.5003 11.8463L16.5005 14.9941C16.4097 15.4092 14.273 16.5 10 16.5Z" fill="currentColor"/>`)}),this.primaryZone.addTab({id:`memory`,label:`Memory`,closable:!1,element:d,pinned:!0,icon:f(`<path d="M10.0039 12.5889C9.11573 12.5889 8.25098 12.1289 7.77588 11.3057C7.06787 10.0781 7.48975 8.50489 8.71582 7.79688C9.30908 7.45313 10.001 7.36329 10.665 7.54004C11.3276 7.71777 11.8814 8.14356 12.2241 8.73731C12.5674 9.33106 12.6582 10.0234 12.481 10.6855C12.3032 11.3486 11.8784 11.9024 11.2842 12.2451C10.8809 12.4785 10.4395 12.5889 10.0039 12.5889ZM9.07471 10.5557C9.36914 11.0645 10.0229 11.2392 10.5342 10.9463C10.7812 10.8037 10.958 10.5732 11.0317 10.2978C11.1055 10.0225 11.0679 9.73436 10.9253 9.48729C10.7822 9.24022 10.5522 9.06346 10.2764 8.98924C10.0015 8.916 9.71337 8.95408 9.46581 9.09569C8.95556 9.39061 8.78027 10.0449 9.07471 10.5557Z" fill="currentColor"/><path d="M6.90674 18.3184C6.56738 18.3184 6.22461 18.2334 5.91455 18.0537L5.09473 17.5811C4.20166 17.0674 3.84473 15.9316 4.28369 14.998L4.86377 13.7646C4.59863 13.4014 4.37402 13.0137 4.19189 12.6035L2.83496 12.4912C1.80615 12.4063 1.00049 11.5313 1.00049 10.5L0.99951 9.55371C0.99951 8.52051 1.80469 7.64453 2.83301 7.55957L4.1875 7.44531C4.2793 7.23633 4.37988 7.03613 4.48926 6.8457C4.59912 6.65429 4.72266 6.46679 4.8584 6.28125L4.27783 5.05176C3.83691 4.11914 4.1914 2.9834 5.08496 2.4668L5.90527 1.99317C6.79785 1.47657 7.95898 1.73438 8.54785 2.58301L9.32519 3.70117C9.76904 3.65137 10.2173 3.65332 10.666 3.70117L11.4414 2.58203C12.0303 1.73242 13.1924 1.47265 14.085 1.98828L14.9048 2.46094C15.7988 2.97656 16.1543 4.11231 15.7153 5.04492L15.1352 6.27734C15.4009 6.6416 15.6255 7.02929 15.8071 7.43847L17.164 7.55077C18.1924 7.63573 18.998 8.51073 18.999 9.54198L18.9995 10.4893C19.0005 11.5205 18.1958 12.3965 17.1675 12.4834L15.812 12.5976C15.7207 12.8066 15.6201 13.0059 15.5093 13.1973C15.3999 13.3867 15.2769 13.5752 15.1411 13.7607L15.7217 14.9902C16.1621 15.9219 15.8081 17.0576 14.915 17.5752L14.0942 18.0498C13.2007 18.5684 12.0405 18.3076 11.4517 17.459L10.6743 16.3408C10.2285 16.3897 9.78028 16.3887 9.3335 16.3418L8.55713 17.4619C8.17334 18.0156 7.54541 18.3184 6.90674 18.3184ZM6.9043 3.22461C6.81934 3.22461 6.73389 3.24609 6.65625 3.29102L5.83545 3.76563C5.61279 3.89454 5.52393 4.17774 5.63428 4.41114L6.41309 6.06153C6.53907 6.32813 6.49707 6.64356 6.30567 6.86817C6.10157 7.10743 5.93262 7.34473 5.78907 7.59376C5.64796 7.83985 5.52393 8.11231 5.42091 8.40333C5.32277 8.68165 5.07081 8.87599 4.77687 8.9004L2.95802 9.05372C2.6963 9.07618 2.49952 9.29005 2.49952 9.55274L2.5005 10.499C2.5005 10.7568 2.70167 10.9756 2.959 10.9971L4.77834 11.1475C5.07229 11.1719 5.32473 11.3662 5.42336 11.6445C5.62209 12.2051 5.92043 12.7207 6.31008 13.1768C6.50197 13.4004 6.54446 13.7168 6.41897 13.9834L5.64114 15.6358C5.53176 15.8692 5.62014 16.1533 5.84378 16.2813L6.66409 16.7549C6.88821 16.8848 7.17825 16.8184 7.32425 16.6074L8.36527 15.1055C8.53275 14.8633 8.82425 14.7363 9.11771 14.7959C9.70609 14.9033 10.3023 14.9043 10.8877 14.7949C11.1773 14.7402 11.4727 14.8613 11.6412 15.1045L12.6831 16.6035C12.8296 16.8135 13.1216 16.8799 13.3438 16.751L14.1641 16.2773C14.3902 16.1465 14.4776 15.8682 14.3653 15.6309L13.5864 13.9805C13.4605 13.7139 13.5025 13.3984 13.6939 13.1738C13.898 12.9336 14.0669 12.6973 14.2095 12.4492L14.21 12.4483C14.3526 12.2012 14.4732 11.9365 14.5786 11.6387C14.6773 11.3604 14.9292 11.166 15.2232 11.1416L17.042 10.9893C17.2984 10.9668 17.4995 10.7481 17.4995 10.4902L17.499 9.54298C17.499 9.28126 17.3018 9.06739 17.0401 9.04493L15.2212 8.89454C14.9273 8.87013 14.6748 8.67579 14.5762 8.39747C14.3784 7.8379 14.0796 7.32227 13.689 6.86524C13.4976 6.64063 13.4551 6.3252 13.5806 6.0586L14.3579 4.40626C14.4678 4.17286 14.3789 3.88868 14.1553 3.75978L13.3355 3.28712C13.1108 3.16017 12.8213 3.2256 12.6743 3.43653L11.6348 4.93653C11.4668 5.17969 11.1758 5.30469 10.8819 5.24708C10.2905 5.1377 9.69435 5.1377 9.11183 5.24708C8.81984 5.29884 8.52638 5.1797 8.35841 4.93751L7.31642 3.43849C7.22023 3.30079 7.06348 3.22461 6.9043 3.22461Z" fill="currentColor"/>`),onActivate:()=>this.panels?.memory?.refresh()}),this.primaryZone.enableAddButton(),this.primaryZone.enableFullpageButton(),this.rightEl.appendChild(this.primaryZoneEl),e.appendChild(this.rightEl),this.iframeContainer=document.createElement(`div`),this.iframeContainer.id=`scoop-iframes`,this.iframeContainer.style.display=`none`,e.appendChild(this.iframeContainer),this.root.appendChild(e),this.panels={chat:new Ti(o),terminal:new Ei(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new Pi(u,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.openTerminal()}}),memory:new Fi(d),scoops:new Li(this.scoopsEl,{onScoopSelect:e=>{this.onScoopSelect?.(e),this.threadHeaderName.textContent=e.assistantLabel},onSendMessage:()=>{},onScoopsChanged:e=>this.updateLogoScoops(e)})},this.panels.chat.onModelChange=e=>this.onModelChange?.(e),this.setupVerticalDrag(),window.addEventListener(`resize`,()=>{})}getIframeContainer(){return this.iframeContainer}async runFileBrowserCommand(e){let t=await this.panels.terminal.runCommand(e);t.exitCode!==0&&t.stderr&&console.warn(`[Layout] File browser command failed:`,t.stderr.trim())}setupVerticalDrag(){if(!this.verticalDivider)return;let e=!1,t=t=>{if(!e)return;let n=this.root.querySelector(`.layout`)?.getBoundingClientRect();if(!n)return;let r=t.clientX-n.left-58,i=n.width-58,a=Math.max(.3,Math.min(.7,r/i));this.leftEl.style.flex=`${a*100} 0 0`,this.rightEl.style.flex=`${(1-a)*100} 0 0`},n=()=>{e=!1,this.verticalDivider.classList.remove(`active`),document.body.style.cursor=``,document.body.style.userSelect=``,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),this.panels?.terminal?.refit()};this.verticalDivider.addEventListener(`mousedown`,r=>{r.preventDefault(),e=!0,this.verticalDivider.classList.add(`active`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)})}updateAddButtons(){let e=this.registry.getClosed().length,t=this.getAvailableSprinkles?.()??[],n=new Set;for(let e of this.registry.ids())e.startsWith(`sprinkle-`)&&this.registry.get(e)?.descriptor.zone!==null&&n.add(e.slice(9));let r=e+t.filter(e=>!n.has(e.name)).length>0;this.primaryZone?.setAddButtonEnabled(r)}showPickerForZone(e,t){let n=new Set;for(let e of this.registry.ids())e.startsWith(`sprinkle-`)&&this.registry.get(e)?.descriptor.zone!==null&&n.add(e.slice(9));let r=(this.getAvailableSprinkles?.()??[]).filter(e=>!n.has(e.name));Xi(t,e,{registry:this.registry,callbacks:{onSelectPanel:(e,t)=>{this.openPanelInZone(e,t)},onSelectSprinkle:(e,t)=>{this.onOpenSprinkle?.(e,t)}},getAvailableSprinkles:()=>r})}openPanelInZone(e,t){let n=this.registry.get(e);if(!n)return;let r=this.primaryZone;this.registry.setZone(e,t),r.addTab({id:n.descriptor.id,label:n.descriptor.label,closable:n.descriptor.closable,element:n.descriptor.element,onActivate:n.descriptor.onActivate}),r.activateTab(e)}dynamicSprinkles=new Map;addSprinkle(e,t,n,r){if(this.isExtension){let r=`sprinkle-${e}`,i=document.createElement(`div`);i.className=`tab-content__panel`,i.appendChild(n),this.extensionZone.addTab({id:r,label:t,closable:!0,element:i}),this.tabContainers.set(r,i),this.dynamicSprinkles.set(e,i),this.extensionZone.activateTab(r)}else{let i=r??`primary`,a=this.primaryZone,o=`sprinkle-${e}`,s=document.createElement(`div`);s.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: auto; flex: 1;`,s.appendChild(n),this.registry.register({id:o,label:t,zone:i,closable:!0,element:s,onClose:()=>this.onSprinkleClose?.(e)}),a.addTab({id:o,label:t,closable:!0,element:s}),this.dynamicSprinkles.set(e,s),a.activateTab(o),this.updateAddButtons()}}removeSprinkle(e){if(this.isExtension){let t=`sprinkle-${e}`;this.extensionZone.removeTab(t),this.tabContainers.delete(t),this.dynamicSprinkles.delete(e)}else{let t=`sprinkle-${e}`;this.primaryZone.removeTab(t),this.registry.unregister(t),this.dynamicSprinkles.delete(e),this.updateAddButtons()}}dispose(){for(this.panels.chat.dispose(),this.panels.terminal.dispose(),this.panels.fileBrowser.dispose(),this.panels.memory.dispose(),this.panels.scoops.dispose();this.root.firstChild;)this.root.removeChild(this.root.firstChild)}},$i=`slicc-theme`,ea=new Set([`dark`,`light`,`system`]);function ta(){let e=localStorage.getItem($i);return e&&ea.has(e)?e:`system`}function na(){let e=ta(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t)}var ra;function ia(){na(),ra=window.matchMedia?.(`(prefers-color-scheme: light)`),ra?.addEventListener?.(`change`,()=>{ta()===`system`&&na()})}var aa=300,oa=6,sa=null,ca=null;function la(){return sa||(sa=document.createElement(`div`),sa.className=`s2-tooltip`,document.body.appendChild(sa)),sa}function ua(e){let t=e.getAttribute(`data-tooltip`);if(!t)return;let n=la();n.textContent=t,n.classList.remove(`s2-tooltip--visible`),n.style.left=`0`,n.style.top=`0`;let r=e.getBoundingClientRect(),i=n.getBoundingClientRect(),a=e.getAttribute(`data-tooltip-pos`)||`bottom`,o,s;a===`top`?(o=r.top-i.height-oa,s=r.left+r.width/2-i.width/2):a===`right`?(o=r.top+r.height/2-i.height/2,s=r.right+oa):(o=r.bottom+oa,s=r.left+r.width/2-i.width/2),a===`bottom`&&o+i.height>window.innerHeight-4?o=r.top-i.height-oa:a===`top`&&o<4&&(o=r.bottom+oa),s<4&&(s=4),s+i.width>window.innerWidth-4&&(s=window.innerWidth-i.width-4),n.style.top=`${o}px`,n.style.left=`${s}px`,n.classList.add(`s2-tooltip--visible`)}function da(){ca&&=(clearTimeout(ca),null),sa?.classList.remove(`s2-tooltip--visible`)}function fa(){document.addEventListener(`pointerenter`,e=>{let t=e.target.closest?.(`[data-tooltip]`);t&&(da(),ca=setTimeout(()=>ua(t),aa))},!0),document.addEventListener(`pointerleave`,e=>{e.target.closest?.(`[data-tooltip]`)&&da()},!0),document.addEventListener(`pointerdown`,da,!0)}function pa(e){return e.toLowerCase().endsWith(ae)}function ma(e){return Array.from(e).find(e=>pa(e.name))??null}function ha(e){if(!e)return!1;if(e.items){for(let t of Array.from(e.items))if(t.kind===`file`)return!0}return!1}function ga(e){if(!e)return null;if(e.files){let t=ma(e.files);if(t)return t}if(!e.items)return null;for(let t of Array.from(e.items)){if(t.kind&&t.kind!==`file`)continue;let e=t.getAsFile?.();if(e&&pa(e.name))return e}return null}var _a=new Map,va=new Map;function ya(e){let t=e.length;return t===0?`0`:`${t}:${e.charCodeAt(0)}:${t>1?e.charCodeAt(1):0}:${t>2?e.charCodeAt(2):0}:${t>3?e.charCodeAt(3):0}:${t>4?e.charCodeAt(Math.floor(t/4)):0}:${t>4?e.charCodeAt(Math.floor(t/2)):0}:${t>4?e.charCodeAt(Math.floor(3*t/4)):0}:${e.charCodeAt(t-1)}`}function ba(e,t){let n=ya(e);_a.set(n,t),setTimeout(()=>_a.delete(n),1e4)}function xa(e,t){va.set(e,t),setTimeout(()=>va.delete(e),1e4)}function Sa(e){let t=va.get(e);return t?(va.delete(e),t):null}function Ca(e){let t=ya(e),n=_a.get(t);return n?(_a.delete(t),n):null}var wa=class{registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}async readFile(e,t){let n=R(e),r=await this.vfs.readFile(n,{encoding:`binary`}),i=r instanceof Uint8Array?r:new TextEncoder().encode(r);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}catch{let e=Array(i.length);for(let t=0;t<i.length;t++)e[t]=String.fromCharCode(i[t]);return e.join(``)}}async readFileBuffer(e){let t=R(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}async writeFile(e,t,n){let r=R(e);if(typeof t==`string`){let e=Ca(t);if(e){await this.vfs.writeFile(r,e);return}let n=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){n=!0;break}if(n)await this.vfs.writeFile(r,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(r,e)}}else await this.vfs.writeFile(r,t)}async appendFile(e,t,n){let r=R(e),i=new Uint8Array;try{let e=await this.vfs.readFile(r,{encoding:`binary`});i=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof L&&e.code===`ENOENT`))throw e}let a;if(typeof t==`string`){a=new Uint8Array(t.length);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e)&255}else a=t instanceof Uint8Array?t:new Uint8Array(t);let o=new Uint8Array(i.length+a.length);o.set(i),o.set(a,i.length),await this.vfs.writeFile(r,o)}async exists(e){let t=R(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)}async stat(e){let t=R(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=await this.vfs.stat(t);return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)}}async lstat(e){let t=R(e),n=await this.vfs.lstat(t);return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)}}async mkdir(e,t){await this.vfs.mkdir(R(e),t)}async readdir(e){let t=R(e);return t===`/usr`?[`bin`]:t===`/usr/bin`?this.getVirtualBinCommands().slice().sort():(await this.vfs.readDir(t)).map(e=>e.name)}async readdirWithFileTypes(e){let t=R(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=await this.vfs.readDir(t),r=[];for(let e of n)if(e.type===`symlink`){let n=!1,i=!1;try{let r=t===`/`?`/${e.name}`:`${t}/${e.name}`,a=await this.vfs.stat(r);n=a.type===`file`,i=a.type===`directory`}catch{}r.push({name:e.name,isFile:n,isDirectory:i,isSymbolicLink:!0})}else r.push({name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1});return r}async rm(e,t){await this.vfs.rm(R(e),t)}async cp(e,t,n){let r=R(e),i=R(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new L(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=ce(e,r.name),i=ce(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){await this.vfs.rename(R(e),R(t))}resolvePath(e,t){return t.startsWith(`/`)?R(t):R(ce(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){await this.vfs.symlink(e,R(t))}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.vfs.readlink(R(e))}async realpath(e){return this.vfs.realpath(R(e))}async utimes(e,t,n){}},Ta=t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),Ea=t((e=>{e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),Da=t((e=>{var t=Ta(),n=Ea(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;var i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,`parent`,{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,`offset`,{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(ye(e,ArrayBuffer)||e&&ye(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(ye(e,SharedArrayBuffer)||e&&ye(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);let i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){let t=e.length<0?0:_(e.length)|0,n=o(t);for(let r=0;r<t;r+=1)n[r]=e[r]&255;return n}function m(e){if(ye(e,Uint8Array)){let t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return p(e)}function h(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);let r;return r=t===void 0&&n===void 0?new Uint8Array(e):n===void 0?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function g(e){if(s.isBuffer(e)){let t=_(e.length)|0,n=o(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||be(e.length)?o(0):p(e);if(e.type===`Buffer`&&Array.isArray(e.data))return p(e.data)}function _(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(ye(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),ye(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},s.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return s.alloc(0);let n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;let r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){let t=e[n];if(ye(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else if(s.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||ye(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return me(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return _e(e).length;default:if(i)return r?-1:me(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return re(this,t,n);case`utf8`:case`utf-8`:return ee(this,t,n);case`ascii`:return te(this,t,n);case`latin1`:case`binary`:return ne(this,t,n);case`base64`:return k(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return ie(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;t<e;t+=2)x(this,t,t+1);return this},s.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let t=0;t<e;t+=4)x(this,t,t+3),x(this,t+1,t+2);return this},s.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let t=0;t<e;t+=8)x(this,t,t+7),x(this,t+1,t+6),x(this,t+2,t+5),x(this,t+3,t+4);return this},s.prototype.toString=function(){let e=this.length;return e===0?``:arguments.length===0?ee(this,0,e):b.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e?!0:s.compare(this,e)===0},s.prototype.inspect=function(){let t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(ye(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){a=l[e],o=u[e];break}return a<o?-1:+(o<a)};function S(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,be(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0)if(i)n=0;else return-1;if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:C(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function C(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,r===-1?0:l-r)){if(r===-1&&(r=l),l-r+1===s)return r*a}else r!==-1&&(l-=l-r),r=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;r<s;r++)if(c(e,l+r)!==c(t,r)){n=!1;break}if(n)return l}return-1}s.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},s.prototype.indexOf=function(e,t,n){return S(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return S(this,e,t,n,!1)};function w(e,t,n,r){n=Number(n)||0;let i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o;for(o=0;o<r;++o){let r=parseInt(t.substr(o*2,2),16);if(be(r))return o;e[n+o]=r}return o}function T(e,t,n,r){return ve(me(t,e.length-n),e,n,r)}function E(e,t,n,r){return ve(he(t),e,n,r)}function D(e,t,n,r){return ve(_e(t),e,n,r)}function O(e,t,n,r){return ve(ge(t,e.length-n),e,n,r)}s.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return w(this,e,t,n);case`utf8`:case`utf-8`:return T(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return E(this,e,t,n);case`base64`:return D(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return O(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function k(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function ee(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i<n;){let t=e[i],a=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return j(r)}var A=4096;function j(e){let t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=A));return n}function te(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function ne(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function re(e,t,n){let r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i=``;for(let r=t;r<n;++r)i+=xe[e[r]];return i}function ie(e,t,n){let r=e.slice(t,n),i=``;for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+r[e+1]*256);return i}s.prototype.slice=function(e,t){let n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);let r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r};function M(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(e,this.length-8);let r=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(e,this.length-8);let r=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)}),s.prototype.readBigInt64BE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!1,52,8)};function N(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a<n&&(i*=256);)this[t+a]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function P(e,t,n,r,i){R(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function ae(e,t,n,r,i){R(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}s.prototype.writeBigUInt64LE=Se(function(e,t=0){return P(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=Se(function(e,t=0){return ae(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i<n&&(a*=256);)e<0&&o===0&&this[t+i-1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeBigInt64LE=Se(function(e,t=0){return P(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=Se(function(e,t=0){return ae(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function F(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function oe(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return oe(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return oe(this,e,t,!1,n)};function I(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return I(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return I(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);let i=r-n;return this===e&&typeof Uint8Array.prototype.copyWithin==`function`?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},s.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!s.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){let t=e.charCodeAt(0);(r===`utf8`&&t<128||r===`latin1`)&&(e=t)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i<n;++i)this[i]=e;else{let a=s.isBuffer(e)?e:s.from(e,r),o=a.length;if(o===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(i=0;i<n-t;++i)this[i+t]=a[i%o]}return this};var L={};function se(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,`message`,{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,`code`,{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}se(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),se(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),se(`ERR_OUT_OF_RANGE`,function(e,t,n){let r=`The value of "${e}" is out of range.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=ce(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=ce(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function ce(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function le(e,t,n){ue(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&de(t,e.length-(n+1))}function R(e,t,n,r,i,a){if(e>n||e<t){let r=typeof t==`bigint`?`n`:``,i;throw i=a>3?t===0||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${(a+1)*8}${r}`:`>= -(2${r} ** ${(a+1)*8-1}${r}) and < 2 ** ${(a+1)*8-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new L.ERR_OUT_OF_RANGE(`value`,i,e)}le(r,i,a)}function ue(e,t){if(typeof e!=`number`)throw new L.ERR_INVALID_ARG_TYPE(t,`number`,e)}function de(e,t,n){throw Math.floor(e)===e?t<0?new L.ERR_BUFFER_OUT_OF_BOUNDS:new L.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(ue(e,n),new L.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}var fe=/[^+/0-9A-Za-z-_]/g;function pe(e){if(e=e.split(`=`)[0],e=e.trim().replace(fe,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function me(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}else if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function he(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function ge(e,t){let n,r,i,a=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function _e(e){return t.toByteArray(pe(e))}function ve(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function ye(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function be(e){return e!==e}var xe=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function Se(e){return typeof BigInt>`u`?Ce:e}function Ce(){throw Error(`BigInt not supported`)}})),Oa=Da();globalThis.Buffer===void 0&&(globalThis.Buffer=Oa.Buffer);var ka=t(((e,t)=>{var n=function(e){if(e||={},this.Promise=e.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=e.domainReentrant||!1,this.domainReentrant){if(typeof process>`u`||process.domain===void 0)throw Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=e.timeout||n.DEFAULT_TIMEOUT,this.maxOccupationTime=e.maxOccupationTime||n.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=e.maxExecutionTime||n.DEFAULT_MAX_EXECUTION_TIME,e.maxPending===1/0||Number.isInteger(e.maxPending)&&e.maxPending>=0?this.maxPending=e.maxPending:this.maxPending=n.DEFAULT_MAX_PENDING};n.DEFAULT_TIMEOUT=0,n.DEFAULT_MAX_OCCUPATION_TIME=0,n.DEFAULT_MAX_EXECUTION_TIME=0,n.DEFAULT_MAX_PENDING=1e3,n.prototype.acquire=function(e,t,n,r){if(Array.isArray(e))return this._acquireBatch(e,t,n,r);if(typeof t!=`function`)throw Error(`You must pass a function to execute`);var i=null,a=null,o=null;typeof n!=`function`&&(r=n,n=null,o=new this.Promise(function(e,t){i=e,a=t})),r||={};var s=!1,c=null,l=null,u=null,d=this,f=function(t,r,c){l&&=(clearTimeout(l),null),u&&=(clearTimeout(u),null),t&&(d.queues[e]&&d.queues[e].length===0&&delete d.queues[e],d.domainReentrant&&delete d.domains[e]),s||=(o?r?a(r):i(c):typeof n==`function`&&n(r,c),!0),t&&d.queues[e]&&d.queues[e].length>0&&d.queues[e].shift()()},p=function(n){if(s)return f(n);c&&=(clearTimeout(c),null),d.domainReentrant&&n&&(d.domains[e]=process.domain);var i=r.maxExecutionTime||d.maxExecutionTime;if(i&&(u=setTimeout(function(){d.queues[e]&&f(n,Error(`Maximum execution time is exceeded `+e))},i)),t.length===1){var a=!1;try{t(function(e,t){a||(a=!0,f(n,e,t))})}catch(e){a||(a=!0,f(n,e))}}else d._promiseTry(function(){return t()}).then(function(e){f(n,void 0,e)},function(e){f(n,e)})};d.domainReentrant&&process.domain&&(p=process.domain.bind(p));var m=r.maxPending||d.maxPending;if(!d.queues[e])d.queues[e]=[],p(!0);else if(d.domainReentrant&&process.domain&&process.domain===d.domains[e])p(!1);else if(d.queues[e].length>=m)f(!1,Error(`Too many pending tasks in queue `+e));else{var h=function(){p(!0)};r.skipQueue?d.queues[e].unshift(h):d.queues[e].push(h);var g=r.timeout||d.timeout;g&&(c=setTimeout(function(){c=null,f(!1,Error(`async-lock timed out in queue `+e))},g))}var _=r.maxOccupationTime||d.maxOccupationTime;if(_&&(l=setTimeout(function(){d.queues[e]&&f(!1,Error(`Maximum occupation time is exceeded in queue `+e))},_)),o)return o},n.prototype._acquireBatch=function(e,t,n,r){typeof n!=`function`&&(r=n,n=null);var i=this,a=function(e,t){return function(n){i.acquire(e,t,n,r)}},o=e.reduceRight(function(e,t){return a(t,e)},t);if(typeof n==`function`)o(n);else return new this.Promise(function(e,t){o.length===1?o(function(n,r){n?t(n):e(r)}):e(o())})},n.prototype.isBusy=function(e){return e?!!this.queues[e]:Object.keys(this.queues).length>0},n.prototype._promiseTry=function(e){try{return this.Promise.resolve(e())}catch(e){return this.Promise.reject(e)}},t.exports=n})),Aa=t(((e,t)=>{t.exports=ka()})),ja=t(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Ma=t(((e,t)=>{var n=Da(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Na=t(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),Pa=t(((e,t)=>{t.exports=TypeError})),Fa=t(((e,t)=>{t.exports=Object})),Ia=t(((e,t)=>{t.exports=Error})),La=t(((e,t)=>{t.exports=EvalError})),Ra=t(((e,t)=>{t.exports=RangeError})),za=t(((e,t)=>{t.exports=ReferenceError})),Ba=t(((e,t)=>{t.exports=SyntaxError})),Va=t(((e,t)=>{t.exports=URIError})),Ha=t(((e,t)=>{t.exports=Math.abs})),Ua=t(((e,t)=>{t.exports=Math.floor})),Wa=t(((e,t)=>{t.exports=Math.max})),Ga=t(((e,t)=>{t.exports=Math.min})),Ka=t(((e,t)=>{t.exports=Math.pow})),qa=t(((e,t)=>{t.exports=Math.round})),Ja=t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),Ya=t(((e,t)=>{var n=Ja();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),Xa=t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),Za=t(((e,t)=>{var n=Xa();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),Qa=t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),$a=t(((e,t)=>{t.exports=function(){if(typeof Symbol!=`function`||typeof Object.getOwnPropertySymbols!=`function`)return!1;if(typeof Symbol.iterator==`symbol`)return!0;var e={},t=Symbol(`test`),n=Object(t);if(typeof t==`string`||Object.prototype.toString.call(t)!==`[object Symbol]`||Object.prototype.toString.call(n)!==`[object Symbol]`)return!1;var r=42;for(var i in e[t]=r,e)return!1;if(typeof Object.keys==`function`&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames==`function`&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor==`function`){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==r||o.enumerable!==!0)return!1}return!0}})),eo=t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=$a();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),to=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),no=t(((e,t)=>{t.exports=Fa().getPrototypeOf||null})),ro=t(((e,t)=>{var n=`Function.prototype.bind called on incompatible `,r=Object.prototype.toString,i=Math.max,a=`[object Function]`,o=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},s=function(e,t){for(var n=[],r=t||0,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n},c=function(e,t){for(var n=``,r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=t);return n};t.exports=function(e){var t=this;if(typeof t!=`function`||r.apply(t)!==a)throw TypeError(n+t);for(var l=s(arguments,1),u,d=function(){if(this instanceof u){var n=t.apply(this,o(l,arguments));return Object(n)===n?n:this}return t.apply(e,o(l,arguments))},f=i(0,t.length-l.length),p=[],m=0;m<f;m++)p[m]=`$`+m;if(u=Function(`binder`,`return function (`+c(p,`,`)+`){ return binder.apply(this,arguments); }`)(d),t.prototype){var h=function(){};h.prototype=t.prototype,u.prototype=new h,h.prototype=null}return u}})),io=t(((e,t)=>{var n=ro();t.exports=Function.prototype.bind||n})),ao=t(((e,t)=>{t.exports=Function.prototype.call})),oo=t(((e,t)=>{t.exports=Function.prototype.apply})),so=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),co=t(((e,t)=>{var n=io(),r=oo(),i=ao();t.exports=so()||n.call(i,r)})),lo=t(((e,t)=>{var n=io(),r=Pa(),i=ao(),a=co();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),uo=t(((e,t)=>{var n=lo(),r=Za(),i;try{i=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!=`object`||!(`code`in e)||e.code!==`ERR_PROTO_ACCESS`)throw e}var a=!!i&&r&&r(Object.prototype,`__proto__`),o=Object,s=o.getPrototypeOf;t.exports=a&&typeof a.get==`function`?n([a.get]):typeof s==`function`?function(e){return s(e==null?e:o(e))}:!1})),fo=t(((e,t)=>{var n=to(),r=no(),i=uo();t.exports=n?function(e){return n(e)}:r?function(e){if(!e||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`getProto: not an object`);return r(e)}:i?function(e){return i(e)}:null})),po=t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=io().call(n,r)})),mo=t(((e,t)=>{var n,r=Fa(),i=Ia(),a=La(),o=Ra(),s=za(),c=Ba(),l=Pa(),u=Va(),d=Ha(),f=Ua(),p=Wa(),m=Ga(),h=Ka(),g=qa(),_=Ya(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=Za(),x=Qa(),S=function(){throw new l},C=b?function(){try{return arguments.callee,S}catch{try{return b(arguments,`callee`).get}catch{return S}}}():S,w=eo()(),T=fo(),E=no(),D=to(),O=oo(),k=ao(),ee={},A=typeof Uint8Array>`u`||!T?n:T(Uint8Array),j={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":ee,"%AsyncGenerator%":ee,"%AsyncGeneratorFunction%":ee,"%AsyncIteratorPrototype%":ee,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":ee,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":A,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":k,"%Function.prototype.apply%":O,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){j[`%Error.prototype%`]=T(T(e))}var te=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return j[t]=n,n},ne={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},re=io(),ie=po(),M=re.call(k,Array.prototype.concat),N=re.call(O,Array.prototype.splice),P=re.call(k,String.prototype.replace),ae=re.call(k,String.prototype.slice),F=re.call(k,RegExp.prototype.exec),oe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,I=/\\(\\)?/g,L=function(e){var t=ae(e,0,1),n=ae(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return P(e,oe,function(e,t,n,i){r[r.length]=n?P(i,I,`$1`):t||e}),r},se=function(e,t){var n=e,r;if(ie(ne,n)&&(r=ne[n],n=`%`+r[0]+`%`),ie(j,n)){var i=j[n];if(i===ee&&(i=te(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(F(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=L(e),r=n.length>0?n[0]:``,i=se(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],N(n,M([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=ae(p,0,1),h=ae(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,ie(j,a))o=j[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=ie(o,p),o=o[p];f&&!s&&(j[a]=o)}}return o}})),ho=t(((e,t)=>{var n=mo(),r=lo(),i=r([n(`%String.prototype.indexOf%`)]);t.exports=function(e,t){var a=n(e,!!t);return typeof a==`function`&&i(e,`.prototype.`)>-1?r([a]):a}})),go=t(((e,t)=>{var n=Function.prototype.toString,r=typeof Reflect==`object`&&Reflect!==null&&Reflect.apply,i,a;if(typeof r==`function`&&typeof Object.defineProperty==`function`)try{i=Object.defineProperty({},`length`,{get:function(){throw a}}),a={},r(function(){throw 42},null,i)}catch(e){e!==a&&(r=null)}else r=null;var o=/^\s*class\b/,s=function(e){try{var t=n.call(e);return o.test(t)}catch{return!1}},c=function(e){try{return s(e)?!1:(n.call(e),!0)}catch{return!1}},l=Object.prototype.toString,u=`[object Object]`,d=`[object Function]`,f=`[object GeneratorFunction]`,p=`[object HTMLAllCollection]`,m=`[object HTML document.all class]`,h=`[object HTMLCollection]`,g=typeof Symbol==`function`&&!!Symbol.toStringTag,_=!(0 in[,]),v=function(){return!1};if(typeof document==`object`){var y=document.all;l.call(y)===l.call(document.all)&&(v=function(e){if((_||!e)&&(e===void 0||typeof e==`object`))try{var t=l.call(e);return(t===p||t===m||t===h||t===u)&&e(``)==null}catch{}return!1})}t.exports=r?function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;try{r(e,null,i)}catch(e){if(e!==a)return!1}return!s(e)&&c(e)}:function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;if(g)return c(e);if(s(e))return!1;var t=l.call(e);return t!==d&&t!==f&&!/^\[object HTML/.test(t)?!1:c(e)}})),_o=t(((e,t)=>{var n=go(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(e,t,n){for(var r=0,a=e.length;r<a;r++)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))},o=function(e,t,n){for(var r=0,i=e.length;r<i;r++)n==null?t(e.charAt(r),r,e):t.call(n,e.charAt(r),r,e)},s=function(e,t,n){for(var r in e)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))};function c(e){return r.call(e)===`[object Array]`}t.exports=function(e,t,r){if(!n(t))throw TypeError(`iterator must be a function`);var i;arguments.length>=3&&(i=r),c(e)?a(e,t,i):typeof e==`string`?o(e,t,i):s(e,t,i)}})),vo=t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),yo=t(((e,t)=>{var n=vo(),r=globalThis;t.exports=function(){for(var e=[],t=0;t<n.length;t++)typeof r[n[t]]==`function`&&(e[e.length]=n[t]);return e}})),bo=t(((e,t)=>{var n=Qa(),r=Ba(),i=Pa(),a=Za();t.exports=function(e,t,o){if(!e||typeof e!=`object`&&typeof e!=`function`)throw new i("`obj` must be an object or a function`");if(typeof t!=`string`&&typeof t!=`symbol`)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=`boolean`&&arguments[3]!==null)throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=`boolean`&&arguments[4]!==null)throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=`boolean`&&arguments[5]!==null)throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=`boolean`)throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!a&&a(e,t);if(n)n(e,t,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:o,writable:c===null&&d?d.writable:!c});else if(u||!s&&!c&&!l)e[t]=o;else throw new r(`This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.`)}})),xo=t(((e,t)=>{var n=Qa(),r=function(){return!!n};r.hasArrayLengthDefineBug=function(){if(!n)return null;try{return n([],`length`,{value:1}).length!==1}catch{return!0}},t.exports=r})),So=t(((e,t)=>{var n=mo(),r=bo(),i=xo()(),a=Za(),o=Pa(),s=n(`%Math.floor%`);t.exports=function(e,t){if(typeof e!=`function`)throw new o("`fn` is not a function");if(typeof t!=`number`||t<0||t>4294967295||s(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],c=!0,l=!0;if(`length`in e&&a){var u=a(e,`length`);u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!n)&&(i?r(e,`length`,t,!0,!0):r(e,`length`,t)),e}})),Co=t(((e,t)=>{var n=io(),r=oo(),i=co();t.exports=function(){return i(n,r,arguments)}})),wo=t(((e,t)=>{var n=So(),r=Qa(),i=lo(),a=Co();t.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},r?r(t.exports,`apply`,{value:a}):t.exports.apply=a})),To=t(((e,t)=>{var n=$a();t.exports=function(){return n()&&!!Symbol.toStringTag}})),Eo=t(((e,t)=>{var n=_o(),r=yo(),i=wo(),a=ho(),o=Za(),s=fo(),c=a(`Object.prototype.toString`),l=To()(),u=globalThis,d=r(),f=a(`String.prototype.slice`),p=a(`Array.prototype.indexOf`,!0)||function(e,t){for(var n=0;n<e.length;n+=1)if(e[n]===t)return n;return-1},m={__proto__:null};l&&o&&s?n(d,function(e){var t=new u[e];if(Symbol.toStringTag in t&&s){var n=s(t),r=o(n,Symbol.toStringTag);if(!r&&n&&(r=o(s(n),Symbol.toStringTag)),r&&r.get){var a=i(r.get);m[`$`+e]=a}}}):n(d,function(e){var t=new u[e],n=t.slice||t.set;if(n){var r=i(n);m[`$`+e]=r}});var h=function(e){var t=!1;return n(m,function(n,r){if(!t)try{`$`+n(e)===r&&(t=f(r,1))}catch{}}),t},g=function(e){var t=!1;return n(m,function(n,r){if(!t)try{n(e),t=f(r,1)}catch{}}),t};t.exports=function(e){if(!e||typeof e!=`object`)return!1;if(!l){var t=f(c(e),8,-1);return p(d,t)>-1?t:t===`Object`?g(e):!1}return o?h(e):null}})),Do=t(((e,t)=>{var n=Eo();t.exports=function(e){return!!n(e)}})),Oo=t(((e,t)=>{var n=Pa(),r=ho()(`TypedArray.prototype.buffer`,!0),i=Do();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),ko=t(((e,t)=>{var n=Ma().Buffer,r=Na(),i=Oo(),a=ArrayBuffer.isView||function(e){try{return i(e),!0}catch{return!1}},o=typeof Uint8Array<`u`,s=typeof ArrayBuffer<`u`&&typeof Uint8Array<`u`,c=s&&(n.prototype instanceof Uint8Array||n.TYPED_ARRAY_SUPPORT);t.exports=function(e,t){if(n.isBuffer(e))return e.constructor&&!(`isBuffer`in e)?n.from(e):e;if(typeof e==`string`)return n.from(e,t);if(s&&a(e)){if(e.byteLength===0)return n.alloc(0);if(c){var i=n.from(e.buffer,e.byteOffset,e.byteLength);if(i.byteLength===e.byteLength)return i}var l=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=n.from(l);if(u.length===e.byteLength)return u}if(o&&e instanceof Uint8Array)return n.from(e);var d=r(e);if(d)for(var f=0;f<e.length;f+=1){var p=e[f];if(typeof p!=`number`||p<0||p>255||~~p!==p)throw RangeError(`Array items must be numbers in the range 0-255.`)}if(d||n.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer==`function`&&e.constructor.isBuffer(e))return n.from(e);throw TypeError(`The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.`)}})),Ao=t(((e,t)=>{var n=Ma().Buffer,r=ko();function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){e=r(e,t||`utf8`);for(var n=this._block,i=this._blockSize,a=e.length,o=this._len,s=0;s<a;){for(var c=o%i,l=Math.min(a-s,i-c),u=0;u<l;u++)n[c+u]=e[s+u];o+=l,s+=l,o%i===0&&this._update(n)}return this._len+=a,this},i.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var n=this._len*8;if(n<=4294967295)this._block.writeUInt32BE(n,this._blockSize-4);else{var r=(n&4294967295)>>>0,i=(n-r)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(r,this._blockSize-4)}this._update(this._block);var a=this._hash();return e?a.toString(e):a},i.prototype._update=function(){throw Error(`_update must be implemented by subclass`)},t.exports=i})),jo=t(((e,t)=>{var n=ja(),r=Ao(),i=Ma().Buffer,a=[1518500249,1859775393,-1894007588,-899497514],o=Array(80);function s(){this.init(),this._w=o,r.call(this,64,56)}n(s,r),s.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function c(e){return e<<1|e>>>31}function l(e){return e<<5|e>>>27}function u(e){return e<<30|e>>>2}function d(e,t,n,r){return e===0?t&n|~t&r:e===2?t&n|t&r|n&r:t^n^r}s.prototype._update=function(e){for(var t=this._w,n=this._a|0,r=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,f=0;f<16;++f)t[f]=e.readInt32BE(f*4);for(;f<80;++f)t[f]=c(t[f-3]^t[f-8]^t[f-14]^t[f-16]);for(var p=0;p<80;++p){var m=~~(p/20),h=l(n)+d(m,r,i,o)+s+t[p]+a[m]|0;s=o,o=i,i=u(r),r=n,n=h}this._a=n+this._a|0,this._b=r+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0},s.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e},t.exports=s})),Mo=t((e=>{(function(t){typeof DO_NOT_EXPORT_CRC>`u`?typeof e==`object`?t(e):typeof define==`function`&&define.amd?define(function(){var e={};return t(e),e}):t({}):t({})})(function(e){e.version=`1.2.2`;function t(){for(var e=0,t=Array(256),n=0;n!=256;++n)e=n,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,t[n]=e;return typeof Int32Array<`u`?new Int32Array(t):t}var n=t();function r(e){var t=0,n=0,r=0,i=typeof Int32Array<`u`?new Int32Array(4096):Array(4096);for(r=0;r!=256;++r)i[r]=e[r];for(r=0;r!=256;++r)for(n=e[r],t=256+r;t<4096;t+=256)n=i[t]=n>>>8^e[n&255];var a=[];for(r=1;r!=16;++r)a[r-1]=typeof Int32Array<`u`?i.subarray(r*256,r*256+256):i.slice(r*256,r*256+256);return a}var i=r(n),a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14];function b(e,t){for(var r=t^-1,i=0,a=e.length;i<a;)r=r>>>8^n[(r^e.charCodeAt(i++))&255];return~r}function x(e,t){for(var r=t^-1,i=e.length-15,b=0;b<i;)r=y[e[b++]^r&255]^v[e[b++]^r>>8&255]^_[e[b++]^r>>16&255]^g[e[b++]^r>>>24]^h[e[b++]]^m[e[b++]]^p[e[b++]]^f[e[b++]]^d[e[b++]]^u[e[b++]]^l[e[b++]]^c[e[b++]]^s[e[b++]]^o[e[b++]]^a[e[b++]]^n[e[b++]];for(i+=15;b<i;)r=r>>>8^n[(r^e[b++])&255];return~r}function S(e,t){for(var r=t^-1,i=0,a=e.length,o=0,s=0;i<a;)o=e.charCodeAt(i++),o<128?r=r>>>8^n[(r^o)&255]:o<2048?(r=r>>>8^n[(r^(192|o>>6&31))&255],r=r>>>8^n[(r^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,s=e.charCodeAt(i++)&1023,r=r>>>8^n[(r^(240|o>>8&7))&255],r=r>>>8^n[(r^(128|o>>2&63))&255],r=r>>>8^n[(r^(128|s>>6&15|(o&3)<<4))&255],r=r>>>8^n[(r^(128|s&63))&255]):(r=r>>>8^n[(r^(224|o>>12&15))&255],r=r>>>8^n[(r^(128|o>>6&63))&255],r=r>>>8^n[(r^(128|o&63))&255]);return~r}e.table=n,e.bstr=b,e.buf=x,e.str=S})})),No=t(((e,t)=>{var n=(e,t)=>function(...n){let r=t.promiseModule;return new r((r,i)=>{t.multiArgs?n.push((...e)=>{t.errorFirst?e[0]?i(e):(e.shift(),r(e)):r(e)}):t.errorFirst?n.push((e,t)=>{e?i(e):r(t)}):n.push(r),e.apply(this,n)})};t.exports=(e,t)=>{t=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},t);let r=typeof e;if(!(e!==null&&(r===`object`||r===`function`)))throw TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${e===null?`null`:r}\``);let i=e=>{let n=t=>typeof t==`string`?e===t:t.test(e);return t.include?t.include.some(n):!t.exclude.some(n)},a;a=r===`function`?function(...r){return t.excludeMain?e(...r):n(e,t).apply(this,r)}:Object.create(Object.getPrototypeOf(e));for(let r in e){let o=e[r];a[r]=typeof o==`function`&&i(r)?n(o,t):o}return a}})),Po=t(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}var r=``,i=` `,a=`\\`,o=/^\s+$/,s=/(?:[^\\]|^)\\$/,c=/^\\!/,l=/^\\#/,u=/\r?\n/g,d=/^\.*\/|^\.+$/,f=`/`,p=`node-ignore`;typeof Symbol<`u`&&(p=Symbol.for(`node-ignore`));var m=p,h=(e,t,n)=>Object.defineProperty(e,t,{value:n}),g=/([0-z])-([0-z])/g,_=()=>!1,v=e=>e.replace(g,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:r),y=e=>{let{length:t}=e;return e.slice(0,t-t%2)},b=[[/^\uFEFF/,()=>r],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?i:r)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+i}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>a],[/\\\\/g,()=>a],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===a?`\\[${n}${y(r)}${i}`:i===`]`&&r.length%2==0?`[${v(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],x=Object.create(null),S=(e,t)=>{let n=x[e];return n||(n=b.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),x[e]=n),t?new RegExp(n,`i`):new RegExp(n)},C=e=>typeof e==`string`,w=e=>e&&C(e)&&!o.test(e)&&!s.test(e)&&e.indexOf(`#`)!==0,T=e=>e.split(u),E=class{constructor(e,t,n,r){this.origin=e,this.pattern=t,this.negative=n,this.regex=r}},D=(e,t)=>{let n=e,r=!1;e.indexOf(`!`)===0&&(r=!0,e=e.substr(1)),e=e.replace(c,`!`).replace(l,`#`);let i=S(e,t);return new E(n,e,r,i)},O=(e,t)=>{throw new t(e)},k=(e,t,n)=>C(e)?e?k.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),ee=e=>d.test(e);k.isNotRelative=ee,k.convert=e=>e;var A=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){h(this,m,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[m]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(w(e)){let t=D(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(C(e)?T(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,r=!1;return this._rules.forEach(i=>{let{negative:a}=i;r===a&&n!==r||a&&!n&&!r&&!t||i.regex.test(e)&&(n=!a,r=a)}),{ignored:n,unignored:r}}_test(e,t,n,r){let i=e&&k.convert(e);return k(i,e,this._allowRelativePaths?_:O),this._t(i,t,n,r)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(f),r.pop(),!r.length)return t[e]=this._testOne(e,n);let i=this._t(r.join(f)+f,t,n,r);return t[e]=i.ignored?i:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},j=e=>new A(e);if(j.isPathValid=e=>k(e&&k.convert(e),e,_),j.default=j,t.exports=j,typeof process<`u`&&({}.IGNORE_TEST_WIN32||process.platform===`win32`)){k.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;k.isNotRelative=t=>e.test(t)||ee(t)}})),Fo=t(((e,t)=>{function n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function r(e,t,r){return t=t instanceof RegExp?t:new RegExp(n(t),`g`),e.replace(t,r)}t.exports={clean:function(e){if(typeof e!=`string`)throw Error(`Expected a string, received: `+e);return e=r(e,`./`,`/`),e=r(e,`..`,`.`),e=r(e,` `,`-`),e=r(e,/^[~^:?*\\\-]/g,``),e=r(e,/[~^:?*\\]/g,`-`),e=r(e,/[~^:?*\\\-]$/g,``),e=r(e,`@{`,`-`),e=r(e,/\.$/g,``),e=r(e,/\/$/g,``),e=r(e,/\.lock$/g,``),e}}})),Io=t(((e,t)=>{t.exports=function(e,t){var n=e,r=t,i=n.length,a=r.length,o=!1,s=null,c=i+1,l=[],u=[],d=[],f=``,p=-1,m=0,h=1,g,_,v=function(){i>=a&&(g=n,_=i,n=r,r=g,i=a,a=_,o=!0,c=i+1)},y=function(e,t,n){return{x:e,y:t,k:n}},b=function(e,t){return{elem:e,t}},x=function(e,t,o){var s=t>o?l[e-1+c]:l[e+1+c],d,f=Math.max(t,o);for(d=f-e;d<i&&f<a&&n[d]===r[f];)++d,++f;return l[e+c]=u.length,u[u.length]=new y(d,f,s),f},S=function(e){var t=i=1,i,a=s=0,s,c;for(c=e.length-1;c>=0;--c)for(;a<e[c].x||s<e[c].y;)e[c].y-e[c].x>s-a?(o?d[d.length]=new b(r[s],p):d[d.length]=new b(r[s],h),++i,++s):e[c].y-e[c].x<s-a?(o?d[d.length]=new b(n[a],h):d[d.length]=new b(n[a],p),++t,++a):(d[d.length]=new b(n[a],m),f+=n[a],++t,++i,++a,++s)};return v(),{SES_DELETE:-1,SES_COMMON:0,SES_ADD:1,editdistance:function(){return s},getlcs:function(){return f},getses:function(){return d},compose:function(){var e=a-i,t=i+a+3,n={},r,o,d,f,p;for(f=0;f<t;++f)n[f]=-1,l[f]=-1;r=-1;do{for(++r,p=-r;p<=e-1;++p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);for(p=e+r;p>=e+1;--p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);n[e+c]=x(e,n[e-1+c]+1,n[e+1+c])}while(n[e+c]!==a);for(s=e+2*r,o=l[e+c],d=[];o!==-1;)d[d.length]=new y(u[o].x,u[o].y,null),o=u[o].k;S(d)}}}})),Lo=t(((e,t)=>{var n=Io();function r(e,t){var r=new n(e,t);r.compose();for(var i=r.getses(),a,o,s=e.length-1,c=t.length-1,l=i.length-1;l>=0;--l)i[l].t===r.SES_COMMON?(o?(o.chain={file1index:s,file2index:c,chain:null},o=o.chain):(a={file1index:s,file2index:c,chain:null},o=a),s--,c--):i[l].t===r.SES_DELETE?s--:i[l].t===r.SES_ADD&&c--;var u={file1index:-1,file2index:-1,chain:null};return o?(o.chain=u,a):u}function i(e,t){for(var n=[],i=e.length,a=t.length,o=r(e,t);o!==null;o=o.chain){var s=i-o.file1index-1,c=a-o.file2index-1;i=o.file1index,a=o.file2index,(s||c)&&n.push({file1:[i+1,s],file2:[a+1,c]})}return n.reverse(),n}function a(e,t,n){var r,a=i(t,e),o=i(t,n),s=[];function c(e,t){s.push([e.file1[0],t,e.file1[1],e.file2[0],e.file2[1]])}for(r=0;r<a.length;r++)c(a[r],0);for(r=0;r<o.length;r++)c(o[r],2);s.sort(function(e,t){return e[0]-t[0]});var l=[],u=0;function d(e){e>u&&(l.push([1,u,e-u]),u=e)}for(var f=0;f<s.length;f++){for(var p=f,m=s[f],h=m[0],g=h+m[2];f<s.length-1;){var _=s[f+1],v=_[0];if(v>g)break;g=Math.max(g,v+_[2]),f++}if(d(h),p==f)m[4]>0&&l.push([m[1],m[3],m[4]]);else{var y={0:[e.length,-1,t.length,-1],2:[n.length,-1,t.length,-1]};for(r=p;r<=f;r++){m=s[r];var b=y[m[1]],x=m[0],S=x+m[2],C=m[3],w=C+m[4];b[0]=Math.min(C,b[0]),b[1]=Math.max(w,b[1]),b[2]=Math.min(x,b[2]),b[3]=Math.max(S,b[3])}var T=y[0][0]+(h-y[0][2]),E=y[0][1]+(g-y[0][3]),D=y[2][0]+(h-y[2][2]),O=y[2][1]+(g-y[2][3]);l.push([-1,T,E-T,h,g-h,D,O-D])}u=g}return d(t.length),l}function o(e,t,n){var r=[],i=[e,t,n],o=a(e,t,n),s=[];function c(){s.length&&r.push({ok:s}),s=[]}function l(e){for(var t=0;t<e.length;t++)s.push(e[t])}function u(t){if(t[2]!=t[6])return!0;for(var r=t[1],i=t[5],a=0;a<t[2];a++)if(e[a+r]!=n[a+i])return!0;return!1}for(var d=0;d<o.length;d++){var f=o[d],p=f[0];p==-1?u(f)?(c(),r.push({conflict:{a:e.slice(f[1],f[1]+f[2]),aIndex:f[1],o:t.slice(f[3],f[3]+f[4]),oIndex:f[3],b:n.slice(f[5],f[5]+f[6]),bIndex:f[5]}})):l(i[0].slice(f[1],f[1]+f[2])):l(i[p].slice(f[1],f[1]+f[2]))}return c(),r}t.exports=o})),Ro=e(Aa(),1),zo=e(jo(),1),Bo=e(Mo(),1),Vo=e(Je(),1),Ho=e(No(),1),Uo=e(Po(),1),Wo=e(Fo(),1),Go=e(Lo(),1),U=class e extends Error{constructor(e){super(e),this.caller=``}toJSON(){return{code:this.code,data:this.data,caller:this.caller,message:this.message,stack:this.stack}}fromJSON(t){let n=new e(t.message);return n.code=t.code,n.data=t.data,n.caller=t.caller,n.stack=t.stack,n}get isIsomorphicGitError(){return!0}},Ko=class e extends U{constructor(t){super(`Modifying the index is not possible because you have unmerged files: ${t.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`),this.code=this.name=e.code,this.data={filepaths:t}}};Ko.code=`UnmergedPathsError`;var W=class e extends U{constructor(t){super(`An internal error caused this command to fail.\n\nIf you're not a developer, report the bug to the developers of the application you're using. If this is a bug in isomorphic-git then you should create a proper bug yourselves. The bug should include a minimal reproduction and details about the version and environment.\n\nPlease file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${t}`),this.code=this.name=e.code,this.data={message:t}}};W.code=`InternalError`;var qo=class e extends U{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};qo.code=`UnsafeFilepathError`;var Jo=class{constructor(e){this.buffer=e,this._start=0}eof(){return this._start>=this.buffer.length}tell(){return this._start}seek(e){this._start=e}slice(e){let t=this.buffer.slice(this._start,this._start+e);return this._start+=e,t}toString(e,t){let n=this.buffer.toString(e,this._start,this._start+t);return this._start+=t,n}write(e,t,n){let r=this.buffer.write(e,this._start,t,n);return this._start+=t,r}copy(e,t,n){let r=e.copy(this.buffer,this._start,t,n);return this._start+=r,r}readUInt8(){let e=this.buffer.readUInt8(this._start);return this._start+=1,e}writeUInt8(e){let t=this.buffer.writeUInt8(e,this._start);return this._start+=1,t}readUInt16BE(){let e=this.buffer.readUInt16BE(this._start);return this._start+=2,e}writeUInt16BE(e){let t=this.buffer.writeUInt16BE(e,this._start);return this._start+=2,t}readUInt32BE(){let e=this.buffer.readUInt32BE(this._start);return this._start+=4,e}writeUInt32BE(e){let t=this.buffer.writeUInt32BE(e,this._start);return this._start+=4,t}};function Yo(e,t){return-(e<t)||+(e>t)}function Xo(e,t){return Yo(e.path,t.path)}function Zo(e){let t=e>0?e>>12:0;t!==4&&t!==8&&t!==10&&t!==14&&(t=8);let n=e&511;return n=n&73?493:420,t!==8&&(n=0),(t<<12)+n}var Qo=2**32;function $o(e,t,n,r){if(e!==void 0&&t!==void 0)return[e,t];n===void 0&&(n=r.valueOf());let i=Math.floor(n/1e3);return[i,(n-i*1e3)*1e6]}function es(e){let[t,n]=$o(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=$o(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%Qo,ctimeNanoseconds:n%Qo,mtimeSeconds:r%Qo,mtimeNanoseconds:i%Qo,dev:e.dev%Qo,ino:e.ino%Qo,mode:Zo(e.mode%Qo),uid:e.uid%Qo,gid:e.gid%Qo,size:e.size>-1?e.size%Qo:0}}function ts(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}var ns=null;async function rs(e){return ns===null&&(ns=await os()),ns?as(e):is(e)}function is(e){return new zo.default().update(e).digest(`hex`)}async function as(e){return ts(await crypto.subtle.digest(`SHA-1`,e))}async function os(){try{return await as(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function ss(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function cs(e){let t=e.flags;return t.extended=!1,t.nameLength=Math.min(Buffer.from(e.path).length,4095),(t.assumeValid?32768:0)+(t.extended?16384:0)+((t.stage&3)<<12)+(t.nameLength&4095)}var ls=class e{constructor(e,t){this._dirty=!1,this._unmergedPaths=t||new Set,this._entries=e||new Map}_addEntry(e){if(e.flags.stage===0)e.stages=[e],this._entries.set(e.path,e),this._unmergedPaths.delete(e.path);else{let t=this._entries.get(e.path);t||=(this._entries.set(e.path,e),e),t.stages[e.flags.stage]=e,this._unmergedPaths.add(e.path)}}static async from(t){if(Buffer.isBuffer(t))return e.fromBuffer(t);if(t===null)return new e(null);throw new W(`invalid type passed to GitIndex.from`)}static async fromBuffer(t){if(t.length===0)throw new W(`Index file is empty (.git/index)`);let n=new e,r=new Jo(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new W(`Invalid dircache magic file number: ${i}`);let a=await rs(t.slice(0,-20)),o=t.slice(-20).toString(`hex`);if(o!==a)throw new W(`Invalid checksum in GitIndex buffer: expected ${o} but saw ${a}`);let s=r.readUInt32BE();if(s!==2)throw new W(`Unsupported dircache version: ${s}`);let c=r.readUInt32BE(),l=0;for(;!r.eof()&&l<c;){let e={};e.ctimeSeconds=r.readUInt32BE(),e.ctimeNanoseconds=r.readUInt32BE(),e.mtimeSeconds=r.readUInt32BE(),e.mtimeNanoseconds=r.readUInt32BE(),e.dev=r.readUInt32BE(),e.ino=r.readUInt32BE(),e.mode=r.readUInt32BE(),e.uid=r.readUInt32BE(),e.gid=r.readUInt32BE(),e.size=r.readUInt32BE(),e.oid=r.slice(20).toString(`hex`),e.flags=ss(r.readUInt16BE());let i=t.indexOf(0,r.tell()+1)-r.tell();if(i<1)throw new W(`Got a path length of: ${i}`);if(e.path=r.toString(`utf8`,i),e.path.includes(`..\\`)||e.path.includes(`../`))throw new qo(e.path);let a=8-(r.tell()-12)%8;for(a===0&&(a=8);a--;){let t=r.readUInt8();if(t!==0)throw new W(`Expected 1-8 null characters but got '${t}' after ${e.path}`);if(r.eof())throw new W(`Unexpected end of file`)}e.stages=[],n._addEntry(e),l++}return n}get unmergedPaths(){return[...this._unmergedPaths]}get entries(){return[...this._entries.values()].sort(Xo)}get entriesMap(){return this._entries}get entriesFlat(){return[...this.entries].flatMap(e=>e.stages.length>1?e.stages.filter(e=>e):e)}*[Symbol.iterator](){for(let e of this.entries)yield e}insert({filepath:e,stats:t,oid:n,stage:r=0}){t||={ctimeSeconds:0,ctimeNanoseconds:0,mtimeSeconds:0,mtimeNanoseconds:0,dev:0,ino:0,mode:0,uid:0,gid:0,size:0},t=es(t);let i=Buffer.from(e),a={ctimeSeconds:t.ctimeSeconds,ctimeNanoseconds:t.ctimeNanoseconds,mtimeSeconds:t.mtimeSeconds,mtimeNanoseconds:t.mtimeNanoseconds,dev:t.dev,ino:t.ino,mode:t.mode||33188,uid:t.uid,gid:t.gid,size:t.size,path:e,oid:n,flags:{assumeValid:!1,extended:!1,stage:r,nameLength:i.length<4095?i.length:4095},stages:[]};this._addEntry(a),this._dirty=!0}delete({filepath:e}){if(this._entries.has(e))this._entries.delete(e);else for(let t of this._entries.keys())t.startsWith(e+`/`)&&this._entries.delete(t);this._unmergedPaths.has(e)&&this._unmergedPaths.delete(e),this._dirty=!0}clear(){this._entries.clear(),this._dirty=!0}has({filepath:e}){return this._entries.has(e)}render(){return this.entries.map(e=>`${e.mode.toString(8)} ${e.oid} ${e.path}`).join(`
726
- `)}static async _entryToBuffer(e){let t=Buffer.from(e.path),n=Math.ceil((62+t.length+1)/8)*8,r=Buffer.alloc(n),i=new Jo(r),a=es(e);return i.writeUInt32BE(a.ctimeSeconds),i.writeUInt32BE(a.ctimeNanoseconds),i.writeUInt32BE(a.mtimeSeconds),i.writeUInt32BE(a.mtimeNanoseconds),i.writeUInt32BE(a.dev),i.writeUInt32BE(a.ino),i.writeUInt32BE(a.mode),i.writeUInt32BE(a.uid),i.writeUInt32BE(a.gid),i.writeUInt32BE(a.size),i.write(e.oid,20,`hex`),i.writeUInt16BE(cs(e)),i.write(e.path,t.length,`utf8`),r}async toObject(){let t=Buffer.alloc(12),n=new Jo(t);n.write(`DIRC`,4,`utf8`),n.writeUInt32BE(2),n.writeUInt32BE(this.entriesFlat.length);let r=[];for(let t of this.entries)if(r.push(e._entryToBuffer(t)),t.stages.length>1)for(let n of t.stages)n&&n!==t&&r.push(e._entryToBuffer(n));r=await Promise.all(r);let i=Buffer.concat(r),a=Buffer.concat([t,i]),o=await rs(a);return Buffer.concat([a,Buffer.from(o,`hex`)])}};function us(e,t,n=!0,r=!0){let i=es(e),a=es(t);return n&&i.mode!==a.mode||i.mtimeSeconds!==a.mtimeSeconds||i.ctimeSeconds!==a.ctimeSeconds||i.uid!==a.uid||i.gid!==a.gid||r&&i.ino!==a.ino||i.size!==a.size}var ds=null,fs=Symbol(`IndexCache`);function ps(){return{map:new Map,stats:new Map}}async function ms(e,t,n){let[r,i]=await Promise.all([e.lstat(t),e.read(t)]),a=await ls.from(i);n.map.set(t,a),n.stats.set(t,r)}async function hs(e,t,n){let r=n.stats.get(t);if(r===void 0)return!0;if(r===null)return!1;let i=await e.lstat(t);return i===null?!1:us(r,i)}var gs=class{static async acquire({fs:e,gitdir:t,cache:n,allowUnmerged:r=!0},i){n[fs]||(n[fs]=ps());let a=`${t}/index`;ds===null&&(ds=new Ro.default({maxPending:1/0}));let o,s=[];return await ds.acquire(a,async()=>{let t=n[fs];await hs(e,a,t)&&await ms(e,a,t);let c=t.map.get(a);if(s=c.unmergedPaths,s.length&&!r)throw new Ko(s);if(o=await i(c),c._dirty){let n=await c.toObject();await e.write(a,n),t.stats.set(a,await e.lstat(a)),c._dirty=!1}}),o}};function _s(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t>-1&&(e=e.slice(t+1)),e}function vs(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t===-1?`.`:t===0?`/`:e.slice(0,t)}function ys(e){let t=new Map,n=function(e){if(!t.has(e)){let r={type:`tree`,fullpath:e,basename:_s(e),metadata:{},children:[]};t.set(e,r),r.parent=n(vs(e)),r.parent&&r.parent!==r&&r.parent.children.push(r)}return t.get(e)},r=function(e,r){if(!t.has(e)){let i={type:`blob`,fullpath:e,basename:_s(e),metadata:r,parent:n(vs(e)),children:[]};i.parent&&i.parent.children.push(i),t.set(e,i)}return t.get(e)};n(`.`);for(let t of e)r(t.path,t);return t}function bs(e){switch(e){case 16384:return`tree`;case 33188:return`blob`;case 33261:return`blob`;case 40960:return`blob`;case 57344:return`commit`}throw new W(`Unexpected GitTree entry mode: ${e.toString(8)}`)}var xs=class{constructor({fs:e,gitdir:t,cache:n}){this.treePromise=gs.acquire({fs:e,gitdir:t,cache:n},async function(e){return ys(e.entries)});let r=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._oid=!1}async type(){return r.type(this)}async mode(){return r.mode(this)}async stat(){return r.stat(this)}async content(){return r.content(this)}async oid(){return r.oid(this)}}}async readdir(e){let t=e._fullpath,n=(await this.treePromise).get(t);if(!n||n.type===`blob`)return null;if(n.type!==`tree`)throw Error(`ENOTDIR: not a directory, scandir '${t}'`);let r=n.children.map(e=>e.fullpath);return r.sort(Yo),r}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let t=(await this.treePromise).get(e._fullpath);if(!t)throw Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let n=t.type===`tree`?{}:es(t.metadata);e._type=t.type===`tree`?`tree`:bs(n.mode),e._mode=n.mode,t.type===`tree`?e._stat=void 0:e._stat=n}return e._stat}async content(e){}async oid(e){return e._oid===!1&&(e._oid=(await this.treePromise).get(e._fullpath).metadata.oid),e._oid}},Ss=Symbol(`GitWalkSymbol`);function Cs(){let e=Object.create(null);return Object.defineProperty(e,Ss,{value:function({fs:e,gitdir:t,cache:n}){return new xs({fs:e,gitdir:t,cache:n})}}),Object.freeze(e),e}var ws=class e extends U{constructor(t){super(`Could not find ${t}.`),this.code=this.name=e.code,this.data={what:t}}};ws.code=`NotFoundError`;var Ts=class e extends U{constructor(t,n,r,i){super(`Object ${t} ${i?`at ${i}`:``}was anticipated to be a ${r} but it is a ${n}.`),this.code=this.name=e.code,this.data={oid:t,actual:n,expected:r,filepath:i}}};Ts.code=`ObjectTypeError`;var Es=class e extends U{constructor(t){super(`Expected a 40-char hex object id but saw "${t}".`),this.code=this.name=e.code,this.data={value:t}}};Es.code=`InvalidOidError`;var Ds=class e extends U{constructor(t){super(`Could not find a fetch refspec for remote "${t}". Make sure the config file has an entry like the following:
725
+ `,document.head.appendChild(e)}},zi=[{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}],Bi=`slicc-hidden-tabs`,Vi=[`terminal`,`memory`];function Hi(){try{let e=localStorage.getItem(Bi);return e?new Set(JSON.parse(e)):new Set(Vi)}catch{return new Set(Vi)}}function Ui(e){let t=e.filter(e=>e!==`chat`);localStorage.setItem(Bi,JSON.stringify(t))}var Wi=zi.filter(e=>!Hi().has(e.id)),Gi=`chat`,Ki=new Set(zi.map(e=>e.id));function qi(e){return Ki.has(e)}var Ji=class{zoneId;tabBar;contentArea;tabs=new Map;activeTabId=null;callbacks;addBtn=null;fullpageBtn=null;isFullpage=!1;separator=null;scrollArea=null;storageKey;classPrefix;constructor(e,t,n,r={},i={}){this.tabBar=e,this.contentArea=t,this.zoneId=n,this.callbacks=r,this.storageKey=`slicc-${n}-tab`,this.classPrefix=i.classPrefix??`mini-tabs`}addTab(e){if(this.tabs.has(e.id))return;let t=document.createElement(`button`);if(t.dataset.tabId=e.id,e.pinned&&e.icon){t.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--icon ${this.classPrefix}__tab--dimmed`,t.innerHTML=e.icon,t.setAttribute(`aria-label`,e.label),t.dataset.tooltip=e.label,t.dataset.tooltipPos=`top`;let n=this.separator||this.findFirstNonPinnedBtn()||this.addBtn;if(n?this.tabBar.insertBefore(t,n):this.tabBar.appendChild(t),!this.separator){this.separator=document.createElement(`div`),this.separator.className=`${this.classPrefix}__separator`,this.scrollArea=document.createElement(`div`),this.scrollArea.className=`${this.classPrefix}__scroll`;let e=this.addBtn||this.fullpageBtn;e?(this.tabBar.insertBefore(this.separator,e),this.tabBar.insertBefore(this.scrollArea,e)):(this.tabBar.appendChild(this.separator),this.tabBar.appendChild(this.scrollArea))}t.addEventListener(`click`,()=>{let t=this.tabs.get(e.id);t&&!t.mounted&&this.enablePinnedTab(e.id),this.activateTab(e.id)}),this.tabs.set(e.id,{btn:t,container:e.element,tab:e,mounted:!1})}else{if(t.className=`${this.classPrefix}__tab`,t.appendChild(document.createTextNode(e.label)),e.closable){let n=document.createElement(`span`);n.className=`${this.classPrefix}__tab-close`,n.title=`Close panel`,n.textContent=`×`,n.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onTabClose?.(e.id)}),t.appendChild(n)}t.addEventListener(`click`,()=>this.activateTab(e.id)),this.scrollArea?this.scrollArea.appendChild(t):this.addBtn?this.tabBar.insertBefore(t,this.addBtn):this.tabBar.appendChild(t);let n=e.element;n.style.display=`none`,this.contentArea.appendChild(n),this.tabs.set(e.id,{btn:t,container:n,tab:e,mounted:!0}),(!this.activeTabId||!this.tabs.get(this.activeTabId)?.mounted)&&this.activateTab(e.id)}}removeTab(e){let t=this.tabs.get(e);if(t&&(t.btn.remove(),t.mounted&&t.container.remove(),this.tabs.delete(e),this.activeTabId===e)){let e=Array.from(this.tabs.entries()).find(([,e])=>e.mounted);e?this.activateTab(e[0]):this.activeTabId=null}}enablePinnedTab(e){let t=this.tabs.get(e);!t||t.mounted||(t.mounted=!0,t.btn.classList.remove(`${this.classPrefix}__tab--dimmed`),t.container.style.display=`none`,this.contentArea.appendChild(t.container))}isPinnedTabEnabled(e){return this.tabs.get(e)?.mounted??!1}activateTab(e){let t=this.tabs.get(e);if(!(!t||!t.mounted)){this.activeTabId=e;for(let[t,{btn:n,container:r,mounted:i}]of this.tabs){let a=t===e;n.classList.toggle(`${this.classPrefix}__tab--active`,a),i&&(r.style.display=a?`flex`:`none`)}try{localStorage.setItem(this.storageKey,e)}catch{}t.tab.onActivate?.(),this.callbacks.onTabActivate?.(e)}}getActiveTabId(){return this.activeTabId}getTabIds(){return Array.from(this.tabs.keys())}hasTab(e){return this.tabs.has(e)}setTabBadge(e,t){let n=this.tabs.get(e);if(!n)return;let r=n.btn.querySelector(`.${this.classPrefix}__tab-badge`);if(!t||t<=0){r?.remove();return}let i=r instanceof HTMLSpanElement?r:document.createElement(`span`);if(i.className=`${this.classPrefix}__tab-badge`,i.textContent=t>99?`99+`:String(t),i.setAttribute(`aria-label`,`${t} notifications`),!r){let e=n.btn.querySelector(`.${this.classPrefix}__tab-close`);e?n.btn.insertBefore(i,e):n.btn.appendChild(i)}}get tabCount(){return this.tabs.size}enableAddButton(){this.addBtn||(this.addBtn=document.createElement(`button`),this.addBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--add`,this.addBtn.textContent=`+`,this.addBtn.dataset.tooltip=`Open panel`,this.addBtn.dataset.tooltipPos=`top`,this.addBtn.setAttribute(`aria-label`,`Open panel`),this.addBtn.addEventListener(`click`,()=>this.callbacks.onAddClick?.()),this.tabBar.appendChild(this.addBtn))}setAddButtonEnabled(e){this.addBtn&&(this.addBtn.disabled=!e)}enableFullpageButton(){this.fullpageBtn||(this.fullpageBtn=document.createElement(`button`),this.fullpageBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--fullpage`,this.fullpageBtn.dataset.tooltip=`Full page`,this.fullpageBtn.dataset.tooltipPos=`top`,this.fullpageBtn.setAttribute(`aria-label`,`Toggle full page`),this.fullpageBtn.innerHTML=`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>`,this.fullpageBtn.addEventListener(`click`,()=>{this.isFullpage=!this.isFullpage,this.fullpageBtn.classList.toggle(`${this.classPrefix}__tab--active`,this.isFullpage),this.fullpageBtn.innerHTML=this.isFullpage?`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 6h-4V2"/><path d="M2 10h4v4"/><path d="M10 6l4.5-4.5"/><path d="M6 10L1.5 14.5"/></svg>`:`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>`,this.fullpageBtn.dataset.tooltip=this.isFullpage?`Exit full page`:`Full page`,this.callbacks.onFullpageToggle?.(this.isFullpage)}),this.tabBar.appendChild(this.fullpageBtn))}restoreActiveTab(){try{let e=localStorage.getItem(this.storageKey);if(e&&this.tabs.has(e)&&this.tabs.get(e).mounted)return this.activateTab(e),e}catch{}return null}findFirstNonPinnedBtn(){for(let[,e]of this.tabs)if(!e.tab.pinned)return e.btn;return null}},Yi=class{entries=new Map;listeners=new Set;register(e){this.entries.set(e.id,{descriptor:e}),this.notify()}unregister(e){this.entries.delete(e),this.notify()}get(e){return this.entries.get(e)}getByZone(e){let t=[];for(let n of this.entries.values())n.descriptor.zone===e&&t.push(n.descriptor);return t}getClosed(){let e=[];for(let t of this.entries.values())t.descriptor.zone===null&&e.push(t.descriptor);return e}setZone(e,t){let n=this.entries.get(e);n&&(n.descriptor.zone=t,this.notify())}ids(){return Array.from(this.entries.keys())}has(e){return this.entries.has(e)}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(let e of this.listeners)e()}};function Xi(e,t,n){let r=document.querySelector(`.sprinkle-picker`);if(r){r.remove();return}let{registry:i,callbacks:a,getAvailableSprinkles:o}=n,s=i.getClosed(),c=o?.()??[];if(s.length===0&&c.length===0)return;let l=document.createElement(`div`);l.className=`sprinkle-picker`,l.style.cssText=`position: absolute; min-width: 160px; max-height: 300px; overflow-y: auto; background: var(--s2-bg-layer-2); border: 1px solid var(--s2-border-default); border-radius: var(--s2-radius-l); padding: 4px 0; box-shadow: var(--s2-shadow-elevated); z-index: 1000;`;let u=()=>{l.remove(),document.removeEventListener(`pointerdown`,f,!0),document.removeEventListener(`keydown`,p,!0)};for(let e of s){let n=Zi(e.label,()=>{a.onSelectPanel(e.id,t),u()});l.appendChild(n)}if(s.length>0&&c.length>0){let e=document.createElement(`div`);e.style.cssText=`height: 1px; background: var(--s2-border-default); margin: 4px 0;`,l.appendChild(e)}for(let e of c){let n=Zi(e.title,()=>{a.onSelectSprinkle(e.name,t),u()});l.appendChild(n)}let d=e.getBoundingClientRect();l.style.top=`${d.bottom+4}px`,l.style.left=`${d.left}px`,document.body.appendChild(l);let f=e=>{l.contains(e.target)||u()},p=e=>{e.key===`Escape`&&u()};requestAnimationFrame(()=>{document.addEventListener(`pointerdown`,f,!0),document.addEventListener(`keydown`,p,!0)})}function Zi(e,t){let n=document.createElement(`div`);return n.className=`sprinkle-picker__item`,n.style.cssText=`padding: 6px 12px; cursor: pointer; font-size: 12px; color: var(--s2-content-default); border-radius: var(--s2-radius-s); margin: 0 4px; transition: background 130ms ease;`,n.textContent=e,n.addEventListener(`mouseenter`,()=>{n.style.background=`var(--s2-bg-elevated)`}),n.addEventListener(`mouseleave`,()=>{n.style.background=``}),n.addEventListener(`click`,t),n}var Qi=class e{root;isExtension;scoopsEl;leftEl;rightEl;verticalDivider;terminalContainer;iframeContainer;threadHeaderEl;threadHeaderName;primaryZoneEl;primaryZone;get drawerZone(){return this.primaryZone}get drawerZoneEl(){return this.primaryZoneEl}tabContainers=new Map;activeTab=`chat`;debugTabContainers=null;scoopSwitcher=null;scoopSwitcherEl=null;avatarEl;logoSvg=null;logoImg=null;logoScoopCount=-1;headerHamburger=null;panels;registry=new Yi;onModelChange;refreshModels;onScoopSelect;onClearChat;onClearFilesystem;onSprinkleClose;getAvailableSprinkles;onOpenSprinkle;constructor(e,t=!1){this.root=e,this.isExtension=t,t?this.buildTabbedLayout():this.buildSplitLayout()}setScoopSwitcherOrchestrator(e){this.scoopSwitcher?.setOrchestrator(e)}updateScoopSwitcherStatus(e,t){this.scoopSwitcher?.updateStatus(e,t)}setScoopSwitcherSelected(e){this.scoopSwitcher?.setSelected(e)}refreshScoopSwitcher(){this.scoopSwitcher?.refresh()}setActiveTab(e){this.isExtension&&this.extensionZone?.activateTab(e)}getActiveTab(){return this.activeTab}setPendingHandoffCount(e){this.isExtension&&this.extensionZone.setTabBadge(`chat`,e>0?e:null)}isTerminalOpen(){return this.isExtension?!0:this.primaryZone.isPinnedTabEnabled(`terminal`)}setAgentProcessing(e){this.threadHeaderEl?.classList.toggle(`thread-header--processing`,e)}openTerminal(){if(this.isExtension)return;this.primaryZone.isPinnedTabEnabled(`terminal`)||this.primaryZone.enablePinnedTab(`terminal`);let e=this.primaryZone.getActiveTabId();e&&e.startsWith(`sprinkle-`)||this.primaryZone.activateTab(`terminal`)}setDebugTabs(e){if(!this.isExtension||!this.debugTabContainers)return;let t=[{id:`terminal`,label:`Terminal`,container:this.debugTabContainers.terminal,onActivate:()=>this.panels?.terminal?.refit?.()},{id:`memory`,label:`Memory`,container:this.debugTabContainers.memory,onActivate:()=>this.panels?.memory?.refresh()}];for(let{id:n,label:r,container:i,onActivate:a}of t)e&&!this.extensionZone.hasTab(n)?(this.extensionZone.addTab({id:n,label:r,closable:!1,element:i,onActivate:a}),this.tabContainers.set(n,i)):!e&&this.extensionZone.hasTab(n)&&(this.extensionZone.removeTab(n),this.tabContainers.delete(n));Ui(e?[]:[`terminal`,`memory`])}buildHeader(e){let t=document.createElement(`div`);t.className=`header`;let n=()=>{if(te())return;let e=j();for(let t of e)if(t.models.length>0){let{defaultModelId:e}=E(t.providerId),n=(e?t.models.find(t=>t.id.toLowerCase().includes(e.toLowerCase())):void 0)??t.models[0];ne(`${t.providerId}:${n.id}`);return}};n(),this.refreshModels=()=>{n(),this.panels?.chat?.refreshModelSelector(),this.refreshAvatar()};let r=document.createElement(`div`);r.className=`header__row`;let i=document.createElement(`div`);if(i.className=`header__brand`,this.isExtension){let e=this.sliccLogo(24);i.appendChild(e)}else{let e=document.createElement(`button`);e.className=`scoops-hamburger`,e.dataset.tooltip=`Toggle navigation`,e.dataset.tooltipPos=`right`,e.setAttribute(`aria-label`,`Toggle navigation`),e.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.61805 16.2451C9.31922 15.958 9.30945 15.4834 9.59754 15.1855L14.5839 10.002L9.58485 4.80469C9.29677 4.50684 9.30653 4.03223 9.60536 3.74512C9.90223 3.45801 10.3778 3.4668 10.6649 3.76563L16.1649 9.48243C16.4452 9.77247 16.4452 10.2315 16.1649 10.5215L10.6776 16.2246C10.5311 16.3779 10.3339 16.4551 10.1376 16.4551C9.95008 16.4551 9.76258 16.3857 9.61805 16.2451Z"/><path d="M3.86805 16.2451C3.56922 15.958 3.55945 15.4834 3.84754 15.1855L8.83387 10.002L3.83485 4.80469C3.54677 4.50684 3.55653 4.03223 3.85536 3.74512C4.15223 3.45801 4.62782 3.4668 4.91493 3.76563L10.4149 9.48243C10.6952 9.77247 10.6952 10.2315 10.4149 10.5215L4.92763 16.2246C4.78114 16.3779 4.58388 16.4551 4.38759 16.4551C4.20008 16.4551 4.01258 16.3857 3.86805 16.2451Z"/></svg>`,this.headerHamburger=e,e.addEventListener(`click`,()=>{this.panels?.scoops?.toggleExpanded(),e.innerHTML=this.scoopsEl?.classList.contains(`layout__scoops--expanded`)?`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.86241 16.4551C9.66612 16.4551 9.46886 16.3779 9.32237 16.2246L3.83507 10.5215C3.5548 10.2315 3.5548 9.77247 3.83507 9.48243L9.33507 3.76563C9.62218 3.4668 10.0978 3.45801 10.3946 3.74512C10.6935 4.03223 10.7032 4.50684 10.4151 4.80469L5.41613 10.002L10.4025 15.1855C10.6906 15.4834 10.6808 15.958 10.382 16.2451C10.2374 16.3857 10.0499 16.4551 9.86241 16.4551Z"/><path d="M15.6124 16.4551C15.4161 16.4551 15.2189 16.3779 15.0724 16.2246L9.58507 10.5215C9.3048 10.2315 9.3048 9.77247 9.58507 9.48243L15.0851 3.76563C15.3722 3.4668 15.8478 3.45801 16.1446 3.74512C16.4435 4.03223 16.4532 4.50684 16.1652 4.80469L11.1661 10.002L16.1525 15.1855C16.4406 15.4834 16.4308 15.958 16.132 16.2451C15.9874 16.3857 15.7999 16.4551 15.6124 16.4551Z"/></svg>`:`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.61805 16.2451C9.31922 15.958 9.30945 15.4834 9.59754 15.1855L14.5839 10.002L9.58485 4.80469C9.29677 4.50684 9.30653 4.03223 9.60536 3.74512C9.90223 3.45801 10.3778 3.4668 10.6649 3.76563L16.1649 9.48243C16.4452 9.77247 16.4452 10.2315 16.1649 10.5215L10.6776 16.2246C10.5311 16.3779 10.3339 16.4551 10.1376 16.4551C9.95008 16.4551 9.76258 16.3857 9.61805 16.2451Z"/><path d="M3.86805 16.2451C3.56922 15.958 3.55945 15.4834 3.84754 15.1855L8.83387 10.002L3.83485 4.80469C3.54677 4.50684 3.55653 4.03223 3.85536 3.74512C4.15223 3.45801 4.62782 3.4668 4.91493 3.76563L10.4149 9.48243C10.6952 9.77247 10.6952 10.2315 10.4149 10.5215L4.92763 16.2246C4.78114 16.3779 4.58388 16.4551 4.38759 16.4551C4.20008 16.4551 4.01258 16.3857 3.86805 16.2451Z"/></svg>`}),i.appendChild(e)}let a=document.createElement(`div`);a.className=`header__title`,a.textContent=`slicc`,i.appendChild(a),r.appendChild(i),this.isExtension&&(this.scoopSwitcherEl=document.createElement(`div`),this.scoopSwitcherEl.className=`scoop-switcher`,this.scoopSwitcher=new Ri(this.scoopSwitcherEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onDeleteScoop:e=>{this.panels?.scoops?.deleteScoop?.(e)}}),r.appendChild(this.scoopSwitcherEl));let o=document.createElement(`div`);o.className=`header__spacer`,r.appendChild(o),this.avatarEl=this.buildUserAvatar(),r.appendChild(this.avatarEl),t.appendChild(r),e.appendChild(t)}static SCOOP_COLORS=[`#f000a0`,`#00f0f0`,`#90f000`,`#15d675`,`#e68619`];sliccLogo(e=22){let t=document.createElement(`img`);return t.width=e,t.height=e,t.src=`/logos/sliccy-color-0scoops-128x128.png`,t.alt=`slicc`,t.classList.add(`header__logo`),t.style.objectFit=`contain`,this.logoImg=t,t}static SCOOP_R=5;static SCOOP_SPACING=8.5;static ROW_STEP=7.5;pyramidLayout(t){if(t===0)return[];let{SCOOP_SPACING:n,ROW_STEP:r}=e,i=1;for(;i*(i+1)/2<t;)i++;let a=[],o=t,s=i;for(;o>0;){let e=Math.min(o,s);a.push(e),o-=e,s--}let c=[],l=19-e.SCOOP_R;for(let e of a){let t=16-(e-1)*n/2;for(let r=0;r<e;r++)c.push({cx:t+r*n,cy:l});l-=r}return c}updateLogoScoops(e){let t=e.filter(e=>!e.isCone),n=this.logoScoopCount;if(n===t.length&&n>=0)return;this.logoScoopCount=t.length;let r=Math.min(Math.max(t.length,0),10);this.logoImg&&(this.logoImg.src=`/logos/sliccy-color-${r}scoops-128x128.png`),this.updateFaviconForScoops(t.length)}updateFaviconForScoops(e){let t=Math.min(Math.max(e,0),10),n=document.querySelector(`link[rel="icon"]`);n&&(n.href=`/logos/sliccy-color-${t}scoops-32x32.png`);let r=typeof chrome<`u`?chrome:null;r?.action?.setIcon&&r.action.setIcon({path:{16:`logos/sliccy-color-${t}scoops-16x16.png`,32:`logos/sliccy-color-${t}scoops-32x32.png`,48:`logos/sliccy-color-${t}scoops-48x48.png`,128:`logos/sliccy-color-${t}scoops-128x128.png`}}).catch(()=>{})}getInitials(e){let t=e.trim().split(/\s+/);return t.length>=2?(t[0][0]+t[t.length-1][0]).toUpperCase():e.slice(0,2).toUpperCase()}buildUserAvatar(){let e=document.createElement(`div`);e.className=`header__avatar`,e.setAttribute(`aria-label`,`Account`),e.dataset.tooltip=`Account`;let t=ee().find(e=>e.userName||e.userAvatar);if(t?.userAvatar){let n=document.createElement(`img`);n.src=t.userAvatar,n.alt=t.userName??`User`,n.addEventListener(`error`,()=>{e.removeChild(n),t.userName&&(e.classList.add(`header__avatar--initials`),e.textContent=this.getInitials(t.userName))}),e.appendChild(n)}else t?.userName?(e.classList.add(`header__avatar--initials`),e.textContent=this.getInitials(t.userName)):(e.classList.add(`header__avatar--placeholder`),e.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M10 10c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4z"/></svg>`);return e.addEventListener(`click`,()=>this.showAvatarPopover()),e}refreshAvatar(){if(!this.avatarEl)return;let e=this.avatarEl.parentElement;if(!e)return;let t=this.buildUserAvatar();e.replaceChild(t,this.avatarEl),this.avatarEl=t}showAvatarPopover(){let e=document.querySelector(`.avatar-popover`);if(e){e.remove();return}let t=document.createElement(`div`);t.className=`avatar-popover`;let n=ee(),r=n.find(e=>e.userName||e.accessToken||e.apiKey);if(r){let e=document.createElement(`div`);e.className=`avatar-popover__user`;let n=document.createElement(`div`);n.className=`avatar-popover__name`,n.textContent=r.userName||`Logged in`,e.appendChild(n);let i=document.createElement(`div`);i.className=`avatar-popover__provider`,i.textContent=E(r.providerId).name,e.appendChild(i),t.appendChild(e);let a=document.createElement(`button`);a.className=`avatar-popover__item`,a.textContent=`Sign out`,a.addEventListener(`click`,()=>{w(r.providerId),t.remove(),this.refreshAvatar(),this.refreshModels?.()}),t.appendChild(a)}if(n.length>0){let e=document.createElement(`div`);e.className=`avatar-popover__separator`,t.appendChild(e);let n=document.createElement(`button`);n.className=`avatar-popover__item avatar-popover__item--danger`,n.textContent=`Clear all accounts`,n.addEventListener(`click`,()=>{A(),t.remove(),this.refreshAvatar(),this.refreshModels?.()}),t.appendChild(n)}let i=document.createElement(`div`);i.className=`avatar-popover__separator`,t.appendChild(i);let a=document.createElement(`button`);a.className=`avatar-popover__item avatar-popover__item--danger`,a.textContent=`Clear chat`,a.addEventListener(`click`,async()=>{t.remove(),await this.panels?.chat?.clearSession(),await this.onClearChat?.(),location.reload()}),t.appendChild(a);let o=document.createElement(`div`);o.className=`avatar-popover__separator`,t.appendChild(o);let s=document.createElement(`button`);s.className=`avatar-popover__item`,s.textContent=`Account settings…`,s.addEventListener(`click`,async()=>{t.remove(),T()||A(),await C()&&(this.refreshAvatar(),this.refreshModels?.())}),t.appendChild(s),document.body.appendChild(t);let c=this.avatarEl.getBoundingClientRect();t.style.top=`${c.bottom+4}px`,t.style.right=`${window.innerWidth-c.right}px`;let l=e=>{if(e instanceof KeyboardEvent){if(e.key!==`Escape`)return}else if(t.contains(e.target)||this.avatarEl.contains(e.target))return;t.remove(),document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,l)};requestAnimationFrame(()=>{document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,l)})}extensionZone;buildTabbedLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);let e=document.createElement(`div`);e.className=`tab-bar`,this.root.appendChild(e);let t=document.createElement(`div`);t.className=`tab-content`,this.root.appendChild(t),this.extensionZone=new Ji(e,t,`primary`,{onTabActivate:e=>{this.activeTab=e,e===`terminal`&&this.panels?.terminal?.refit?.(),e===`memory`&&this.panels?.memory?.refresh()},onTabClose:e=>{let t=e.startsWith(`sprinkle-`)?e.slice(9):e;this.onSprinkleClose?.(t)},onAddClick:()=>this.showExtensionPicker(e)},{classPrefix:`tab-bar`});let n=document.createElement(`div`);n.className=`tab-content__panel`;let r=document.createElement(`div`);r.className=`tab-content__panel`;let i=document.createElement(`div`);i.className=`tab-content__panel`;let a=document.createElement(`div`);a.className=`tab-content__panel`;for(let{id:e,label:t}of Wi){let o=e===`chat`?n:e===`terminal`?r:e===`files`?i:a;this.extensionZone.addTab({id:e,label:t,closable:!1,element:o,onActivate:e===`terminal`?()=>this.panels?.terminal?.refit?.():e===`memory`?()=>this.panels?.memory?.refresh():void 0}),this.tabContainers.set(e,o)}this.debugTabContainers={terminal:r,memory:a},this.extensionZone.enableAddButton(),this.iframeContainer=document.createElement(`div`),this.iframeContainer.id=`scoop-iframes`,this.iframeContainer.style.display=`none`,this.root.appendChild(this.iframeContainer),this.scoopsEl=document.createElement(`div`),this.scoopsEl.style.display=`none`,this.root.appendChild(this.scoopsEl),this.panels={chat:new Ti(n),terminal:new Ei(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new Pi(i,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.extensionZone.activateTab(`terminal`)}}),memory:new Fi(a),scoops:new Li(this.scoopsEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onSendMessage:()=>{},onScoopsChanged:e=>this.updateLogoScoops(e)})},this.panels.chat.onModelChange=e=>this.onModelChange?.(e)}showExtensionPicker(e){let t=this.getAvailableSprinkles?.()??[],n=new Set(this.extensionZone.getTabIds()),r=t.filter(e=>!n.has(`sprinkle-${e.name}`));r.length!==0&&Xi(e,`primary`,{registry:this.registry,callbacks:{onSelectPanel:()=>{},onSelectSprinkle:e=>{this.onOpenSprinkle?.(e)}},getAvailableSprinkles:()=>r})}switchTab(e){this.extensionZone&&this.extensionZone.activateTab(e)}buildSplitLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);let e=document.createElement(`div`);e.className=`layout`,this.scoopsEl=document.createElement(`div`),this.scoopsEl.className=`layout__scoops`,e.appendChild(this.scoopsEl),this.leftEl=document.createElement(`div`),this.leftEl.className=`layout__left`,this.threadHeaderEl=document.createElement(`div`),this.threadHeaderEl.className=`thread-header`;let t=document.createElement(`div`);t.className=`thread-header__title`;let n=document.createElement(`span`);n.className=`thread-header__icon`,n.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4h14a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H7l-4 3V5a1 1 0 0 1 1-1z"/><path d="M7 8h6"/><path d="M7 11h3"/></svg>`,t.appendChild(n),this.threadHeaderName=document.createElement(`span`),this.threadHeaderName.className=`thread-header__name`,this.threadHeaderName.textContent=`sliccy`,t.appendChild(this.threadHeaderName),this.threadHeaderEl.appendChild(t);let r=document.createElement(`button`);r.className=`thread-header__panel-toggle thread-header__panel-toggle--right`,r.dataset.tooltip=`Toggle panel`,r.setAttribute(`aria-label`,`Toggle panel`),r.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M12 3v14"/></svg>`,r.addEventListener(`click`,()=>{this.rightEl.classList.toggle(`layout__right--open`)});let i=document.createElement(`button`);i.className=`thread-header__panel-toggle`,i.dataset.tooltip=`Clear Chat`,i.setAttribute(`aria-label`,`Clear Chat`),i.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>`,i.addEventListener(`click`,async()=>{await this.panels.chat.clearSession(),await this.onClearChat?.(),location.reload()});let a=document.createElement(`div`);a.className=`thread-header__actions`,a.appendChild(i),a.appendChild(r),this.threadHeaderEl.appendChild(a),this.leftEl.appendChild(this.threadHeaderEl);let o=document.createElement(`div`);o.style.cssText=`display: flex; flex-direction: column; flex: 1; min-height: 0;`,this.leftEl.appendChild(o),e.appendChild(this.leftEl),this.verticalDivider=document.createElement(`div`),this.verticalDivider.className=`layout__divider layout__divider--vertical`,e.appendChild(this.verticalDivider),this.rightEl=document.createElement(`div`),this.rightEl.className=`layout__right`,this.primaryZoneEl=document.createElement(`div`),this.primaryZoneEl.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let s=document.createElement(`div`);s.className=`mini-tabs`;let c=document.createElement(`button`);c.className=`thread-header__panel-toggle thread-header__panel-toggle--right`,c.dataset.tooltip=`Close panel`,c.setAttribute(`aria-label`,`Close panel`),c.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v14"/><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>`,c.addEventListener(`click`,()=>{this.rightEl.classList.remove(`layout__right--open`)}),s.appendChild(c),this.primaryZoneEl.appendChild(s);let l=document.createElement(`div`);l.style.cssText=`flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden;`,this.primaryZoneEl.appendChild(l),this.primaryZone=new Ji(s,l,`primary`,{onTabActivate:e=>{e===`terminal`&&this.panels?.terminal?.refit(),e===`memory`&&this.panels?.memory?.refresh()},onTabClose:e=>{let t=e.startsWith(`sprinkle-`)?e.slice(9):e;this.onSprinkleClose?.(t)},onAddClick:()=>this.showPickerForZone(`primary`,s),onFullpageToggle:e=>{this.leftEl.classList.toggle(`layout__left--fullpage-hidden`,e),this.verticalDivider.classList.toggle(`layout__divider--fullpage-hidden`,e),this.scoopsEl.classList.toggle(`layout__scoops--fullpage-hidden`,e),this.rightEl.classList.toggle(`layout__right--fullpage`,e)}}),this.terminalContainer=document.createElement(`div`),this.terminalContainer.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let u=document.createElement(`div`);u.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let d=document.createElement(`div`);d.style.cssText=`display: flex; flex-direction: column; min-height: 0; flex: 1;`;let f=e=>`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">${e}</svg>`;this.primaryZone.addTab({id:`terminal`,label:`Terminal`,closable:!1,element:this.terminalContainer,pinned:!0,icon:f(`<path d="M5.5 14.5C5.30762 14.5 5.11621 14.4268 4.96973 14.2803L1.21973 10.5303C0.92676 10.2373 0.92676 9.76269 1.21973 9.46972L4.96973 5.71972C5.2627 5.42675 5.73731 5.42675 6.03028 5.71972C6.32325 6.01269 6.32325 6.4873 6.03028 6.78027L2.81055 10L6.03028 13.2197C6.32325 13.5127 6.32325 13.9873 6.03028 14.2803C5.8838 14.4268 5.69238 14.5 5.5 14.5Z" fill="currentColor"/><path d="M14.5 14.5C14.3076 14.5 14.1162 14.4268 13.9697 14.2803C13.6768 13.9873 13.6768 13.5127 13.9697 13.2197L17.1895 9.99999L13.9697 6.78026C13.6768 6.48729 13.6768 6.01268 13.9697 5.71971C14.2627 5.42674 14.7373 5.42674 15.0303 5.71971L18.7803 9.46971C19.0732 9.76268 19.0732 10.2373 18.7803 10.5303L15.0303 14.2803C14.8838 14.4267 14.6924 14.5 14.5 14.5Z" fill="currentColor"/><path d="M8.22852 18C8.16993 18 8.11036 17.9932 8.05176 17.9795C7.64844 17.8818 7.40137 17.4766 7.49805 17.0742L10.998 2.57422C11.0957 2.1709 11.5078 1.92871 11.9033 2.02051C12.3066 2.11817 12.5537 2.52344 12.457 2.92578L8.95703 17.4258C8.87402 17.7695 8.56642 18 8.22852 18Z" fill="currentColor"/>`),onActivate:()=>this.panels?.terminal?.refit()}),this.primaryZone.addTab({id:`files`,label:`Files`,closable:!1,element:u,pinned:!0,icon:f(`<path d="M18 4.75C18 2.61621 13.9756 1.5 10 1.5C6.02441 1.5 2 2.61621 2 4.75C2 4.81714 2.01538 4.88037 2.02325 4.94556C2.01696 4.98462 2 5.01978 2 5.06055V15C2 17.0615 6.14697 18 10 18C13.853 18 18 17.0615 18 15V5.06055C18 5.01978 17.983 4.98462 17.9767 4.94556C17.9846 4.88037 18 4.81714 18 4.75ZM16.5002 9.99451C16.4084 10.4097 14.2719 11.5 10 11.5C5.72705 11.5 3.59033 10.4092 3.5 10V6.72449C5.02985 7.56665 7.52393 8 10 8C12.4761 8 14.9701 7.56665 16.5001 6.72437L16.5002 9.99451ZM10 3C14.2886 3 16.5 4.22656 16.5 4.75C16.5 5.27344 14.2886 6.5 10 6.5C5.71143 6.5 3.5 5.27344 3.5 4.75C3.5 4.22656 5.71143 3 10 3ZM10 16.5C5.72705 16.5 3.59033 15.4092 3.5 15V11.8464C5.05219 12.6304 7.58337 13 10 13C12.4168 13 14.9482 12.6304 16.5003 11.8463L16.5005 14.9941C16.4097 15.4092 14.273 16.5 10 16.5Z" fill="currentColor"/>`)}),this.primaryZone.addTab({id:`memory`,label:`Memory`,closable:!1,element:d,pinned:!0,icon:f(`<path d="M10.0039 12.5889C9.11573 12.5889 8.25098 12.1289 7.77588 11.3057C7.06787 10.0781 7.48975 8.50489 8.71582 7.79688C9.30908 7.45313 10.001 7.36329 10.665 7.54004C11.3276 7.71777 11.8814 8.14356 12.2241 8.73731C12.5674 9.33106 12.6582 10.0234 12.481 10.6855C12.3032 11.3486 11.8784 11.9024 11.2842 12.2451C10.8809 12.4785 10.4395 12.5889 10.0039 12.5889ZM9.07471 10.5557C9.36914 11.0645 10.0229 11.2392 10.5342 10.9463C10.7812 10.8037 10.958 10.5732 11.0317 10.2978C11.1055 10.0225 11.0679 9.73436 10.9253 9.48729C10.7822 9.24022 10.5522 9.06346 10.2764 8.98924C10.0015 8.916 9.71337 8.95408 9.46581 9.09569C8.95556 9.39061 8.78027 10.0449 9.07471 10.5557Z" fill="currentColor"/><path d="M6.90674 18.3184C6.56738 18.3184 6.22461 18.2334 5.91455 18.0537L5.09473 17.5811C4.20166 17.0674 3.84473 15.9316 4.28369 14.998L4.86377 13.7646C4.59863 13.4014 4.37402 13.0137 4.19189 12.6035L2.83496 12.4912C1.80615 12.4063 1.00049 11.5313 1.00049 10.5L0.99951 9.55371C0.99951 8.52051 1.80469 7.64453 2.83301 7.55957L4.1875 7.44531C4.2793 7.23633 4.37988 7.03613 4.48926 6.8457C4.59912 6.65429 4.72266 6.46679 4.8584 6.28125L4.27783 5.05176C3.83691 4.11914 4.1914 2.9834 5.08496 2.4668L5.90527 1.99317C6.79785 1.47657 7.95898 1.73438 8.54785 2.58301L9.32519 3.70117C9.76904 3.65137 10.2173 3.65332 10.666 3.70117L11.4414 2.58203C12.0303 1.73242 13.1924 1.47265 14.085 1.98828L14.9048 2.46094C15.7988 2.97656 16.1543 4.11231 15.7153 5.04492L15.1352 6.27734C15.4009 6.6416 15.6255 7.02929 15.8071 7.43847L17.164 7.55077C18.1924 7.63573 18.998 8.51073 18.999 9.54198L18.9995 10.4893C19.0005 11.5205 18.1958 12.3965 17.1675 12.4834L15.812 12.5976C15.7207 12.8066 15.6201 13.0059 15.5093 13.1973C15.3999 13.3867 15.2769 13.5752 15.1411 13.7607L15.7217 14.9902C16.1621 15.9219 15.8081 17.0576 14.915 17.5752L14.0942 18.0498C13.2007 18.5684 12.0405 18.3076 11.4517 17.459L10.6743 16.3408C10.2285 16.3897 9.78028 16.3887 9.3335 16.3418L8.55713 17.4619C8.17334 18.0156 7.54541 18.3184 6.90674 18.3184ZM6.9043 3.22461C6.81934 3.22461 6.73389 3.24609 6.65625 3.29102L5.83545 3.76563C5.61279 3.89454 5.52393 4.17774 5.63428 4.41114L6.41309 6.06153C6.53907 6.32813 6.49707 6.64356 6.30567 6.86817C6.10157 7.10743 5.93262 7.34473 5.78907 7.59376C5.64796 7.83985 5.52393 8.11231 5.42091 8.40333C5.32277 8.68165 5.07081 8.87599 4.77687 8.9004L2.95802 9.05372C2.6963 9.07618 2.49952 9.29005 2.49952 9.55274L2.5005 10.499C2.5005 10.7568 2.70167 10.9756 2.959 10.9971L4.77834 11.1475C5.07229 11.1719 5.32473 11.3662 5.42336 11.6445C5.62209 12.2051 5.92043 12.7207 6.31008 13.1768C6.50197 13.4004 6.54446 13.7168 6.41897 13.9834L5.64114 15.6358C5.53176 15.8692 5.62014 16.1533 5.84378 16.2813L6.66409 16.7549C6.88821 16.8848 7.17825 16.8184 7.32425 16.6074L8.36527 15.1055C8.53275 14.8633 8.82425 14.7363 9.11771 14.7959C9.70609 14.9033 10.3023 14.9043 10.8877 14.7949C11.1773 14.7402 11.4727 14.8613 11.6412 15.1045L12.6831 16.6035C12.8296 16.8135 13.1216 16.8799 13.3438 16.751L14.1641 16.2773C14.3902 16.1465 14.4776 15.8682 14.3653 15.6309L13.5864 13.9805C13.4605 13.7139 13.5025 13.3984 13.6939 13.1738C13.898 12.9336 14.0669 12.6973 14.2095 12.4492L14.21 12.4483C14.3526 12.2012 14.4732 11.9365 14.5786 11.6387C14.6773 11.3604 14.9292 11.166 15.2232 11.1416L17.042 10.9893C17.2984 10.9668 17.4995 10.7481 17.4995 10.4902L17.499 9.54298C17.499 9.28126 17.3018 9.06739 17.0401 9.04493L15.2212 8.89454C14.9273 8.87013 14.6748 8.67579 14.5762 8.39747C14.3784 7.8379 14.0796 7.32227 13.689 6.86524C13.4976 6.64063 13.4551 6.3252 13.5806 6.0586L14.3579 4.40626C14.4678 4.17286 14.3789 3.88868 14.1553 3.75978L13.3355 3.28712C13.1108 3.16017 12.8213 3.2256 12.6743 3.43653L11.6348 4.93653C11.4668 5.17969 11.1758 5.30469 10.8819 5.24708C10.2905 5.1377 9.69435 5.1377 9.11183 5.24708C8.81984 5.29884 8.52638 5.1797 8.35841 4.93751L7.31642 3.43849C7.22023 3.30079 7.06348 3.22461 6.9043 3.22461Z" fill="currentColor"/>`),onActivate:()=>this.panels?.memory?.refresh()}),this.primaryZone.enableAddButton(),this.primaryZone.enableFullpageButton(),this.rightEl.appendChild(this.primaryZoneEl),e.appendChild(this.rightEl),this.iframeContainer=document.createElement(`div`),this.iframeContainer.id=`scoop-iframes`,this.iframeContainer.style.display=`none`,e.appendChild(this.iframeContainer),this.root.appendChild(e),this.panels={chat:new Ti(o),terminal:new Ei(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new Pi(u,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.openTerminal()}}),memory:new Fi(d),scoops:new Li(this.scoopsEl,{onScoopSelect:e=>{this.onScoopSelect?.(e),this.threadHeaderName.textContent=e.assistantLabel},onSendMessage:()=>{},onScoopsChanged:e=>this.updateLogoScoops(e)})},this.panels.chat.onModelChange=e=>this.onModelChange?.(e),this.setupVerticalDrag(),window.addEventListener(`resize`,()=>{})}getIframeContainer(){return this.iframeContainer}async runFileBrowserCommand(e){let t=await this.panels.terminal.runCommand(e);t.exitCode!==0&&t.stderr&&console.warn(`[Layout] File browser command failed:`,t.stderr.trim())}setupVerticalDrag(){if(!this.verticalDivider)return;let e=!1,t=t=>{if(!e)return;let n=this.root.querySelector(`.layout`)?.getBoundingClientRect();if(!n)return;let r=t.clientX-n.left-58,i=n.width-58,a=Math.max(.3,Math.min(.7,r/i));this.leftEl.style.flex=`${a*100} 0 0`,this.rightEl.style.flex=`${(1-a)*100} 0 0`},n=()=>{e=!1,this.verticalDivider.classList.remove(`active`),document.body.style.cursor=``,document.body.style.userSelect=``,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),this.panels?.terminal?.refit()};this.verticalDivider.addEventListener(`mousedown`,r=>{r.preventDefault(),e=!0,this.verticalDivider.classList.add(`active`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)})}updateAddButtons(){let e=this.registry.getClosed().length,t=this.getAvailableSprinkles?.()??[],n=new Set;for(let e of this.registry.ids())e.startsWith(`sprinkle-`)&&this.registry.get(e)?.descriptor.zone!==null&&n.add(e.slice(9));let r=e+t.filter(e=>!n.has(e.name)).length>0;this.primaryZone?.setAddButtonEnabled(r)}showPickerForZone(e,t){let n=new Set;for(let e of this.registry.ids())e.startsWith(`sprinkle-`)&&this.registry.get(e)?.descriptor.zone!==null&&n.add(e.slice(9));let r=(this.getAvailableSprinkles?.()??[]).filter(e=>!n.has(e.name));Xi(t,e,{registry:this.registry,callbacks:{onSelectPanel:(e,t)=>{this.openPanelInZone(e,t)},onSelectSprinkle:(e,t)=>{this.onOpenSprinkle?.(e,t)}},getAvailableSprinkles:()=>r})}openPanelInZone(e,t){let n=this.registry.get(e);if(!n)return;let r=this.primaryZone;this.registry.setZone(e,t),r.addTab({id:n.descriptor.id,label:n.descriptor.label,closable:n.descriptor.closable,element:n.descriptor.element,onActivate:n.descriptor.onActivate}),r.activateTab(e)}dynamicSprinkles=new Map;addSprinkle(e,t,n,r){if(this.isExtension){let r=`sprinkle-${e}`,i=document.createElement(`div`);i.className=`tab-content__panel`,i.appendChild(n),this.extensionZone.addTab({id:r,label:t,closable:!0,element:i}),this.tabContainers.set(r,i),this.dynamicSprinkles.set(e,i),this.extensionZone.activateTab(r)}else{let i=r??`primary`,a=this.primaryZone,o=`sprinkle-${e}`,s=document.createElement(`div`);s.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: auto; flex: 1;`,s.appendChild(n),this.registry.register({id:o,label:t,zone:i,closable:!0,element:s,onClose:()=>this.onSprinkleClose?.(e)}),a.addTab({id:o,label:t,closable:!0,element:s}),this.dynamicSprinkles.set(e,s),a.activateTab(o),this.updateAddButtons()}}removeSprinkle(e){if(this.isExtension){let t=`sprinkle-${e}`;this.extensionZone.removeTab(t),this.tabContainers.delete(t),this.dynamicSprinkles.delete(e)}else{let t=`sprinkle-${e}`;this.primaryZone.removeTab(t),this.registry.unregister(t),this.dynamicSprinkles.delete(e),this.updateAddButtons()}}dispose(){for(this.panels.chat.dispose(),this.panels.terminal.dispose(),this.panels.fileBrowser.dispose(),this.panels.memory.dispose(),this.panels.scoops.dispose();this.root.firstChild;)this.root.removeChild(this.root.firstChild)}},$i=`slicc-theme`,ea=new Set([`dark`,`light`,`system`]);function ta(){let e=localStorage.getItem($i);return e&&ea.has(e)?e:`system`}function na(){let e=ta(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t)}var ra;function ia(){na(),ra=window.matchMedia?.(`(prefers-color-scheme: light)`),ra?.addEventListener?.(`change`,()=>{ta()===`system`&&na()})}var aa=300,oa=6,sa=null,ca=null;function la(){return sa||(sa=document.createElement(`div`),sa.className=`s2-tooltip`,document.body.appendChild(sa)),sa}function ua(e){let t=e.getAttribute(`data-tooltip`);if(!t)return;let n=la();n.textContent=t,n.classList.remove(`s2-tooltip--visible`),n.style.left=`0`,n.style.top=`0`;let r=e.getBoundingClientRect(),i=n.getBoundingClientRect(),a=e.getAttribute(`data-tooltip-pos`)||`bottom`,o,s;a===`top`?(o=r.top-i.height-oa,s=r.left+r.width/2-i.width/2):a===`right`?(o=r.top+r.height/2-i.height/2,s=r.right+oa):(o=r.bottom+oa,s=r.left+r.width/2-i.width/2),a===`bottom`&&o+i.height>window.innerHeight-4?o=r.top-i.height-oa:a===`top`&&o<4&&(o=r.bottom+oa),s<4&&(s=4),s+i.width>window.innerWidth-4&&(s=window.innerWidth-i.width-4),n.style.top=`${o}px`,n.style.left=`${s}px`,n.classList.add(`s2-tooltip--visible`)}function da(){ca&&=(clearTimeout(ca),null),sa?.classList.remove(`s2-tooltip--visible`)}function fa(){document.addEventListener(`pointerenter`,e=>{let t=e.target.closest?.(`[data-tooltip]`);t&&(da(),ca=setTimeout(()=>ua(t),aa))},!0),document.addEventListener(`pointerleave`,e=>{e.target.closest?.(`[data-tooltip]`)&&da()},!0),document.addEventListener(`pointerdown`,da,!0)}function pa(e){return e.toLowerCase().endsWith(ae)}function ma(e){return Array.from(e).find(e=>pa(e.name))??null}function ha(e){if(!e)return!1;if(e.items){for(let t of Array.from(e.items))if(t.kind===`file`)return!0}return!1}function ga(e){if(!e)return null;if(e.files){let t=ma(e.files);if(t)return t}if(!e.items)return null;for(let t of Array.from(e.items)){if(t.kind&&t.kind!==`file`)continue;let e=t.getAsFile?.();if(e&&pa(e.name))return e}return null}var _a=new Map,va=new Map;function ya(e){let t=e.length;return t===0?`0`:`${t}:${e.charCodeAt(0)}:${t>1?e.charCodeAt(1):0}:${t>2?e.charCodeAt(2):0}:${t>3?e.charCodeAt(3):0}:${t>4?e.charCodeAt(Math.floor(t/4)):0}:${t>4?e.charCodeAt(Math.floor(t/2)):0}:${t>4?e.charCodeAt(Math.floor(3*t/4)):0}:${e.charCodeAt(t-1)}`}function ba(e,t){let n=ya(e);_a.set(n,t),setTimeout(()=>_a.delete(n),1e4)}function xa(e,t){va.set(e,t),setTimeout(()=>va.delete(e),1e4)}function Sa(e){let t=va.get(e);return t?(va.delete(e),t):null}function Ca(e){let t=ya(e),n=_a.get(t);return n?(_a.delete(t),n):null}var wa=class{registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}async readFile(e,t){let n=R(e),r=await this.vfs.readFile(n,{encoding:`binary`}),i=r instanceof Uint8Array?r:new TextEncoder().encode(r);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}catch{let e=Array(i.length);for(let t=0;t<i.length;t++)e[t]=String.fromCharCode(i[t]);return e.join(``)}}async readFileBuffer(e){let t=R(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}async writeFile(e,t,n){let r=R(e);if(typeof t==`string`){let e=Ca(t);if(e){await this.vfs.writeFile(r,e);return}let n=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){n=!0;break}if(n)await this.vfs.writeFile(r,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(r,e)}}else await this.vfs.writeFile(r,t)}async appendFile(e,t,n){let r=R(e),i=new Uint8Array;try{let e=await this.vfs.readFile(r,{encoding:`binary`});i=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof L&&e.code===`ENOENT`))throw e}let a;if(typeof t==`string`){a=new Uint8Array(t.length);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e)&255}else a=t instanceof Uint8Array?t:new Uint8Array(t);let o=new Uint8Array(i.length+a.length);o.set(i),o.set(a,i.length),await this.vfs.writeFile(r,o)}async exists(e){let t=R(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)}async stat(e){let t=R(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=await this.vfs.stat(t);return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)}}async lstat(e){let t=R(e),n=await this.vfs.lstat(t);return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)}}async mkdir(e,t){await this.vfs.mkdir(R(e),t)}async readdir(e){let t=R(e);return t===`/usr`?[`bin`]:t===`/usr/bin`?this.getVirtualBinCommands().slice().sort():(await this.vfs.readDir(t)).map(e=>e.name)}async readdirWithFileTypes(e){let t=R(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=await this.vfs.readDir(t),r=[];for(let e of n)if(e.type===`symlink`){let n=!1,i=!1;try{let r=t===`/`?`/${e.name}`:`${t}/${e.name}`,a=await this.vfs.stat(r);n=a.type===`file`,i=a.type===`directory`}catch{}r.push({name:e.name,isFile:n,isDirectory:i,isSymbolicLink:!0})}else r.push({name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1});return r}async rm(e,t){await this.vfs.rm(R(e),t)}async cp(e,t,n){let r=R(e),i=R(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new L(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=ce(e,r.name),i=ce(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){await this.vfs.rename(R(e),R(t))}resolvePath(e,t){return t.startsWith(`/`)?R(t):R(ce(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){await this.vfs.symlink(e,R(t))}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.vfs.readlink(R(e))}async realpath(e){return this.vfs.realpath(R(e))}async utimes(e,t,n){}},Ta=new TextDecoder;function Ea(e){return typeof e==`string`?e:Ta.decode(e)}function Da(e){return JSON.parse(Ea(e))}function Oa(e){if(typeof e!=`string`)return e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}var ka=t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),Aa=t((e=>{e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),ja=t((e=>{var t=ka(),n=Aa(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;var i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,`parent`,{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,`offset`,{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(ye(e,ArrayBuffer)||e&&ye(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(ye(e,SharedArrayBuffer)||e&&ye(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);let i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){let t=e.length<0?0:_(e.length)|0,n=o(t);for(let r=0;r<t;r+=1)n[r]=e[r]&255;return n}function m(e){if(ye(e,Uint8Array)){let t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return p(e)}function h(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);let r;return r=t===void 0&&n===void 0?new Uint8Array(e):n===void 0?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function g(e){if(s.isBuffer(e)){let t=_(e.length)|0,n=o(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||be(e.length)?o(0):p(e);if(e.type===`Buffer`&&Array.isArray(e.data))return p(e.data)}function _(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(ye(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),ye(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},s.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return s.alloc(0);let n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;let r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){let t=e[n];if(ye(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else if(s.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||ye(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return me(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return _e(e).length;default:if(i)return r?-1:me(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return re(this,t,n);case`utf8`:case`utf-8`:return ee(this,t,n);case`ascii`:return te(this,t,n);case`latin1`:case`binary`:return ne(this,t,n);case`base64`:return k(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return ie(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;t<e;t+=2)x(this,t,t+1);return this},s.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let t=0;t<e;t+=4)x(this,t,t+3),x(this,t+1,t+2);return this},s.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let t=0;t<e;t+=8)x(this,t,t+7),x(this,t+1,t+6),x(this,t+2,t+5),x(this,t+3,t+4);return this},s.prototype.toString=function(){let e=this.length;return e===0?``:arguments.length===0?ee(this,0,e):b.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e?!0:s.compare(this,e)===0},s.prototype.inspect=function(){let t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(ye(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){a=l[e],o=u[e];break}return a<o?-1:+(o<a)};function S(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,be(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0)if(i)n=0;else return-1;if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:C(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function C(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,r===-1?0:l-r)){if(r===-1&&(r=l),l-r+1===s)return r*a}else r!==-1&&(l-=l-r),r=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;r<s;r++)if(c(e,l+r)!==c(t,r)){n=!1;break}if(n)return l}return-1}s.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},s.prototype.indexOf=function(e,t,n){return S(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return S(this,e,t,n,!1)};function w(e,t,n,r){n=Number(n)||0;let i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o;for(o=0;o<r;++o){let r=parseInt(t.substr(o*2,2),16);if(be(r))return o;e[n+o]=r}return o}function T(e,t,n,r){return ve(me(t,e.length-n),e,n,r)}function E(e,t,n,r){return ve(he(t),e,n,r)}function D(e,t,n,r){return ve(_e(t),e,n,r)}function O(e,t,n,r){return ve(ge(t,e.length-n),e,n,r)}s.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return w(this,e,t,n);case`utf8`:case`utf-8`:return T(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return E(this,e,t,n);case`base64`:return D(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return O(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function k(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function ee(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i<n;){let t=e[i],a=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return j(r)}var A=4096;function j(e){let t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=A));return n}function te(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function ne(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function re(e,t,n){let r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i=``;for(let r=t;r<n;++r)i+=xe[e[r]];return i}function ie(e,t,n){let r=e.slice(t,n),i=``;for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+r[e+1]*256);return i}s.prototype.slice=function(e,t){let n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);let r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r};function M(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(e,this.length-8);let r=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(e,this.length-8);let r=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)}),s.prototype.readBigInt64BE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!1,52,8)};function N(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a<n&&(i*=256);)this[t+a]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function P(e,t,n,r,i){R(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function ae(e,t,n,r,i){R(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}s.prototype.writeBigUInt64LE=Se(function(e,t=0){return P(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=Se(function(e,t=0){return ae(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i<n&&(a*=256);)e<0&&o===0&&this[t+i-1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeBigInt64LE=Se(function(e,t=0){return P(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=Se(function(e,t=0){return ae(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function F(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function oe(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return oe(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return oe(this,e,t,!1,n)};function I(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return I(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return I(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);let i=r-n;return this===e&&typeof Uint8Array.prototype.copyWithin==`function`?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},s.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!s.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){let t=e.charCodeAt(0);(r===`utf8`&&t<128||r===`latin1`)&&(e=t)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i<n;++i)this[i]=e;else{let a=s.isBuffer(e)?e:s.from(e,r),o=a.length;if(o===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(i=0;i<n-t;++i)this[i+t]=a[i%o]}return this};var L={};function se(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,`message`,{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,`code`,{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}se(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),se(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),se(`ERR_OUT_OF_RANGE`,function(e,t,n){let r=`The value of "${e}" is out of range.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=ce(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=ce(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function ce(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function le(e,t,n){ue(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&de(t,e.length-(n+1))}function R(e,t,n,r,i,a){if(e>n||e<t){let r=typeof t==`bigint`?`n`:``,i;throw i=a>3?t===0||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${(a+1)*8}${r}`:`>= -(2${r} ** ${(a+1)*8-1}${r}) and < 2 ** ${(a+1)*8-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new L.ERR_OUT_OF_RANGE(`value`,i,e)}le(r,i,a)}function ue(e,t){if(typeof e!=`number`)throw new L.ERR_INVALID_ARG_TYPE(t,`number`,e)}function de(e,t,n){throw Math.floor(e)===e?t<0?new L.ERR_BUFFER_OUT_OF_BOUNDS:new L.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(ue(e,n),new L.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}var fe=/[^+/0-9A-Za-z-_]/g;function pe(e){if(e=e.split(`=`)[0],e=e.trim().replace(fe,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function me(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}else if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function he(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function ge(e,t){let n,r,i,a=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function _e(e){return t.toByteArray(pe(e))}function ve(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function ye(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function be(e){return e!==e}var xe=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function Se(e){return typeof BigInt>`u`?Ce:e}function Ce(){throw Error(`BigInt not supported`)}})),Ma=ja();globalThis.Buffer===void 0&&(globalThis.Buffer=Ma.Buffer);var Na=t(((e,t)=>{var n=function(e){if(e||={},this.Promise=e.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=e.domainReentrant||!1,this.domainReentrant){if(typeof process>`u`||process.domain===void 0)throw Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=e.timeout||n.DEFAULT_TIMEOUT,this.maxOccupationTime=e.maxOccupationTime||n.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=e.maxExecutionTime||n.DEFAULT_MAX_EXECUTION_TIME,e.maxPending===1/0||Number.isInteger(e.maxPending)&&e.maxPending>=0?this.maxPending=e.maxPending:this.maxPending=n.DEFAULT_MAX_PENDING};n.DEFAULT_TIMEOUT=0,n.DEFAULT_MAX_OCCUPATION_TIME=0,n.DEFAULT_MAX_EXECUTION_TIME=0,n.DEFAULT_MAX_PENDING=1e3,n.prototype.acquire=function(e,t,n,r){if(Array.isArray(e))return this._acquireBatch(e,t,n,r);if(typeof t!=`function`)throw Error(`You must pass a function to execute`);var i=null,a=null,o=null;typeof n!=`function`&&(r=n,n=null,o=new this.Promise(function(e,t){i=e,a=t})),r||={};var s=!1,c=null,l=null,u=null,d=this,f=function(t,r,c){l&&=(clearTimeout(l),null),u&&=(clearTimeout(u),null),t&&(d.queues[e]&&d.queues[e].length===0&&delete d.queues[e],d.domainReentrant&&delete d.domains[e]),s||=(o?r?a(r):i(c):typeof n==`function`&&n(r,c),!0),t&&d.queues[e]&&d.queues[e].length>0&&d.queues[e].shift()()},p=function(n){if(s)return f(n);c&&=(clearTimeout(c),null),d.domainReentrant&&n&&(d.domains[e]=process.domain);var i=r.maxExecutionTime||d.maxExecutionTime;if(i&&(u=setTimeout(function(){d.queues[e]&&f(n,Error(`Maximum execution time is exceeded `+e))},i)),t.length===1){var a=!1;try{t(function(e,t){a||(a=!0,f(n,e,t))})}catch(e){a||(a=!0,f(n,e))}}else d._promiseTry(function(){return t()}).then(function(e){f(n,void 0,e)},function(e){f(n,e)})};d.domainReentrant&&process.domain&&(p=process.domain.bind(p));var m=r.maxPending||d.maxPending;if(!d.queues[e])d.queues[e]=[],p(!0);else if(d.domainReentrant&&process.domain&&process.domain===d.domains[e])p(!1);else if(d.queues[e].length>=m)f(!1,Error(`Too many pending tasks in queue `+e));else{var h=function(){p(!0)};r.skipQueue?d.queues[e].unshift(h):d.queues[e].push(h);var g=r.timeout||d.timeout;g&&(c=setTimeout(function(){c=null,f(!1,Error(`async-lock timed out in queue `+e))},g))}var _=r.maxOccupationTime||d.maxOccupationTime;if(_&&(l=setTimeout(function(){d.queues[e]&&f(!1,Error(`Maximum occupation time is exceeded in queue `+e))},_)),o)return o},n.prototype._acquireBatch=function(e,t,n,r){typeof n!=`function`&&(r=n,n=null);var i=this,a=function(e,t){return function(n){i.acquire(e,t,n,r)}},o=e.reduceRight(function(e,t){return a(t,e)},t);if(typeof n==`function`)o(n);else return new this.Promise(function(e,t){o.length===1?o(function(n,r){n?t(n):e(r)}):e(o())})},n.prototype.isBusy=function(e){return e?!!this.queues[e]:Object.keys(this.queues).length>0},n.prototype._promiseTry=function(e){try{return this.Promise.resolve(e())}catch(e){return this.Promise.reject(e)}},t.exports=n})),Pa=t(((e,t)=>{t.exports=Na()})),Fa=t(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Ia=t(((e,t)=>{var n=ja(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),La=t(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),Ra=t(((e,t)=>{t.exports=TypeError})),za=t(((e,t)=>{t.exports=Object})),Ba=t(((e,t)=>{t.exports=Error})),Va=t(((e,t)=>{t.exports=EvalError})),Ha=t(((e,t)=>{t.exports=RangeError})),Ua=t(((e,t)=>{t.exports=ReferenceError})),Wa=t(((e,t)=>{t.exports=SyntaxError})),Ga=t(((e,t)=>{t.exports=URIError})),Ka=t(((e,t)=>{t.exports=Math.abs})),qa=t(((e,t)=>{t.exports=Math.floor})),Ja=t(((e,t)=>{t.exports=Math.max})),Ya=t(((e,t)=>{t.exports=Math.min})),Xa=t(((e,t)=>{t.exports=Math.pow})),Za=t(((e,t)=>{t.exports=Math.round})),Qa=t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),$a=t(((e,t)=>{var n=Qa();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),eo=t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),to=t(((e,t)=>{var n=eo();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),no=t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),ro=t(((e,t)=>{t.exports=function(){if(typeof Symbol!=`function`||typeof Object.getOwnPropertySymbols!=`function`)return!1;if(typeof Symbol.iterator==`symbol`)return!0;var e={},t=Symbol(`test`),n=Object(t);if(typeof t==`string`||Object.prototype.toString.call(t)!==`[object Symbol]`||Object.prototype.toString.call(n)!==`[object Symbol]`)return!1;var r=42;for(var i in e[t]=r,e)return!1;if(typeof Object.keys==`function`&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames==`function`&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor==`function`){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==r||o.enumerable!==!0)return!1}return!0}})),io=t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=ro();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),ao=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),oo=t(((e,t)=>{t.exports=za().getPrototypeOf||null})),so=t(((e,t)=>{var n=`Function.prototype.bind called on incompatible `,r=Object.prototype.toString,i=Math.max,a=`[object Function]`,o=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},s=function(e,t){for(var n=[],r=t||0,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n},c=function(e,t){for(var n=``,r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=t);return n};t.exports=function(e){var t=this;if(typeof t!=`function`||r.apply(t)!==a)throw TypeError(n+t);for(var l=s(arguments,1),u,d=function(){if(this instanceof u){var n=t.apply(this,o(l,arguments));return Object(n)===n?n:this}return t.apply(e,o(l,arguments))},f=i(0,t.length-l.length),p=[],m=0;m<f;m++)p[m]=`$`+m;if(u=Function(`binder`,`return function (`+c(p,`,`)+`){ return binder.apply(this,arguments); }`)(d),t.prototype){var h=function(){};h.prototype=t.prototype,u.prototype=new h,h.prototype=null}return u}})),co=t(((e,t)=>{var n=so();t.exports=Function.prototype.bind||n})),lo=t(((e,t)=>{t.exports=Function.prototype.call})),uo=t(((e,t)=>{t.exports=Function.prototype.apply})),fo=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),po=t(((e,t)=>{var n=co(),r=uo(),i=lo();t.exports=fo()||n.call(i,r)})),mo=t(((e,t)=>{var n=co(),r=Ra(),i=lo(),a=po();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),ho=t(((e,t)=>{var n=mo(),r=to(),i;try{i=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!=`object`||!(`code`in e)||e.code!==`ERR_PROTO_ACCESS`)throw e}var a=!!i&&r&&r(Object.prototype,`__proto__`),o=Object,s=o.getPrototypeOf;t.exports=a&&typeof a.get==`function`?n([a.get]):typeof s==`function`?function(e){return s(e==null?e:o(e))}:!1})),go=t(((e,t)=>{var n=ao(),r=oo(),i=ho();t.exports=n?function(e){return n(e)}:r?function(e){if(!e||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`getProto: not an object`);return r(e)}:i?function(e){return i(e)}:null})),_o=t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=co().call(n,r)})),vo=t(((e,t)=>{var n,r=za(),i=Ba(),a=Va(),o=Ha(),s=Ua(),c=Wa(),l=Ra(),u=Ga(),d=Ka(),f=qa(),p=Ja(),m=Ya(),h=Xa(),g=Za(),_=$a(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=to(),x=no(),S=function(){throw new l},C=b?function(){try{return arguments.callee,S}catch{try{return b(arguments,`callee`).get}catch{return S}}}():S,w=io()(),T=go(),E=oo(),D=ao(),O=uo(),k=lo(),ee={},A=typeof Uint8Array>`u`||!T?n:T(Uint8Array),j={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":ee,"%AsyncGenerator%":ee,"%AsyncGeneratorFunction%":ee,"%AsyncIteratorPrototype%":ee,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":ee,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":A,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":k,"%Function.prototype.apply%":O,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){j[`%Error.prototype%`]=T(T(e))}var te=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return j[t]=n,n},ne={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},re=co(),ie=_o(),M=re.call(k,Array.prototype.concat),N=re.call(O,Array.prototype.splice),P=re.call(k,String.prototype.replace),ae=re.call(k,String.prototype.slice),F=re.call(k,RegExp.prototype.exec),oe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,I=/\\(\\)?/g,L=function(e){var t=ae(e,0,1),n=ae(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return P(e,oe,function(e,t,n,i){r[r.length]=n?P(i,I,`$1`):t||e}),r},se=function(e,t){var n=e,r;if(ie(ne,n)&&(r=ne[n],n=`%`+r[0]+`%`),ie(j,n)){var i=j[n];if(i===ee&&(i=te(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(F(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=L(e),r=n.length>0?n[0]:``,i=se(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],N(n,M([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=ae(p,0,1),h=ae(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,ie(j,a))o=j[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=ie(o,p),o=o[p];f&&!s&&(j[a]=o)}}return o}})),yo=t(((e,t)=>{var n=vo(),r=mo(),i=r([n(`%String.prototype.indexOf%`)]);t.exports=function(e,t){var a=n(e,!!t);return typeof a==`function`&&i(e,`.prototype.`)>-1?r([a]):a}})),bo=t(((e,t)=>{var n=Function.prototype.toString,r=typeof Reflect==`object`&&Reflect!==null&&Reflect.apply,i,a;if(typeof r==`function`&&typeof Object.defineProperty==`function`)try{i=Object.defineProperty({},`length`,{get:function(){throw a}}),a={},r(function(){throw 42},null,i)}catch(e){e!==a&&(r=null)}else r=null;var o=/^\s*class\b/,s=function(e){try{var t=n.call(e);return o.test(t)}catch{return!1}},c=function(e){try{return s(e)?!1:(n.call(e),!0)}catch{return!1}},l=Object.prototype.toString,u=`[object Object]`,d=`[object Function]`,f=`[object GeneratorFunction]`,p=`[object HTMLAllCollection]`,m=`[object HTML document.all class]`,h=`[object HTMLCollection]`,g=typeof Symbol==`function`&&!!Symbol.toStringTag,_=!(0 in[,]),v=function(){return!1};if(typeof document==`object`){var y=document.all;l.call(y)===l.call(document.all)&&(v=function(e){if((_||!e)&&(e===void 0||typeof e==`object`))try{var t=l.call(e);return(t===p||t===m||t===h||t===u)&&e(``)==null}catch{}return!1})}t.exports=r?function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;try{r(e,null,i)}catch(e){if(e!==a)return!1}return!s(e)&&c(e)}:function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;if(g)return c(e);if(s(e))return!1;var t=l.call(e);return t!==d&&t!==f&&!/^\[object HTML/.test(t)?!1:c(e)}})),xo=t(((e,t)=>{var n=bo(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(e,t,n){for(var r=0,a=e.length;r<a;r++)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))},o=function(e,t,n){for(var r=0,i=e.length;r<i;r++)n==null?t(e.charAt(r),r,e):t.call(n,e.charAt(r),r,e)},s=function(e,t,n){for(var r in e)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))};function c(e){return r.call(e)===`[object Array]`}t.exports=function(e,t,r){if(!n(t))throw TypeError(`iterator must be a function`);var i;arguments.length>=3&&(i=r),c(e)?a(e,t,i):typeof e==`string`?o(e,t,i):s(e,t,i)}})),So=t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),Co=t(((e,t)=>{var n=So(),r=globalThis;t.exports=function(){for(var e=[],t=0;t<n.length;t++)typeof r[n[t]]==`function`&&(e[e.length]=n[t]);return e}})),wo=t(((e,t)=>{var n=no(),r=Wa(),i=Ra(),a=to();t.exports=function(e,t,o){if(!e||typeof e!=`object`&&typeof e!=`function`)throw new i("`obj` must be an object or a function`");if(typeof t!=`string`&&typeof t!=`symbol`)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=`boolean`&&arguments[3]!==null)throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=`boolean`&&arguments[4]!==null)throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=`boolean`&&arguments[5]!==null)throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=`boolean`)throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!a&&a(e,t);if(n)n(e,t,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:o,writable:c===null&&d?d.writable:!c});else if(u||!s&&!c&&!l)e[t]=o;else throw new r(`This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.`)}})),To=t(((e,t)=>{var n=no(),r=function(){return!!n};r.hasArrayLengthDefineBug=function(){if(!n)return null;try{return n([],`length`,{value:1}).length!==1}catch{return!0}},t.exports=r})),Eo=t(((e,t)=>{var n=vo(),r=wo(),i=To()(),a=to(),o=Ra(),s=n(`%Math.floor%`);t.exports=function(e,t){if(typeof e!=`function`)throw new o("`fn` is not a function");if(typeof t!=`number`||t<0||t>4294967295||s(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],c=!0,l=!0;if(`length`in e&&a){var u=a(e,`length`);u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!n)&&(i?r(e,`length`,t,!0,!0):r(e,`length`,t)),e}})),Do=t(((e,t)=>{var n=co(),r=uo(),i=po();t.exports=function(){return i(n,r,arguments)}})),Oo=t(((e,t)=>{var n=Eo(),r=no(),i=mo(),a=Do();t.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},r?r(t.exports,`apply`,{value:a}):t.exports.apply=a})),ko=t(((e,t)=>{var n=ro();t.exports=function(){return n()&&!!Symbol.toStringTag}})),Ao=t(((e,t)=>{var n=xo(),r=Co(),i=Oo(),a=yo(),o=to(),s=go(),c=a(`Object.prototype.toString`),l=ko()(),u=globalThis,d=r(),f=a(`String.prototype.slice`),p=a(`Array.prototype.indexOf`,!0)||function(e,t){for(var n=0;n<e.length;n+=1)if(e[n]===t)return n;return-1},m={__proto__:null};l&&o&&s?n(d,function(e){var t=new u[e];if(Symbol.toStringTag in t&&s){var n=s(t),r=o(n,Symbol.toStringTag);if(!r&&n&&(r=o(s(n),Symbol.toStringTag)),r&&r.get){var a=i(r.get);m[`$`+e]=a}}}):n(d,function(e){var t=new u[e],n=t.slice||t.set;if(n){var r=i(n);m[`$`+e]=r}});var h=function(e){var t=!1;return n(m,function(n,r){if(!t)try{`$`+n(e)===r&&(t=f(r,1))}catch{}}),t},g=function(e){var t=!1;return n(m,function(n,r){if(!t)try{n(e),t=f(r,1)}catch{}}),t};t.exports=function(e){if(!e||typeof e!=`object`)return!1;if(!l){var t=f(c(e),8,-1);return p(d,t)>-1?t:t===`Object`?g(e):!1}return o?h(e):null}})),jo=t(((e,t)=>{var n=Ao();t.exports=function(e){return!!n(e)}})),Mo=t(((e,t)=>{var n=Ra(),r=yo()(`TypedArray.prototype.buffer`,!0),i=jo();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),No=t(((e,t)=>{var n=Ia().Buffer,r=La(),i=Mo(),a=ArrayBuffer.isView||function(e){try{return i(e),!0}catch{return!1}},o=typeof Uint8Array<`u`,s=typeof ArrayBuffer<`u`&&typeof Uint8Array<`u`,c=s&&(n.prototype instanceof Uint8Array||n.TYPED_ARRAY_SUPPORT);t.exports=function(e,t){if(n.isBuffer(e))return e.constructor&&!(`isBuffer`in e)?n.from(e):e;if(typeof e==`string`)return n.from(e,t);if(s&&a(e)){if(e.byteLength===0)return n.alloc(0);if(c){var i=n.from(e.buffer,e.byteOffset,e.byteLength);if(i.byteLength===e.byteLength)return i}var l=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=n.from(l);if(u.length===e.byteLength)return u}if(o&&e instanceof Uint8Array)return n.from(e);var d=r(e);if(d)for(var f=0;f<e.length;f+=1){var p=e[f];if(typeof p!=`number`||p<0||p>255||~~p!==p)throw RangeError(`Array items must be numbers in the range 0-255.`)}if(d||n.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer==`function`&&e.constructor.isBuffer(e))return n.from(e);throw TypeError(`The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.`)}})),Po=t(((e,t)=>{var n=Ia().Buffer,r=No();function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){e=r(e,t||`utf8`);for(var n=this._block,i=this._blockSize,a=e.length,o=this._len,s=0;s<a;){for(var c=o%i,l=Math.min(a-s,i-c),u=0;u<l;u++)n[c+u]=e[s+u];o+=l,s+=l,o%i===0&&this._update(n)}return this._len+=a,this},i.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var n=this._len*8;if(n<=4294967295)this._block.writeUInt32BE(n,this._blockSize-4);else{var r=(n&4294967295)>>>0,i=(n-r)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(r,this._blockSize-4)}this._update(this._block);var a=this._hash();return e?a.toString(e):a},i.prototype._update=function(){throw Error(`_update must be implemented by subclass`)},t.exports=i})),Fo=t(((e,t)=>{var n=Fa(),r=Po(),i=Ia().Buffer,a=[1518500249,1859775393,-1894007588,-899497514],o=Array(80);function s(){this.init(),this._w=o,r.call(this,64,56)}n(s,r),s.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function c(e){return e<<1|e>>>31}function l(e){return e<<5|e>>>27}function u(e){return e<<30|e>>>2}function d(e,t,n,r){return e===0?t&n|~t&r:e===2?t&n|t&r|n&r:t^n^r}s.prototype._update=function(e){for(var t=this._w,n=this._a|0,r=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,f=0;f<16;++f)t[f]=e.readInt32BE(f*4);for(;f<80;++f)t[f]=c(t[f-3]^t[f-8]^t[f-14]^t[f-16]);for(var p=0;p<80;++p){var m=~~(p/20),h=l(n)+d(m,r,i,o)+s+t[p]+a[m]|0;s=o,o=i,i=u(r),r=n,n=h}this._a=n+this._a|0,this._b=r+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0},s.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e},t.exports=s})),Io=t((e=>{(function(t){typeof DO_NOT_EXPORT_CRC>`u`?typeof e==`object`?t(e):typeof define==`function`&&define.amd?define(function(){var e={};return t(e),e}):t({}):t({})})(function(e){e.version=`1.2.2`;function t(){for(var e=0,t=Array(256),n=0;n!=256;++n)e=n,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,t[n]=e;return typeof Int32Array<`u`?new Int32Array(t):t}var n=t();function r(e){var t=0,n=0,r=0,i=typeof Int32Array<`u`?new Int32Array(4096):Array(4096);for(r=0;r!=256;++r)i[r]=e[r];for(r=0;r!=256;++r)for(n=e[r],t=256+r;t<4096;t+=256)n=i[t]=n>>>8^e[n&255];var a=[];for(r=1;r!=16;++r)a[r-1]=typeof Int32Array<`u`?i.subarray(r*256,r*256+256):i.slice(r*256,r*256+256);return a}var i=r(n),a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14];function b(e,t){for(var r=t^-1,i=0,a=e.length;i<a;)r=r>>>8^n[(r^e.charCodeAt(i++))&255];return~r}function x(e,t){for(var r=t^-1,i=e.length-15,b=0;b<i;)r=y[e[b++]^r&255]^v[e[b++]^r>>8&255]^_[e[b++]^r>>16&255]^g[e[b++]^r>>>24]^h[e[b++]]^m[e[b++]]^p[e[b++]]^f[e[b++]]^d[e[b++]]^u[e[b++]]^l[e[b++]]^c[e[b++]]^s[e[b++]]^o[e[b++]]^a[e[b++]]^n[e[b++]];for(i+=15;b<i;)r=r>>>8^n[(r^e[b++])&255];return~r}function S(e,t){for(var r=t^-1,i=0,a=e.length,o=0,s=0;i<a;)o=e.charCodeAt(i++),o<128?r=r>>>8^n[(r^o)&255]:o<2048?(r=r>>>8^n[(r^(192|o>>6&31))&255],r=r>>>8^n[(r^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,s=e.charCodeAt(i++)&1023,r=r>>>8^n[(r^(240|o>>8&7))&255],r=r>>>8^n[(r^(128|o>>2&63))&255],r=r>>>8^n[(r^(128|s>>6&15|(o&3)<<4))&255],r=r>>>8^n[(r^(128|s&63))&255]):(r=r>>>8^n[(r^(224|o>>12&15))&255],r=r>>>8^n[(r^(128|o>>6&63))&255],r=r>>>8^n[(r^(128|o&63))&255]);return~r}e.table=n,e.bstr=b,e.buf=x,e.str=S})})),Lo=t(((e,t)=>{var n=(e,t)=>function(...n){let r=t.promiseModule;return new r((r,i)=>{t.multiArgs?n.push((...e)=>{t.errorFirst?e[0]?i(e):(e.shift(),r(e)):r(e)}):t.errorFirst?n.push((e,t)=>{e?i(e):r(t)}):n.push(r),e.apply(this,n)})};t.exports=(e,t)=>{t=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},t);let r=typeof e;if(!(e!==null&&(r===`object`||r===`function`)))throw TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${e===null?`null`:r}\``);let i=e=>{let n=t=>typeof t==`string`?e===t:t.test(e);return t.include?t.include.some(n):!t.exclude.some(n)},a;a=r===`function`?function(...r){return t.excludeMain?e(...r):n(e,t).apply(this,r)}:Object.create(Object.getPrototypeOf(e));for(let r in e){let o=e[r];a[r]=typeof o==`function`&&i(r)?n(o,t):o}return a}})),Ro=t(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}var r=``,i=` `,a=`\\`,o=/^\s+$/,s=/(?:[^\\]|^)\\$/,c=/^\\!/,l=/^\\#/,u=/\r?\n/g,d=/^\.*\/|^\.+$/,f=`/`,p=`node-ignore`;typeof Symbol<`u`&&(p=Symbol.for(`node-ignore`));var m=p,h=(e,t,n)=>Object.defineProperty(e,t,{value:n}),g=/([0-z])-([0-z])/g,_=()=>!1,v=e=>e.replace(g,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:r),y=e=>{let{length:t}=e;return e.slice(0,t-t%2)},b=[[/^\uFEFF/,()=>r],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?i:r)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+i}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>a],[/\\\\/g,()=>a],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===a?`\\[${n}${y(r)}${i}`:i===`]`&&r.length%2==0?`[${v(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],x=Object.create(null),S=(e,t)=>{let n=x[e];return n||(n=b.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),x[e]=n),t?new RegExp(n,`i`):new RegExp(n)},C=e=>typeof e==`string`,w=e=>e&&C(e)&&!o.test(e)&&!s.test(e)&&e.indexOf(`#`)!==0,T=e=>e.split(u),E=class{constructor(e,t,n,r){this.origin=e,this.pattern=t,this.negative=n,this.regex=r}},D=(e,t)=>{let n=e,r=!1;e.indexOf(`!`)===0&&(r=!0,e=e.substr(1)),e=e.replace(c,`!`).replace(l,`#`);let i=S(e,t);return new E(n,e,r,i)},O=(e,t)=>{throw new t(e)},k=(e,t,n)=>C(e)?e?k.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),ee=e=>d.test(e);k.isNotRelative=ee,k.convert=e=>e;var A=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){h(this,m,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[m]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(w(e)){let t=D(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(C(e)?T(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,r=!1;return this._rules.forEach(i=>{let{negative:a}=i;r===a&&n!==r||a&&!n&&!r&&!t||i.regex.test(e)&&(n=!a,r=a)}),{ignored:n,unignored:r}}_test(e,t,n,r){let i=e&&k.convert(e);return k(i,e,this._allowRelativePaths?_:O),this._t(i,t,n,r)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(f),r.pop(),!r.length)return t[e]=this._testOne(e,n);let i=this._t(r.join(f)+f,t,n,r);return t[e]=i.ignored?i:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},j=e=>new A(e);if(j.isPathValid=e=>k(e&&k.convert(e),e,_),j.default=j,t.exports=j,typeof process<`u`&&({}.IGNORE_TEST_WIN32||process.platform===`win32`)){k.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;k.isNotRelative=t=>e.test(t)||ee(t)}})),zo=t(((e,t)=>{function n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function r(e,t,r){return t=t instanceof RegExp?t:new RegExp(n(t),`g`),e.replace(t,r)}t.exports={clean:function(e){if(typeof e!=`string`)throw Error(`Expected a string, received: `+e);return e=r(e,`./`,`/`),e=r(e,`..`,`.`),e=r(e,` `,`-`),e=r(e,/^[~^:?*\\\-]/g,``),e=r(e,/[~^:?*\\]/g,`-`),e=r(e,/[~^:?*\\\-]$/g,``),e=r(e,`@{`,`-`),e=r(e,/\.$/g,``),e=r(e,/\/$/g,``),e=r(e,/\.lock$/g,``),e}}})),Bo=t(((e,t)=>{t.exports=function(e,t){var n=e,r=t,i=n.length,a=r.length,o=!1,s=null,c=i+1,l=[],u=[],d=[],f=``,p=-1,m=0,h=1,g,_,v=function(){i>=a&&(g=n,_=i,n=r,r=g,i=a,a=_,o=!0,c=i+1)},y=function(e,t,n){return{x:e,y:t,k:n}},b=function(e,t){return{elem:e,t}},x=function(e,t,o){var s=t>o?l[e-1+c]:l[e+1+c],d,f=Math.max(t,o);for(d=f-e;d<i&&f<a&&n[d]===r[f];)++d,++f;return l[e+c]=u.length,u[u.length]=new y(d,f,s),f},S=function(e){var t=i=1,i,a=s=0,s,c;for(c=e.length-1;c>=0;--c)for(;a<e[c].x||s<e[c].y;)e[c].y-e[c].x>s-a?(o?d[d.length]=new b(r[s],p):d[d.length]=new b(r[s],h),++i,++s):e[c].y-e[c].x<s-a?(o?d[d.length]=new b(n[a],h):d[d.length]=new b(n[a],p),++t,++a):(d[d.length]=new b(n[a],m),f+=n[a],++t,++i,++a,++s)};return v(),{SES_DELETE:-1,SES_COMMON:0,SES_ADD:1,editdistance:function(){return s},getlcs:function(){return f},getses:function(){return d},compose:function(){var e=a-i,t=i+a+3,n={},r,o,d,f,p;for(f=0;f<t;++f)n[f]=-1,l[f]=-1;r=-1;do{for(++r,p=-r;p<=e-1;++p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);for(p=e+r;p>=e+1;--p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);n[e+c]=x(e,n[e-1+c]+1,n[e+1+c])}while(n[e+c]!==a);for(s=e+2*r,o=l[e+c],d=[];o!==-1;)d[d.length]=new y(u[o].x,u[o].y,null),o=u[o].k;S(d)}}}})),Vo=t(((e,t)=>{var n=Bo();function r(e,t){var r=new n(e,t);r.compose();for(var i=r.getses(),a,o,s=e.length-1,c=t.length-1,l=i.length-1;l>=0;--l)i[l].t===r.SES_COMMON?(o?(o.chain={file1index:s,file2index:c,chain:null},o=o.chain):(a={file1index:s,file2index:c,chain:null},o=a),s--,c--):i[l].t===r.SES_DELETE?s--:i[l].t===r.SES_ADD&&c--;var u={file1index:-1,file2index:-1,chain:null};return o?(o.chain=u,a):u}function i(e,t){for(var n=[],i=e.length,a=t.length,o=r(e,t);o!==null;o=o.chain){var s=i-o.file1index-1,c=a-o.file2index-1;i=o.file1index,a=o.file2index,(s||c)&&n.push({file1:[i+1,s],file2:[a+1,c]})}return n.reverse(),n}function a(e,t,n){var r,a=i(t,e),o=i(t,n),s=[];function c(e,t){s.push([e.file1[0],t,e.file1[1],e.file2[0],e.file2[1]])}for(r=0;r<a.length;r++)c(a[r],0);for(r=0;r<o.length;r++)c(o[r],2);s.sort(function(e,t){return e[0]-t[0]});var l=[],u=0;function d(e){e>u&&(l.push([1,u,e-u]),u=e)}for(var f=0;f<s.length;f++){for(var p=f,m=s[f],h=m[0],g=h+m[2];f<s.length-1;){var _=s[f+1],v=_[0];if(v>g)break;g=Math.max(g,v+_[2]),f++}if(d(h),p==f)m[4]>0&&l.push([m[1],m[3],m[4]]);else{var y={0:[e.length,-1,t.length,-1],2:[n.length,-1,t.length,-1]};for(r=p;r<=f;r++){m=s[r];var b=y[m[1]],x=m[0],S=x+m[2],C=m[3],w=C+m[4];b[0]=Math.min(C,b[0]),b[1]=Math.max(w,b[1]),b[2]=Math.min(x,b[2]),b[3]=Math.max(S,b[3])}var T=y[0][0]+(h-y[0][2]),E=y[0][1]+(g-y[0][3]),D=y[2][0]+(h-y[2][2]),O=y[2][1]+(g-y[2][3]);l.push([-1,T,E-T,h,g-h,D,O-D])}u=g}return d(t.length),l}function o(e,t,n){var r=[],i=[e,t,n],o=a(e,t,n),s=[];function c(){s.length&&r.push({ok:s}),s=[]}function l(e){for(var t=0;t<e.length;t++)s.push(e[t])}function u(t){if(t[2]!=t[6])return!0;for(var r=t[1],i=t[5],a=0;a<t[2];a++)if(e[a+r]!=n[a+i])return!0;return!1}for(var d=0;d<o.length;d++){var f=o[d],p=f[0];p==-1?u(f)?(c(),r.push({conflict:{a:e.slice(f[1],f[1]+f[2]),aIndex:f[1],o:t.slice(f[3],f[3]+f[4]),oIndex:f[3],b:n.slice(f[5],f[5]+f[6]),bIndex:f[5]}})):l(i[0].slice(f[1],f[1]+f[2])):l(i[p].slice(f[1],f[1]+f[2]))}return c(),r}t.exports=o})),Ho=e(Pa(),1),Uo=e(Fo(),1),Wo=e(Io(),1),Go=e(Je(),1),Ko=e(Lo(),1),qo=e(Ro(),1),Jo=e(zo(),1),Yo=e(Vo(),1),U=class e extends Error{constructor(e){super(e),this.caller=``}toJSON(){return{code:this.code,data:this.data,caller:this.caller,message:this.message,stack:this.stack}}fromJSON(t){let n=new e(t.message);return n.code=t.code,n.data=t.data,n.caller=t.caller,n.stack=t.stack,n}get isIsomorphicGitError(){return!0}},Xo=class e extends U{constructor(t){super(`Modifying the index is not possible because you have unmerged files: ${t.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`),this.code=this.name=e.code,this.data={filepaths:t}}};Xo.code=`UnmergedPathsError`;var W=class e extends U{constructor(t){super(`An internal error caused this command to fail.\n\nIf you're not a developer, report the bug to the developers of the application you're using. If this is a bug in isomorphic-git then you should create a proper bug yourselves. The bug should include a minimal reproduction and details about the version and environment.\n\nPlease file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${t}`),this.code=this.name=e.code,this.data={message:t}}};W.code=`InternalError`;var Zo=class e extends U{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};Zo.code=`UnsafeFilepathError`;var Qo=class{constructor(e){this.buffer=e,this._start=0}eof(){return this._start>=this.buffer.length}tell(){return this._start}seek(e){this._start=e}slice(e){let t=this.buffer.slice(this._start,this._start+e);return this._start+=e,t}toString(e,t){let n=this.buffer.toString(e,this._start,this._start+t);return this._start+=t,n}write(e,t,n){let r=this.buffer.write(e,this._start,t,n);return this._start+=t,r}copy(e,t,n){let r=e.copy(this.buffer,this._start,t,n);return this._start+=r,r}readUInt8(){let e=this.buffer.readUInt8(this._start);return this._start+=1,e}writeUInt8(e){let t=this.buffer.writeUInt8(e,this._start);return this._start+=1,t}readUInt16BE(){let e=this.buffer.readUInt16BE(this._start);return this._start+=2,e}writeUInt16BE(e){let t=this.buffer.writeUInt16BE(e,this._start);return this._start+=2,t}readUInt32BE(){let e=this.buffer.readUInt32BE(this._start);return this._start+=4,e}writeUInt32BE(e){let t=this.buffer.writeUInt32BE(e,this._start);return this._start+=4,t}};function $o(e,t){return-(e<t)||+(e>t)}function es(e,t){return $o(e.path,t.path)}function ts(e){let t=e>0?e>>12:0;t!==4&&t!==8&&t!==10&&t!==14&&(t=8);let n=e&511;return n=n&73?493:420,t!==8&&(n=0),(t<<12)+n}var ns=2**32;function rs(e,t,n,r){if(e!==void 0&&t!==void 0)return[e,t];n===void 0&&(n=r.valueOf());let i=Math.floor(n/1e3);return[i,(n-i*1e3)*1e6]}function is(e){let[t,n]=rs(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=rs(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%ns,ctimeNanoseconds:n%ns,mtimeSeconds:r%ns,mtimeNanoseconds:i%ns,dev:e.dev%ns,ino:e.ino%ns,mode:ts(e.mode%ns),uid:e.uid%ns,gid:e.gid%ns,size:e.size>-1?e.size%ns:0}}function as(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}var os=null;async function ss(e){return os===null&&(os=await us()),os?ls(e):cs(e)}function cs(e){return new Uo.default().update(e).digest(`hex`)}async function ls(e){return as(await crypto.subtle.digest(`SHA-1`,e))}async function us(){try{return await ls(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function ds(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function fs(e){let t=e.flags;return t.extended=!1,t.nameLength=Math.min(Buffer.from(e.path).length,4095),(t.assumeValid?32768:0)+(t.extended?16384:0)+((t.stage&3)<<12)+(t.nameLength&4095)}var ps=class e{constructor(e,t){this._dirty=!1,this._unmergedPaths=t||new Set,this._entries=e||new Map}_addEntry(e){if(e.flags.stage===0)e.stages=[e],this._entries.set(e.path,e),this._unmergedPaths.delete(e.path);else{let t=this._entries.get(e.path);t||=(this._entries.set(e.path,e),e),t.stages[e.flags.stage]=e,this._unmergedPaths.add(e.path)}}static async from(t){if(Buffer.isBuffer(t))return e.fromBuffer(t);if(t===null)return new e(null);throw new W(`invalid type passed to GitIndex.from`)}static async fromBuffer(t){if(t.length===0)throw new W(`Index file is empty (.git/index)`);let n=new e,r=new Qo(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new W(`Invalid dircache magic file number: ${i}`);let a=await ss(t.slice(0,-20)),o=t.slice(-20).toString(`hex`);if(o!==a)throw new W(`Invalid checksum in GitIndex buffer: expected ${o} but saw ${a}`);let s=r.readUInt32BE();if(s!==2)throw new W(`Unsupported dircache version: ${s}`);let c=r.readUInt32BE(),l=0;for(;!r.eof()&&l<c;){let e={};e.ctimeSeconds=r.readUInt32BE(),e.ctimeNanoseconds=r.readUInt32BE(),e.mtimeSeconds=r.readUInt32BE(),e.mtimeNanoseconds=r.readUInt32BE(),e.dev=r.readUInt32BE(),e.ino=r.readUInt32BE(),e.mode=r.readUInt32BE(),e.uid=r.readUInt32BE(),e.gid=r.readUInt32BE(),e.size=r.readUInt32BE(),e.oid=r.slice(20).toString(`hex`),e.flags=ds(r.readUInt16BE());let i=t.indexOf(0,r.tell()+1)-r.tell();if(i<1)throw new W(`Got a path length of: ${i}`);if(e.path=r.toString(`utf8`,i),e.path.includes(`..\\`)||e.path.includes(`../`))throw new Zo(e.path);let a=8-(r.tell()-12)%8;for(a===0&&(a=8);a--;){let t=r.readUInt8();if(t!==0)throw new W(`Expected 1-8 null characters but got '${t}' after ${e.path}`);if(r.eof())throw new W(`Unexpected end of file`)}e.stages=[],n._addEntry(e),l++}return n}get unmergedPaths(){return[...this._unmergedPaths]}get entries(){return[...this._entries.values()].sort(es)}get entriesMap(){return this._entries}get entriesFlat(){return[...this.entries].flatMap(e=>e.stages.length>1?e.stages.filter(e=>e):e)}*[Symbol.iterator](){for(let e of this.entries)yield e}insert({filepath:e,stats:t,oid:n,stage:r=0}){t||={ctimeSeconds:0,ctimeNanoseconds:0,mtimeSeconds:0,mtimeNanoseconds:0,dev:0,ino:0,mode:0,uid:0,gid:0,size:0},t=is(t);let i=Buffer.from(e),a={ctimeSeconds:t.ctimeSeconds,ctimeNanoseconds:t.ctimeNanoseconds,mtimeSeconds:t.mtimeSeconds,mtimeNanoseconds:t.mtimeNanoseconds,dev:t.dev,ino:t.ino,mode:t.mode||33188,uid:t.uid,gid:t.gid,size:t.size,path:e,oid:n,flags:{assumeValid:!1,extended:!1,stage:r,nameLength:i.length<4095?i.length:4095},stages:[]};this._addEntry(a),this._dirty=!0}delete({filepath:e}){if(this._entries.has(e))this._entries.delete(e);else for(let t of this._entries.keys())t.startsWith(e+`/`)&&this._entries.delete(t);this._unmergedPaths.has(e)&&this._unmergedPaths.delete(e),this._dirty=!0}clear(){this._entries.clear(),this._dirty=!0}has({filepath:e}){return this._entries.has(e)}render(){return this.entries.map(e=>`${e.mode.toString(8)} ${e.oid} ${e.path}`).join(`
726
+ `)}static async _entryToBuffer(e){let t=Buffer.from(e.path),n=Math.ceil((62+t.length+1)/8)*8,r=Buffer.alloc(n),i=new Qo(r),a=is(e);return i.writeUInt32BE(a.ctimeSeconds),i.writeUInt32BE(a.ctimeNanoseconds),i.writeUInt32BE(a.mtimeSeconds),i.writeUInt32BE(a.mtimeNanoseconds),i.writeUInt32BE(a.dev),i.writeUInt32BE(a.ino),i.writeUInt32BE(a.mode),i.writeUInt32BE(a.uid),i.writeUInt32BE(a.gid),i.writeUInt32BE(a.size),i.write(e.oid,20,`hex`),i.writeUInt16BE(fs(e)),i.write(e.path,t.length,`utf8`),r}async toObject(){let t=Buffer.alloc(12),n=new Qo(t);n.write(`DIRC`,4,`utf8`),n.writeUInt32BE(2),n.writeUInt32BE(this.entriesFlat.length);let r=[];for(let t of this.entries)if(r.push(e._entryToBuffer(t)),t.stages.length>1)for(let n of t.stages)n&&n!==t&&r.push(e._entryToBuffer(n));r=await Promise.all(r);let i=Buffer.concat(r),a=Buffer.concat([t,i]),o=await ss(a);return Buffer.concat([a,Buffer.from(o,`hex`)])}};function ms(e,t,n=!0,r=!0){let i=is(e),a=is(t);return n&&i.mode!==a.mode||i.mtimeSeconds!==a.mtimeSeconds||i.ctimeSeconds!==a.ctimeSeconds||i.uid!==a.uid||i.gid!==a.gid||r&&i.ino!==a.ino||i.size!==a.size}var hs=null,gs=Symbol(`IndexCache`);function _s(){return{map:new Map,stats:new Map}}async function vs(e,t,n){let[r,i]=await Promise.all([e.lstat(t),e.read(t)]),a=await ps.from(i);n.map.set(t,a),n.stats.set(t,r)}async function ys(e,t,n){let r=n.stats.get(t);if(r===void 0)return!0;if(r===null)return!1;let i=await e.lstat(t);return i===null?!1:ms(r,i)}var bs=class{static async acquire({fs:e,gitdir:t,cache:n,allowUnmerged:r=!0},i){n[gs]||(n[gs]=_s());let a=`${t}/index`;hs===null&&(hs=new Ho.default({maxPending:1/0}));let o,s=[];return await hs.acquire(a,async()=>{let t=n[gs];await ys(e,a,t)&&await vs(e,a,t);let c=t.map.get(a);if(s=c.unmergedPaths,s.length&&!r)throw new Xo(s);if(o=await i(c),c._dirty){let n=await c.toObject();await e.write(a,n),t.stats.set(a,await e.lstat(a)),c._dirty=!1}}),o}};function xs(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t>-1&&(e=e.slice(t+1)),e}function Ss(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t===-1?`.`:t===0?`/`:e.slice(0,t)}function Cs(e){let t=new Map,n=function(e){if(!t.has(e)){let r={type:`tree`,fullpath:e,basename:xs(e),metadata:{},children:[]};t.set(e,r),r.parent=n(Ss(e)),r.parent&&r.parent!==r&&r.parent.children.push(r)}return t.get(e)},r=function(e,r){if(!t.has(e)){let i={type:`blob`,fullpath:e,basename:xs(e),metadata:r,parent:n(Ss(e)),children:[]};i.parent&&i.parent.children.push(i),t.set(e,i)}return t.get(e)};n(`.`);for(let t of e)r(t.path,t);return t}function ws(e){switch(e){case 16384:return`tree`;case 33188:return`blob`;case 33261:return`blob`;case 40960:return`blob`;case 57344:return`commit`}throw new W(`Unexpected GitTree entry mode: ${e.toString(8)}`)}var Ts=class{constructor({fs:e,gitdir:t,cache:n}){this.treePromise=bs.acquire({fs:e,gitdir:t,cache:n},async function(e){return Cs(e.entries)});let r=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._oid=!1}async type(){return r.type(this)}async mode(){return r.mode(this)}async stat(){return r.stat(this)}async content(){return r.content(this)}async oid(){return r.oid(this)}}}async readdir(e){let t=e._fullpath,n=(await this.treePromise).get(t);if(!n||n.type===`blob`)return null;if(n.type!==`tree`)throw Error(`ENOTDIR: not a directory, scandir '${t}'`);let r=n.children.map(e=>e.fullpath);return r.sort($o),r}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let t=(await this.treePromise).get(e._fullpath);if(!t)throw Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let n=t.type===`tree`?{}:is(t.metadata);e._type=t.type===`tree`?`tree`:ws(n.mode),e._mode=n.mode,t.type===`tree`?e._stat=void 0:e._stat=n}return e._stat}async content(e){}async oid(e){return e._oid===!1&&(e._oid=(await this.treePromise).get(e._fullpath).metadata.oid),e._oid}},Es=Symbol(`GitWalkSymbol`);function Ds(){let e=Object.create(null);return Object.defineProperty(e,Es,{value:function({fs:e,gitdir:t,cache:n}){return new Ts({fs:e,gitdir:t,cache:n})}}),Object.freeze(e),e}var Os=class e extends U{constructor(t){super(`Could not find ${t}.`),this.code=this.name=e.code,this.data={what:t}}};Os.code=`NotFoundError`;var ks=class e extends U{constructor(t,n,r,i){super(`Object ${t} ${i?`at ${i}`:``}was anticipated to be a ${r} but it is a ${n}.`),this.code=this.name=e.code,this.data={oid:t,actual:n,expected:r,filepath:i}}};ks.code=`ObjectTypeError`;var As=class e extends U{constructor(t){super(`Expected a 40-char hex object id but saw "${t}".`),this.code=this.name=e.code,this.data={value:t}}};As.code=`InvalidOidError`;var js=class e extends U{constructor(t){super(`Could not find a fetch refspec for remote "${t}". Make sure the config file has an entry like the following:
727
727
  [remote "${t}"]
728
728
  \tfetch = +refs/heads/*:refs/remotes/origin/*
729
- `),this.code=this.name=e.code,this.data={remote:t}}};Ds.code=`NoRefspecError`;var Os=class e{constructor(e){if(this.refs=new Map,this.parsedConfig=[],e){let t=null;this.parsedConfig=e.trim().split(`
729
+ `),this.code=this.name=e.code,this.data={remote:t}}};js.code=`NoRefspecError`;var Ms=class e{constructor(e){if(this.refs=new Map,this.parsedConfig=[],e){let t=null;this.parsedConfig=e.trim().split(`
730
730
  `).map(e=>{if(/^\s*#/.test(e))return{line:e,comment:!0};let n=e.indexOf(` `);if(e.startsWith(`^`)){let n=e.slice(1);return this.refs.set(t+`^{}`,n),{line:e,ref:t,peeled:n}}else{let r=e.slice(0,n);return t=e.slice(n+1),this.refs.set(t,r),{line:e,ref:t,oid:r}}})}return this}static from(t){return new e(t)}delete(e){this.parsedConfig=this.parsedConfig.filter(t=>t.ref!==e),this.refs.delete(e)}toString(){return this.parsedConfig.map(({line:e})=>e).join(`
731
731
  `)+`
732
- `}},ks=class e{constructor({remotePath:e,localPath:t,force:n,matchPrefix:r}){Object.assign(this,{remotePath:e,localPath:t,force:n,matchPrefix:r})}static from(t){let[n,r,i,a,o]=t.match(/^(\+?)(.*?)(\*?):(.*?)(\*?)$/).slice(1),s=n===`+`,c=i===`*`;if(c!==(o===`*`))throw new W(`Invalid refspec`);return new e({remotePath:r,localPath:a,force:s,matchPrefix:c})}translate(e){if(this.matchPrefix){if(e.startsWith(this.remotePath))return this.localPath+e.replace(this.remotePath,``)}else if(e===this.remotePath)return this.localPath;return null}reverseTranslate(e){if(this.matchPrefix){if(e.startsWith(this.localPath))return this.remotePath+e.replace(this.localPath,``)}else if(e===this.localPath)return this.remotePath;return null}},As=class e{constructor(e=[]){this.rules=e}static from(t){let n=[];for(let e of t)n.push(ks.from(e));return new e(n)}add(e){let t=ks.from(e);this.rules.push(t)}translate(e){let t=[];for(let n of this.rules)for(let r of e){let e=n.translate(r);e&&t.push([r,e])}return t}translateOne(e){let t=null;for(let n of this.rules){let r=n.translate(e);r&&(t=r)}return t}localNamespaces(){return this.rules.filter(e=>e.matchPrefix).map(e=>e.localPath.replace(/\/$/,``))}};function js(e,t){let n=e.replace(/\^\{\}$/,``),r=t.replace(/\^\{\}$/,``),i=-(n<r)||+(n>r);return i===0?e.endsWith(`^{}`)?1:-1:i}function Ms(e,t){let n=``,r=0,i=-1,a=0,o=`\0`;for(let s=0;s<=e.length;++s){if(s<e.length)o=e[s];else if(o===`/`)break;else o=`/`;if(o===`/`){if(!(i===s-1||a===1))if(a===2){if(n.length<2||r!==2||n.at(-1)!==`.`||n.at(-2)!==`.`){if(n.length>2){let e=n.lastIndexOf(`/`);e===-1?(n=``,r=0):(n=n.slice(0,e),r=n.length-1-n.lastIndexOf(`/`)),i=s,a=0;continue}else if(n.length!==0){n=``,r=0,i=s,a=0;continue}}t&&(n+=n.length>0?`/..`:`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,s):n=e.slice(i+1,s),r=s-i-1;i=s,a=0}else o===`.`&&a!==-1?++a:a=-1}return n}function Ns(e){if(!e.length)return`.`;let t=e[0]===`/`,n=e.at(-1)===`/`;return e=Ms(e,!t),e.length?(n&&(e+=`/`),t?`/${e}`:e):t?`/`:n?`./`:`.`}function G(...e){if(e.length===0)return`.`;let t;for(let n=0;n<e.length;++n){let r=e[n];r.length>0&&(t===void 0?t=r:t+=`/`+r)}return t===void 0?`.`:Ns(t)}var Ps=e=>{if(typeof e==`number`)return e;e=e.toLowerCase();let t=parseInt(e);return e.endsWith(`k`)&&(t*=1024),e.endsWith(`m`)&&(t*=1024*1024),e.endsWith(`g`)&&(t*=1024*1024*1024),t},Fs=e=>{if(typeof e==`boolean`)return e;if(e=e.trim().toLowerCase(),e===`true`||e===`yes`||e===`on`)return!0;if(e===`false`||e===`no`||e===`off`)return!1;throw Error(`Expected 'true', 'false', 'yes', 'no', 'on', or 'off', but got ${e}`)},Is={core:{filemode:Fs,bare:Fs,logallrefupdates:Fs,symlinks:Fs,ignorecase:Fs,bigFileThreshold:Ps}},Ls=/^\[([A-Za-z0-9-.]+)(?: "(.*)")?\]$/,Rs=/^[A-Za-z0-9-.]+$/,zs=/^([A-Za-z][A-Za-z-]*)(?: *= *(.*))?$/,Bs=/^[A-Za-z][A-Za-z-]*$/,Vs=/^(.*?)( *[#;].*)$/,Hs=e=>{let t=Ls.exec(e);if(t!=null){let[e,n]=t.slice(1);return[e,n]}return null},Us=e=>{let t=zs.exec(e);if(t!=null){let[e,n=`true`]=t.slice(1);return[e,Ks(Ws(n))]}return null},Ws=e=>{let t=Vs.exec(e);if(t==null)return e;let[n,r]=t.slice(1);return Gs(n)&&Gs(r)?`${n}${r}`:n},Gs=e=>(e.match(/(?:^|[^\\])"/g)||[]).length%2!=0,Ks=e=>e.split(``).reduce((e,t,n,r)=>{let i=t===`"`&&r[n-1]!==`\\`,a=t===`\\`&&r[n+1]===`"`;return i||a?e:e+t},``),qs=e=>e==null?null:e.toLowerCase(),Js=(e,t,n)=>[qs(e),t,qs(n)].filter(e=>e!=null).join(`.`),Ys=e=>{let t=e.split(`.`),n=t.shift(),r=t.pop(),i=t.length?t.join(`.`):void 0;return{section:n,subsection:i,name:r,path:Js(n,i,r),sectionPath:Js(n,i,null),isSection:!!n}},Xs=(e,t)=>e.reduce((e,n,r)=>t(n)?r:e,-1),Zs=class e{constructor(e){let t=null,n=null;this.parsedConfig=e?e.split(`
733
- `).map(e=>{let r=null,i=null,a=e.trim(),o=Hs(a),s=o!=null;if(s)[t,n]=o;else{let e=Us(a);e!=null&&([r,i]=e)}let c=Js(t,n,r);return{line:e,isSection:s,section:t,subsection:n,name:r,value:i,path:c}}):[]}static from(t){return new e(t)}async get(e,t=!1){let n=Ys(e).path,r=this.parsedConfig.filter(e=>e.path===n).map(({section:e,name:t,value:n})=>{let r=Is[e]&&Is[e][t];return r?r(n):n});return t?r:r.pop()}async getall(e){return this.get(e,!0)}async getSubsections(e){return this.parsedConfig.filter(t=>t.isSection&&t.section===e).map(e=>e.subsection)}async deleteSection(e,t){this.parsedConfig=this.parsedConfig.filter(n=>!(n.section===e&&n.subsection===t))}async append(e,t){return this.set(e,t,!0)}async set(e,t,n=!1){let{section:r,subsection:i,name:a,path:o,sectionPath:s,isSection:c}=Ys(e),l=Xs(this.parsedConfig,e=>e.path===o);if(t==null)l!==-1&&this.parsedConfig.splice(l,1);else if(l!==-1){let e=this.parsedConfig[l],r=Object.assign({},e,{name:a,value:t,modified:!0});n?this.parsedConfig.splice(l+1,0,r):this.parsedConfig[l]=r}else{let e=this.parsedConfig.findIndex(e=>e.path===s),n={section:r,subsection:i,name:a,value:t,modified:!0,path:o};if(Rs.test(r)&&Bs.test(a))if(e>=0)this.parsedConfig.splice(e+1,0,n);else{let e={isSection:c,section:r,subsection:i,modified:!0,path:s};this.parsedConfig.push(e,n)}}}toString(){return this.parsedConfig.map(({line:e,section:t,subsection:n,name:r,value:i,modified:a=!1})=>a?r!=null&&i!=null?typeof i==`string`&&/[#;]/.test(i)?`\t${r} = "${i}"`:`\t${r} = ${i}`:n==null?`[${t}]`:`[${t} "${n}"]`:e).join(`
734
- `)}},Qs=class{static async get({fs:e,gitdir:t}){let n=await e.read(`${t}/config`,{encoding:`utf8`});return Zs.from(n)}static async save({fs:e,gitdir:t,config:n}){await e.write(`${t}/config`,n.toString(),{encoding:`utf8`})}},$s=e=>[`${e}`,`refs/${e}`,`refs/tags/${e}`,`refs/heads/${e}`,`refs/remotes/${e}`,`refs/remotes/${e}/HEAD`],ec=[`config`,`description`,`index`,`shallow`,`commondir`],tc;async function nc(e,t){return tc===void 0&&(tc=new Ro.default),tc.acquire(e,t)}var K=class e{static async updateRemoteRefs({fs:t,gitdir:n,remote:r,refs:i,symrefs:a,tags:o,refspecs:s=void 0,prune:c=!1,pruneTags:l=!1}){for(let e of i.values())if(!e.match(/[0-9a-f]{40}/))throw new Es(e);let u=await Qs.get({fs:t,gitdir:n});if(!s){if(s=await u.getall(`remote.${r}.fetch`),s.length===0)throw new Ds(r);s.unshift(`+HEAD:refs/remotes/${r}/HEAD`)}let d=As.from(s),f=new Map;if(l){let r=await e.listRefs({fs:t,gitdir:n,filepath:`refs/tags`});await e.deleteRefs({fs:t,gitdir:n,refs:r.map(e=>`refs/tags/${e}`)})}if(o){for(let r of i.keys())if(r.startsWith(`refs/tags`)&&!r.endsWith(`^{}`)&&!await e.exists({fs:t,gitdir:n,ref:r})){let e=i.get(r);f.set(r,e)}}let p=d.translate([...i.keys()]);for(let[e,t]of p){let n=i.get(e);f.set(t,n)}let m=d.translate([...a.keys()]);for(let[e,t]of m){let n=a.get(e),r=d.translateOne(n);r&&f.set(t,`ref: ${r}`)}let h=[];if(c){for(let r of d.localNamespaces()){let i=(await e.listRefs({fs:t,gitdir:n,filepath:r})).map(e=>`${r}/${e}`);for(let e of i)f.has(e)||h.push(e)}h.length>0&&await e.deleteRefs({fs:t,gitdir:n,refs:h})}for(let[e,r]of f)await nc(e,async()=>t.write(G(n,e),`${r.trim()}\n`,`utf8`));return{pruned:h}}static async writeRef({fs:e,gitdir:t,ref:n,value:r}){if(!r.match(/[0-9a-f]{40}/))throw new Es(r);await nc(n,async()=>e.write(G(t,n),`${r.trim()}\n`,`utf8`))}static async writeSymbolicRef({fs:e,gitdir:t,ref:n,value:r}){await nc(n,async()=>e.write(G(t,n),`ref: ${r.trim()}\n`,`utf8`))}static async deleteRef({fs:t,gitdir:n,ref:r}){return e.deleteRefs({fs:t,gitdir:n,refs:[r]})}static async deleteRefs({fs:e,gitdir:t,refs:n}){await Promise.all(n.map(n=>e.rm(G(t,n))));let r=await nc(`packed-refs`,async()=>e.read(`${t}/packed-refs`,{encoding:`utf8`})),i=Os.from(r),a=i.refs.size;for(let e of n)i.refs.has(e)&&i.delete(e);i.refs.size<a&&(r=i.toString(),await nc(`packed-refs`,async()=>e.write(`${t}/packed-refs`,r,{encoding:`utf8`})))}static async resolve({fs:t,gitdir:n,ref:r,depth:i=void 0}){if(i!==void 0&&(i--,i===-1))return r;if(r.startsWith(`ref: `))return r=r.slice(5),e.resolve({fs:t,gitdir:n,ref:r,depth:i});if(r.length===40&&/[0-9a-f]{40}/.test(r))return r;let a=await e.packedRefs({fs:t,gitdir:n}),o=$s(r).filter(e=>!ec.includes(e));for(let r of o){let o=await nc(r,async()=>await t.read(`${n}/${r}`,{encoding:`utf8`})||a.get(r));if(o)return e.resolve({fs:t,gitdir:n,ref:o.trim(),depth:i})}throw new ws(r)}static async exists({fs:t,gitdir:n,ref:r}){try{return await e.expand({fs:t,gitdir:n,ref:r}),!0}catch{return!1}}static async expand({fs:t,gitdir:n,ref:r}){if(r.length===40&&/[0-9a-f]{40}/.test(r))return r;let i=await e.packedRefs({fs:t,gitdir:n}),a=$s(r);for(let e of a)if(await nc(e,async()=>t.exists(`${n}/${e}`))||i.has(e))return e;throw new ws(r)}static async expandAgainstMap({ref:e,map:t}){let n=$s(e);for(let e of n)if(await t.has(e))return e;throw new ws(e)}static resolveAgainstMap({ref:t,fullref:n=t,depth:r=void 0,map:i}){if(r!==void 0&&(r--,r===-1))return{fullref:n,oid:t};if(t.startsWith(`ref: `))return t=t.slice(5),e.resolveAgainstMap({ref:t,fullref:n,depth:r,map:i});if(t.length===40&&/[0-9a-f]{40}/.test(t))return{fullref:n,oid:t};let a=$s(t);for(let t of a){let n=i.get(t);if(n)return e.resolveAgainstMap({ref:n.trim(),fullref:t,depth:r,map:i})}throw new ws(t)}static async packedRefs({fs:e,gitdir:t}){let n=await nc(`packed-refs`,async()=>e.read(`${t}/packed-refs`,{encoding:`utf8`}));return Os.from(n).refs}static async listRefs({fs:t,gitdir:n,filepath:r}){let i=e.packedRefs({fs:t,gitdir:n}),a=null;try{a=await t.readdirDeep(`${n}/${r}`),a=a.map(e=>e.replace(`${n}/${r}/`,``))}catch{a=[]}for(let e of(await i).keys())e.startsWith(r)&&(e=e.replace(r+`/`,``),a.includes(e)||a.push(e));return a.sort(js),a}static async listBranches({fs:t,gitdir:n,remote:r}){return r?e.listRefs({fs:t,gitdir:n,filepath:`refs/remotes/${r}`}):e.listRefs({fs:t,gitdir:n,filepath:`refs/heads`})}static async listTags({fs:t,gitdir:n}){return(await e.listRefs({fs:t,gitdir:n,filepath:`refs/tags`})).filter(e=>!e.endsWith(`^{}`))}};function rc(e,t){return Yo(ic(e),ic(t))}function ic(e){return e.mode===`040000`?e.path+`/`:e.path}function ac(e){switch(e){case`040000`:return`tree`;case`100644`:return`blob`;case`100755`:return`blob`;case`120000`:return`blob`;case`160000`:return`commit`}throw new W(`Unexpected GitTree entry mode: ${e}`)}function oc(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(32,n);if(r===-1)throw new W(`GitTree: Error parsing buffer at byte location ${n}: Could not find the next space character.`);let i=e.indexOf(0,n);if(i===-1)throw new W(`GitTree: Error parsing buffer at byte location ${n}: Could not find the next null character.`);let a=e.slice(n,r).toString(`utf8`);a===`40000`&&(a=`040000`);let o=ac(a),s=e.slice(r+1,i).toString(`utf8`);if(s.includes(`\\`)||s.includes(`/`))throw new qo(s);let c=e.slice(i+1,i+21).toString(`hex`);n=i+21,t.push({mode:a,path:s,oid:c,type:o})}return t}function sc(e){if(typeof e==`number`&&(e=e.toString(8)),e.match(/^0?4.*/))return`040000`;if(e.match(/^1006.*/))return`100644`;if(e.match(/^1007.*/))return`100755`;if(e.match(/^120.*/))return`120000`;if(e.match(/^160.*/))return`160000`;throw new W(`Could not understand file mode: ${e}`)}function cc(e){return!e.oid&&e.sha&&(e.oid=e.sha),e.mode=sc(e.mode),e.type||=ac(e.mode),e}var lc=class e{constructor(e){if(Buffer.isBuffer(e))this._entries=oc(e);else if(Array.isArray(e))this._entries=e.map(cc);else throw new W(`invalid type passed to GitTree constructor`);this._entries.sort(Xo)}static from(t){return new e(t)}render(){return this._entries.map(e=>`${e.mode} ${e.type} ${e.oid} ${e.path}`).join(`
735
- `)}toObject(){let e=[...this._entries];return e.sort(rc),Buffer.concat(e.map(e=>{let t=Buffer.from(e.mode.replace(/^0/,``)),n=Buffer.from(` `),r=Buffer.from(e.path,`utf8`),i=Buffer.from([0]),a=Buffer.from(e.oid,`hex`);return Buffer.concat([t,n,r,i,a])}))}entries(){return this._entries}*[Symbol.iterator](){for(let e of this._entries)yield e}},uc=class{static wrap({type:e,object:t}){let n=`${e} ${t.length}\x00`,r=n.length,i=r+t.length,a=new Uint8Array(i);for(let e=0;e<r;e++)a[e]=n.charCodeAt(e);return a.set(t,r),a}static unwrap(e){let t=e.indexOf(32),n=e.indexOf(0),r=e.slice(0,t).toString(`utf8`),i=e.slice(t+1,n).toString(`utf8`),a=e.length-(n+1);if(parseInt(i)!==a)throw new W(`Length mismatch: expected ${i} bytes but got ${a} instead.`);return{type:r,object:Buffer.from(e.slice(n+1))}}};async function dc({fs:e,gitdir:t,oid:n}){let r=`objects/${n.slice(0,2)}/${n.slice(2)}`,i=await e.read(`${t}/${r}`);return i?{object:i,format:`deflated`,source:r}:null}function fc(e,t){let n=new Jo(e),r=pc(n);if(r!==t.byteLength)throw new W(`applyDelta expected source buffer to be ${r} bytes but the provided buffer was ${t.length} bytes`);let i=pc(n),a,o=hc(n,t);if(o.byteLength===i)a=o;else{a=Buffer.alloc(i);let e=new Jo(a);for(e.copy(o);!n.eof();)e.copy(hc(n,t));let r=e.tell();if(i!==r)throw new W(`applyDelta expected target buffer to be ${i} bytes but the resulting buffer was ${r} bytes`)}return a}function pc(e){let t=0,n=0,r=null;do r=e.readUInt8(),t|=(r&127)<<n,n+=7;while(r&128);return t}function mc(e,t,n){let r=0,i=0;for(;n--;)t&1&&(r|=e.readUInt8()<<i),t>>=1,i+=8;return r}function hc(e,t){let n=e.readUInt8();if(n&128){let r=mc(e,n&15,4),i=mc(e,(n&112)>>4,3);return i===0&&(i=65536),t.slice(r,r+i)}else return e.slice(n)}function gc(e){let t=[e];return{next(){return Promise.resolve({done:t.length===0,value:t.pop()})},return(){return t=[],{}},[Symbol.asyncIterator](){return this}}}function _c(e){return e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]?e[Symbol.iterator]():e.next?e:gc(e)}var vc=class{constructor(e){if(typeof Buffer>`u`)throw Error(`Missing Buffer dependency`);this.stream=_c(e),this.buffer=null,this.cursor=0,this.undoCursor=0,this.started=!1,this._ended=!1,this._discardedBytes=0}eof(){return this._ended&&this.cursor===this.buffer.length}tell(){return this._discardedBytes+this.cursor}async byte(){if(!this.eof()&&(this.started||await this._init(),!(this.cursor===this.buffer.length&&(await this._loadnext(),this._ended))))return this._moveCursor(1),this.buffer[this.undoCursor]}async chunk(){if(!this.eof()&&(this.started||await this._init(),!(this.cursor===this.buffer.length&&(await this._loadnext(),this._ended))))return this._moveCursor(this.buffer.length),this.buffer.slice(this.undoCursor,this.cursor)}async read(e){if(!this.eof())return this.started||await this._init(),this.cursor+e>this.buffer.length&&(this._trim(),await this._accumulate(e)),this._moveCursor(e),this.buffer.slice(this.undoCursor,this.cursor)}async skip(e){this.eof()||(this.started||await this._init(),this.cursor+e>this.buffer.length&&(this._trim(),await this._accumulate(e)),this._moveCursor(e))}async undo(){this.cursor=this.undoCursor}async _next(){this.started=!0;let{done:e,value:t}=await this.stream.next();return e&&(this._ended=!0,!t)?Buffer.alloc(0):(t&&=Buffer.from(t),t)}_trim(){this.buffer=this.buffer.slice(this.undoCursor),this.cursor-=this.undoCursor,this._discardedBytes+=this.undoCursor,this.undoCursor=0}_moveCursor(e){this.undoCursor=this.cursor,this.cursor+=e,this.cursor>this.buffer.length&&(this.cursor=this.buffer.length)}async _accumulate(e){if(this._ended)return;let t=[this.buffer];for(;this.cursor+e>yc(t);){let e=await this._next();if(this._ended)break;t.push(e)}this.buffer=Buffer.concat(t)}async _loadnext(){this._discardedBytes+=this.buffer.length,this.undoCursor=0,this.cursor=0,this.buffer=await this._next()}async _init(){this.buffer=await this._next()}};function yc(e){return e.reduce((e,t)=>e+t.length,0)}async function bc(e,t){let n=new vc(e),r=await n.read(4);if(r=r.toString(`utf8`),r!==`PACK`)throw new W(`Invalid PACK header '${r}'`);let i=await n.read(4);if(i=i.readUInt32BE(0),i!==2)throw new W(`Invalid packfile version: ${i}`);let a=await n.read(4);if(a=a.readUInt32BE(0),!(a<1))for(;!n.eof()&&a--;){let e=n.tell(),{type:r,length:i,ofs:o,reference:s}=await xc(n),c=new Vo.default.Inflate;for(;!c.result;){let l=await n.chunk();if(!l)break;if(c.push(l,!1),c.err)throw new W(`Pako error: ${c.msg}`);if(c.result){if(c.result.length!==i)throw new W(`Inflated object size is different from that stated in packfile.`);await n.undo(),await n.read(l.length-c.strm.avail_in);let u=n.tell();await t({data:c.result,type:r,num:a,offset:e,end:u,reference:s,ofs:o})}}}}async function xc(e){let t=await e.byte(),n=t>>4&7,r=t&15;if(t&128){let n=4;do t=await e.byte(),r|=(t&127)<<n,n+=7;while(t&128)}let i,a;if(n===6){let n=0;i=0;let r=[];do t=await e.byte(),i|=(t&127)<<n,n+=7,r.push(t);while(t&128);a=Buffer.from(r)}return n===7&&(a=await e.read(20)),{type:n,length:r,ofs:i,reference:a}}var Sc=!1;async function Cc(e){return Sc===null&&(Sc=Tc()),Sc?wc(e):Vo.default.inflate(e)}async function wc(e){let t=new DecompressionStream(`deflate`),n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}function Tc(){try{if(new DecompressionStream(`deflate`))return!0}catch{}return!1}function Ec(e){let t=[],n=0,r=0;do{n=e.readUInt8();let i=n&127;t.push(i),r=n&128}while(r);return t.reduce((e,t)=>e+1<<7|t,-1)}function Dc(e,t){let n=t,r=4,i=null;do i=e.readUInt8(),n|=(i&127)<<r,r+=7;while(i&128);return n}var Oc=class e{constructor(e){Object.assign(this,e),this.offsetCache={}}static async fromIdx({idx:t,getExternalRefDelta:n}){let r=new Jo(t);if(r.slice(4).toString(`hex`)!==`ff744f63`)return;let i=r.readUInt32BE();if(i!==2)throw new W(`Unable to read version ${i} packfile IDX. (Only version 2 supported)`);if(t.byteLength>2048*1024*1024)throw new W(`To keep implementation simple, I haven't implemented the layer 5 feature needed to support packfiles > 2GB in size.`);r.seek(r.tell()+1020);let a=r.readUInt32BE(),o=[];for(let e=0;e<a;e++)o[e]=r.slice(20).toString(`hex`);r.seek(r.tell()+4*a);let s=new Map;for(let e=0;e<a;e++)s.set(o[e],r.readUInt32BE());return new e({hashes:o,crcs:{},offsets:s,packfileSha:r.slice(20).toString(`hex`),getExternalRefDelta:n})}static async fromPack({pack:t,getExternalRefDelta:n,onProgress:r}){let i={1:`commit`,2:`tree`,3:`blob`,4:`tag`,6:`ofs-delta`,7:`ref-delta`},a={},o=t.slice(-20).toString(`hex`),s=[],c={},l=new Map,u=null,d=null;await bc([t],async({data:e,type:t,reference:n,offset:o,num:s})=>{u===null&&(u=s);let c=Math.floor((u-s)*100/u);c!==d&&r&&await r({phase:`Receiving objects`,loaded:u-s,total:u}),d=c,t=i[t],([`commit`,`tree`,`blob`,`tag`].includes(t)||t===`ofs-delta`||t===`ref-delta`)&&(a[o]={type:t,offset:o})});let f=Object.keys(a).map(Number);for(let[e,n]of f.entries()){let r=e+1===f.length?t.byteLength-20:f[e+1],i=a[n],o=Bo.default.buf(t.slice(n,r))>>>0;i.end=r,i.crc=o}let p=new e({pack:Promise.resolve(t),packfileSha:o,crcs:c,hashes:s,offsets:l,getExternalRefDelta:n});d=null;let m=0,h=[0,0,0,0,0,0,0,0,0,0,0,0];for(let e in a){e=Number(e);let t=Math.floor(m*100/u);t!==d&&r&&await r({phase:`Resolving deltas`,loaded:m,total:u}),m++,d=t;let n=a[e];if(!n.oid)try{p.readDepth=0,p.externalReadDepth=0;let{type:t,object:r}=await p.readSlice({start:e});h[p.readDepth]+=1;let i=await rs(uc.wrap({type:t,object:r}));n.oid=i,s.push(i),l.set(i,e),c[i]=n.crc}catch{continue}}return s.sort(),p}async toBuffer(){let e=[],t=(t,n)=>{e.push(Buffer.from(t,n))};t(`ff744f63`,`hex`),t(`00000002`,`hex`);let n=new Jo(Buffer.alloc(256*4));for(let e=0;e<256;e++){let t=0;for(let n of this.hashes)parseInt(n.slice(0,2),16)<=e&&t++;n.writeUInt32BE(t)}e.push(n.buffer);for(let e of this.hashes)t(e,`hex`);let r=new Jo(Buffer.alloc(this.hashes.length*4));for(let e of this.hashes)r.writeUInt32BE(this.crcs[e]);e.push(r.buffer);let i=new Jo(Buffer.alloc(this.hashes.length*4));for(let e of this.hashes)i.writeUInt32BE(this.offsets.get(e));e.push(i.buffer),t(this.packfileSha,`hex`);let a=Buffer.concat(e),o=await rs(a),s=Buffer.alloc(20);return s.write(o,`hex`),Buffer.concat([a,s])}async load({pack:e}){this.pack=e}async unload(){this.pack=null}async read({oid:e}){if(!this.offsets.get(e)){if(this.getExternalRefDelta)return this.externalReadDepth++,this.getExternalRefDelta(e);throw new W(`Could not read object ${e} from packfile`)}let t=this.offsets.get(e);return this.readSlice({start:t})}async readSlice({start:e}){if(this.offsetCache[e])return Object.assign({},this.offsetCache[e]);this.readDepth++;let t={16:`commit`,32:`tree`,48:`blob`,64:`tag`,96:`ofs_delta`,112:`ref_delta`},n=await this.pack;if(!n)throw new W(`Could not read packfile data. The packfile may be missing, corrupted, or too large to read into memory.`);let r=n.slice(e),i=new Jo(r),a=i.readUInt8(),o=a&112,s=t[o];if(s===void 0)throw new W(`Unrecognized type: 0b`+o.toString(2));let c=a&15,l=c;a&128&&(l=Dc(i,c));let u=null,d=null;if(s===`ofs_delta`){let t=e-Ec(i);({object:u,type:s}=await this.readSlice({start:t}))}if(s===`ref_delta`){let e=i.slice(20).toString(`hex`);({object:u,type:s}=await this.read({oid:e}))}let f=r.slice(i.tell());if(d=Buffer.from(await Cc(f)),d.byteLength!==l)throw new W(`Packfile told us object would have length ${l} but it had length ${d.byteLength}`);return u&&(d=Buffer.from(fc(d,u))),this.readDepth>3&&(this.offsetCache[e]={type:s,object:d}),{type:s,format:`content`,object:d}}},kc=Symbol(`PackfileCache`);async function Ac({fs:e,filename:t,getExternalRefDelta:n,emitter:r,emitterPrefix:i}){let a=await e.read(t);return Oc.fromIdx({idx:a,getExternalRefDelta:n})}function jc({fs:e,cache:t,filename:n,getExternalRefDelta:r,emitter:i,emitterPrefix:a}){t[kc]||(t[kc]=new Map);let o=t[kc].get(n);return o||(o=Ac({fs:e,filename:n,getExternalRefDelta:r,emitter:i,emitterPrefix:a}),t[kc].set(n,o)),o}async function Mc(e,{start:t=0,end:n=e.length}={}){return rs(e.subarray(t,n))}async function Nc({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`,getExternalRefDelta:a}){let o=await e.readdir(G(n,`objects/pack`));o=o.filter(e=>e.endsWith(`.idx`));for(let i of o){let o=`${n}/objects/pack/${i}`,s=await jc({fs:e,cache:t,filename:o,getExternalRefDelta:a});if(s.error)throw new W(s.error);if(s.offsets.has(r)){let t=o.replace(/idx$/,`pack`);s.pack||=e.read(t);let n=await s.pack;if(!n)throw s.pack=null,new W(`Could not read packfile at ${t}. The file may be missing, corrupted, or too large to read into memory.`);if(!s._checksumVerified){let e=s.packfileSha,t=n.subarray(-20),r=Array.from(t).map(e=>e.toString(16).padStart(2,`0`)).join(``);if(r!==e)throw new W(`Packfile trailer mismatch: expected ${e}, got ${r}. The packfile may be corrupted.`);let i=await Mc(n,{start:0,end:n.length-20});if(i!==e)throw new W(`Packfile payload corrupted: calculated ${i} but expected ${e}. The packfile may have been tampered with.`);s._checksumVerified=!0}let c=await s.read({oid:r,getExternalRefDelta:a});return c.format=`content`,c.source=`objects/pack/${i.replace(/idx$/,`pack`)}`,c}}return null}async function Pc({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`}){let a=r=>Pc({fs:e,cache:t,gitdir:n,oid:r}),o;if(r===`4b825dc642cb6eb9a060e54bf8d69288fbee4904`&&(o={format:`wrapped`,object:Buffer.from(`tree 0\0`)}),o||=await dc({fs:e,gitdir:n,oid:r}),!o){if(o=await Nc({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:a}),!o)throw new ws(r);return o}if(i===`deflated`||(o.format===`deflated`&&(o.object=Buffer.from(await Cc(o.object)),o.format=`wrapped`),i===`wrapped`))return o;let s=await rs(o.object);if(s!==r)throw new W(`SHA check failed! Expected ${r}, computed ${s}`);let{object:c,type:l}=uc.unwrap(o.object);if(o.type=l,o.object=c,o.format=`content`,i===`content`)return o;throw new W(`invalid requested format "${i}"`)}var Fc=class e extends U{constructor(t,n,r=!0){super(`Failed to create ${t} at ${n} because it already exists.${r?` (Hint: use 'force: true' parameter to overwrite existing ${t}.)`:``}`),this.code=this.name=e.code,this.data={noun:t,where:n,canForce:r}}};Fc.code=`AlreadyExistsError`;var Ic=class e extends U{constructor(t,n,r){super(`Found multiple ${t} matching "${n}" (${r.join(`, `)}). Use a longer abbreviation length to disambiguate them.`),this.code=this.name=e.code,this.data={nouns:t,short:n,matches:r}}};Ic.code=`AmbiguousError`;var Lc=class e extends U{constructor(t){super(`Your local changes to the following files would be overwritten by checkout: ${t.join(`, `)}`),this.code=this.name=e.code,this.data={filepaths:t}}};Lc.code=`CheckoutConflictError`;var Rc=class e extends U{constructor(t,n){super(`Cannot cherry-pick merge commit ${t}. Merge commits have ${n} parents and require specifying which parent to use as the base.`),this.code=this.name=e.code,this.data={oid:t,parentCount:n}}};Rc.code=`CherryPickMergeCommitError`;var zc=class e extends U{constructor(t){super(`Cannot cherry-pick root commit ${t}. Root commits have no parents.`),this.code=this.name=e.code,this.data={oid:t}}};zc.code=`CherryPickRootCommitError`;var Bc=class e extends U{constructor(t,n){super(`Failed to checkout "${t}" because commit ${n} is not available locally. Do a git fetch to make the branch available locally.`),this.code=this.name=e.code,this.data={ref:t,oid:n}}};Bc.code=`CommitNotFetchedError`;var Vc=class e extends U{constructor(){super(`Empty response from git server.`),this.code=this.name=e.code,this.data={}}};Vc.code=`EmptyServerResponseError`;var Hc=class e extends U{constructor(){super(`A simple fast-forward merge was not possible.`),this.code=this.name=e.code,this.data={}}};Hc.code=`FastForwardError`;var Uc=class e extends U{constructor(t,n){super(`One or more branches were not updated: ${t}`),this.code=this.name=e.code,this.data={prettyDetails:t,result:n}}};Uc.code=`GitPushError`;var Wc=class e extends U{constructor(t,n,r){super(`HTTP Error: ${t} ${n}`),this.code=this.name=e.code,this.data={statusCode:t,statusMessage:n,response:r}}};Wc.code=`HttpError`;var Gc=class e extends U{constructor(t){let n=`invalid filepath`;t===`leading-slash`||t===`trailing-slash`?n=`"filepath" parameter should not include leading or trailing directory separators because these can cause problems on some platforms.`:t===`directory`&&(n=`"filepath" should not be a directory.`),super(n),this.code=this.name=e.code,this.data={reason:t}}};Gc.code=`InvalidFilepathError`;var Kc=class e extends U{constructor(t,n){super(`"${t}" would be an invalid git reference. (Hint: a valid alternative would be "${n}".)`),this.code=this.name=e.code,this.data={ref:t,suggestion:n}}};Kc.code=`InvalidRefNameError`;var qc=class e extends U{constructor(t){super(`Maximum search depth of ${t} exceeded.`),this.code=this.name=e.code,this.data={depth:t}}};qc.code=`MaxDepthError`;var Jc=class e extends U{constructor(){super(`Merges with conflicts are not supported yet.`),this.code=this.name=e.code,this.data={}}};Jc.code=`MergeNotSupportedError`;var Yc=class e extends U{constructor(t,n,r,i){super(`Automatic merge failed with one or more merge conflicts in the following files: ${t.toString()}. Fix conflicts then commit the result.`),this.code=this.name=e.code,this.data={filepaths:t,bothModified:n,deleteByUs:r,deleteByTheirs:i}}};Yc.code=`MergeConflictError`;var Xc=class e extends U{constructor(t){super(`No name was provided for ${t} in the argument or in the .git/config file.`),this.code=this.name=e.code,this.data={role:t}}};Xc.code=`MissingNameError`;var Zc=class e extends U{constructor(t){super(`The function requires a "${t}" parameter but none was provided.`),this.code=this.name=e.code,this.data={parameter:t}}};Zc.code=`MissingParameterError`;var Qc=class e extends U{constructor(t){super(`There are multiple errors that were thrown by the method. Please refer to the "errors" property to see more`),this.code=this.name=e.code,this.data={errors:t},this.errors=t}};Qc.code=`MultipleGitError`;var $c=class e extends U{constructor(t,n){super(`Expected "${t}" but received "${n}".`),this.code=this.name=e.code,this.data={expected:t,actual:n}}};$c.code=`ParseError`;var el=class e extends U{constructor(t){let n=``;t===`not-fast-forward`?n=` because it was not a simple fast-forward`:t===`tag-exists`&&(n=` because tag already exists`),super(`Push rejected${n}. Use "force: true" to override.`),this.code=this.name=e.code,this.data={reason:t}}};el.code=`PushRejectedError`;var tl=class e extends U{constructor(t,n){super(`Remote does not support the "${t}" so the "${n}" parameter cannot be used.`),this.code=this.name=e.code,this.data={capability:t,parameter:n}}};tl.code=`RemoteCapabilityError`;var nl=class e extends U{constructor(t,n){super(`Remote did not reply using the "smart" HTTP protocol. Expected "001e# service=git-upload-pack" but received: ${t}`),this.code=this.name=e.code,this.data={preview:t,response:n}}};nl.code=`SmartHttpError`;var rl=class e extends U{constructor(t,n,r){super(`Git remote "${t}" uses an unrecognized transport protocol: "${n}"`),this.code=this.name=e.code,this.data={url:t,transport:n,suggestion:r}}};rl.code=`UnknownTransportError`;var il=class e extends U{constructor(t){super(`Cannot parse remote URL: "${t}"`),this.code=this.name=e.code,this.data={url:t}}};il.code=`UrlParseError`;var al=class e extends U{constructor(){super(`The operation was canceled.`),this.code=this.name=e.code,this.data={}}};al.code=`UserCanceledError`;var ol=class e extends U{constructor(t){super(`Could not merge index: Entry for '${t}' is not up to date. Either reset the index entry to HEAD, or stage your unstaged changes.`),this.code=this.name=e.code,this.data={filepath:t}}};ol.code=`IndexResetError`;var sl=class e extends U{constructor(t){super(`"${t}" does not point to any commit. You're maybe working on a repository with no commits yet. `),this.code=this.name=e.code,this.data={ref:t}}};sl.code=`NoCommitError`;function cl({name:e,email:t,timestamp:n,timezoneOffset:r}){return r=ll(r),`${e} <${t}> ${n} ${r}`}function ll(e){let t=ul(dl(e));e=Math.abs(e);let n=Math.floor(e/60);e-=n*60;let r=String(n),i=String(e);return r.length<2&&(r=`0`+r),i.length<2&&(i=`0`+i),(t===-1?`-`:`+`)+r+i}function ul(e){return Math.sign(e)||(Object.is(e,-0)?-1:1)}function dl(e){return e===0?e:-e}function fl(e){return e=e.replace(/\r/g,``),e=e.replace(/^\n+/,``),e=e.replace(/\n+$/,``)+`
736
- `,e}function pl(e){let[,t,n,r,i]=e.match(/^(.*) <(.*)> (.*) (.*)$/);return{name:t,email:n,timestamp:Number(r),timezoneOffset:ml(i)}}function ml(e){let[,t,n,r]=e.match(/(\+|-)(\d\d)(\d\d)/);return r=(t===`+`?1:-1)*(Number(n)*60+Number(r)),hl(r)}function hl(e){return e===0?e:-e}var gl=class e{constructor(t){if(typeof t==`string`)this._tag=t;else if(Buffer.isBuffer(t))this._tag=t.toString(`utf8`);else if(typeof t==`object`)this._tag=e.render(t);else throw new W(`invalid type passed to GitAnnotatedTag constructor`)}static from(t){return new e(t)}static render(e){return`object ${e.object}
732
+ `}},Ns=class e{constructor({remotePath:e,localPath:t,force:n,matchPrefix:r}){Object.assign(this,{remotePath:e,localPath:t,force:n,matchPrefix:r})}static from(t){let[n,r,i,a,o]=t.match(/^(\+?)(.*?)(\*?):(.*?)(\*?)$/).slice(1),s=n===`+`,c=i===`*`;if(c!==(o===`*`))throw new W(`Invalid refspec`);return new e({remotePath:r,localPath:a,force:s,matchPrefix:c})}translate(e){if(this.matchPrefix){if(e.startsWith(this.remotePath))return this.localPath+e.replace(this.remotePath,``)}else if(e===this.remotePath)return this.localPath;return null}reverseTranslate(e){if(this.matchPrefix){if(e.startsWith(this.localPath))return this.remotePath+e.replace(this.localPath,``)}else if(e===this.localPath)return this.remotePath;return null}},Ps=class e{constructor(e=[]){this.rules=e}static from(t){let n=[];for(let e of t)n.push(Ns.from(e));return new e(n)}add(e){let t=Ns.from(e);this.rules.push(t)}translate(e){let t=[];for(let n of this.rules)for(let r of e){let e=n.translate(r);e&&t.push([r,e])}return t}translateOne(e){let t=null;for(let n of this.rules){let r=n.translate(e);r&&(t=r)}return t}localNamespaces(){return this.rules.filter(e=>e.matchPrefix).map(e=>e.localPath.replace(/\/$/,``))}};function Fs(e,t){let n=e.replace(/\^\{\}$/,``),r=t.replace(/\^\{\}$/,``),i=-(n<r)||+(n>r);return i===0?e.endsWith(`^{}`)?1:-1:i}function Is(e,t){let n=``,r=0,i=-1,a=0,o=`\0`;for(let s=0;s<=e.length;++s){if(s<e.length)o=e[s];else if(o===`/`)break;else o=`/`;if(o===`/`){if(!(i===s-1||a===1))if(a===2){if(n.length<2||r!==2||n.at(-1)!==`.`||n.at(-2)!==`.`){if(n.length>2){let e=n.lastIndexOf(`/`);e===-1?(n=``,r=0):(n=n.slice(0,e),r=n.length-1-n.lastIndexOf(`/`)),i=s,a=0;continue}else if(n.length!==0){n=``,r=0,i=s,a=0;continue}}t&&(n+=n.length>0?`/..`:`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,s):n=e.slice(i+1,s),r=s-i-1;i=s,a=0}else o===`.`&&a!==-1?++a:a=-1}return n}function Ls(e){if(!e.length)return`.`;let t=e[0]===`/`,n=e.at(-1)===`/`;return e=Is(e,!t),e.length?(n&&(e+=`/`),t?`/${e}`:e):t?`/`:n?`./`:`.`}function G(...e){if(e.length===0)return`.`;let t;for(let n=0;n<e.length;++n){let r=e[n];r.length>0&&(t===void 0?t=r:t+=`/`+r)}return t===void 0?`.`:Ls(t)}var Rs=e=>{if(typeof e==`number`)return e;e=e.toLowerCase();let t=parseInt(e);return e.endsWith(`k`)&&(t*=1024),e.endsWith(`m`)&&(t*=1024*1024),e.endsWith(`g`)&&(t*=1024*1024*1024),t},zs=e=>{if(typeof e==`boolean`)return e;if(e=e.trim().toLowerCase(),e===`true`||e===`yes`||e===`on`)return!0;if(e===`false`||e===`no`||e===`off`)return!1;throw Error(`Expected 'true', 'false', 'yes', 'no', 'on', or 'off', but got ${e}`)},Bs={core:{filemode:zs,bare:zs,logallrefupdates:zs,symlinks:zs,ignorecase:zs,bigFileThreshold:Rs}},Vs=/^\[([A-Za-z0-9-.]+)(?: "(.*)")?\]$/,Hs=/^[A-Za-z0-9-.]+$/,Us=/^([A-Za-z][A-Za-z-]*)(?: *= *(.*))?$/,Ws=/^[A-Za-z][A-Za-z-]*$/,Gs=/^(.*?)( *[#;].*)$/,Ks=e=>{let t=Vs.exec(e);if(t!=null){let[e,n]=t.slice(1);return[e,n]}return null},qs=e=>{let t=Us.exec(e);if(t!=null){let[e,n=`true`]=t.slice(1);return[e,Xs(Js(n))]}return null},Js=e=>{let t=Gs.exec(e);if(t==null)return e;let[n,r]=t.slice(1);return Ys(n)&&Ys(r)?`${n}${r}`:n},Ys=e=>(e.match(/(?:^|[^\\])"/g)||[]).length%2!=0,Xs=e=>e.split(``).reduce((e,t,n,r)=>{let i=t===`"`&&r[n-1]!==`\\`,a=t===`\\`&&r[n+1]===`"`;return i||a?e:e+t},``),Zs=e=>e==null?null:e.toLowerCase(),Qs=(e,t,n)=>[Zs(e),t,Zs(n)].filter(e=>e!=null).join(`.`),$s=e=>{let t=e.split(`.`),n=t.shift(),r=t.pop(),i=t.length?t.join(`.`):void 0;return{section:n,subsection:i,name:r,path:Qs(n,i,r),sectionPath:Qs(n,i,null),isSection:!!n}},ec=(e,t)=>e.reduce((e,n,r)=>t(n)?r:e,-1),tc=class e{constructor(e){let t=null,n=null;this.parsedConfig=e?e.split(`
733
+ `).map(e=>{let r=null,i=null,a=e.trim(),o=Ks(a),s=o!=null;if(s)[t,n]=o;else{let e=qs(a);e!=null&&([r,i]=e)}let c=Qs(t,n,r);return{line:e,isSection:s,section:t,subsection:n,name:r,value:i,path:c}}):[]}static from(t){return new e(t)}async get(e,t=!1){let n=$s(e).path,r=this.parsedConfig.filter(e=>e.path===n).map(({section:e,name:t,value:n})=>{let r=Bs[e]&&Bs[e][t];return r?r(n):n});return t?r:r.pop()}async getall(e){return this.get(e,!0)}async getSubsections(e){return this.parsedConfig.filter(t=>t.isSection&&t.section===e).map(e=>e.subsection)}async deleteSection(e,t){this.parsedConfig=this.parsedConfig.filter(n=>!(n.section===e&&n.subsection===t))}async append(e,t){return this.set(e,t,!0)}async set(e,t,n=!1){let{section:r,subsection:i,name:a,path:o,sectionPath:s,isSection:c}=$s(e),l=ec(this.parsedConfig,e=>e.path===o);if(t==null)l!==-1&&this.parsedConfig.splice(l,1);else if(l!==-1){let e=this.parsedConfig[l],r=Object.assign({},e,{name:a,value:t,modified:!0});n?this.parsedConfig.splice(l+1,0,r):this.parsedConfig[l]=r}else{let e=this.parsedConfig.findIndex(e=>e.path===s),n={section:r,subsection:i,name:a,value:t,modified:!0,path:o};if(Hs.test(r)&&Ws.test(a))if(e>=0)this.parsedConfig.splice(e+1,0,n);else{let e={isSection:c,section:r,subsection:i,modified:!0,path:s};this.parsedConfig.push(e,n)}}}toString(){return this.parsedConfig.map(({line:e,section:t,subsection:n,name:r,value:i,modified:a=!1})=>a?r!=null&&i!=null?typeof i==`string`&&/[#;]/.test(i)?`\t${r} = "${i}"`:`\t${r} = ${i}`:n==null?`[${t}]`:`[${t} "${n}"]`:e).join(`
734
+ `)}},nc=class{static async get({fs:e,gitdir:t}){let n=await e.read(`${t}/config`,{encoding:`utf8`});return tc.from(n)}static async save({fs:e,gitdir:t,config:n}){await e.write(`${t}/config`,n.toString(),{encoding:`utf8`})}},rc=e=>[`${e}`,`refs/${e}`,`refs/tags/${e}`,`refs/heads/${e}`,`refs/remotes/${e}`,`refs/remotes/${e}/HEAD`],ic=[`config`,`description`,`index`,`shallow`,`commondir`],ac;async function oc(e,t){return ac===void 0&&(ac=new Ho.default),ac.acquire(e,t)}var K=class e{static async updateRemoteRefs({fs:t,gitdir:n,remote:r,refs:i,symrefs:a,tags:o,refspecs:s=void 0,prune:c=!1,pruneTags:l=!1}){for(let e of i.values())if(!e.match(/[0-9a-f]{40}/))throw new As(e);let u=await nc.get({fs:t,gitdir:n});if(!s){if(s=await u.getall(`remote.${r}.fetch`),s.length===0)throw new js(r);s.unshift(`+HEAD:refs/remotes/${r}/HEAD`)}let d=Ps.from(s),f=new Map;if(l){let r=await e.listRefs({fs:t,gitdir:n,filepath:`refs/tags`});await e.deleteRefs({fs:t,gitdir:n,refs:r.map(e=>`refs/tags/${e}`)})}if(o){for(let r of i.keys())if(r.startsWith(`refs/tags`)&&!r.endsWith(`^{}`)&&!await e.exists({fs:t,gitdir:n,ref:r})){let e=i.get(r);f.set(r,e)}}let p=d.translate([...i.keys()]);for(let[e,t]of p){let n=i.get(e);f.set(t,n)}let m=d.translate([...a.keys()]);for(let[e,t]of m){let n=a.get(e),r=d.translateOne(n);r&&f.set(t,`ref: ${r}`)}let h=[];if(c){for(let r of d.localNamespaces()){let i=(await e.listRefs({fs:t,gitdir:n,filepath:r})).map(e=>`${r}/${e}`);for(let e of i)f.has(e)||h.push(e)}h.length>0&&await e.deleteRefs({fs:t,gitdir:n,refs:h})}for(let[e,r]of f)await oc(e,async()=>t.write(G(n,e),`${r.trim()}\n`,`utf8`));return{pruned:h}}static async writeRef({fs:e,gitdir:t,ref:n,value:r}){if(!r.match(/[0-9a-f]{40}/))throw new As(r);await oc(n,async()=>e.write(G(t,n),`${r.trim()}\n`,`utf8`))}static async writeSymbolicRef({fs:e,gitdir:t,ref:n,value:r}){await oc(n,async()=>e.write(G(t,n),`ref: ${r.trim()}\n`,`utf8`))}static async deleteRef({fs:t,gitdir:n,ref:r}){return e.deleteRefs({fs:t,gitdir:n,refs:[r]})}static async deleteRefs({fs:e,gitdir:t,refs:n}){await Promise.all(n.map(n=>e.rm(G(t,n))));let r=await oc(`packed-refs`,async()=>e.read(`${t}/packed-refs`,{encoding:`utf8`})),i=Ms.from(r),a=i.refs.size;for(let e of n)i.refs.has(e)&&i.delete(e);i.refs.size<a&&(r=i.toString(),await oc(`packed-refs`,async()=>e.write(`${t}/packed-refs`,r,{encoding:`utf8`})))}static async resolve({fs:t,gitdir:n,ref:r,depth:i=void 0}){if(i!==void 0&&(i--,i===-1))return r;if(r.startsWith(`ref: `))return r=r.slice(5),e.resolve({fs:t,gitdir:n,ref:r,depth:i});if(r.length===40&&/[0-9a-f]{40}/.test(r))return r;let a=await e.packedRefs({fs:t,gitdir:n}),o=rc(r).filter(e=>!ic.includes(e));for(let r of o){let o=await oc(r,async()=>await t.read(`${n}/${r}`,{encoding:`utf8`})||a.get(r));if(o)return e.resolve({fs:t,gitdir:n,ref:o.trim(),depth:i})}throw new Os(r)}static async exists({fs:t,gitdir:n,ref:r}){try{return await e.expand({fs:t,gitdir:n,ref:r}),!0}catch{return!1}}static async expand({fs:t,gitdir:n,ref:r}){if(r.length===40&&/[0-9a-f]{40}/.test(r))return r;let i=await e.packedRefs({fs:t,gitdir:n}),a=rc(r);for(let e of a)if(await oc(e,async()=>t.exists(`${n}/${e}`))||i.has(e))return e;throw new Os(r)}static async expandAgainstMap({ref:e,map:t}){let n=rc(e);for(let e of n)if(await t.has(e))return e;throw new Os(e)}static resolveAgainstMap({ref:t,fullref:n=t,depth:r=void 0,map:i}){if(r!==void 0&&(r--,r===-1))return{fullref:n,oid:t};if(t.startsWith(`ref: `))return t=t.slice(5),e.resolveAgainstMap({ref:t,fullref:n,depth:r,map:i});if(t.length===40&&/[0-9a-f]{40}/.test(t))return{fullref:n,oid:t};let a=rc(t);for(let t of a){let n=i.get(t);if(n)return e.resolveAgainstMap({ref:n.trim(),fullref:t,depth:r,map:i})}throw new Os(t)}static async packedRefs({fs:e,gitdir:t}){let n=await oc(`packed-refs`,async()=>e.read(`${t}/packed-refs`,{encoding:`utf8`}));return Ms.from(n).refs}static async listRefs({fs:t,gitdir:n,filepath:r}){let i=e.packedRefs({fs:t,gitdir:n}),a=null;try{a=await t.readdirDeep(`${n}/${r}`),a=a.map(e=>e.replace(`${n}/${r}/`,``))}catch{a=[]}for(let e of(await i).keys())e.startsWith(r)&&(e=e.replace(r+`/`,``),a.includes(e)||a.push(e));return a.sort(Fs),a}static async listBranches({fs:t,gitdir:n,remote:r}){return r?e.listRefs({fs:t,gitdir:n,filepath:`refs/remotes/${r}`}):e.listRefs({fs:t,gitdir:n,filepath:`refs/heads`})}static async listTags({fs:t,gitdir:n}){return(await e.listRefs({fs:t,gitdir:n,filepath:`refs/tags`})).filter(e=>!e.endsWith(`^{}`))}};function sc(e,t){return $o(cc(e),cc(t))}function cc(e){return e.mode===`040000`?e.path+`/`:e.path}function lc(e){switch(e){case`040000`:return`tree`;case`100644`:return`blob`;case`100755`:return`blob`;case`120000`:return`blob`;case`160000`:return`commit`}throw new W(`Unexpected GitTree entry mode: ${e}`)}function uc(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(32,n);if(r===-1)throw new W(`GitTree: Error parsing buffer at byte location ${n}: Could not find the next space character.`);let i=e.indexOf(0,n);if(i===-1)throw new W(`GitTree: Error parsing buffer at byte location ${n}: Could not find the next null character.`);let a=e.slice(n,r).toString(`utf8`);a===`40000`&&(a=`040000`);let o=lc(a),s=e.slice(r+1,i).toString(`utf8`);if(s.includes(`\\`)||s.includes(`/`))throw new Zo(s);let c=e.slice(i+1,i+21).toString(`hex`);n=i+21,t.push({mode:a,path:s,oid:c,type:o})}return t}function dc(e){if(typeof e==`number`&&(e=e.toString(8)),e.match(/^0?4.*/))return`040000`;if(e.match(/^1006.*/))return`100644`;if(e.match(/^1007.*/))return`100755`;if(e.match(/^120.*/))return`120000`;if(e.match(/^160.*/))return`160000`;throw new W(`Could not understand file mode: ${e}`)}function fc(e){return!e.oid&&e.sha&&(e.oid=e.sha),e.mode=dc(e.mode),e.type||=lc(e.mode),e}var pc=class e{constructor(e){if(Buffer.isBuffer(e))this._entries=uc(e);else if(Array.isArray(e))this._entries=e.map(fc);else throw new W(`invalid type passed to GitTree constructor`);this._entries.sort(es)}static from(t){return new e(t)}render(){return this._entries.map(e=>`${e.mode} ${e.type} ${e.oid} ${e.path}`).join(`
735
+ `)}toObject(){let e=[...this._entries];return e.sort(sc),Buffer.concat(e.map(e=>{let t=Buffer.from(e.mode.replace(/^0/,``)),n=Buffer.from(` `),r=Buffer.from(e.path,`utf8`),i=Buffer.from([0]),a=Buffer.from(e.oid,`hex`);return Buffer.concat([t,n,r,i,a])}))}entries(){return this._entries}*[Symbol.iterator](){for(let e of this._entries)yield e}},mc=class{static wrap({type:e,object:t}){let n=`${e} ${t.length}\x00`,r=n.length,i=r+t.length,a=new Uint8Array(i);for(let e=0;e<r;e++)a[e]=n.charCodeAt(e);return a.set(t,r),a}static unwrap(e){let t=e.indexOf(32),n=e.indexOf(0),r=e.slice(0,t).toString(`utf8`),i=e.slice(t+1,n).toString(`utf8`),a=e.length-(n+1);if(parseInt(i)!==a)throw new W(`Length mismatch: expected ${i} bytes but got ${a} instead.`);return{type:r,object:Buffer.from(e.slice(n+1))}}};async function hc({fs:e,gitdir:t,oid:n}){let r=`objects/${n.slice(0,2)}/${n.slice(2)}`,i=await e.read(`${t}/${r}`);return i?{object:i,format:`deflated`,source:r}:null}function gc(e,t){let n=new Qo(e),r=_c(n);if(r!==t.byteLength)throw new W(`applyDelta expected source buffer to be ${r} bytes but the provided buffer was ${t.length} bytes`);let i=_c(n),a,o=yc(n,t);if(o.byteLength===i)a=o;else{a=Buffer.alloc(i);let e=new Qo(a);for(e.copy(o);!n.eof();)e.copy(yc(n,t));let r=e.tell();if(i!==r)throw new W(`applyDelta expected target buffer to be ${i} bytes but the resulting buffer was ${r} bytes`)}return a}function _c(e){let t=0,n=0,r=null;do r=e.readUInt8(),t|=(r&127)<<n,n+=7;while(r&128);return t}function vc(e,t,n){let r=0,i=0;for(;n--;)t&1&&(r|=e.readUInt8()<<i),t>>=1,i+=8;return r}function yc(e,t){let n=e.readUInt8();if(n&128){let r=vc(e,n&15,4),i=vc(e,(n&112)>>4,3);return i===0&&(i=65536),t.slice(r,r+i)}else return e.slice(n)}function bc(e){let t=[e];return{next(){return Promise.resolve({done:t.length===0,value:t.pop()})},return(){return t=[],{}},[Symbol.asyncIterator](){return this}}}function xc(e){return e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]?e[Symbol.iterator]():e.next?e:bc(e)}var Sc=class{constructor(e){if(typeof Buffer>`u`)throw Error(`Missing Buffer dependency`);this.stream=xc(e),this.buffer=null,this.cursor=0,this.undoCursor=0,this.started=!1,this._ended=!1,this._discardedBytes=0}eof(){return this._ended&&this.cursor===this.buffer.length}tell(){return this._discardedBytes+this.cursor}async byte(){if(!this.eof()&&(this.started||await this._init(),!(this.cursor===this.buffer.length&&(await this._loadnext(),this._ended))))return this._moveCursor(1),this.buffer[this.undoCursor]}async chunk(){if(!this.eof()&&(this.started||await this._init(),!(this.cursor===this.buffer.length&&(await this._loadnext(),this._ended))))return this._moveCursor(this.buffer.length),this.buffer.slice(this.undoCursor,this.cursor)}async read(e){if(!this.eof())return this.started||await this._init(),this.cursor+e>this.buffer.length&&(this._trim(),await this._accumulate(e)),this._moveCursor(e),this.buffer.slice(this.undoCursor,this.cursor)}async skip(e){this.eof()||(this.started||await this._init(),this.cursor+e>this.buffer.length&&(this._trim(),await this._accumulate(e)),this._moveCursor(e))}async undo(){this.cursor=this.undoCursor}async _next(){this.started=!0;let{done:e,value:t}=await this.stream.next();return e&&(this._ended=!0,!t)?Buffer.alloc(0):(t&&=Buffer.from(t),t)}_trim(){this.buffer=this.buffer.slice(this.undoCursor),this.cursor-=this.undoCursor,this._discardedBytes+=this.undoCursor,this.undoCursor=0}_moveCursor(e){this.undoCursor=this.cursor,this.cursor+=e,this.cursor>this.buffer.length&&(this.cursor=this.buffer.length)}async _accumulate(e){if(this._ended)return;let t=[this.buffer];for(;this.cursor+e>Cc(t);){let e=await this._next();if(this._ended)break;t.push(e)}this.buffer=Buffer.concat(t)}async _loadnext(){this._discardedBytes+=this.buffer.length,this.undoCursor=0,this.cursor=0,this.buffer=await this._next()}async _init(){this.buffer=await this._next()}};function Cc(e){return e.reduce((e,t)=>e+t.length,0)}async function wc(e,t){let n=new Sc(e),r=await n.read(4);if(r=r.toString(`utf8`),r!==`PACK`)throw new W(`Invalid PACK header '${r}'`);let i=await n.read(4);if(i=i.readUInt32BE(0),i!==2)throw new W(`Invalid packfile version: ${i}`);let a=await n.read(4);if(a=a.readUInt32BE(0),!(a<1))for(;!n.eof()&&a--;){let e=n.tell(),{type:r,length:i,ofs:o,reference:s}=await Tc(n),c=new Go.default.Inflate;for(;!c.result;){let l=await n.chunk();if(!l)break;if(c.push(l,!1),c.err)throw new W(`Pako error: ${c.msg}`);if(c.result){if(c.result.length!==i)throw new W(`Inflated object size is different from that stated in packfile.`);await n.undo(),await n.read(l.length-c.strm.avail_in);let u=n.tell();await t({data:c.result,type:r,num:a,offset:e,end:u,reference:s,ofs:o})}}}}async function Tc(e){let t=await e.byte(),n=t>>4&7,r=t&15;if(t&128){let n=4;do t=await e.byte(),r|=(t&127)<<n,n+=7;while(t&128)}let i,a;if(n===6){let n=0;i=0;let r=[];do t=await e.byte(),i|=(t&127)<<n,n+=7,r.push(t);while(t&128);a=Buffer.from(r)}return n===7&&(a=await e.read(20)),{type:n,length:r,ofs:i,reference:a}}var Ec=!1;async function Dc(e){return Ec===null&&(Ec=kc()),Ec?Oc(e):Go.default.inflate(e)}async function Oc(e){let t=new DecompressionStream(`deflate`),n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}function kc(){try{if(new DecompressionStream(`deflate`))return!0}catch{}return!1}function Ac(e){let t=[],n=0,r=0;do{n=e.readUInt8();let i=n&127;t.push(i),r=n&128}while(r);return t.reduce((e,t)=>e+1<<7|t,-1)}function jc(e,t){let n=t,r=4,i=null;do i=e.readUInt8(),n|=(i&127)<<r,r+=7;while(i&128);return n}var Mc=class e{constructor(e){Object.assign(this,e),this.offsetCache={}}static async fromIdx({idx:t,getExternalRefDelta:n}){let r=new Qo(t);if(r.slice(4).toString(`hex`)!==`ff744f63`)return;let i=r.readUInt32BE();if(i!==2)throw new W(`Unable to read version ${i} packfile IDX. (Only version 2 supported)`);if(t.byteLength>2048*1024*1024)throw new W(`To keep implementation simple, I haven't implemented the layer 5 feature needed to support packfiles > 2GB in size.`);r.seek(r.tell()+1020);let a=r.readUInt32BE(),o=[];for(let e=0;e<a;e++)o[e]=r.slice(20).toString(`hex`);r.seek(r.tell()+4*a);let s=new Map;for(let e=0;e<a;e++)s.set(o[e],r.readUInt32BE());return new e({hashes:o,crcs:{},offsets:s,packfileSha:r.slice(20).toString(`hex`),getExternalRefDelta:n})}static async fromPack({pack:t,getExternalRefDelta:n,onProgress:r}){let i={1:`commit`,2:`tree`,3:`blob`,4:`tag`,6:`ofs-delta`,7:`ref-delta`},a={},o=t.slice(-20).toString(`hex`),s=[],c={},l=new Map,u=null,d=null;await wc([t],async({data:e,type:t,reference:n,offset:o,num:s})=>{u===null&&(u=s);let c=Math.floor((u-s)*100/u);c!==d&&r&&await r({phase:`Receiving objects`,loaded:u-s,total:u}),d=c,t=i[t],([`commit`,`tree`,`blob`,`tag`].includes(t)||t===`ofs-delta`||t===`ref-delta`)&&(a[o]={type:t,offset:o})});let f=Object.keys(a).map(Number);for(let[e,n]of f.entries()){let r=e+1===f.length?t.byteLength-20:f[e+1],i=a[n],o=Wo.default.buf(t.slice(n,r))>>>0;i.end=r,i.crc=o}let p=new e({pack:Promise.resolve(t),packfileSha:o,crcs:c,hashes:s,offsets:l,getExternalRefDelta:n});d=null;let m=0,h=[0,0,0,0,0,0,0,0,0,0,0,0];for(let e in a){e=Number(e);let t=Math.floor(m*100/u);t!==d&&r&&await r({phase:`Resolving deltas`,loaded:m,total:u}),m++,d=t;let n=a[e];if(!n.oid)try{p.readDepth=0,p.externalReadDepth=0;let{type:t,object:r}=await p.readSlice({start:e});h[p.readDepth]+=1;let i=await ss(mc.wrap({type:t,object:r}));n.oid=i,s.push(i),l.set(i,e),c[i]=n.crc}catch{continue}}return s.sort(),p}async toBuffer(){let e=[],t=(t,n)=>{e.push(Buffer.from(t,n))};t(`ff744f63`,`hex`),t(`00000002`,`hex`);let n=new Qo(Buffer.alloc(256*4));for(let e=0;e<256;e++){let t=0;for(let n of this.hashes)parseInt(n.slice(0,2),16)<=e&&t++;n.writeUInt32BE(t)}e.push(n.buffer);for(let e of this.hashes)t(e,`hex`);let r=new Qo(Buffer.alloc(this.hashes.length*4));for(let e of this.hashes)r.writeUInt32BE(this.crcs[e]);e.push(r.buffer);let i=new Qo(Buffer.alloc(this.hashes.length*4));for(let e of this.hashes)i.writeUInt32BE(this.offsets.get(e));e.push(i.buffer),t(this.packfileSha,`hex`);let a=Buffer.concat(e),o=await ss(a),s=Buffer.alloc(20);return s.write(o,`hex`),Buffer.concat([a,s])}async load({pack:e}){this.pack=e}async unload(){this.pack=null}async read({oid:e}){if(!this.offsets.get(e)){if(this.getExternalRefDelta)return this.externalReadDepth++,this.getExternalRefDelta(e);throw new W(`Could not read object ${e} from packfile`)}let t=this.offsets.get(e);return this.readSlice({start:t})}async readSlice({start:e}){if(this.offsetCache[e])return Object.assign({},this.offsetCache[e]);this.readDepth++;let t={16:`commit`,32:`tree`,48:`blob`,64:`tag`,96:`ofs_delta`,112:`ref_delta`},n=await this.pack;if(!n)throw new W(`Could not read packfile data. The packfile may be missing, corrupted, or too large to read into memory.`);let r=n.slice(e),i=new Qo(r),a=i.readUInt8(),o=a&112,s=t[o];if(s===void 0)throw new W(`Unrecognized type: 0b`+o.toString(2));let c=a&15,l=c;a&128&&(l=jc(i,c));let u=null,d=null;if(s===`ofs_delta`){let t=e-Ac(i);({object:u,type:s}=await this.readSlice({start:t}))}if(s===`ref_delta`){let e=i.slice(20).toString(`hex`);({object:u,type:s}=await this.read({oid:e}))}let f=r.slice(i.tell());if(d=Buffer.from(await Dc(f)),d.byteLength!==l)throw new W(`Packfile told us object would have length ${l} but it had length ${d.byteLength}`);return u&&(d=Buffer.from(gc(d,u))),this.readDepth>3&&(this.offsetCache[e]={type:s,object:d}),{type:s,format:`content`,object:d}}},Nc=Symbol(`PackfileCache`);async function Pc({fs:e,filename:t,getExternalRefDelta:n,emitter:r,emitterPrefix:i}){let a=await e.read(t);return Mc.fromIdx({idx:a,getExternalRefDelta:n})}function Fc({fs:e,cache:t,filename:n,getExternalRefDelta:r,emitter:i,emitterPrefix:a}){t[Nc]||(t[Nc]=new Map);let o=t[Nc].get(n);return o||(o=Pc({fs:e,filename:n,getExternalRefDelta:r,emitter:i,emitterPrefix:a}),t[Nc].set(n,o)),o}async function Ic(e,{start:t=0,end:n=e.length}={}){return ss(e.subarray(t,n))}async function Lc({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`,getExternalRefDelta:a}){let o=await e.readdir(G(n,`objects/pack`));o=o.filter(e=>e.endsWith(`.idx`));for(let i of o){let o=`${n}/objects/pack/${i}`,s=await Fc({fs:e,cache:t,filename:o,getExternalRefDelta:a});if(s.error)throw new W(s.error);if(s.offsets.has(r)){let t=o.replace(/idx$/,`pack`);s.pack||=e.read(t);let n=await s.pack;if(!n)throw s.pack=null,new W(`Could not read packfile at ${t}. The file may be missing, corrupted, or too large to read into memory.`);if(!s._checksumVerified){let e=s.packfileSha,t=n.subarray(-20),r=Array.from(t).map(e=>e.toString(16).padStart(2,`0`)).join(``);if(r!==e)throw new W(`Packfile trailer mismatch: expected ${e}, got ${r}. The packfile may be corrupted.`);let i=await Ic(n,{start:0,end:n.length-20});if(i!==e)throw new W(`Packfile payload corrupted: calculated ${i} but expected ${e}. The packfile may have been tampered with.`);s._checksumVerified=!0}let c=await s.read({oid:r,getExternalRefDelta:a});return c.format=`content`,c.source=`objects/pack/${i.replace(/idx$/,`pack`)}`,c}}return null}async function Rc({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`}){let a=r=>Rc({fs:e,cache:t,gitdir:n,oid:r}),o;if(r===`4b825dc642cb6eb9a060e54bf8d69288fbee4904`&&(o={format:`wrapped`,object:Buffer.from(`tree 0\0`)}),o||=await hc({fs:e,gitdir:n,oid:r}),!o){if(o=await Lc({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:a}),!o)throw new Os(r);return o}if(i===`deflated`||(o.format===`deflated`&&(o.object=Buffer.from(await Dc(o.object)),o.format=`wrapped`),i===`wrapped`))return o;let s=await ss(o.object);if(s!==r)throw new W(`SHA check failed! Expected ${r}, computed ${s}`);let{object:c,type:l}=mc.unwrap(o.object);if(o.type=l,o.object=c,o.format=`content`,i===`content`)return o;throw new W(`invalid requested format "${i}"`)}var zc=class e extends U{constructor(t,n,r=!0){super(`Failed to create ${t} at ${n} because it already exists.${r?` (Hint: use 'force: true' parameter to overwrite existing ${t}.)`:``}`),this.code=this.name=e.code,this.data={noun:t,where:n,canForce:r}}};zc.code=`AlreadyExistsError`;var Bc=class e extends U{constructor(t,n,r){super(`Found multiple ${t} matching "${n}" (${r.join(`, `)}). Use a longer abbreviation length to disambiguate them.`),this.code=this.name=e.code,this.data={nouns:t,short:n,matches:r}}};Bc.code=`AmbiguousError`;var Vc=class e extends U{constructor(t){super(`Your local changes to the following files would be overwritten by checkout: ${t.join(`, `)}`),this.code=this.name=e.code,this.data={filepaths:t}}};Vc.code=`CheckoutConflictError`;var Hc=class e extends U{constructor(t,n){super(`Cannot cherry-pick merge commit ${t}. Merge commits have ${n} parents and require specifying which parent to use as the base.`),this.code=this.name=e.code,this.data={oid:t,parentCount:n}}};Hc.code=`CherryPickMergeCommitError`;var Uc=class e extends U{constructor(t){super(`Cannot cherry-pick root commit ${t}. Root commits have no parents.`),this.code=this.name=e.code,this.data={oid:t}}};Uc.code=`CherryPickRootCommitError`;var Wc=class e extends U{constructor(t,n){super(`Failed to checkout "${t}" because commit ${n} is not available locally. Do a git fetch to make the branch available locally.`),this.code=this.name=e.code,this.data={ref:t,oid:n}}};Wc.code=`CommitNotFetchedError`;var Gc=class e extends U{constructor(){super(`Empty response from git server.`),this.code=this.name=e.code,this.data={}}};Gc.code=`EmptyServerResponseError`;var Kc=class e extends U{constructor(){super(`A simple fast-forward merge was not possible.`),this.code=this.name=e.code,this.data={}}};Kc.code=`FastForwardError`;var qc=class e extends U{constructor(t,n){super(`One or more branches were not updated: ${t}`),this.code=this.name=e.code,this.data={prettyDetails:t,result:n}}};qc.code=`GitPushError`;var Jc=class e extends U{constructor(t,n,r){super(`HTTP Error: ${t} ${n}`),this.code=this.name=e.code,this.data={statusCode:t,statusMessage:n,response:r}}};Jc.code=`HttpError`;var Yc=class e extends U{constructor(t){let n=`invalid filepath`;t===`leading-slash`||t===`trailing-slash`?n=`"filepath" parameter should not include leading or trailing directory separators because these can cause problems on some platforms.`:t===`directory`&&(n=`"filepath" should not be a directory.`),super(n),this.code=this.name=e.code,this.data={reason:t}}};Yc.code=`InvalidFilepathError`;var Xc=class e extends U{constructor(t,n){super(`"${t}" would be an invalid git reference. (Hint: a valid alternative would be "${n}".)`),this.code=this.name=e.code,this.data={ref:t,suggestion:n}}};Xc.code=`InvalidRefNameError`;var Zc=class e extends U{constructor(t){super(`Maximum search depth of ${t} exceeded.`),this.code=this.name=e.code,this.data={depth:t}}};Zc.code=`MaxDepthError`;var Qc=class e extends U{constructor(){super(`Merges with conflicts are not supported yet.`),this.code=this.name=e.code,this.data={}}};Qc.code=`MergeNotSupportedError`;var $c=class e extends U{constructor(t,n,r,i){super(`Automatic merge failed with one or more merge conflicts in the following files: ${t.toString()}. Fix conflicts then commit the result.`),this.code=this.name=e.code,this.data={filepaths:t,bothModified:n,deleteByUs:r,deleteByTheirs:i}}};$c.code=`MergeConflictError`;var el=class e extends U{constructor(t){super(`No name was provided for ${t} in the argument or in the .git/config file.`),this.code=this.name=e.code,this.data={role:t}}};el.code=`MissingNameError`;var tl=class e extends U{constructor(t){super(`The function requires a "${t}" parameter but none was provided.`),this.code=this.name=e.code,this.data={parameter:t}}};tl.code=`MissingParameterError`;var nl=class e extends U{constructor(t){super(`There are multiple errors that were thrown by the method. Please refer to the "errors" property to see more`),this.code=this.name=e.code,this.data={errors:t},this.errors=t}};nl.code=`MultipleGitError`;var rl=class e extends U{constructor(t,n){super(`Expected "${t}" but received "${n}".`),this.code=this.name=e.code,this.data={expected:t,actual:n}}};rl.code=`ParseError`;var il=class e extends U{constructor(t){let n=``;t===`not-fast-forward`?n=` because it was not a simple fast-forward`:t===`tag-exists`&&(n=` because tag already exists`),super(`Push rejected${n}. Use "force: true" to override.`),this.code=this.name=e.code,this.data={reason:t}}};il.code=`PushRejectedError`;var al=class e extends U{constructor(t,n){super(`Remote does not support the "${t}" so the "${n}" parameter cannot be used.`),this.code=this.name=e.code,this.data={capability:t,parameter:n}}};al.code=`RemoteCapabilityError`;var ol=class e extends U{constructor(t,n){super(`Remote did not reply using the "smart" HTTP protocol. Expected "001e# service=git-upload-pack" but received: ${t}`),this.code=this.name=e.code,this.data={preview:t,response:n}}};ol.code=`SmartHttpError`;var sl=class e extends U{constructor(t,n,r){super(`Git remote "${t}" uses an unrecognized transport protocol: "${n}"`),this.code=this.name=e.code,this.data={url:t,transport:n,suggestion:r}}};sl.code=`UnknownTransportError`;var cl=class e extends U{constructor(t){super(`Cannot parse remote URL: "${t}"`),this.code=this.name=e.code,this.data={url:t}}};cl.code=`UrlParseError`;var ll=class e extends U{constructor(){super(`The operation was canceled.`),this.code=this.name=e.code,this.data={}}};ll.code=`UserCanceledError`;var ul=class e extends U{constructor(t){super(`Could not merge index: Entry for '${t}' is not up to date. Either reset the index entry to HEAD, or stage your unstaged changes.`),this.code=this.name=e.code,this.data={filepath:t}}};ul.code=`IndexResetError`;var dl=class e extends U{constructor(t){super(`"${t}" does not point to any commit. You're maybe working on a repository with no commits yet. `),this.code=this.name=e.code,this.data={ref:t}}};dl.code=`NoCommitError`;function fl({name:e,email:t,timestamp:n,timezoneOffset:r}){return r=pl(r),`${e} <${t}> ${n} ${r}`}function pl(e){let t=ml(hl(e));e=Math.abs(e);let n=Math.floor(e/60);e-=n*60;let r=String(n),i=String(e);return r.length<2&&(r=`0`+r),i.length<2&&(i=`0`+i),(t===-1?`-`:`+`)+r+i}function ml(e){return Math.sign(e)||(Object.is(e,-0)?-1:1)}function hl(e){return e===0?e:-e}function gl(e){return e=e.replace(/\r/g,``),e=e.replace(/^\n+/,``),e=e.replace(/\n+$/,``)+`
736
+ `,e}function _l(e){let[,t,n,r,i]=e.match(/^(.*) <(.*)> (.*) (.*)$/);return{name:t,email:n,timestamp:Number(r),timezoneOffset:vl(i)}}function vl(e){let[,t,n,r]=e.match(/(\+|-)(\d\d)(\d\d)/);return r=(t===`+`?1:-1)*(Number(n)*60+Number(r)),yl(r)}function yl(e){return e===0?e:-e}var bl=class e{constructor(t){if(typeof t==`string`)this._tag=t;else if(Buffer.isBuffer(t))this._tag=t.toString(`utf8`);else if(typeof t==`object`)this._tag=e.render(t);else throw new W(`invalid type passed to GitAnnotatedTag constructor`)}static from(t){return new e(t)}static render(e){return`object ${e.object}
737
737
  type ${e.type}
738
738
  tag ${e.tag}
739
- tagger ${cl(e.tagger)}
739
+ tagger ${fl(e.tagger)}
740
740
 
741
741
  ${e.message}
742
742
  ${e.gpgsig?e.gpgsig:``}`}justHeaders(){return this._tag.slice(0,this._tag.indexOf(`
@@ -745,50 +745,50 @@ ${e.gpgsig?e.gpgsig:``}`}justHeaders(){return this._tag.slice(0,this._tag.indexO
745
745
 
746
746
  `)+2)}parse(){return Object.assign(this.headers(),{message:this.message(),gpgsig:this.gpgsig()})}render(){return this._tag}headers(){let e=this.justHeaders().split(`
747
747
  `),t=[];for(let n of e)n[0]===` `?t[t.length-1]+=`
748
- `+n.slice(1):t.push(n);let n={};for(let e of t){let t=e.slice(0,e.indexOf(` `)),r=e.slice(e.indexOf(` `)+1);Array.isArray(n[t])?n[t].push(r):n[t]=r}return n.tagger&&=pl(n.tagger),n.committer&&=pl(n.committer),n}withoutSignature(){let e=fl(this._tag);return e.indexOf(`
748
+ `+n.slice(1):t.push(n);let n={};for(let e of t){let t=e.slice(0,e.indexOf(` `)),r=e.slice(e.indexOf(` `)+1);Array.isArray(n[t])?n[t].push(r):n[t]=r}return n.tagger&&=_l(n.tagger),n.committer&&=_l(n.committer),n}withoutSignature(){let e=gl(this._tag);return e.indexOf(`
749
749
  -----BEGIN PGP SIGNATURE-----`)===-1?e:e.slice(0,e.lastIndexOf(`
750
750
  -----BEGIN PGP SIGNATURE-----`))}gpgsig(){if(this._tag.indexOf(`
751
- -----BEGIN PGP SIGNATURE-----`)!==-1)return fl(this._tag.slice(this._tag.indexOf(`-----BEGIN PGP SIGNATURE-----`),this._tag.indexOf(`-----END PGP SIGNATURE-----`)+27))}payload(){return this.withoutSignature()+`
752
- `}toObject(){return Buffer.from(this._tag,`utf8`)}static async sign(t,n,r){let i=t.payload(),{signature:a}=await n({payload:i,secretKey:r});a=fl(a);let o=i+a;return e.from(o)}};function _l(e){return e.trim().split(`
751
+ -----BEGIN PGP SIGNATURE-----`)!==-1)return gl(this._tag.slice(this._tag.indexOf(`-----BEGIN PGP SIGNATURE-----`),this._tag.indexOf(`-----END PGP SIGNATURE-----`)+27))}payload(){return this.withoutSignature()+`
752
+ `}toObject(){return Buffer.from(this._tag,`utf8`)}static async sign(t,n,r){let i=t.payload(),{signature:a}=await n({payload:i,secretKey:r});a=gl(a);let o=i+a;return e.from(o)}};function xl(e){return e.trim().split(`
753
753
  `).map(e=>` `+e).join(`
754
754
  `)+`
755
- `}function vl(e){return e.split(`
755
+ `}function Sl(e){return e.split(`
756
756
  `).map(e=>e.replace(/^ /,``)).join(`
757
- `)}var yl=class e{constructor(t){if(typeof t==`string`)this._commit=t;else if(Buffer.isBuffer(t))this._commit=t.toString(`utf8`);else if(typeof t==`object`)this._commit=e.render(t);else throw new W(`invalid type passed to GitCommit constructor`)}static fromPayloadSignature({payload:t,signature:n}){let r=e.justHeaders(t),i=e.justMessage(t);return new e(fl(r+`
758
- gpgsig`+_l(n)+`
759
- `+i))}static from(t){return new e(t)}toObject(){return Buffer.from(this._commit,`utf8`)}headers(){return this.parseHeaders()}message(){return e.justMessage(this._commit)}parse(){return Object.assign({message:this.message()},this.headers())}static justMessage(e){return fl(e.slice(e.indexOf(`
757
+ `)}var Cl=class e{constructor(t){if(typeof t==`string`)this._commit=t;else if(Buffer.isBuffer(t))this._commit=t.toString(`utf8`);else if(typeof t==`object`)this._commit=e.render(t);else throw new W(`invalid type passed to GitCommit constructor`)}static fromPayloadSignature({payload:t,signature:n}){let r=e.justHeaders(t),i=e.justMessage(t);return new e(gl(r+`
758
+ gpgsig`+xl(n)+`
759
+ `+i))}static from(t){return new e(t)}toObject(){return Buffer.from(this._commit,`utf8`)}headers(){return this.parseHeaders()}message(){return e.justMessage(this._commit)}parse(){return Object.assign({message:this.message()},this.headers())}static justMessage(e){return gl(e.slice(e.indexOf(`
760
760
 
761
761
  `)+2))}static justHeaders(e){return e.slice(0,e.indexOf(`
762
762
 
763
763
  `))}parseHeaders(){let t=e.justHeaders(this._commit).split(`
764
764
  `),n=[];for(let e of t)e[0]===` `?n[n.length-1]+=`
765
- `+e.slice(1):n.push(e);let r={parent:[]};for(let e of n){let t=e.slice(0,e.indexOf(` `)),n=e.slice(e.indexOf(` `)+1);Array.isArray(r[t])?r[t].push(n):r[t]=n}return r.author&&=pl(r.author),r.committer&&=pl(r.committer),r}static renderHeaders(e){let t=``;if(e.tree?t+=`tree ${e.tree}\n`:t+=`tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
766
- `,e.parent){if(e.parent.length===void 0)throw new W(`commit 'parent' property should be an array`);for(let n of e.parent)t+=`parent ${n}\n`}let n=e.author;t+=`author ${cl(n)}\n`;let r=e.committer||e.author;return t+=`committer ${cl(r)}\n`,e.gpgsig&&(t+=`gpgsig`+_l(e.gpgsig)),t}static render(t){return e.renderHeaders(t)+`
767
- `+fl(t.message)}render(){return this._commit}withoutSignature(){let e=fl(this._commit);if(e.indexOf(`
765
+ `+e.slice(1):n.push(e);let r={parent:[]};for(let e of n){let t=e.slice(0,e.indexOf(` `)),n=e.slice(e.indexOf(` `)+1);Array.isArray(r[t])?r[t].push(n):r[t]=n}return r.author&&=_l(r.author),r.committer&&=_l(r.committer),r}static renderHeaders(e){let t=``;if(e.tree?t+=`tree ${e.tree}\n`:t+=`tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
766
+ `,e.parent){if(e.parent.length===void 0)throw new W(`commit 'parent' property should be an array`);for(let n of e.parent)t+=`parent ${n}\n`}let n=e.author;t+=`author ${fl(n)}\n`;let r=e.committer||e.author;return t+=`committer ${fl(r)}\n`,e.gpgsig&&(t+=`gpgsig`+xl(e.gpgsig)),t}static render(t){return e.renderHeaders(t)+`
767
+ `+gl(t.message)}render(){return this._commit}withoutSignature(){let e=gl(this._commit);if(e.indexOf(`
768
768
  gpgsig`)===-1)return e;let t=e.slice(0,e.indexOf(`
769
769
  gpgsig`)),n=e.slice(e.indexOf(`-----END PGP SIGNATURE-----
770
- `)+28);return fl(t+`
771
- `+n)}isolateSignature(){return vl(this._commit.slice(this._commit.indexOf(`-----BEGIN PGP SIGNATURE-----`),this._commit.indexOf(`-----END PGP SIGNATURE-----`)+27))}static async sign(t,n,r){let i=t.withoutSignature(),a=e.justMessage(t._commit),{signature:o}=await n({payload:i,secretKey:r});o=fl(o);let s=e.justHeaders(t._commit)+`
772
- gpgsig`+_l(o)+`
773
- `+a;return e.from(s)}};async function bl({fs:e,cache:t,gitdir:n,oid:r}){if(r===`4b825dc642cb6eb9a060e54bf8d69288fbee4904`)return{tree:lc.from([]),oid:r};let{type:i,object:a}=await Pc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=gl.from(a).parse().object,bl({fs:e,cache:t,gitdir:n,oid:r});if(i===`commit`)return r=yl.from(a).parse().tree,bl({fs:e,cache:t,gitdir:n,oid:r});if(i!==`tree`)throw new Ts(r,i,`tree`);return{tree:lc.from(a),oid:r}}var xl=class{constructor({fs:e,gitdir:t,ref:n,cache:r}){this.fs=e,this.cache=r,this.gitdir=t,this.mapPromise=(async()=>{let r=new Map,i;try{i=await K.resolve({fs:e,gitdir:t,ref:n})}catch(e){e instanceof ws&&(i=`4b825dc642cb6eb9a060e54bf8d69288fbee4904`)}let a=await bl({fs:e,cache:this.cache,gitdir:t,oid:i});return a.type=`tree`,a.mode=`40000`,r.set(`.`,a),r})();let i=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let t=e._fullpath,{fs:n,cache:r,gitdir:i}=this,a=await this.mapPromise,o=a.get(t);if(!o)throw Error(`No obj for ${t}`);let s=o.oid;if(!s)throw Error(`No oid for obj ${JSON.stringify(o)}`);if(o.type!==`tree`)return null;let{type:c,object:l}=await Pc({fs:n,cache:r,gitdir:i,oid:s});if(c!==o.type)throw new Ts(s,c,o.type);let u=lc.from(l);for(let e of u)a.set(G(t,e.path),e);return u.entries().map(e=>G(t,e.path))}async type(e){if(e._type===!1){let{type:t}=(await this.mapPromise).get(e._fullpath);e._type=t}return e._type}async mode(e){if(e._mode===!1){let{mode:t}=(await this.mapPromise).get(e._fullpath);e._mode=Zo(parseInt(t,8))}return e._mode}async stat(e){}async content(e){if(e._content===!1){let t=await this.mapPromise,{fs:n,cache:r,gitdir:i}=this,a=t.get(e._fullpath).oid,{type:o,object:s}=await Pc({fs:n,cache:r,gitdir:i,oid:a});o===`blob`?e._content=new Uint8Array(s):e._content=void 0}return e._content}async oid(e){return e._oid===!1&&(e._oid=(await this.mapPromise).get(e._fullpath).oid),e._oid}};function Sl({ref:e=`HEAD`}={}){let t=Object.create(null);return Object.defineProperty(t,Ss,{value:function({fs:t,gitdir:n,cache:r}){return new xl({fs:t,gitdir:n,ref:e,cache:r})}}),Object.freeze(t),t}var Cl=class{constructor({fs:e,dir:t,gitdir:n,cache:r}){this.fs=e,this.cache=r,this.dir=t,this.gitdir=n,this.config=null;let i=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let t=e._fullpath,{fs:n,dir:r}=this,i=await n.readdir(G(r,t));return i===null?null:i.map(e=>G(t,e))}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let{fs:t,dir:n}=this,r=await t.lstat(`${n}/${e._fullpath}`);if(!r)throw Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let i=r.isDirectory()?`tree`:`blob`;i===`blob`&&!r.isFile()&&!r.isSymbolicLink()&&(i=`special`),e._type=i,r=es(r),e._mode=r.mode,r.size===-1&&e._actualSize&&(r.size=e._actualSize),e._stat=r}return e._stat}async content(e){if(e._content===!1){let{fs:t,dir:n,gitdir:r}=this;if(await e.type()===`tree`)e._content=void 0;else{let i;if(await e.mode()>>12==10)i=await t.readlink(`${n}/${e._fullpath}`);else{let a=await(await this._getGitConfig(t,r)).get(`core.autocrlf`);i=await t.read(`${n}/${e._fullpath}`,{autocrlf:a})}e._actualSize=i.length,e._stat&&e._stat.size===-1&&(e._stat.size=e._actualSize),e._content=new Uint8Array(i)}}return e._content}async oid(e){if(e._oid===!1){let t=this,{fs:n,gitdir:r,cache:i}=this,a;await gs.acquire({fs:n,gitdir:r,cache:i},async function(i){let o=i.entriesMap.get(e._fullpath),s=await e.stat(),c=await(await t._getGitConfig(n,r)).get(`core.filemode`),l=typeof process<`u`?process.platform!==`win32`:!0;if(!o||us(s,o,c,l)){let t=await e.content();t===void 0?a=void 0:(a=await rs(uc.wrap({type:`blob`,object:t})),o&&a===o.oid&&(!c||s.mode===o.mode)&&us(s,o,c,l)&&i.insert({filepath:e._fullpath,stats:s,oid:a}))}else a=o.oid}),e._oid=a}return e._oid}async _getGitConfig(e,t){return this.config||=await Qs.get({fs:e,gitdir:t}),this.config}};function wl(){let e=Object.create(null);return Object.defineProperty(e,Ss,{value:function({fs:e,dir:t,gitdir:n,cache:r}){return new Cl({fs:e,dir:t,gitdir:n,cache:r})}}),Object.freeze(e),e}function Tl(e,t){let n=t-e;return Array.from({length:n},(t,n)=>e+n)}var El=Array.prototype.flat===void 0?e=>e.reduce((e,t)=>e.concat(t),[]):e=>e.flat(),Dl=class{constructor(){this.value=null}consider(e){e!=null&&(this.value===null||e<this.value)&&(this.value=e)}reset(){this.value=null}};function*Ol(e){let t=new Dl,n,r=[],i=e.length;for(let n=0;n<i;n++)r[n]=e[n].next().value,r[n]!==void 0&&t.consider(r[n]);if(t.value!==null)for(;;){let a=[];n=t.value,t.reset();for(let o=0;o<i;o++)r[o]!==void 0&&r[o]===n?(a[o]=r[o],r[o]=e[o].next().value):a[o]=null,r[o]!==void 0&&t.consider(r[o]);if(yield a,t.value===null)return}}async function kl({fs:e,cache:t,dir:n,gitdir:r,trees:i,map:a=async(e,t)=>t,reduce:o=async(e,t)=>{let n=El(t);return e!==void 0&&n.unshift(e),n},iterate:s=(e,t)=>Promise.all([...t].map(e))}){let c=i.map(i=>i[Ss]({fs:e,dir:n,gitdir:r,cache:t})),l=Array(c.length).fill(`.`),u=Tl(0,c.length),d=async e=>(u.forEach(t=>{let n=e[t];e[t]=n&&new c[t].ConstructEntry(n)}),{entries:e,children:Ol((await Promise.all(u.map(t=>{let n=e[t];return n?c[t].readdir(n):[]}))).map(e=>(e===null?[]:e)[Symbol.iterator]()))}),f=async e=>{let{entries:t,children:n}=await d(e),r=t.find(e=>e&&e._fullpath)._fullpath,i=await a(r,t);if(i!==null){let e=await s(f,n);return e=e.filter(e=>e!==void 0),o(i,e)}};return f(l)}async function Al(e,t){let n=await e.readdir(t);n==null?await e.rm(t):n.length?await Promise.all(n.map(n=>{let r=G(t,n);return e.lstat(r).then(t=>{if(t)return t.isDirectory()?Al(e,r):e.rm(r)})})).then(()=>e.rmdir(t)):await e.rmdir(t)}function jl(e){return Ml(e)&&Nl(e.then)&&Nl(e.catch)}function Ml(e){return e&&typeof e==`object`}function Nl(e){return typeof e==`function`}function Pl(e){return jl((e=>{try{return e.readFile().catch(e=>e)}catch(e){return e}})(e))}var Fl=[`readFile`,`writeFile`,`mkdir`,`rmdir`,`unlink`,`stat`,`lstat`,`readdir`,`readlink`,`symlink`];function Il(e,t){if(Pl(t))for(let n of Fl)e[`_${n}`]=t[n].bind(t);else for(let n of Fl)e[`_${n}`]=(0,Ho.default)(t[n].bind(t));Pl(t)?(t.cp&&(e._cp=t.cp.bind(t)),t.rm?e._rm=t.rm.bind(t):t.rmdir.length>1?e._rm=t.rmdir.bind(t):e._rm=Al.bind(null,e)):(t.cp&&(e._cp=(0,Ho.default)(t.cp.bind(t))),t.rm?e._rm=(0,Ho.default)(t.rm.bind(t)):t.rmdir.length>2?e._rm=(0,Ho.default)(t.rmdir.bind(t)):e._rm=Al.bind(null,e))}var q=class{constructor(e){if(e._original_unwrapped_fs!==void 0)return e;let t=Object.getOwnPropertyDescriptor(e,`promises`);t&&t.enumerable?Il(this,e.promises):Il(this,e),this._original_unwrapped_fs=e}async exists(e,t={}){try{return await this._stat(e),!0}catch(e){if(e.code===`ENOENT`||e.code===`ENOTDIR`||(e.code||``).includes(`ENS`))return!1;throw console.log(`Unhandled error in "FileSystem.exists()" function`,e),e}}async read(e,t={}){try{let n=await this._readFile(e,t);if(t.autocrlf===`true`)try{n=new TextDecoder(`utf8`,{fatal:!0}).decode(n),n=n.replace(/\r\n/g,`
774
- `),n=new TextEncoder().encode(n)}catch{}return typeof n!=`string`&&(n=Buffer.from(n)),n}catch{return null}}async write(e,t,n={}){try{await this._writeFile(e,t,n)}catch{await this.mkdir(vs(e)),await this._writeFile(e,t,n)}}async mkdir(e,t=!1){try{await this._mkdir(e)}catch(n){if(n===null||n.code===`EEXIST`)return;if(t)throw n;if(n.code===`ENOENT`){let t=vs(e);if(t===`.`||t===`/`||t===e)throw n;await this.mkdir(t),await this.mkdir(e,!0)}}}async rm(e){try{await this._unlink(e)}catch(e){if(e.code!==`ENOENT`)throw e}}async rmdir(e,t){try{t&&t.recursive?await this._rm(e,t):await this._rmdir(e)}catch(e){if(e.code!==`ENOENT`)throw e}}async readdir(e){try{let t=await this._readdir(e);return t.sort(Yo),t}catch(e){return e.code===`ENOTDIR`?null:[]}}async readdirDeep(e){let t=await this._readdir(e);return(await Promise.all(t.map(async t=>{let n=e+`/`+t;return(await this._stat(n)).isDirectory()?this.readdirDeep(n):n}))).reduce((e,t)=>e.concat(t),[])}async lstat(e){try{return await this._lstat(e)}catch(e){if(e.code===`ENOENT`||(e.code||``).includes(`ENS`))return null;throw e}}async readlink(e,t={encoding:`buffer`}){try{let n=await this._readlink(e,t);return Buffer.isBuffer(n)?n:Buffer.from(n)}catch(e){if(e.code===`ENOENT`||(e.code||``).includes(`ENS`))return null;throw e}}async writelink(e,t){return this._symlink(t.toString(`utf8`),e)}};function J(e,t){if(t===void 0)throw new Zc(e)}function Ll(e){return e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)}async function Y({fsp:e,dotgit:t}){J(`fsp`,e),J(`dotgit`,t);let n=await e._stat(t).catch(()=>({isFile:()=>!1,isDirectory:()=>!1}));return n.isDirectory()?t:n.isFile()?e._readFile(t,`utf8`).then(e=>e.trimRight().substr(8)).then(e=>Ll(e)?e:G(vs(t),e)):t}async function Rl(e,t){return!e&&!t?!1:e&&!t||!e&&t?!0:!(await e.type()===`tree`&&await t.type()===`tree`||await e.type()===await t.type()&&await e.mode()===await t.mode()&&await e.oid()===await t.oid())}var zl=class{static async isIgnored({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r}){if(_s(r)===`.git`)return!0;if(r===`.`)return!1;let i=``,a=G(n,`info`,`exclude`);await e.exists(a)&&(i=await e.read(a,`utf8`));let o=[{gitignore:G(t,`.gitignore`),filepath:r}],s=r.split(`/`).filter(Boolean);for(let e=1;e<s.length;e++){let n=s.slice(0,e).join(`/`),r=s.slice(e).join(`/`);o.push({gitignore:G(t,n,`.gitignore`),filepath:r})}let c=!1;for(let t of o){let n;try{n=await e.read(t.gitignore,`utf8`)}catch(e){if(e.code===`NOENT`)continue}let r=(0,Uo.default)().add(i);r.add(n);let a=vs(t.filepath);if(a!==`.`&&r.ignores(a))return!0;c=c?!r.test(t.filepath).unignored:r.test(t.filepath).ignored}return c}};async function Bl({fs:e,gitdir:t,object:n,format:r,oid:i}){if(r!==`deflated`)throw new W(`GitObjectStoreLoose expects objects to write to be in deflated format`);let a=`${t}/${`objects/${i.slice(0,2)}/${i.slice(2)}`}`;await e.exists(a)||await e.write(a,n)}var Vl=null;async function Hl(e){return Vl===null&&(Vl=Wl()),Vl?Ul(e):Vo.default.deflate(e)}async function Ul(e){let t=new CompressionStream(`deflate`),n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}function Wl(){try{return new CompressionStream(`deflate`).writable.close(),new Blob([]).stream().cancel(),!0}catch{return!1}}async function Gl({fs:e,gitdir:t,type:n,object:r,format:i=`content`,oid:a=void 0,dryRun:o=!1}){return i!==`deflated`&&(i!==`wrapped`&&(r=uc.wrap({type:n,object:r})),a=await rs(r),r=Buffer.from(await Hl(r))),o||await Bl({fs:e,gitdir:t,object:r,format:`deflated`,oid:a}),a}function Kl(e){let t;for(;~(t=e.indexOf(92));)e[t]=47;return e}async function ql({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,cache:i={},force:a=!1,parallel:o=!0}){try{J(`fs`,e),J(`dir`,t),J(`gitdir`,n),J(`filepath`,r);let s=new q(e),c=await Y({fsp:s,dotgit:n});await gs.acquire({fs:s,gitdir:c,cache:i},async e=>Jl({dir:t,gitdir:c,fs:s,filepath:r,index:e,force:a,parallel:o,autocrlf:await(await Qs.get({fs:s,gitdir:c})).get(`core.autocrlf`)}))}catch(e){throw e.caller=`git.add`,e}}async function Jl({dir:e,gitdir:t,fs:n,filepath:r,index:i,force:a,parallel:o,autocrlf:s}){r=Array.isArray(r)?r:[r];let c=r.map(async r=>{if(!a&&await zl.isIgnored({fs:n,dir:e,gitdir:t,filepath:r}))return;let c=await n.lstat(G(e,r));if(!c)throw new ws(r);if(c.isDirectory()){let c=await n.readdir(G(e,r));if(o){let l=c.map(c=>Jl({dir:e,gitdir:t,fs:n,filepath:[G(r,c)],index:i,force:a,parallel:o,autocrlf:s}));await Promise.all(l)}else for(let l of c)await Jl({dir:e,gitdir:t,fs:n,filepath:[G(r,l)],index:i,force:a,parallel:o,autocrlf:s})}else{let a=c.isSymbolicLink()?await n.readlink(G(e,r)).then(Kl):await n.read(G(e,r),{autocrlf:s});if(a===null)throw new ws(r);let o=await Gl({fs:n,gitdir:t,type:`blob`,object:a});i.insert({filepath:r,stats:c,oid:o})}}),l=await Promise.allSettled(c),u=l.filter(e=>e.status===`rejected`).map(e=>e.reason);if(u.length>1)throw new Qc(u);if(u.length===1)throw u[0];return l.filter(e=>e.status===`fulfilled`&&e.value).map(e=>e.value)}async function Yl({fs:e,gitdir:t,path:n}){return(await Qs.get({fs:e,gitdir:t})).get(n)}function Xl(e,...t){for(let n of t)if(n)for(let t of Object.keys(n)){let r=n[t];r!==void 0&&(e[t]=r)}return e}async function Zl({fs:e,gitdir:t,author:n,commit:r}){let i=Math.floor(Date.now()/1e3),a=Xl({},{name:await Yl({fs:e,gitdir:t,path:`user.name`}),email:await Yl({fs:e,gitdir:t,path:`user.email`})||``,timestamp:i,timezoneOffset:new Date(i*1e3).getTimezoneOffset()},r?r.author:void 0,n);if(a.name!==void 0)return a}async function Ql({fs:e,gitdir:t,author:n,committer:r,commit:i}){let a=Math.floor(Date.now()/1e3),o=Xl({},{name:await Yl({fs:e,gitdir:t,path:`user.name`}),email:await Yl({fs:e,gitdir:t,path:`user.email`})||``,timestamp:a,timezoneOffset:new Date(a*1e3).getTimezoneOffset()},i?i.committer:void 0,n,r);if(o.name!==void 0)return o}async function $l({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await Pc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=gl.from(a).parse().object,$l({fs:e,cache:t,gitdir:n,oid:r});if(i!==`commit`)throw new Ts(r,i,`commit`);return{commit:yl.from(a),oid:r}}async function eu({fs:e,cache:t,gitdir:n,oid:r}){let{commit:i,oid:a}=await $l({fs:e,cache:t,gitdir:n,oid:r});return{oid:a,commit:i.parse(),payload:i.withoutSignature()}}async function tu({fs:e,cache:t,onSign:n,gitdir:r,message:i,author:a,committer:o,signingKey:s,amend:c=!1,dryRun:l=!1,noUpdateBranch:u=!1,ref:d,parent:f,tree:p}){let m=!1,h=!1;d||=(h=!(await e.read(`${r}/HEAD`,{encoding:`utf8`})).startsWith(`ref:`),await K.resolve({fs:e,gitdir:r,ref:`HEAD`,depth:2}));let g,_;try{g=await K.resolve({fs:e,gitdir:r,ref:d}),_=await eu({fs:e,gitdir:r,oid:g,cache:{}})}catch{m=!0}if(c&&m)throw new sl(d);let v=c?await Zl({fs:e,gitdir:r,author:a,commit:_.commit}):await Zl({fs:e,gitdir:r,author:a});if(!v)throw new Xc(`author`);let y=c?await Ql({fs:e,gitdir:r,author:v,committer:o,commit:_.commit}):await Ql({fs:e,gitdir:r,author:v,committer:o});if(!y)throw new Xc(`committer`);return gs.acquire({fs:e,gitdir:r,cache:t,allowUnmerged:!1},async function(t){let a=ys(t.entries).get(`.`);if(p||=await nu({fs:e,gitdir:r,inode:a,dryRun:l}),f=f?await Promise.all(f.map(t=>K.resolve({fs:e,gitdir:r,ref:t}))):c?_.commit.parent:g?[g]:[],!i)if(c)i=_.commit.message;else throw new Zc(`message`);let o=yl.from({tree:p,parent:f,author:v,committer:y,message:i});s&&(o=await yl.sign(o,n,s));let m=await Gl({fs:e,gitdir:r,type:`commit`,object:o.toObject(),dryRun:l});return!u&&!l&&await K.writeRef({fs:e,gitdir:r,ref:h?`HEAD`:d,value:m}),m})}async function nu({fs:e,gitdir:t,inode:n,dryRun:r}){let i=n.children;for(let n of i)n.type===`tree`&&(n.metadata.mode=`040000`,n.metadata.oid=await nu({fs:e,gitdir:t,inode:n,dryRun:r}));let a=i.map(e=>({mode:e.metadata.mode,path:e.basename,oid:e.metadata.oid,type:e.type}));return await Gl({fs:e,gitdir:t,type:`tree`,object:lc.from(a).toObject(),dryRun:r})}async function ru({fs:e,cache:t,gitdir:n,oid:r,filepath:i}){if(i.startsWith(`/`))throw new Gc(`leading-slash`);if(i.endsWith(`/`))throw new Gc(`trailing-slash`);let a=r,o=await bl({fs:e,cache:t,gitdir:n,oid:r}),s=o.tree;return r=i===``?o.oid:await iu({fs:e,cache:t,gitdir:n,tree:s,pathArray:i.split(`/`),oid:a,filepath:i}),r}async function iu({fs:e,cache:t,gitdir:n,tree:r,pathArray:i,oid:a,filepath:o}){let s=i.shift();for(let c of r)if(c.path===s){if(i.length===0)return c.oid;{let{type:s,object:l}=await Pc({fs:e,cache:t,gitdir:n,oid:c.oid});if(s!==`tree`)throw new Ts(a,s,`tree`,o);return r=lc.from(l),iu({fs:e,cache:t,gitdir:n,tree:r,pathArray:i,oid:a,filepath:o})}}throw new ws(`file or directory found at "${a}:${o}"`)}async function au({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){i!==void 0&&(r=await ru({fs:e,cache:t,gitdir:n,oid:r,filepath:i}));let{tree:a,oid:o}=await bl({fs:e,cache:t,gitdir:n,oid:r});return{oid:o,tree:a.entries()}}async function ou({fs:e,gitdir:t,tree:n}){return await Gl({fs:e,gitdir:t,type:`tree`,object:lc.from(n).toObject(),format:`content`})}var su=/(^|[/.])([/.]|$)|^@$|@{|[\x00-\x20\x7f~^:?*[\\]|\.lock(\/|$)/;function cu(e,t){if(typeof e!=`string`)throw TypeError(`Reference name must be a string`);return!su.test(e)&&(!!t||e.includes(`/`))}async function lu({fs:e,gitdir:t,remote:n,url:r,force:i}){if(!cu(n,!0))throw new Kc(n,Wo.default.clean(n));let a=await Qs.get({fs:e,gitdir:t});if(!i&&(await a.getSubsections(`remote`)).includes(n)&&r!==await a.get(`remote.${n}.url`))throw new Fc(`remote`,n);await a.set(`remote.${n}.url`,r),await a.set(`remote.${n}.fetch`,`+refs/heads/*:refs/remotes/${n}/*`),await Qs.save({fs:e,gitdir:t,config:a})}async function uu({fs:e,dir:t,gitdir:n=G(t,`.git`),remote:r,url:i,force:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`remote`,r),J(`url`,i);let t=new q(e);return await lu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),remote:r,url:i,force:a})}catch(e){throw e.caller=`git.addRemote`,e}}async function du({fs:e,cache:t,onSign:n,gitdir:r,ref:i,tagger:a,message:o=i,gpgsig:s,object:c,signingKey:l,force:u=!1}){if(i=i.startsWith(`refs/tags/`)?i:`refs/tags/${i}`,!u&&await K.exists({fs:e,gitdir:r,ref:i}))throw new Fc(`tag`,i);let d=await K.resolve({fs:e,gitdir:r,ref:c||`HEAD`}),{type:f}=await Pc({fs:e,cache:t,gitdir:r,oid:d}),p=gl.from({object:d,type:f,tag:i.replace(`refs/tags/`,``),tagger:a,message:o,gpgsig:s});l&&(p=await gl.sign(p,n,l));let m=await Gl({fs:e,gitdir:r,type:`tag`,object:p.toObject()});await K.writeRef({fs:e,gitdir:r,ref:i,value:m})}async function fu({fs:e,onSign:t,dir:n,gitdir:r=G(n,`.git`),ref:i,tagger:a,message:o=i,gpgsig:s,object:c,signingKey:l,force:u=!1,cache:d={}}){try{J(`fs`,e),J(`gitdir`,r),J(`ref`,i),l&&J(`onSign`,t);let n=new q(e),f=await Y({fsp:n,dotgit:r}),p=await Zl({fs:n,gitdir:f,author:a});if(!p)throw new Xc(`tagger`);return await du({fs:n,cache:d,onSign:t,gitdir:f,ref:i,tagger:p,message:o,gpgsig:s,object:c,signingKey:l,force:u})}catch(e){throw e.caller=`git.annotatedTag`,e}}async function pu({fs:e,gitdir:t,ref:n,object:r,checkout:i=!1,force:a=!1}){if(!cu(n,!0))throw new Kc(n,Wo.default.clean(n));let o=`refs/heads/${n}`;if(!a&&await K.exists({fs:e,gitdir:t,ref:o}))throw new Fc(`branch`,n,!1);let s;try{s=await K.resolve({fs:e,gitdir:t,ref:r||`HEAD`})}catch{}s&&await K.writeRef({fs:e,gitdir:t,ref:o,value:s}),i&&await K.writeSymbolicRef({fs:e,gitdir:t,ref:`HEAD`,value:o})}async function mu({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,object:i,checkout:a=!1,force:o=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e);return await pu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r,object:i,checkout:a,force:o})}catch(e){throw e.caller=`git.branch`,e}}var hu=(e,t)=>e===`.`||t==null||t.length===0||t===`.`?!0:t.length>=e.length?t.startsWith(e):e.startsWith(t);async function gu({fs:e,cache:t,onProgress:n,onPostCheckout:r,dir:i,gitdir:a,remote:o,ref:s,filepaths:c,noCheckout:l,noUpdateHead:u,dryRun:d,force:f,track:p=!0,nonBlocking:m=!1,batchSize:h=100}){let g;if(r)try{g=await K.resolve({fs:e,gitdir:a,ref:`HEAD`})}catch{g=`0000000000000000000000000000000000000000`}let _;try{_=await K.resolve({fs:e,gitdir:a,ref:s})}catch(t){if(s===`HEAD`)throw t;let n=`${o}/${s}`;if(_=await K.resolve({fs:e,gitdir:a,ref:n}),p){let t=await Qs.get({fs:e,gitdir:a});await t.set(`branch.${s}.remote`,o),await t.set(`branch.${s}.merge`,`refs/heads/${s}`),await Qs.save({fs:e,gitdir:a,config:t})}await K.writeRef({fs:e,gitdir:a,ref:`refs/heads/${s}`,value:_})}if(!l){let o;try{o=await _u({fs:e,cache:t,onProgress:n,dir:i,gitdir:a,ref:s,force:f,filepaths:c})}catch(e){throw e instanceof ws&&e.data.what===_?new Bc(s,_):e}let l=o.filter(([e])=>e===`conflict`).map(([e,t])=>t);if(l.length>0)throw new Lc(l);let u=o.filter(([e])=>e===`error`).map(([e,t])=>t);if(u.length>0)throw new W(u.join(`, `));if(d){r&&await r({previousHead:g,newHead:_,type:c!=null&&c.length>0?`file`:`branch`});return}let p=0,v=o.length;if(await gs.acquire({fs:e,gitdir:a,cache:t},async function(t){await Promise.all(o.filter(([e])=>e===`delete`||e===`delete-index`).map(async function([r,a]){let o=`${i}/${a}`;r===`delete`&&await e.rm(o),t.delete({filepath:a}),n&&await n({phase:`Updating workdir`,loaded:++p,total:v})}))}),await gs.acquire({fs:e,gitdir:a,cache:t},async function(t){for(let[r,a]of o)if(r===`rmdir`||r===`rmdir-index`){let o=`${i}/${a}`;try{r===`rmdir`&&await e.rmdir(o),t.delete({filepath:a}),n&&await n({phase:`Updating workdir`,loaded:++p,total:v})}catch(e){if(e.code===`ENOTEMPTY`)console.log(`Did not delete ${a} because directory is not empty`);else throw e}}}),await Promise.all(o.filter(([e])=>e===`mkdir`||e===`mkdir-index`).map(async function([t,r]){let a=`${i}/${r}`;await e.mkdir(a),n&&await n({phase:`Updating workdir`,loaded:++p,total:v})})),m){let r=await bu(`Update Working Dir`,o.filter(([e])=>e===`create`||e===`create-index`||e===`update`||e===`mkdir-index`).map(([n,r,o,s,c])=>()=>yu({fs:e,cache:t,gitdir:a,dir:i},[n,r,o,s,c])),n,h);await gs.acquire({fs:e,gitdir:a,cache:t,allowUnmerged:!0},async function(e){await bu(`Update Index`,r.map(([t,n,r])=>()=>vu({index:e,fullpath:t,oid:n,stats:r})),n,h)})}else await gs.acquire({fs:e,gitdir:a,cache:t,allowUnmerged:!0},async function(r){await Promise.all(o.filter(([e])=>e===`create`||e===`create-index`||e===`update`||e===`mkdir-index`).map(async function([o,s,c,l,u]){let d=`${i}/${s}`;try{if(o!==`create-index`&&o!==`mkdir-index`){let{object:n}=await Pc({fs:e,cache:t,gitdir:a,oid:c});if(u&&await e.rm(d),l===33188)await e.write(d,n);else if(l===33261)await e.write(d,n,{mode:511});else if(l===40960)await e.writelink(d,n);else throw new W(`Invalid mode 0o${l.toString(8)} detected in blob ${c}`)}let i=await e.lstat(d);l===33261&&(i.mode=493),o===`mkdir-index`&&(i.mode=57344),r.insert({filepath:s,stats:i,oid:c}),n&&await n({phase:`Updating workdir`,loaded:++p,total:v})}catch(e){console.log(e)}}))});r&&await r({previousHead:g,newHead:_,type:c!=null&&c.length>0?`file`:`branch`})}if(!u){let t=await K.expand({fs:e,gitdir:a,ref:s});t.startsWith(`refs/heads`)?await K.writeSymbolicRef({fs:e,gitdir:a,ref:`HEAD`,value:t}):await K.writeRef({fs:e,gitdir:a,ref:`HEAD`,value:_})}}async function _u({fs:e,cache:t,onProgress:n,dir:r,gitdir:i,ref:a,force:o,filepaths:s}){let c=0;return kl({fs:e,cache:t,dir:r,gitdir:i,trees:[Sl({ref:a}),wl(),Cs()],map:async function(e,[t,r,i]){if(e!==`.`){if(s&&!s.some(t=>hu(e,t)))return null;switch(n&&await n({phase:`Analyzing workdir`,loaded:++c}),[!!i,!!t,!!r].map(Number).join(``)){case`000`:return;case`001`:return o&&s&&s.includes(e)?[`delete`,e]:void 0;case`010`:switch(await t.type()){case`tree`:return[`mkdir`,e];case`blob`:return[`create`,e,await t.oid(),await t.mode()];case`commit`:return[`mkdir-index`,e,await t.oid(),await t.mode()];default:return[`error`,`new entry Unhandled type ${await t.type()}`]}case`011`:switch(`${await t.type()}-${await r.type()}`){case`tree-tree`:return;case`tree-blob`:case`blob-tree`:return[`conflict`,e];case`blob-blob`:return await t.oid()===await r.oid()?await t.mode()===await r.mode()?[`create-index`,e,await t.oid(),await t.mode()]:o?[`update`,e,await t.oid(),await t.mode(),!0]:[`conflict`,e]:o?[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await r.mode()]:[`conflict`,e];case`commit-tree`:return;case`commit-blob`:return[`conflict`,e];default:return[`error`,`new entry Unhandled type ${t.type}`]}case`100`:return[`delete-index`,e];case`101`:switch(await i.type()){case`tree`:return[`rmdir-index`,e];case`blob`:return await i.oid()===await r.oid()||o?[`delete`,e]:[`conflict`,e];case`commit`:return[`rmdir-index`,e];default:return[`error`,`delete entry Unhandled type ${await i.type()}`]}case`110`:case`111`:switch(`${await i.type()}-${await t.type()}`){case`tree-tree`:return;case`blob-blob`:if(await i.oid()===await t.oid()&&await i.mode()===await t.mode()&&!o)return;if(r){if(await r.oid()!==await i.oid()&&await r.oid()!==await t.oid())return o?[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await r.mode()]:[`conflict`,e]}else if(o)return[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await i.mode()];return await t.mode()===await i.mode()?await t.oid()===await i.oid()?void 0:[`update`,e,await t.oid(),await t.mode(),!1]:[`update`,e,await t.oid(),await t.mode(),!0];case`tree-blob`:return[`update-dir-to-blob`,e,await t.oid()];case`blob-tree`:return[`update-blob-to-tree`,e];case`commit-commit`:return[`mkdir-index`,e,await t.oid(),await t.mode()];default:return[`error`,`update entry Unhandled type ${await i.type()}-${await t.type()}`]}}}},reduce:async function(e,t){return t=El(t),e?e&&e[0]===`rmdir`?(t.push(e),t):(t.unshift(e),t):t}})}async function vu({index:e,fullpath:t,stats:n,oid:r}){try{e.insert({filepath:t,stats:n,oid:r})}catch(e){console.warn(`Error inserting ${t} into index:`,e)}}async function yu({fs:e,cache:t,gitdir:n,dir:r},[i,a,o,s,c]){let l=`${r}/${a}`;if(i!==`create-index`&&i!==`mkdir-index`){let{object:r}=await Pc({fs:e,cache:t,gitdir:n,oid:o});if(c&&await e.rm(l),s===33188)await e.write(l,r);else if(s===33261)await e.write(l,r,{mode:511});else if(s===40960)await e.writelink(l,r);else throw new W(`Invalid mode 0o${s.toString(8)} detected in blob ${o}`)}let u=await e.lstat(l);return s===33261&&(u.mode=493),i===`mkdir-index`&&(u.mode=57344),[a,o,u]}async function bu(e,t,n,r){let i=[];try{for(let e=0;e<t.length;e+=r){let a=t.slice(e,e+r).map(e=>e());(await Promise.allSettled(a)).forEach(e=>{e.status===`fulfilled`&&i.push(e.value)}),n&&await n({phase:`Updating workdir`,loaded:e+a.length,total:t.length})}return i}catch(t){console.error(`Error during ${e}: ${t}`)}return i}async function xu({fs:e,onProgress:t,onPostCheckout:n,dir:r,gitdir:i=G(r,`.git`),remote:a=`origin`,ref:o,filepaths:s,noCheckout:c=!1,noUpdateHead:l=o===void 0,dryRun:u=!1,force:d=!1,track:f=!0,cache:p={},nonBlocking:m=!1,batchSize:h=100}){try{J(`fs`,e),J(`dir`,r),J(`gitdir`,i);let g=o||`HEAD`,_=new q(e);return await gu({fs:_,cache:p,onProgress:t,onPostCheckout:n,dir:r,gitdir:await Y({fsp:_,dotgit:i}),remote:a,ref:g,filepaths:s,noCheckout:c,noUpdateHead:l,dryRun:u,force:d,track:f,nonBlocking:m,batchSize:h})}catch(e){throw e.caller=`git.checkout`,e}}var Su=/^.*(\r?\n|$)/gm;function Cu({branches:e,contents:t}){let n=e[1],r=e[2],i=t[0],a=t[1],o=t[2],s=(0,Go.default)(a.match(Su),i.match(Su),o.match(Su)),c=``,l=!0;for(let e of s)e.ok&&(c+=e.ok.join(``)),e.conflict&&(l=!1,c+=`${`<`.repeat(7)} ${n}\n`,c+=e.conflict.a.join(``),c+=`${`=`.repeat(7)}\n`,c+=e.conflict.b.join(``),c+=`${`>`.repeat(7)} ${r}\n`);return{cleanMerge:l,mergedText:c}}async function wu({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),index:i,ourOid:a,baseOid:o,theirOid:s,ourName:c=`ours`,baseName:l=`base`,theirName:u=`theirs`,dryRun:d=!1,abortOnConflict:f=!0,mergeDriver:p}){let m=Sl({ref:a}),h=Sl({ref:o}),g=Sl({ref:s}),_=[],v=[],y=[],b=[],x=await kl({fs:e,cache:t,dir:n,gitdir:r,trees:[m,h,g],map:async function(t,[n,a,o]){let s=_s(t);switch(`${await Rl(n,a)}-${await Rl(o,a)}`){case`false-false`:return{mode:await a.mode(),path:s,oid:await a.oid(),type:await a.type()};case`false-true`:return!o&&await n.type()===`tree`?{mode:await n.mode(),path:s,oid:await n.oid(),type:await n.type()}:o?{mode:await o.mode(),path:s,oid:await o.oid(),type:await o.type()}:void 0;case`true-false`:return!n&&await o.type()===`tree`?{mode:await o.mode(),path:s,oid:await o.oid(),type:await o.type()}:n?{mode:await n.mode(),path:s,oid:await n.oid(),type:await n.type()}:void 0;case`true-true`:if(n&&o&&await n.type()===`tree`&&await o.type()===`tree`)return{mode:await n.mode(),path:s,oid:await n.oid(),type:`tree`};if(n&&o&&await n.type()===`blob`&&await o.type()===`blob`)return Tu({fs:e,gitdir:r,path:s,ours:n,base:a,theirs:o,ourName:c,baseName:l,theirName:u,mergeDriver:p}).then(async e=>{if(e.cleanMerge)f||i.insert({filepath:t,oid:e.mergeResult.oid,stage:0});else if(_.push(t),v.push(t),!f){let e=``;a&&await a.type()===`blob`&&(e=await a.oid());let r=await n.oid(),s=await o.oid();i.delete({filepath:t}),e&&i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:r,stage:2}),i.insert({filepath:t,oid:s,stage:3})}return e.mergeResult});if(a&&!n&&o&&await a.type()===`blob`&&await o.type()===`blob`){if(_.push(t),y.push(t),!f){let e=await a.oid(),n=await o.oid();i.delete({filepath:t}),i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:n,stage:3})}return{mode:await o.mode(),oid:await o.oid(),type:`blob`,path:s}}if(a&&n&&!o&&await a.type()===`blob`&&await n.type()===`blob`){if(_.push(t),b.push(t),!f){let e=await a.oid(),r=await n.oid();i.delete({filepath:t}),i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:r,stage:2})}return{mode:await n.mode(),oid:await n.oid(),type:`blob`,path:s}}if(a&&!n&&!o&&(await a.type()===`blob`||await a.type()===`tree`))return;throw new Jc}},reduce:_.length!==0&&(!n||f)?void 0:async(t,n)=>{let i=n.filter(Boolean);if(t&&!(t&&t.type===`tree`&&i.length===0&&t.path!==`.`))return(i.length>0||t.path===`.`&&i.length===0)&&(t.oid=await Gl({fs:e,gitdir:r,type:`tree`,object:new lc(i).toObject(),dryRun:d})),t}});return _.length===0?x.oid:(n&&!f&&await kl({fs:e,cache:t,dir:n,gitdir:r,trees:[Sl({ref:x.oid})],map:async function(t,[r]){let i=`${n}/${t}`;if(await r.type()===`blob`){let t=await r.mode(),n=new TextDecoder().decode(await r.content());await e.write(i,n,{mode:t})}return!0}}),new Yc(_,v,y,b))}async function Tu({fs:e,gitdir:t,path:n,ours:r,base:i,theirs:a,ourName:o,theirName:s,baseName:c,dryRun:l,mergeDriver:u=Cu}){let d=`blob`,f=`100755`,p=``,m=``;i&&await i.type()===`blob`&&(f=await i.mode(),p=await i.oid(),m=Buffer.from(await i.content()).toString(`utf8`));let h=f===await r.mode()?await a.mode():await r.mode();if(await r.oid()===await a.oid())return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await r.oid(),type:d}};if(await r.oid()===p)return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await a.oid(),type:d}};if(await a.oid()===p)return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await r.oid(),type:d}};let g=Buffer.from(await r.content()).toString(`utf8`),_=Buffer.from(await a.content()).toString(`utf8`),{mergedText:v,cleanMerge:y}=await u({branches:[c,o,s],contents:[m,g,_],path:n});return{cleanMerge:y,mergeResult:{mode:h,path:n,oid:await Gl({fs:e,gitdir:t,type:`blob`,object:Buffer.from(v,`utf8`),dryRun:l}),type:d}}}var Eu=/^refs\/(heads\/|tags\/|remotes\/)?(.*)/;function Du(e){let t=Eu.exec(e);return t?t[1]===`remotes/`&&e.endsWith(`/HEAD`)?t[2].slice(0,-5):t[2]:e}async function Ou({fs:e,gitdir:t,fullname:n=!1,test:r=!1}){let i=await K.resolve({fs:e,gitdir:t,ref:`HEAD`,depth:2});if(r)try{await K.resolve({fs:e,gitdir:t,ref:i})}catch{return}if(i.startsWith(`refs/`))return n?i:Du(i)}function ku(e){return e=e.replace(/^git@([^:]+):/,`https://$1/`),e=e.replace(/^ssh:\/\//,`https://`),e}function Au({username:e=``,password:t=``}){return`Basic ${Buffer.from(`${e}:${t}`).toString(`base64`)}`}async function ju(e,t){let n=_c(e);for(;;){let{value:e,done:r}=await n.next();if(e&&await t(e),r)break}n.return&&n.return()}async function Mu(e){let t=0,n=[];await ju(e,e=>{n.push(e),t+=e.byteLength});let r=new Uint8Array(t),i=0;for(let e of n)r.set(e,i),i+=e.byteLength;return r}function Nu(e){let t=e.match(/^https?:\/\/([^/]+)@/);if(t==null)return{url:e,auth:{}};t=t[1];let[n,r]=t.split(`:`);return e=e.replace(`${t}@`,``),{url:e,auth:{username:n,password:r}}}function Pu(e,t){let n=t.toString(16);return`0`.repeat(e-n.length)+n}var Fu=class{static flush(){return Buffer.from(`0000`,`utf8`)}static delim(){return Buffer.from(`0001`,`utf8`)}static encode(e){typeof e==`string`&&(e=Buffer.from(e));let t=Pu(4,e.length+4);return Buffer.concat([Buffer.from(t,`utf8`),e])}static streamReader(e){let t=new vc(e);return async function(){try{let e=await t.read(4);return e==null?!0:(e=parseInt(e.toString(`utf8`),16),e===0||e===1?null:await t.read(e-4)??!0)}catch(t){return e.error=t,!0}}}};async function Iu(e){let t={},n;for(;n=await e(),n!==!0;){if(n===null)continue;n=n.toString(`utf8`).replace(/\n$/,``);let e=n.indexOf(`=`);if(e>-1){let r=n.slice(0,e);t[r]=n.slice(e+1)}else t[n]=!0}return{protocolVersion:2,capabilities2:t}}async function Lu(e,{service:t}){let n=new Set,r=new Map,i=new Map,a=Fu.streamReader(e),o=await a();for(;o===null;)o=await a();if(o===!0)throw new Vc;if(o.includes(`version 2`))return Iu(a);if(o.toString(`utf8`).replace(/\n$/,``)!==`# service=${t}`)throw new $c(`# service=${t}\\n`,o.toString(`utf8`));let s=await a();for(;s===null;)s=await a();if(s===!0)return{capabilities:n,refs:r,symrefs:i};if(s=s.toString(`utf8`),s.includes(`version 2`))return Iu(a);let[c,l]=Ru(s,`\0`,`\\x00`);if(l.split(` `).map(e=>n.add(e)),c!==`0000000000000000000000000000000000000000 capabilities^{}`){let[e,t]=Ru(c,` `,` `);for(r.set(t,e);;){let e=await a();if(e===!0)break;if(e!==null){let[t,n]=Ru(e.toString(`utf8`),` `,` `);r.set(n,t)}}}for(let e of n)if(e.startsWith(`symref=`)){let t=e.match(/symref=([^:]+):(.*)/);t.length===3&&i.set(t[1],t[2])}return{protocolVersion:1,capabilities:n,refs:r,symrefs:i}}function Ru(e,t,n){let r=e.trim().split(t);if(r.length!==2)throw new $c(`Two strings separated by '${n}'`,e.toString(`utf8`));return r}var zu=(e,t)=>e.endsWith(`?`)?`${e}${t}`:`${e}/${t.replace(/^https?:\/\//,``)}`,Bu=(e,t)=>{(t.username||t.password)&&(e.Authorization=Au(t)),t.headers&&Object.assign(e,t.headers)},Vu=async e=>{try{let t=Buffer.from(await Mu(e.body)),n=t.toString(`utf8`);return{preview:n.length<256?n:n.slice(0,256)+`...`,response:n,data:t}}catch{return{}}},Hu=class{static async capabilities(){return[`discover`,`connect`]}static async discover({http:e,onProgress:t,onAuth:n,onAuthSuccess:r,onAuthFailure:i,corsProxy:a,service:o,url:s,headers:c,protocolVersion:l}){let{url:u,auth:d}=Nu(s),f=a?zu(a,u):u;(d.username||d.password)&&(c.Authorization=Au(d)),l===2&&(c[`Git-Protocol`]=`version=2`);let p,m,h=!1;do if(p=await e.request({onProgress:t,method:`GET`,url:`${f}/info/refs?service=${o}`,headers:c}),m=!1,p.statusCode===401||p.statusCode===203){let e=h?i:n;if(e){if(d=await e(u,{...d,headers:{...c}}),d&&d.cancel)throw new al;d&&(Bu(c,d),h=!0,m=!0)}}else p.statusCode===200&&h&&r&&await r(u,d);while(m);if(p.statusCode!==200){let{response:e}=await Vu(p);throw new Wc(p.statusCode,p.statusMessage,e)}if(p.headers[`content-type`]===`application/x-${o}-advertisement`){let e=await Lu(p.body,{service:o});return e.auth=d,e}else{let{preview:e,response:t,data:n}=await Vu(p);try{let e=await Lu([n],{service:o});return e.auth=d,e}catch{throw new nl(e,t)}}}static async connect({http:e,onProgress:t,corsProxy:n,service:r,url:i,auth:a,body:o,headers:s}){let c=Nu(i);c&&(i=c.url),n&&(i=zu(n,i)),s[`content-type`]=`application/x-${r}-request`,s.accept=`application/x-${r}-result`,Bu(s,a);let l=await e.request({onProgress:t,method:`POST`,url:`${i}/${r}`,body:o,headers:s});if(l.statusCode!==200){let{response:e}=Vu(l);throw new Wc(l.statusCode,l.statusMessage,e)}return l}},Uu=class{static getRemoteHelperFor({url:e}){let t=new Map;t.set(`http`,Hu),t.set(`https`,Hu);let n=Wu({url:e});if(!n)throw new il(e);if(t.has(n.transport))return t.get(n.transport);throw new rl(e,n.transport,n.transport===`ssh`?ku(e):void 0)}};function Wu({url:e}){if(e.startsWith(`git@`))return{transport:`ssh`,address:e};let t=e.match(/(\w+)(:\/\/|::)(.*)/);if(t!==null){if(t[2]===`://`)return{transport:t[1],address:t[0]};if(t[2]===`::`)return{transport:t[1],address:t[3]}}}var Gu=null,Ku=class{static async read({fs:e,gitdir:t}){Gu===null&&(Gu=new Ro.default);let n=G(t,`shallow`),r=new Set;return await Gu.acquire(n,async function(){let t=await e.read(n,{encoding:`utf8`});if(t===null||t.trim()===``)return r;t.trim().split(`
775
- `).map(e=>r.add(e))}),r}static async write({fs:e,gitdir:t,oids:n}){Gu===null&&(Gu=new Ro.default);let r=G(t,`shallow`);if(n.size>0){let t=[...n].join(`
770
+ `)+28);return gl(t+`
771
+ `+n)}isolateSignature(){return Sl(this._commit.slice(this._commit.indexOf(`-----BEGIN PGP SIGNATURE-----`),this._commit.indexOf(`-----END PGP SIGNATURE-----`)+27))}static async sign(t,n,r){let i=t.withoutSignature(),a=e.justMessage(t._commit),{signature:o}=await n({payload:i,secretKey:r});o=gl(o);let s=e.justHeaders(t._commit)+`
772
+ gpgsig`+xl(o)+`
773
+ `+a;return e.from(s)}};async function wl({fs:e,cache:t,gitdir:n,oid:r}){if(r===`4b825dc642cb6eb9a060e54bf8d69288fbee4904`)return{tree:pc.from([]),oid:r};let{type:i,object:a}=await Rc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=bl.from(a).parse().object,wl({fs:e,cache:t,gitdir:n,oid:r});if(i===`commit`)return r=Cl.from(a).parse().tree,wl({fs:e,cache:t,gitdir:n,oid:r});if(i!==`tree`)throw new ks(r,i,`tree`);return{tree:pc.from(a),oid:r}}var Tl=class{constructor({fs:e,gitdir:t,ref:n,cache:r}){this.fs=e,this.cache=r,this.gitdir=t,this.mapPromise=(async()=>{let r=new Map,i;try{i=await K.resolve({fs:e,gitdir:t,ref:n})}catch(e){e instanceof Os&&(i=`4b825dc642cb6eb9a060e54bf8d69288fbee4904`)}let a=await wl({fs:e,cache:this.cache,gitdir:t,oid:i});return a.type=`tree`,a.mode=`40000`,r.set(`.`,a),r})();let i=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let t=e._fullpath,{fs:n,cache:r,gitdir:i}=this,a=await this.mapPromise,o=a.get(t);if(!o)throw Error(`No obj for ${t}`);let s=o.oid;if(!s)throw Error(`No oid for obj ${JSON.stringify(o)}`);if(o.type!==`tree`)return null;let{type:c,object:l}=await Rc({fs:n,cache:r,gitdir:i,oid:s});if(c!==o.type)throw new ks(s,c,o.type);let u=pc.from(l);for(let e of u)a.set(G(t,e.path),e);return u.entries().map(e=>G(t,e.path))}async type(e){if(e._type===!1){let{type:t}=(await this.mapPromise).get(e._fullpath);e._type=t}return e._type}async mode(e){if(e._mode===!1){let{mode:t}=(await this.mapPromise).get(e._fullpath);e._mode=ts(parseInt(t,8))}return e._mode}async stat(e){}async content(e){if(e._content===!1){let t=await this.mapPromise,{fs:n,cache:r,gitdir:i}=this,a=t.get(e._fullpath).oid,{type:o,object:s}=await Rc({fs:n,cache:r,gitdir:i,oid:a});o===`blob`?e._content=new Uint8Array(s):e._content=void 0}return e._content}async oid(e){return e._oid===!1&&(e._oid=(await this.mapPromise).get(e._fullpath).oid),e._oid}};function El({ref:e=`HEAD`}={}){let t=Object.create(null);return Object.defineProperty(t,Es,{value:function({fs:t,gitdir:n,cache:r}){return new Tl({fs:t,gitdir:n,ref:e,cache:r})}}),Object.freeze(t),t}var Dl=class{constructor({fs:e,dir:t,gitdir:n,cache:r}){this.fs=e,this.cache=r,this.dir=t,this.gitdir=n,this.config=null;let i=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let t=e._fullpath,{fs:n,dir:r}=this,i=await n.readdir(G(r,t));return i===null?null:i.map(e=>G(t,e))}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let{fs:t,dir:n}=this,r=await t.lstat(`${n}/${e._fullpath}`);if(!r)throw Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let i=r.isDirectory()?`tree`:`blob`;i===`blob`&&!r.isFile()&&!r.isSymbolicLink()&&(i=`special`),e._type=i,r=is(r),e._mode=r.mode,r.size===-1&&e._actualSize&&(r.size=e._actualSize),e._stat=r}return e._stat}async content(e){if(e._content===!1){let{fs:t,dir:n,gitdir:r}=this;if(await e.type()===`tree`)e._content=void 0;else{let i;if(await e.mode()>>12==10)i=await t.readlink(`${n}/${e._fullpath}`);else{let a=await(await this._getGitConfig(t,r)).get(`core.autocrlf`);i=await t.read(`${n}/${e._fullpath}`,{autocrlf:a})}e._actualSize=i.length,e._stat&&e._stat.size===-1&&(e._stat.size=e._actualSize),e._content=new Uint8Array(i)}}return e._content}async oid(e){if(e._oid===!1){let t=this,{fs:n,gitdir:r,cache:i}=this,a;await bs.acquire({fs:n,gitdir:r,cache:i},async function(i){let o=i.entriesMap.get(e._fullpath),s=await e.stat(),c=await(await t._getGitConfig(n,r)).get(`core.filemode`),l=typeof process<`u`?process.platform!==`win32`:!0;if(!o||ms(s,o,c,l)){let t=await e.content();t===void 0?a=void 0:(a=await ss(mc.wrap({type:`blob`,object:t})),o&&a===o.oid&&(!c||s.mode===o.mode)&&ms(s,o,c,l)&&i.insert({filepath:e._fullpath,stats:s,oid:a}))}else a=o.oid}),e._oid=a}return e._oid}async _getGitConfig(e,t){return this.config||=await nc.get({fs:e,gitdir:t}),this.config}};function Ol(){let e=Object.create(null);return Object.defineProperty(e,Es,{value:function({fs:e,dir:t,gitdir:n,cache:r}){return new Dl({fs:e,dir:t,gitdir:n,cache:r})}}),Object.freeze(e),e}function kl(e,t){let n=t-e;return Array.from({length:n},(t,n)=>e+n)}var Al=Array.prototype.flat===void 0?e=>e.reduce((e,t)=>e.concat(t),[]):e=>e.flat(),jl=class{constructor(){this.value=null}consider(e){e!=null&&(this.value===null||e<this.value)&&(this.value=e)}reset(){this.value=null}};function*Ml(e){let t=new jl,n,r=[],i=e.length;for(let n=0;n<i;n++)r[n]=e[n].next().value,r[n]!==void 0&&t.consider(r[n]);if(t.value!==null)for(;;){let a=[];n=t.value,t.reset();for(let o=0;o<i;o++)r[o]!==void 0&&r[o]===n?(a[o]=r[o],r[o]=e[o].next().value):a[o]=null,r[o]!==void 0&&t.consider(r[o]);if(yield a,t.value===null)return}}async function Nl({fs:e,cache:t,dir:n,gitdir:r,trees:i,map:a=async(e,t)=>t,reduce:o=async(e,t)=>{let n=Al(t);return e!==void 0&&n.unshift(e),n},iterate:s=(e,t)=>Promise.all([...t].map(e))}){let c=i.map(i=>i[Es]({fs:e,dir:n,gitdir:r,cache:t})),l=Array(c.length).fill(`.`),u=kl(0,c.length),d=async e=>(u.forEach(t=>{let n=e[t];e[t]=n&&new c[t].ConstructEntry(n)}),{entries:e,children:Ml((await Promise.all(u.map(t=>{let n=e[t];return n?c[t].readdir(n):[]}))).map(e=>(e===null?[]:e)[Symbol.iterator]()))}),f=async e=>{let{entries:t,children:n}=await d(e),r=t.find(e=>e&&e._fullpath)._fullpath,i=await a(r,t);if(i!==null){let e=await s(f,n);return e=e.filter(e=>e!==void 0),o(i,e)}};return f(l)}async function Pl(e,t){let n=await e.readdir(t);n==null?await e.rm(t):n.length?await Promise.all(n.map(n=>{let r=G(t,n);return e.lstat(r).then(t=>{if(t)return t.isDirectory()?Pl(e,r):e.rm(r)})})).then(()=>e.rmdir(t)):await e.rmdir(t)}function Fl(e){return Il(e)&&Ll(e.then)&&Ll(e.catch)}function Il(e){return e&&typeof e==`object`}function Ll(e){return typeof e==`function`}function Rl(e){return Fl((e=>{try{return e.readFile().catch(e=>e)}catch(e){return e}})(e))}var zl=[`readFile`,`writeFile`,`mkdir`,`rmdir`,`unlink`,`stat`,`lstat`,`readdir`,`readlink`,`symlink`];function Bl(e,t){if(Rl(t))for(let n of zl)e[`_${n}`]=t[n].bind(t);else for(let n of zl)e[`_${n}`]=(0,Ko.default)(t[n].bind(t));Rl(t)?(t.cp&&(e._cp=t.cp.bind(t)),t.rm?e._rm=t.rm.bind(t):t.rmdir.length>1?e._rm=t.rmdir.bind(t):e._rm=Pl.bind(null,e)):(t.cp&&(e._cp=(0,Ko.default)(t.cp.bind(t))),t.rm?e._rm=(0,Ko.default)(t.rm.bind(t)):t.rmdir.length>2?e._rm=(0,Ko.default)(t.rmdir.bind(t)):e._rm=Pl.bind(null,e))}var q=class{constructor(e){if(e._original_unwrapped_fs!==void 0)return e;let t=Object.getOwnPropertyDescriptor(e,`promises`);t&&t.enumerable?Bl(this,e.promises):Bl(this,e),this._original_unwrapped_fs=e}async exists(e,t={}){try{return await this._stat(e),!0}catch(e){if(e.code===`ENOENT`||e.code===`ENOTDIR`||(e.code||``).includes(`ENS`))return!1;throw console.log(`Unhandled error in "FileSystem.exists()" function`,e),e}}async read(e,t={}){try{let n=await this._readFile(e,t);if(t.autocrlf===`true`)try{n=new TextDecoder(`utf8`,{fatal:!0}).decode(n),n=n.replace(/\r\n/g,`
774
+ `),n=new TextEncoder().encode(n)}catch{}return typeof n!=`string`&&(n=Buffer.from(n)),n}catch{return null}}async write(e,t,n={}){try{await this._writeFile(e,t,n)}catch{await this.mkdir(Ss(e)),await this._writeFile(e,t,n)}}async mkdir(e,t=!1){try{await this._mkdir(e)}catch(n){if(n===null||n.code===`EEXIST`)return;if(t)throw n;if(n.code===`ENOENT`){let t=Ss(e);if(t===`.`||t===`/`||t===e)throw n;await this.mkdir(t),await this.mkdir(e,!0)}}}async rm(e){try{await this._unlink(e)}catch(e){if(e.code!==`ENOENT`)throw e}}async rmdir(e,t){try{t&&t.recursive?await this._rm(e,t):await this._rmdir(e)}catch(e){if(e.code!==`ENOENT`)throw e}}async readdir(e){try{let t=await this._readdir(e);return t.sort($o),t}catch(e){return e.code===`ENOTDIR`?null:[]}}async readdirDeep(e){let t=await this._readdir(e);return(await Promise.all(t.map(async t=>{let n=e+`/`+t;return(await this._stat(n)).isDirectory()?this.readdirDeep(n):n}))).reduce((e,t)=>e.concat(t),[])}async lstat(e){try{return await this._lstat(e)}catch(e){if(e.code===`ENOENT`||(e.code||``).includes(`ENS`))return null;throw e}}async readlink(e,t={encoding:`buffer`}){try{let n=await this._readlink(e,t);return Buffer.isBuffer(n)?n:Buffer.from(n)}catch(e){if(e.code===`ENOENT`||(e.code||``).includes(`ENS`))return null;throw e}}async writelink(e,t){return this._symlink(t.toString(`utf8`),e)}};function J(e,t){if(t===void 0)throw new tl(e)}function Vl(e){return e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)}async function Y({fsp:e,dotgit:t}){J(`fsp`,e),J(`dotgit`,t);let n=await e._stat(t).catch(()=>({isFile:()=>!1,isDirectory:()=>!1}));return n.isDirectory()?t:n.isFile()?e._readFile(t,`utf8`).then(e=>e.trimRight().substr(8)).then(e=>Vl(e)?e:G(Ss(t),e)):t}async function Hl(e,t){return!e&&!t?!1:e&&!t||!e&&t?!0:!(await e.type()===`tree`&&await t.type()===`tree`||await e.type()===await t.type()&&await e.mode()===await t.mode()&&await e.oid()===await t.oid())}var Ul=class{static async isIgnored({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r}){if(xs(r)===`.git`)return!0;if(r===`.`)return!1;let i=``,a=G(n,`info`,`exclude`);await e.exists(a)&&(i=await e.read(a,`utf8`));let o=[{gitignore:G(t,`.gitignore`),filepath:r}],s=r.split(`/`).filter(Boolean);for(let e=1;e<s.length;e++){let n=s.slice(0,e).join(`/`),r=s.slice(e).join(`/`);o.push({gitignore:G(t,n,`.gitignore`),filepath:r})}let c=!1;for(let t of o){let n;try{n=await e.read(t.gitignore,`utf8`)}catch(e){if(e.code===`NOENT`)continue}let r=(0,qo.default)().add(i);r.add(n);let a=Ss(t.filepath);if(a!==`.`&&r.ignores(a))return!0;c=c?!r.test(t.filepath).unignored:r.test(t.filepath).ignored}return c}};async function Wl({fs:e,gitdir:t,object:n,format:r,oid:i}){if(r!==`deflated`)throw new W(`GitObjectStoreLoose expects objects to write to be in deflated format`);let a=`${t}/${`objects/${i.slice(0,2)}/${i.slice(2)}`}`;await e.exists(a)||await e.write(a,n)}var Gl=null;async function Kl(e){return Gl===null&&(Gl=Jl()),Gl?ql(e):Go.default.deflate(e)}async function ql(e){let t=new CompressionStream(`deflate`),n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}function Jl(){try{return new CompressionStream(`deflate`).writable.close(),new Blob([]).stream().cancel(),!0}catch{return!1}}async function Yl({fs:e,gitdir:t,type:n,object:r,format:i=`content`,oid:a=void 0,dryRun:o=!1}){return i!==`deflated`&&(i!==`wrapped`&&(r=mc.wrap({type:n,object:r})),a=await ss(r),r=Buffer.from(await Kl(r))),o||await Wl({fs:e,gitdir:t,object:r,format:`deflated`,oid:a}),a}function Xl(e){let t;for(;~(t=e.indexOf(92));)e[t]=47;return e}async function Zl({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,cache:i={},force:a=!1,parallel:o=!0}){try{J(`fs`,e),J(`dir`,t),J(`gitdir`,n),J(`filepath`,r);let s=new q(e),c=await Y({fsp:s,dotgit:n});await bs.acquire({fs:s,gitdir:c,cache:i},async e=>Ql({dir:t,gitdir:c,fs:s,filepath:r,index:e,force:a,parallel:o,autocrlf:await(await nc.get({fs:s,gitdir:c})).get(`core.autocrlf`)}))}catch(e){throw e.caller=`git.add`,e}}async function Ql({dir:e,gitdir:t,fs:n,filepath:r,index:i,force:a,parallel:o,autocrlf:s}){r=Array.isArray(r)?r:[r];let c=r.map(async r=>{if(!a&&await Ul.isIgnored({fs:n,dir:e,gitdir:t,filepath:r}))return;let c=await n.lstat(G(e,r));if(!c)throw new Os(r);if(c.isDirectory()){let c=await n.readdir(G(e,r));if(o){let l=c.map(c=>Ql({dir:e,gitdir:t,fs:n,filepath:[G(r,c)],index:i,force:a,parallel:o,autocrlf:s}));await Promise.all(l)}else for(let l of c)await Ql({dir:e,gitdir:t,fs:n,filepath:[G(r,l)],index:i,force:a,parallel:o,autocrlf:s})}else{let a=c.isSymbolicLink()?await n.readlink(G(e,r)).then(Xl):await n.read(G(e,r),{autocrlf:s});if(a===null)throw new Os(r);let o=await Yl({fs:n,gitdir:t,type:`blob`,object:a});i.insert({filepath:r,stats:c,oid:o})}}),l=await Promise.allSettled(c),u=l.filter(e=>e.status===`rejected`).map(e=>e.reason);if(u.length>1)throw new nl(u);if(u.length===1)throw u[0];return l.filter(e=>e.status===`fulfilled`&&e.value).map(e=>e.value)}async function $l({fs:e,gitdir:t,path:n}){return(await nc.get({fs:e,gitdir:t})).get(n)}function eu(e,...t){for(let n of t)if(n)for(let t of Object.keys(n)){let r=n[t];r!==void 0&&(e[t]=r)}return e}async function tu({fs:e,gitdir:t,author:n,commit:r}){let i=Math.floor(Date.now()/1e3),a=eu({},{name:await $l({fs:e,gitdir:t,path:`user.name`}),email:await $l({fs:e,gitdir:t,path:`user.email`})||``,timestamp:i,timezoneOffset:new Date(i*1e3).getTimezoneOffset()},r?r.author:void 0,n);if(a.name!==void 0)return a}async function nu({fs:e,gitdir:t,author:n,committer:r,commit:i}){let a=Math.floor(Date.now()/1e3),o=eu({},{name:await $l({fs:e,gitdir:t,path:`user.name`}),email:await $l({fs:e,gitdir:t,path:`user.email`})||``,timestamp:a,timezoneOffset:new Date(a*1e3).getTimezoneOffset()},i?i.committer:void 0,n,r);if(o.name!==void 0)return o}async function ru({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await Rc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=bl.from(a).parse().object,ru({fs:e,cache:t,gitdir:n,oid:r});if(i!==`commit`)throw new ks(r,i,`commit`);return{commit:Cl.from(a),oid:r}}async function iu({fs:e,cache:t,gitdir:n,oid:r}){let{commit:i,oid:a}=await ru({fs:e,cache:t,gitdir:n,oid:r});return{oid:a,commit:i.parse(),payload:i.withoutSignature()}}async function au({fs:e,cache:t,onSign:n,gitdir:r,message:i,author:a,committer:o,signingKey:s,amend:c=!1,dryRun:l=!1,noUpdateBranch:u=!1,ref:d,parent:f,tree:p}){let m=!1,h=!1;d||=(h=!(await e.read(`${r}/HEAD`,{encoding:`utf8`})).startsWith(`ref:`),await K.resolve({fs:e,gitdir:r,ref:`HEAD`,depth:2}));let g,_;try{g=await K.resolve({fs:e,gitdir:r,ref:d}),_=await iu({fs:e,gitdir:r,oid:g,cache:{}})}catch{m=!0}if(c&&m)throw new dl(d);let v=c?await tu({fs:e,gitdir:r,author:a,commit:_.commit}):await tu({fs:e,gitdir:r,author:a});if(!v)throw new el(`author`);let y=c?await nu({fs:e,gitdir:r,author:v,committer:o,commit:_.commit}):await nu({fs:e,gitdir:r,author:v,committer:o});if(!y)throw new el(`committer`);return bs.acquire({fs:e,gitdir:r,cache:t,allowUnmerged:!1},async function(t){let a=Cs(t.entries).get(`.`);if(p||=await ou({fs:e,gitdir:r,inode:a,dryRun:l}),f=f?await Promise.all(f.map(t=>K.resolve({fs:e,gitdir:r,ref:t}))):c?_.commit.parent:g?[g]:[],!i)if(c)i=_.commit.message;else throw new tl(`message`);let o=Cl.from({tree:p,parent:f,author:v,committer:y,message:i});s&&(o=await Cl.sign(o,n,s));let m=await Yl({fs:e,gitdir:r,type:`commit`,object:o.toObject(),dryRun:l});return!u&&!l&&await K.writeRef({fs:e,gitdir:r,ref:h?`HEAD`:d,value:m}),m})}async function ou({fs:e,gitdir:t,inode:n,dryRun:r}){let i=n.children;for(let n of i)n.type===`tree`&&(n.metadata.mode=`040000`,n.metadata.oid=await ou({fs:e,gitdir:t,inode:n,dryRun:r}));let a=i.map(e=>({mode:e.metadata.mode,path:e.basename,oid:e.metadata.oid,type:e.type}));return await Yl({fs:e,gitdir:t,type:`tree`,object:pc.from(a).toObject(),dryRun:r})}async function su({fs:e,cache:t,gitdir:n,oid:r,filepath:i}){if(i.startsWith(`/`))throw new Yc(`leading-slash`);if(i.endsWith(`/`))throw new Yc(`trailing-slash`);let a=r,o=await wl({fs:e,cache:t,gitdir:n,oid:r}),s=o.tree;return r=i===``?o.oid:await cu({fs:e,cache:t,gitdir:n,tree:s,pathArray:i.split(`/`),oid:a,filepath:i}),r}async function cu({fs:e,cache:t,gitdir:n,tree:r,pathArray:i,oid:a,filepath:o}){let s=i.shift();for(let c of r)if(c.path===s){if(i.length===0)return c.oid;{let{type:s,object:l}=await Rc({fs:e,cache:t,gitdir:n,oid:c.oid});if(s!==`tree`)throw new ks(a,s,`tree`,o);return r=pc.from(l),cu({fs:e,cache:t,gitdir:n,tree:r,pathArray:i,oid:a,filepath:o})}}throw new Os(`file or directory found at "${a}:${o}"`)}async function lu({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){i!==void 0&&(r=await su({fs:e,cache:t,gitdir:n,oid:r,filepath:i}));let{tree:a,oid:o}=await wl({fs:e,cache:t,gitdir:n,oid:r});return{oid:o,tree:a.entries()}}async function uu({fs:e,gitdir:t,tree:n}){return await Yl({fs:e,gitdir:t,type:`tree`,object:pc.from(n).toObject(),format:`content`})}var du=/(^|[/.])([/.]|$)|^@$|@{|[\x00-\x20\x7f~^:?*[\\]|\.lock(\/|$)/;function fu(e,t){if(typeof e!=`string`)throw TypeError(`Reference name must be a string`);return!du.test(e)&&(!!t||e.includes(`/`))}async function pu({fs:e,gitdir:t,remote:n,url:r,force:i}){if(!fu(n,!0))throw new Xc(n,Jo.default.clean(n));let a=await nc.get({fs:e,gitdir:t});if(!i&&(await a.getSubsections(`remote`)).includes(n)&&r!==await a.get(`remote.${n}.url`))throw new zc(`remote`,n);await a.set(`remote.${n}.url`,r),await a.set(`remote.${n}.fetch`,`+refs/heads/*:refs/remotes/${n}/*`),await nc.save({fs:e,gitdir:t,config:a})}async function mu({fs:e,dir:t,gitdir:n=G(t,`.git`),remote:r,url:i,force:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`remote`,r),J(`url`,i);let t=new q(e);return await pu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),remote:r,url:i,force:a})}catch(e){throw e.caller=`git.addRemote`,e}}async function hu({fs:e,cache:t,onSign:n,gitdir:r,ref:i,tagger:a,message:o=i,gpgsig:s,object:c,signingKey:l,force:u=!1}){if(i=i.startsWith(`refs/tags/`)?i:`refs/tags/${i}`,!u&&await K.exists({fs:e,gitdir:r,ref:i}))throw new zc(`tag`,i);let d=await K.resolve({fs:e,gitdir:r,ref:c||`HEAD`}),{type:f}=await Rc({fs:e,cache:t,gitdir:r,oid:d}),p=bl.from({object:d,type:f,tag:i.replace(`refs/tags/`,``),tagger:a,message:o,gpgsig:s});l&&(p=await bl.sign(p,n,l));let m=await Yl({fs:e,gitdir:r,type:`tag`,object:p.toObject()});await K.writeRef({fs:e,gitdir:r,ref:i,value:m})}async function gu({fs:e,onSign:t,dir:n,gitdir:r=G(n,`.git`),ref:i,tagger:a,message:o=i,gpgsig:s,object:c,signingKey:l,force:u=!1,cache:d={}}){try{J(`fs`,e),J(`gitdir`,r),J(`ref`,i),l&&J(`onSign`,t);let n=new q(e),f=await Y({fsp:n,dotgit:r}),p=await tu({fs:n,gitdir:f,author:a});if(!p)throw new el(`tagger`);return await hu({fs:n,cache:d,onSign:t,gitdir:f,ref:i,tagger:p,message:o,gpgsig:s,object:c,signingKey:l,force:u})}catch(e){throw e.caller=`git.annotatedTag`,e}}async function _u({fs:e,gitdir:t,ref:n,object:r,checkout:i=!1,force:a=!1}){if(!fu(n,!0))throw new Xc(n,Jo.default.clean(n));let o=`refs/heads/${n}`;if(!a&&await K.exists({fs:e,gitdir:t,ref:o}))throw new zc(`branch`,n,!1);let s;try{s=await K.resolve({fs:e,gitdir:t,ref:r||`HEAD`})}catch{}s&&await K.writeRef({fs:e,gitdir:t,ref:o,value:s}),i&&await K.writeSymbolicRef({fs:e,gitdir:t,ref:`HEAD`,value:o})}async function vu({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,object:i,checkout:a=!1,force:o=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e);return await _u({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r,object:i,checkout:a,force:o})}catch(e){throw e.caller=`git.branch`,e}}var yu=(e,t)=>e===`.`||t==null||t.length===0||t===`.`?!0:t.length>=e.length?t.startsWith(e):e.startsWith(t);async function bu({fs:e,cache:t,onProgress:n,onPostCheckout:r,dir:i,gitdir:a,remote:o,ref:s,filepaths:c,noCheckout:l,noUpdateHead:u,dryRun:d,force:f,track:p=!0,nonBlocking:m=!1,batchSize:h=100}){let g;if(r)try{g=await K.resolve({fs:e,gitdir:a,ref:`HEAD`})}catch{g=`0000000000000000000000000000000000000000`}let _;try{_=await K.resolve({fs:e,gitdir:a,ref:s})}catch(t){if(s===`HEAD`)throw t;let n=`${o}/${s}`;if(_=await K.resolve({fs:e,gitdir:a,ref:n}),p){let t=await nc.get({fs:e,gitdir:a});await t.set(`branch.${s}.remote`,o),await t.set(`branch.${s}.merge`,`refs/heads/${s}`),await nc.save({fs:e,gitdir:a,config:t})}await K.writeRef({fs:e,gitdir:a,ref:`refs/heads/${s}`,value:_})}if(!l){let o;try{o=await xu({fs:e,cache:t,onProgress:n,dir:i,gitdir:a,ref:s,force:f,filepaths:c})}catch(e){throw e instanceof Os&&e.data.what===_?new Wc(s,_):e}let l=o.filter(([e])=>e===`conflict`).map(([e,t])=>t);if(l.length>0)throw new Vc(l);let u=o.filter(([e])=>e===`error`).map(([e,t])=>t);if(u.length>0)throw new W(u.join(`, `));if(d){r&&await r({previousHead:g,newHead:_,type:c!=null&&c.length>0?`file`:`branch`});return}let p=0,v=o.length;if(await bs.acquire({fs:e,gitdir:a,cache:t},async function(t){await Promise.all(o.filter(([e])=>e===`delete`||e===`delete-index`).map(async function([r,a]){let o=`${i}/${a}`;r===`delete`&&await e.rm(o),t.delete({filepath:a}),n&&await n({phase:`Updating workdir`,loaded:++p,total:v})}))}),await bs.acquire({fs:e,gitdir:a,cache:t},async function(t){for(let[r,a]of o)if(r===`rmdir`||r===`rmdir-index`){let o=`${i}/${a}`;try{r===`rmdir`&&await e.rmdir(o),t.delete({filepath:a}),n&&await n({phase:`Updating workdir`,loaded:++p,total:v})}catch(e){if(e.code===`ENOTEMPTY`)console.log(`Did not delete ${a} because directory is not empty`);else throw e}}}),await Promise.all(o.filter(([e])=>e===`mkdir`||e===`mkdir-index`).map(async function([t,r]){let a=`${i}/${r}`;await e.mkdir(a),n&&await n({phase:`Updating workdir`,loaded:++p,total:v})})),m){let r=await wu(`Update Working Dir`,o.filter(([e])=>e===`create`||e===`create-index`||e===`update`||e===`mkdir-index`).map(([n,r,o,s,c])=>()=>Cu({fs:e,cache:t,gitdir:a,dir:i},[n,r,o,s,c])),n,h);await bs.acquire({fs:e,gitdir:a,cache:t,allowUnmerged:!0},async function(e){await wu(`Update Index`,r.map(([t,n,r])=>()=>Su({index:e,fullpath:t,oid:n,stats:r})),n,h)})}else await bs.acquire({fs:e,gitdir:a,cache:t,allowUnmerged:!0},async function(r){await Promise.all(o.filter(([e])=>e===`create`||e===`create-index`||e===`update`||e===`mkdir-index`).map(async function([o,s,c,l,u]){let d=`${i}/${s}`;try{if(o!==`create-index`&&o!==`mkdir-index`){let{object:n}=await Rc({fs:e,cache:t,gitdir:a,oid:c});if(u&&await e.rm(d),l===33188)await e.write(d,n);else if(l===33261)await e.write(d,n,{mode:511});else if(l===40960)await e.writelink(d,n);else throw new W(`Invalid mode 0o${l.toString(8)} detected in blob ${c}`)}let i=await e.lstat(d);l===33261&&(i.mode=493),o===`mkdir-index`&&(i.mode=57344),r.insert({filepath:s,stats:i,oid:c}),n&&await n({phase:`Updating workdir`,loaded:++p,total:v})}catch(e){console.log(e)}}))});r&&await r({previousHead:g,newHead:_,type:c!=null&&c.length>0?`file`:`branch`})}if(!u){let t=await K.expand({fs:e,gitdir:a,ref:s});t.startsWith(`refs/heads`)?await K.writeSymbolicRef({fs:e,gitdir:a,ref:`HEAD`,value:t}):await K.writeRef({fs:e,gitdir:a,ref:`HEAD`,value:_})}}async function xu({fs:e,cache:t,onProgress:n,dir:r,gitdir:i,ref:a,force:o,filepaths:s}){let c=0;return Nl({fs:e,cache:t,dir:r,gitdir:i,trees:[El({ref:a}),Ol(),Ds()],map:async function(e,[t,r,i]){if(e!==`.`){if(s&&!s.some(t=>yu(e,t)))return null;switch(n&&await n({phase:`Analyzing workdir`,loaded:++c}),[!!i,!!t,!!r].map(Number).join(``)){case`000`:return;case`001`:return o&&s&&s.includes(e)?[`delete`,e]:void 0;case`010`:switch(await t.type()){case`tree`:return[`mkdir`,e];case`blob`:return[`create`,e,await t.oid(),await t.mode()];case`commit`:return[`mkdir-index`,e,await t.oid(),await t.mode()];default:return[`error`,`new entry Unhandled type ${await t.type()}`]}case`011`:switch(`${await t.type()}-${await r.type()}`){case`tree-tree`:return;case`tree-blob`:case`blob-tree`:return[`conflict`,e];case`blob-blob`:return await t.oid()===await r.oid()?await t.mode()===await r.mode()?[`create-index`,e,await t.oid(),await t.mode()]:o?[`update`,e,await t.oid(),await t.mode(),!0]:[`conflict`,e]:o?[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await r.mode()]:[`conflict`,e];case`commit-tree`:return;case`commit-blob`:return[`conflict`,e];default:return[`error`,`new entry Unhandled type ${t.type}`]}case`100`:return[`delete-index`,e];case`101`:switch(await i.type()){case`tree`:return[`rmdir-index`,e];case`blob`:return await i.oid()===await r.oid()||o?[`delete`,e]:[`conflict`,e];case`commit`:return[`rmdir-index`,e];default:return[`error`,`delete entry Unhandled type ${await i.type()}`]}case`110`:case`111`:switch(`${await i.type()}-${await t.type()}`){case`tree-tree`:return;case`blob-blob`:if(await i.oid()===await t.oid()&&await i.mode()===await t.mode()&&!o)return;if(r){if(await r.oid()!==await i.oid()&&await r.oid()!==await t.oid())return o?[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await r.mode()]:[`conflict`,e]}else if(o)return[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await i.mode()];return await t.mode()===await i.mode()?await t.oid()===await i.oid()?void 0:[`update`,e,await t.oid(),await t.mode(),!1]:[`update`,e,await t.oid(),await t.mode(),!0];case`tree-blob`:return[`update-dir-to-blob`,e,await t.oid()];case`blob-tree`:return[`update-blob-to-tree`,e];case`commit-commit`:return[`mkdir-index`,e,await t.oid(),await t.mode()];default:return[`error`,`update entry Unhandled type ${await i.type()}-${await t.type()}`]}}}},reduce:async function(e,t){return t=Al(t),e?e&&e[0]===`rmdir`?(t.push(e),t):(t.unshift(e),t):t}})}async function Su({index:e,fullpath:t,stats:n,oid:r}){try{e.insert({filepath:t,stats:n,oid:r})}catch(e){console.warn(`Error inserting ${t} into index:`,e)}}async function Cu({fs:e,cache:t,gitdir:n,dir:r},[i,a,o,s,c]){let l=`${r}/${a}`;if(i!==`create-index`&&i!==`mkdir-index`){let{object:r}=await Rc({fs:e,cache:t,gitdir:n,oid:o});if(c&&await e.rm(l),s===33188)await e.write(l,r);else if(s===33261)await e.write(l,r,{mode:511});else if(s===40960)await e.writelink(l,r);else throw new W(`Invalid mode 0o${s.toString(8)} detected in blob ${o}`)}let u=await e.lstat(l);return s===33261&&(u.mode=493),i===`mkdir-index`&&(u.mode=57344),[a,o,u]}async function wu(e,t,n,r){let i=[];try{for(let e=0;e<t.length;e+=r){let a=t.slice(e,e+r).map(e=>e());(await Promise.allSettled(a)).forEach(e=>{e.status===`fulfilled`&&i.push(e.value)}),n&&await n({phase:`Updating workdir`,loaded:e+a.length,total:t.length})}return i}catch(t){console.error(`Error during ${e}: ${t}`)}return i}async function Tu({fs:e,onProgress:t,onPostCheckout:n,dir:r,gitdir:i=G(r,`.git`),remote:a=`origin`,ref:o,filepaths:s,noCheckout:c=!1,noUpdateHead:l=o===void 0,dryRun:u=!1,force:d=!1,track:f=!0,cache:p={},nonBlocking:m=!1,batchSize:h=100}){try{J(`fs`,e),J(`dir`,r),J(`gitdir`,i);let g=o||`HEAD`,_=new q(e);return await bu({fs:_,cache:p,onProgress:t,onPostCheckout:n,dir:r,gitdir:await Y({fsp:_,dotgit:i}),remote:a,ref:g,filepaths:s,noCheckout:c,noUpdateHead:l,dryRun:u,force:d,track:f,nonBlocking:m,batchSize:h})}catch(e){throw e.caller=`git.checkout`,e}}var Eu=/^.*(\r?\n|$)/gm;function Du({branches:e,contents:t}){let n=e[1],r=e[2],i=t[0],a=t[1],o=t[2],s=(0,Yo.default)(a.match(Eu),i.match(Eu),o.match(Eu)),c=``,l=!0;for(let e of s)e.ok&&(c+=e.ok.join(``)),e.conflict&&(l=!1,c+=`${`<`.repeat(7)} ${n}\n`,c+=e.conflict.a.join(``),c+=`${`=`.repeat(7)}\n`,c+=e.conflict.b.join(``),c+=`${`>`.repeat(7)} ${r}\n`);return{cleanMerge:l,mergedText:c}}async function Ou({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),index:i,ourOid:a,baseOid:o,theirOid:s,ourName:c=`ours`,baseName:l=`base`,theirName:u=`theirs`,dryRun:d=!1,abortOnConflict:f=!0,mergeDriver:p}){let m=El({ref:a}),h=El({ref:o}),g=El({ref:s}),_=[],v=[],y=[],b=[],x=await Nl({fs:e,cache:t,dir:n,gitdir:r,trees:[m,h,g],map:async function(t,[n,a,o]){let s=xs(t);switch(`${await Hl(n,a)}-${await Hl(o,a)}`){case`false-false`:return{mode:await a.mode(),path:s,oid:await a.oid(),type:await a.type()};case`false-true`:return!o&&await n.type()===`tree`?{mode:await n.mode(),path:s,oid:await n.oid(),type:await n.type()}:o?{mode:await o.mode(),path:s,oid:await o.oid(),type:await o.type()}:void 0;case`true-false`:return!n&&await o.type()===`tree`?{mode:await o.mode(),path:s,oid:await o.oid(),type:await o.type()}:n?{mode:await n.mode(),path:s,oid:await n.oid(),type:await n.type()}:void 0;case`true-true`:if(n&&o&&await n.type()===`tree`&&await o.type()===`tree`)return{mode:await n.mode(),path:s,oid:await n.oid(),type:`tree`};if(n&&o&&await n.type()===`blob`&&await o.type()===`blob`)return ku({fs:e,gitdir:r,path:s,ours:n,base:a,theirs:o,ourName:c,baseName:l,theirName:u,mergeDriver:p}).then(async e=>{if(e.cleanMerge)f||i.insert({filepath:t,oid:e.mergeResult.oid,stage:0});else if(_.push(t),v.push(t),!f){let e=``;a&&await a.type()===`blob`&&(e=await a.oid());let r=await n.oid(),s=await o.oid();i.delete({filepath:t}),e&&i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:r,stage:2}),i.insert({filepath:t,oid:s,stage:3})}return e.mergeResult});if(a&&!n&&o&&await a.type()===`blob`&&await o.type()===`blob`){if(_.push(t),y.push(t),!f){let e=await a.oid(),n=await o.oid();i.delete({filepath:t}),i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:n,stage:3})}return{mode:await o.mode(),oid:await o.oid(),type:`blob`,path:s}}if(a&&n&&!o&&await a.type()===`blob`&&await n.type()===`blob`){if(_.push(t),b.push(t),!f){let e=await a.oid(),r=await n.oid();i.delete({filepath:t}),i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:r,stage:2})}return{mode:await n.mode(),oid:await n.oid(),type:`blob`,path:s}}if(a&&!n&&!o&&(await a.type()===`blob`||await a.type()===`tree`))return;throw new Qc}},reduce:_.length!==0&&(!n||f)?void 0:async(t,n)=>{let i=n.filter(Boolean);if(t&&!(t&&t.type===`tree`&&i.length===0&&t.path!==`.`))return(i.length>0||t.path===`.`&&i.length===0)&&(t.oid=await Yl({fs:e,gitdir:r,type:`tree`,object:new pc(i).toObject(),dryRun:d})),t}});return _.length===0?x.oid:(n&&!f&&await Nl({fs:e,cache:t,dir:n,gitdir:r,trees:[El({ref:x.oid})],map:async function(t,[r]){let i=`${n}/${t}`;if(await r.type()===`blob`){let t=await r.mode(),n=new TextDecoder().decode(await r.content());await e.write(i,n,{mode:t})}return!0}}),new $c(_,v,y,b))}async function ku({fs:e,gitdir:t,path:n,ours:r,base:i,theirs:a,ourName:o,theirName:s,baseName:c,dryRun:l,mergeDriver:u=Du}){let d=`blob`,f=`100755`,p=``,m=``;i&&await i.type()===`blob`&&(f=await i.mode(),p=await i.oid(),m=Buffer.from(await i.content()).toString(`utf8`));let h=f===await r.mode()?await a.mode():await r.mode();if(await r.oid()===await a.oid())return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await r.oid(),type:d}};if(await r.oid()===p)return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await a.oid(),type:d}};if(await a.oid()===p)return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await r.oid(),type:d}};let g=Buffer.from(await r.content()).toString(`utf8`),_=Buffer.from(await a.content()).toString(`utf8`),{mergedText:v,cleanMerge:y}=await u({branches:[c,o,s],contents:[m,g,_],path:n});return{cleanMerge:y,mergeResult:{mode:h,path:n,oid:await Yl({fs:e,gitdir:t,type:`blob`,object:Buffer.from(v,`utf8`),dryRun:l}),type:d}}}var Au=/^refs\/(heads\/|tags\/|remotes\/)?(.*)/;function ju(e){let t=Au.exec(e);return t?t[1]===`remotes/`&&e.endsWith(`/HEAD`)?t[2].slice(0,-5):t[2]:e}async function Mu({fs:e,gitdir:t,fullname:n=!1,test:r=!1}){let i=await K.resolve({fs:e,gitdir:t,ref:`HEAD`,depth:2});if(r)try{await K.resolve({fs:e,gitdir:t,ref:i})}catch{return}if(i.startsWith(`refs/`))return n?i:ju(i)}function Nu(e){return e=e.replace(/^git@([^:]+):/,`https://$1/`),e=e.replace(/^ssh:\/\//,`https://`),e}function Pu({username:e=``,password:t=``}){return`Basic ${Buffer.from(`${e}:${t}`).toString(`base64`)}`}async function Fu(e,t){let n=xc(e);for(;;){let{value:e,done:r}=await n.next();if(e&&await t(e),r)break}n.return&&n.return()}async function Iu(e){let t=0,n=[];await Fu(e,e=>{n.push(e),t+=e.byteLength});let r=new Uint8Array(t),i=0;for(let e of n)r.set(e,i),i+=e.byteLength;return r}function Lu(e){let t=e.match(/^https?:\/\/([^/]+)@/);if(t==null)return{url:e,auth:{}};t=t[1];let[n,r]=t.split(`:`);return e=e.replace(`${t}@`,``),{url:e,auth:{username:n,password:r}}}function Ru(e,t){let n=t.toString(16);return`0`.repeat(e-n.length)+n}var zu=class{static flush(){return Buffer.from(`0000`,`utf8`)}static delim(){return Buffer.from(`0001`,`utf8`)}static encode(e){typeof e==`string`&&(e=Buffer.from(e));let t=Ru(4,e.length+4);return Buffer.concat([Buffer.from(t,`utf8`),e])}static streamReader(e){let t=new Sc(e);return async function(){try{let e=await t.read(4);return e==null?!0:(e=parseInt(e.toString(`utf8`),16),e===0||e===1?null:await t.read(e-4)??!0)}catch(t){return e.error=t,!0}}}};async function Bu(e){let t={},n;for(;n=await e(),n!==!0;){if(n===null)continue;n=n.toString(`utf8`).replace(/\n$/,``);let e=n.indexOf(`=`);if(e>-1){let r=n.slice(0,e);t[r]=n.slice(e+1)}else t[n]=!0}return{protocolVersion:2,capabilities2:t}}async function Vu(e,{service:t}){let n=new Set,r=new Map,i=new Map,a=zu.streamReader(e),o=await a();for(;o===null;)o=await a();if(o===!0)throw new Gc;if(o.includes(`version 2`))return Bu(a);if(o.toString(`utf8`).replace(/\n$/,``)!==`# service=${t}`)throw new rl(`# service=${t}\\n`,o.toString(`utf8`));let s=await a();for(;s===null;)s=await a();if(s===!0)return{capabilities:n,refs:r,symrefs:i};if(s=s.toString(`utf8`),s.includes(`version 2`))return Bu(a);let[c,l]=Hu(s,`\0`,`\\x00`);if(l.split(` `).map(e=>n.add(e)),c!==`0000000000000000000000000000000000000000 capabilities^{}`){let[e,t]=Hu(c,` `,` `);for(r.set(t,e);;){let e=await a();if(e===!0)break;if(e!==null){let[t,n]=Hu(e.toString(`utf8`),` `,` `);r.set(n,t)}}}for(let e of n)if(e.startsWith(`symref=`)){let t=e.match(/symref=([^:]+):(.*)/);t.length===3&&i.set(t[1],t[2])}return{protocolVersion:1,capabilities:n,refs:r,symrefs:i}}function Hu(e,t,n){let r=e.trim().split(t);if(r.length!==2)throw new rl(`Two strings separated by '${n}'`,e.toString(`utf8`));return r}var Uu=(e,t)=>e.endsWith(`?`)?`${e}${t}`:`${e}/${t.replace(/^https?:\/\//,``)}`,Wu=(e,t)=>{(t.username||t.password)&&(e.Authorization=Pu(t)),t.headers&&Object.assign(e,t.headers)},Gu=async e=>{try{let t=Buffer.from(await Iu(e.body)),n=t.toString(`utf8`);return{preview:n.length<256?n:n.slice(0,256)+`...`,response:n,data:t}}catch{return{}}},Ku=class{static async capabilities(){return[`discover`,`connect`]}static async discover({http:e,onProgress:t,onAuth:n,onAuthSuccess:r,onAuthFailure:i,corsProxy:a,service:o,url:s,headers:c,protocolVersion:l}){let{url:u,auth:d}=Lu(s),f=a?Uu(a,u):u;(d.username||d.password)&&(c.Authorization=Pu(d)),l===2&&(c[`Git-Protocol`]=`version=2`);let p,m,h=!1;do if(p=await e.request({onProgress:t,method:`GET`,url:`${f}/info/refs?service=${o}`,headers:c}),m=!1,p.statusCode===401||p.statusCode===203){let e=h?i:n;if(e){if(d=await e(u,{...d,headers:{...c}}),d&&d.cancel)throw new ll;d&&(Wu(c,d),h=!0,m=!0)}}else p.statusCode===200&&h&&r&&await r(u,d);while(m);if(p.statusCode!==200){let{response:e}=await Gu(p);throw new Jc(p.statusCode,p.statusMessage,e)}if(p.headers[`content-type`]===`application/x-${o}-advertisement`){let e=await Vu(p.body,{service:o});return e.auth=d,e}else{let{preview:e,response:t,data:n}=await Gu(p);try{let e=await Vu([n],{service:o});return e.auth=d,e}catch{throw new ol(e,t)}}}static async connect({http:e,onProgress:t,corsProxy:n,service:r,url:i,auth:a,body:o,headers:s}){let c=Lu(i);c&&(i=c.url),n&&(i=Uu(n,i)),s[`content-type`]=`application/x-${r}-request`,s.accept=`application/x-${r}-result`,Wu(s,a);let l=await e.request({onProgress:t,method:`POST`,url:`${i}/${r}`,body:o,headers:s});if(l.statusCode!==200){let{response:e}=Gu(l);throw new Jc(l.statusCode,l.statusMessage,e)}return l}},qu=class{static getRemoteHelperFor({url:e}){let t=new Map;t.set(`http`,Ku),t.set(`https`,Ku);let n=Ju({url:e});if(!n)throw new cl(e);if(t.has(n.transport))return t.get(n.transport);throw new sl(e,n.transport,n.transport===`ssh`?Nu(e):void 0)}};function Ju({url:e}){if(e.startsWith(`git@`))return{transport:`ssh`,address:e};let t=e.match(/(\w+)(:\/\/|::)(.*)/);if(t!==null){if(t[2]===`://`)return{transport:t[1],address:t[0]};if(t[2]===`::`)return{transport:t[1],address:t[3]}}}var Yu=null,Xu=class{static async read({fs:e,gitdir:t}){Yu===null&&(Yu=new Ho.default);let n=G(t,`shallow`),r=new Set;return await Yu.acquire(n,async function(){let t=await e.read(n,{encoding:`utf8`});if(t===null||t.trim()===``)return r;t.trim().split(`
775
+ `).map(e=>r.add(e))}),r}static async write({fs:e,gitdir:t,oids:n}){Yu===null&&(Yu=new Ho.default);let r=G(t,`shallow`);if(n.size>0){let t=[...n].join(`
776
776
  `)+`
777
- `;await Gu.acquire(r,async function(){await e.write(r,t,{encoding:`utf8`})})}else await Gu.acquire(r,async function(){await e.rm(r)})}};async function qu({fs:e,gitdir:t,oid:n}){let r=`objects/${n.slice(0,2)}/${n.slice(2)}`;return e.exists(`${t}/${r}`)}async function Ju({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i}){let a=await e.readdir(G(n,`objects/pack`));a=a.filter(e=>e.endsWith(`.idx`));for(let o of a){let a=await jc({fs:e,cache:t,filename:`${n}/objects/pack/${o}`,getExternalRefDelta:i});if(a.error)throw new W(a.error);if(a.offsets.has(r))return!0}return!1}async function Yu({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`}){let a=r=>Pc({fs:e,cache:t,gitdir:n,oid:r}),o=await qu({fs:e,gitdir:n,oid:r});return o||=await Ju({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:a}),o}function Xu(e){return e.slice(0,12).toString(`hex`)===`5041434b0000000200000000`}function Zu(e,t){let n=e.map(e=>e.split(`=`,1)[0]);return t.filter(e=>{let t=e.split(`=`,1)[0];return n.includes(t)})}var Qu={name:`isomorphic-git`,version:`1.37.5`,agent:`git/isomorphic-git@1.37.5`},$u=class{constructor(){this._queue=[]}write(e){if(this._ended)throw Error(`You cannot write to a FIFO that has already been ended!`);if(this._waiting){let t=this._waiting;this._waiting=null,t({value:e})}else this._queue.push(e)}end(){if(this._ended=!0,this._waiting){let e=this._waiting;this._waiting=null,e({done:!0})}}destroy(e){this.error=e,this.end()}async next(){if(this._queue.length>0)return{value:this._queue.shift()};if(this._ended)return{done:!0};if(this._waiting)throw Error(`You cannot call read until the previous call to read has returned!`);return new Promise(e=>{this._waiting=e})}};function ed(e){let t=e.indexOf(`\r`),n=e.indexOf(`
778
- `);return t===-1&&n===-1?-1:t===-1?n+1:n===-1?t+1:n===t+1?n+1:Math.min(t,n)+1}function td(e){let t=new $u,n=``;return(async()=>{await ju(e,e=>{for(e=e.toString(`utf8`),n+=e;;){let e=ed(n);if(e===-1)break;t.write(n.slice(0,e)),n=n.slice(e)}}),n.length>0&&t.write(n),t.end()})(),t}var nd=class{static demux(e){let t=Fu.streamReader(e),n=new $u,r=new $u,i=new $u,a=async function(){let o=await t();if(o===null)return a();if(o===!0){n.end(),i.end(),e.error?r.destroy(e.error):r.end();return}switch(o[0]){case 1:r.write(o.slice(1));break;case 2:i.write(o.slice(1));break;case 3:{let e=o.slice(1);i.write(e),n.end(),i.end(),r.destroy(Error(e.toString(`utf8`)));return}default:n.write(o)}a()};return a(),{packetlines:n,packfile:r,progress:i}}};async function rd(e){let{packetlines:t,packfile:n,progress:r}=nd.demux(e),i=[],a=[],o=[],s=!1,c=!1;return new Promise((l,u)=>{ju(t,t=>{let d=t.toString(`utf8`).trim();if(d.startsWith(`shallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new Es(e)),i.push(e)}else if(d.startsWith(`unshallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new Es(e)),a.push(e)}else if(d.startsWith(`ACK`)){let[,e,t]=d.split(` `);o.push({oid:e,status:t}),t||(c=!0)}else d.startsWith(`NAK`)?(s=!0,c=!0):(c=!0,s=!0);c&&(e.error?u(e.error):l({shallows:i,unshallows:a,acks:o,nak:s,packfile:n,progress:r}))}).finally(()=>{c||(e.error?u(e.error):l({shallows:i,unshallows:a,acks:o,nak:s,packfile:n,progress:r}))})})}function id({capabilities:e=[],wants:t=[],haves:n=[],shallows:r=[],depth:i=null,since:a=null,exclude:o=[]}){let s=[];t=[...new Set(t)];let c=` ${e.join(` `)}`;for(let e of t)s.push(Fu.encode(`want ${e}${c}\n`)),c=``;for(let e of r)s.push(Fu.encode(`shallow ${e}\n`));i!==null&&s.push(Fu.encode(`deepen ${i}\n`)),a!==null&&s.push(Fu.encode(`deepen-since ${Math.floor(a.valueOf()/1e3)}\n`));for(let e of o)s.push(Fu.encode(`deepen-not ${e}\n`));s.push(Fu.flush());for(let e of n)s.push(Fu.encode(`have ${e}\n`));return s.push(Fu.encode(`done
779
- `)),s}async function ad({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:c,ref:l,remoteRef:u,remote:d,url:f,corsProxy:p,depth:m=null,since:h=null,exclude:g=[],relative:_=!1,tags:v=!1,singleBranch:y=!1,headers:b={},prune:x=!1,pruneTags:S=!1}){let C=l||await Ou({fs:e,gitdir:c,test:!0}),w=await Qs.get({fs:e,gitdir:c}),T=d||C&&await w.get(`branch.${C}.remote`)||`origin`,E=f||await w.get(`remote.${T}.url`);if(E===void 0)throw new Zc(`remote OR url`);let D=u||C&&await w.get(`branch.${C}.merge`)||l||`HEAD`;p===void 0&&(p=await w.get(`http.corsProxy`));let O=Uu.getRemoteHelperFor({url:E}),k=await O.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:p,service:`git-upload-pack`,url:E,headers:b,protocolVersion:1}),ee=k.auth,A=k.refs;if(A.size===0)return{defaultBranch:null,fetchHead:null,fetchHeadDescription:null};if(m!==null&&!k.capabilities.has(`shallow`))throw new tl(`shallow`,`depth`);if(h!==null&&!k.capabilities.has(`deepen-since`))throw new tl(`deepen-since`,`since`);if(g.length>0&&!k.capabilities.has(`deepen-not`))throw new tl(`deepen-not`,`exclude`);if(_===!0&&!k.capabilities.has(`deepen-relative`))throw new tl(`deepen-relative`,`relative`);let{oid:j,fullref:te}=K.resolveAgainstMap({ref:D,map:A});for(let e of A.keys())e===te||e===`HEAD`||e.startsWith(`refs/heads/`)||v&&e.startsWith(`refs/tags/`)||A.delete(e);let ne=Zu([...k.capabilities],[`multi_ack_detailed`,`no-done`,`side-band-64k`,`ofs-delta`,`agent=${Qu.agent}`]);_&&ne.push(`deepen-relative`);let re=y?[j]:A.values(),ie=y?[C]:await K.listRefs({fs:e,gitdir:c,filepath:`refs`}),M=[];for(let n of ie)try{n=await K.expand({fs:e,gitdir:c,ref:n});let r=await K.resolve({fs:e,gitdir:c,ref:n});await Yu({fs:e,cache:t,gitdir:c,oid:r})&&M.push(r)}catch{}M=[...new Set(M)];let N=await Ku.read({fs:e,gitdir:c}),P=k.capabilities.has(`shallow`)?[...N]:[],ae=id({capabilities:ne,wants:re,haves:M,shallows:P,depth:m,since:h,exclude:g}),F=Buffer.from(await Mu(ae)),oe=await O.connect({http:n,onProgress:r,corsProxy:p,service:`git-upload-pack`,url:E,auth:ee,body:[F],headers:b}),I=await rd(oe.body);oe.headers&&(I.headers=oe.headers);for(let n of I.shallows)if(!N.has(n))try{let{object:r}=await Pc({fs:e,cache:t,gitdir:c,oid:n}),i=new yl(r),a=await Promise.all(i.headers().parent.map(n=>Yu({fs:e,cache:t,gitdir:c,oid:n})));a.length===0||a.every(e=>e)||N.add(n)}catch{N.add(n)}for(let e of I.unshallows)N.delete(e);if(await Ku.write({fs:e,gitdir:c,oids:N}),y){let t=new Map([[te,j]]),n=new Map,r=10,i=te;for(;r--;){let e=k.symrefs.get(i);if(e===void 0)break;n.set(i,e),i=e}let a=A.get(i);a&&t.set(i,a);let{pruned:o}=await K.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:t,symrefs:n,tags:v,prune:x});x&&(I.pruned=o)}else{let{pruned:t}=await K.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:A,symrefs:k.symrefs,tags:v,prune:x,pruneTags:S});x&&(I.pruned=t)}if(I.HEAD=k.symrefs.get(`HEAD`),I.HEAD===void 0){let{oid:e}=K.resolveAgainstMap({ref:`HEAD`,map:A});for(let[t,n]of A.entries())if(t!==`HEAD`&&n===e){I.HEAD=t;break}}I.FETCH_HEAD={oid:j,description:`${te.startsWith(`refs/tags`)?`tag`:`branch`} '${Du(te)}' of ${E}`},(r||i)&&ju(td(I.progress),async e=>{if(i&&await i(e),r){let t=e.match(/([^:]*).*\((\d+?)\/(\d+?)\)/);t&&await r({phase:t[1].trim(),loaded:parseInt(t[2],10),total:parseInt(t[3],10)})}});let L=Buffer.from(await Mu(I.packfile));if(oe.body.error)throw oe.body.error;let se=L.slice(-20).toString(`hex`),ce={defaultBranch:I.HEAD,fetchHead:I.FETCH_HEAD.oid,fetchHeadDescription:I.FETCH_HEAD.description};if(I.headers&&(ce.headers=I.headers),x&&(ce.pruned=I.pruned),se!==``&&!Xu(L)){ce.packfile=`objects/pack/pack-${se}.pack`;let n=G(c,ce.packfile);await e.write(n,L);let i=await Oc.fromPack({pack:L,getExternalRefDelta:n=>Pc({fs:e,cache:t,gitdir:c,oid:n}),onProgress:r});await e.write(n.replace(/\.pack$/,`.idx`),await i.toBuffer())}return ce}async function od({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:G(n,`.git`),defaultBranch:i=`master`}){if(await e.exists(r+`/config`))return;let a=[`hooks`,`info`,`objects/info`,`objects/pack`,`refs/heads`,`refs/tags`];a=a.map(e=>r+`/`+e);for(let t of a)await e.mkdir(t);await e.write(r+`/config`,`[core]
777
+ `;await Yu.acquire(r,async function(){await e.write(r,t,{encoding:`utf8`})})}else await Yu.acquire(r,async function(){await e.rm(r)})}};async function Zu({fs:e,gitdir:t,oid:n}){let r=`objects/${n.slice(0,2)}/${n.slice(2)}`;return e.exists(`${t}/${r}`)}async function Qu({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i}){let a=await e.readdir(G(n,`objects/pack`));a=a.filter(e=>e.endsWith(`.idx`));for(let o of a){let a=await Fc({fs:e,cache:t,filename:`${n}/objects/pack/${o}`,getExternalRefDelta:i});if(a.error)throw new W(a.error);if(a.offsets.has(r))return!0}return!1}async function $u({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`}){let a=r=>Rc({fs:e,cache:t,gitdir:n,oid:r}),o=await Zu({fs:e,gitdir:n,oid:r});return o||=await Qu({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:a}),o}function ed(e){return e.slice(0,12).toString(`hex`)===`5041434b0000000200000000`}function td(e,t){let n=e.map(e=>e.split(`=`,1)[0]);return t.filter(e=>{let t=e.split(`=`,1)[0];return n.includes(t)})}var nd={name:`isomorphic-git`,version:`1.37.5`,agent:`git/isomorphic-git@1.37.5`},rd=class{constructor(){this._queue=[]}write(e){if(this._ended)throw Error(`You cannot write to a FIFO that has already been ended!`);if(this._waiting){let t=this._waiting;this._waiting=null,t({value:e})}else this._queue.push(e)}end(){if(this._ended=!0,this._waiting){let e=this._waiting;this._waiting=null,e({done:!0})}}destroy(e){this.error=e,this.end()}async next(){if(this._queue.length>0)return{value:this._queue.shift()};if(this._ended)return{done:!0};if(this._waiting)throw Error(`You cannot call read until the previous call to read has returned!`);return new Promise(e=>{this._waiting=e})}};function id(e){let t=e.indexOf(`\r`),n=e.indexOf(`
778
+ `);return t===-1&&n===-1?-1:t===-1?n+1:n===-1?t+1:n===t+1?n+1:Math.min(t,n)+1}function ad(e){let t=new rd,n=``;return(async()=>{await Fu(e,e=>{for(e=e.toString(`utf8`),n+=e;;){let e=id(n);if(e===-1)break;t.write(n.slice(0,e)),n=n.slice(e)}}),n.length>0&&t.write(n),t.end()})(),t}var od=class{static demux(e){let t=zu.streamReader(e),n=new rd,r=new rd,i=new rd,a=async function(){let o=await t();if(o===null)return a();if(o===!0){n.end(),i.end(),e.error?r.destroy(e.error):r.end();return}switch(o[0]){case 1:r.write(o.slice(1));break;case 2:i.write(o.slice(1));break;case 3:{let e=o.slice(1);i.write(e),n.end(),i.end(),r.destroy(Error(e.toString(`utf8`)));return}default:n.write(o)}a()};return a(),{packetlines:n,packfile:r,progress:i}}};async function sd(e){let{packetlines:t,packfile:n,progress:r}=od.demux(e),i=[],a=[],o=[],s=!1,c=!1;return new Promise((l,u)=>{Fu(t,t=>{let d=t.toString(`utf8`).trim();if(d.startsWith(`shallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new As(e)),i.push(e)}else if(d.startsWith(`unshallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new As(e)),a.push(e)}else if(d.startsWith(`ACK`)){let[,e,t]=d.split(` `);o.push({oid:e,status:t}),t||(c=!0)}else d.startsWith(`NAK`)?(s=!0,c=!0):(c=!0,s=!0);c&&(e.error?u(e.error):l({shallows:i,unshallows:a,acks:o,nak:s,packfile:n,progress:r}))}).finally(()=>{c||(e.error?u(e.error):l({shallows:i,unshallows:a,acks:o,nak:s,packfile:n,progress:r}))})})}function cd({capabilities:e=[],wants:t=[],haves:n=[],shallows:r=[],depth:i=null,since:a=null,exclude:o=[]}){let s=[];t=[...new Set(t)];let c=` ${e.join(` `)}`;for(let e of t)s.push(zu.encode(`want ${e}${c}\n`)),c=``;for(let e of r)s.push(zu.encode(`shallow ${e}\n`));i!==null&&s.push(zu.encode(`deepen ${i}\n`)),a!==null&&s.push(zu.encode(`deepen-since ${Math.floor(a.valueOf()/1e3)}\n`));for(let e of o)s.push(zu.encode(`deepen-not ${e}\n`));s.push(zu.flush());for(let e of n)s.push(zu.encode(`have ${e}\n`));return s.push(zu.encode(`done
779
+ `)),s}async function ld({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:c,ref:l,remoteRef:u,remote:d,url:f,corsProxy:p,depth:m=null,since:h=null,exclude:g=[],relative:_=!1,tags:v=!1,singleBranch:y=!1,headers:b={},prune:x=!1,pruneTags:S=!1}){let C=l||await Mu({fs:e,gitdir:c,test:!0}),w=await nc.get({fs:e,gitdir:c}),T=d||C&&await w.get(`branch.${C}.remote`)||`origin`,E=f||await w.get(`remote.${T}.url`);if(E===void 0)throw new tl(`remote OR url`);let D=u||C&&await w.get(`branch.${C}.merge`)||l||`HEAD`;p===void 0&&(p=await w.get(`http.corsProxy`));let O=qu.getRemoteHelperFor({url:E}),k=await O.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:p,service:`git-upload-pack`,url:E,headers:b,protocolVersion:1}),ee=k.auth,A=k.refs;if(A.size===0)return{defaultBranch:null,fetchHead:null,fetchHeadDescription:null};if(m!==null&&!k.capabilities.has(`shallow`))throw new al(`shallow`,`depth`);if(h!==null&&!k.capabilities.has(`deepen-since`))throw new al(`deepen-since`,`since`);if(g.length>0&&!k.capabilities.has(`deepen-not`))throw new al(`deepen-not`,`exclude`);if(_===!0&&!k.capabilities.has(`deepen-relative`))throw new al(`deepen-relative`,`relative`);let{oid:j,fullref:te}=K.resolveAgainstMap({ref:D,map:A});for(let e of A.keys())e===te||e===`HEAD`||e.startsWith(`refs/heads/`)||v&&e.startsWith(`refs/tags/`)||A.delete(e);let ne=td([...k.capabilities],[`multi_ack_detailed`,`no-done`,`side-band-64k`,`ofs-delta`,`agent=${nd.agent}`]);_&&ne.push(`deepen-relative`);let re=y?[j]:A.values(),ie=y?[C]:await K.listRefs({fs:e,gitdir:c,filepath:`refs`}),M=[];for(let n of ie)try{n=await K.expand({fs:e,gitdir:c,ref:n});let r=await K.resolve({fs:e,gitdir:c,ref:n});await $u({fs:e,cache:t,gitdir:c,oid:r})&&M.push(r)}catch{}M=[...new Set(M)];let N=await Xu.read({fs:e,gitdir:c}),P=k.capabilities.has(`shallow`)?[...N]:[],ae=cd({capabilities:ne,wants:re,haves:M,shallows:P,depth:m,since:h,exclude:g}),F=Buffer.from(await Iu(ae)),oe=await O.connect({http:n,onProgress:r,corsProxy:p,service:`git-upload-pack`,url:E,auth:ee,body:[F],headers:b}),I=await sd(oe.body);oe.headers&&(I.headers=oe.headers);for(let n of I.shallows)if(!N.has(n))try{let{object:r}=await Rc({fs:e,cache:t,gitdir:c,oid:n}),i=new Cl(r),a=await Promise.all(i.headers().parent.map(n=>$u({fs:e,cache:t,gitdir:c,oid:n})));a.length===0||a.every(e=>e)||N.add(n)}catch{N.add(n)}for(let e of I.unshallows)N.delete(e);if(await Xu.write({fs:e,gitdir:c,oids:N}),y){let t=new Map([[te,j]]),n=new Map,r=10,i=te;for(;r--;){let e=k.symrefs.get(i);if(e===void 0)break;n.set(i,e),i=e}let a=A.get(i);a&&t.set(i,a);let{pruned:o}=await K.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:t,symrefs:n,tags:v,prune:x});x&&(I.pruned=o)}else{let{pruned:t}=await K.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:A,symrefs:k.symrefs,tags:v,prune:x,pruneTags:S});x&&(I.pruned=t)}if(I.HEAD=k.symrefs.get(`HEAD`),I.HEAD===void 0){let{oid:e}=K.resolveAgainstMap({ref:`HEAD`,map:A});for(let[t,n]of A.entries())if(t!==`HEAD`&&n===e){I.HEAD=t;break}}I.FETCH_HEAD={oid:j,description:`${te.startsWith(`refs/tags`)?`tag`:`branch`} '${ju(te)}' of ${E}`},(r||i)&&Fu(ad(I.progress),async e=>{if(i&&await i(e),r){let t=e.match(/([^:]*).*\((\d+?)\/(\d+?)\)/);t&&await r({phase:t[1].trim(),loaded:parseInt(t[2],10),total:parseInt(t[3],10)})}});let L=Buffer.from(await Iu(I.packfile));if(oe.body.error)throw oe.body.error;let se=L.slice(-20).toString(`hex`),ce={defaultBranch:I.HEAD,fetchHead:I.FETCH_HEAD.oid,fetchHeadDescription:I.FETCH_HEAD.description};if(I.headers&&(ce.headers=I.headers),x&&(ce.pruned=I.pruned),se!==``&&!ed(L)){ce.packfile=`objects/pack/pack-${se}.pack`;let n=G(c,ce.packfile);await e.write(n,L);let i=await Mc.fromPack({pack:L,getExternalRefDelta:n=>Rc({fs:e,cache:t,gitdir:c,oid:n}),onProgress:r});await e.write(n.replace(/\.pack$/,`.idx`),await i.toBuffer())}return ce}async function ud({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:G(n,`.git`),defaultBranch:i=`master`}){if(await e.exists(r+`/config`))return;let a=[`hooks`,`info`,`objects/info`,`objects/pack`,`refs/heads`,`refs/tags`];a=a.map(e=>r+`/`+e);for(let t of a)await e.mkdir(t);await e.write(r+`/config`,`[core]
780
780
  repositoryformatversion = 0
781
781
  filemode = false
782
782
  \tbare = ${t}\n`+(t?``:` logallrefupdates = true
783
783
  `)+` symlinks = false
784
784
  ignorecase = true
785
- `),await e.write(r+`/HEAD`,`ref: refs/heads/${i}\n`)}async function sd({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,onPostCheckout:c,dir:l,gitdir:u,url:d,corsProxy:f,ref:p,remote:m,depth:h,since:g,exclude:_,relative:v,singleBranch:y,noCheckout:b,noTags:x,headers:S,nonBlocking:C,batchSize:w=100}){try{if(await od({fs:e,gitdir:u}),await lu({fs:e,gitdir:u,remote:m,url:d,force:!1}),f){let t=await Qs.get({fs:e,gitdir:u});await t.set(`http.corsProxy`,f),await Qs.save({fs:e,gitdir:u,config:t})}let{defaultBranch:T,fetchHead:E}=await ad({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:u,ref:p,remote:m,corsProxy:f,depth:h,since:g,exclude:_,relative:v,singleBranch:y,headers:S,tags:!x});if(E===null)return;p||=T,p=p.replace(`refs/heads/`,``),await gu({fs:e,cache:t,onProgress:r,onPostCheckout:c,dir:l,gitdir:u,ref:p,remote:m,noCheckout:b,nonBlocking:C,batchSize:w})}catch(t){throw await e.rmdir(u,{recursive:!0,maxRetries:10}).catch(()=>void 0),t}}async function cd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:s,dir:c,gitdir:l=G(c,`.git`),url:u,corsProxy:d=void 0,ref:f=void 0,remote:p=`origin`,depth:m=void 0,since:h=void 0,exclude:g=[],relative:_=!1,singleBranch:v=!1,noCheckout:y=!1,noTags:b=!1,headers:x={},cache:S={},nonBlocking:C=!1,batchSize:w=100}){try{J(`fs`,e),J(`http`,t),J(`gitdir`,l),y||J(`dir`,c),J(`url`,u);let T=new q(e);return await sd({fs:T,cache:S,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:s,dir:c,gitdir:await Y({fsp:T,dotgit:l}),url:u,corsProxy:d,ref:f,remote:p,depth:m,since:h,exclude:g,relative:_,singleBranch:v,noCheckout:y,noTags:b,headers:x,nonBlocking:C,batchSize:w})}catch(e){throw e.caller=`git.clone`,e}}async function ld({fs:e,onSign:t,dir:n,gitdir:r=G(n,`.git`),message:i,author:a,committer:o,signingKey:s,amend:c=!1,dryRun:l=!1,noUpdateBranch:u=!1,ref:d,parent:f,tree:p,cache:m={}}){try{J(`fs`,e),c||J(`message`,i),s&&J(`onSign`,t);let n=new q(e);return await tu({fs:n,cache:m,onSign:t,gitdir:await Y({fsp:n,dotgit:r}),message:i,author:a,committer:o,signingKey:s,amend:c,dryRun:l,noUpdateBranch:u,ref:d,parent:f,tree:p})}catch(e){throw e.caller=`git.commit`,e}}async function ud({fs:e,dir:t,gitdir:n=G(t,`.git`),fullname:r=!1,test:i=!1}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await Ou({fs:t,gitdir:await Y({fsp:t,dotgit:n}),fullname:r,test:i})}catch(e){throw e.caller=`git.currentBranch`,e}}async function dd({fs:e,gitdir:t,ref:n}){if(n=n.startsWith(`refs/heads/`)?n:`refs/heads/${n}`,!await K.exists({fs:e,gitdir:t,ref:n}))throw new ws(n);let r=await K.expand({fs:e,gitdir:t,ref:n});if(r===await Ou({fs:e,gitdir:t,fullname:!0})){let n=await K.resolve({fs:e,gitdir:t,ref:r});await K.writeRef({fs:e,gitdir:t,ref:`HEAD`,value:n})}await K.deleteRef({fs:e,gitdir:t,ref:r});let i=Du(n),a=await Qs.get({fs:e,gitdir:t});await a.deleteSection(`branch`,i),await Qs.save({fs:e,gitdir:t,config:a})}async function fd({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r}){try{J(`fs`,e),J(`ref`,r);let t=new q(e);return await dd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteBranch`,e}}async function pd({fs:e,gitdir:t,remote:n}){let r=await Qs.get({fs:e,gitdir:t});await r.deleteSection(`remote`,n),await Qs.save({fs:e,gitdir:t,config:r})}async function md({fs:e,dir:t,gitdir:n=G(t,`.git`),remote:r}){try{J(`fs`,e),J(`remote`,r);let t=new q(e);return await pd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),remote:r})}catch(e){throw e.caller=`git.deleteRemote`,e}}async function hd({fs:e,gitdir:t,ref:n}){n=n.startsWith(`refs/tags/`)?n:`refs/tags/${n}`,await K.deleteRef({fs:e,gitdir:t,ref:n})}async function gd({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r}){try{J(`fs`,e),J(`ref`,r);let t=new q(e);return await hd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteTag`,e}}async function _d({fs:e,gitdir:t,oid:n}){let r=n.slice(0,2);return(await e.readdir(`${t}/objects/${r}`)).map(e=>`${r}${e}`).filter(e=>e.startsWith(n))}async function vd({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i}){let a=[],o=await e.readdir(G(n,`objects/pack`));o=o.filter(e=>e.endsWith(`.idx`));for(let s of o){let o=await jc({fs:e,cache:t,filename:`${n}/objects/pack/${s}`,getExternalRefDelta:i});if(o.error)throw new W(o.error);for(let e of o.offsets.keys())e.startsWith(r)&&a.push(e)}return a}async function yd({fs:e,cache:t,gitdir:n,oid:r}){let i=r=>Pc({fs:e,cache:t,gitdir:n,oid:r}),a=await _d({fs:e,gitdir:n,oid:r}),o=await vd({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i});for(let e of o)a.indexOf(e)===-1&&a.push(e);if(a.length===1)return a[0];throw a.length>1?new Ic(`oids`,r,a):new ws(`an object matching "${r}"`)}async function bd({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await yd({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.expandOid`,e}}async function xd({fs:e,cache:t,gitdir:n,oids:r}){let i={},a=r.length,o=r.map((e,t)=>({index:t,oid:e}));for(;o.length;){let r=new Set;for(let{oid:e,index:t}of o)i[e]||(i[e]=new Set),i[e].add(t),i[e].size===a&&r.add(e);if(r.size>0)return[...r];let s=new Map;for(let{oid:r,index:a}of o)try{let{object:o}=await Pc({fs:e,cache:t,gitdir:n,oid:r}),{parent:c}=yl.from(o).parseHeaders();for(let e of c)(!i[e]||!i[e].has(a))&&s.set(e+`:`+a,{oid:e,index:a})}catch{}o=Array.from(s.values())}return[]}async function Sd({fs:e,cache:t,dir:n,gitdir:r,ours:i,theirs:a,fastForward:o=!0,fastForwardOnly:s=!1,dryRun:c=!1,noUpdateBranch:l=!1,abortOnConflict:u=!0,message:d,author:f,committer:p,signingKey:m,onSign:h,mergeDriver:g,allowUnrelatedHistories:_=!1}){i===void 0&&(i=await Ou({fs:e,gitdir:r,fullname:!0})),i=await K.expand({fs:e,gitdir:r,ref:i}),a=await K.expand({fs:e,gitdir:r,ref:a});let v=await K.resolve({fs:e,gitdir:r,ref:i}),y=await K.resolve({fs:e,gitdir:r,ref:a}),b=await xd({fs:e,cache:t,gitdir:r,oids:[v,y]});if(b.length!==1)if(b.length===0&&_)b.push(`4b825dc642cb6eb9a060e54bf8d69288fbee4904`);else throw new Jc;let x=b[0];if(x===y)return{oid:v,alreadyMerged:!0};if(o&&x===v)return!c&&!l&&await K.writeRef({fs:e,gitdir:r,ref:i,value:y}),{oid:y,fastForward:!0};{if(s)throw new Hc;let o=await gs.acquire({fs:e,gitdir:r,cache:t,allowUnmerged:!1},async o=>wu({fs:e,cache:t,dir:n,gitdir:r,index:o,ourOid:v,theirOid:y,baseOid:x,ourName:Du(i),baseName:`base`,theirName:Du(a),dryRun:c,abortOnConflict:u,mergeDriver:g}));if(o instanceof Yc)throw o;return d||=`Merge branch '${Du(a)}' into ${Du(i)}`,{oid:await tu({fs:e,cache:t,gitdir:r,message:d,ref:i,tree:o,parent:[v,y],author:f,committer:p,signingKey:m,onSign:h,dryRun:c,noUpdateBranch:l}),tree:o,mergeCommit:!0}}}async function Cd({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,dir:c,gitdir:l,ref:u,url:d,remote:f,remoteRef:p,prune:m,pruneTags:h,fastForward:g,fastForwardOnly:_,corsProxy:v,singleBranch:y,headers:b,author:x,committer:S,signingKey:C}){try{if(!u){let t=await Ou({fs:e,gitdir:l});if(!t)throw new Zc(`ref`);u=t}let{fetchHead:w,fetchHeadDescription:T}=await ad({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:l,corsProxy:v,ref:u,url:d,remote:f,remoteRef:p,singleBranch:y,headers:b,prune:m,pruneTags:h});await Sd({fs:e,cache:t,gitdir:l,ours:u,theirs:w,fastForward:g,fastForwardOnly:_,message:`Merge ${T}`,author:x,committer:S,signingKey:C,dryRun:!1,noUpdateBranch:!1}),await gu({fs:e,cache:t,onProgress:r,dir:c,gitdir:l,ref:u,remote:f,noCheckout:!1})}catch(e){throw e.caller=`git.pull`,e}}async function wd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:c=G(s,`.git`),ref:l,remote:u,remoteRef:d,url:f,corsProxy:p,depth:m=null,since:h=null,exclude:g=[],relative:_=!1,tags:v=!1,singleBranch:y=!1,headers:b={},prune:x=!1,pruneTags:S=!1,cache:C={}}){try{J(`fs`,e),J(`http`,t),J(`gitdir`,c);let s=new q(e);return await ad({fs:s,cache:C,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,gitdir:await Y({fsp:s,dotgit:c}),ref:l,remote:u,remoteRef:d,url:f,corsProxy:p,depth:m,since:h,exclude:g,relative:_,tags:v,singleBranch:y,headers:b,prune:x,pruneTags:S})}catch(e){throw e.caller=`git.fetch`,e}}async function Td({fs:e,filepath:t}){if(await e.exists(G(t,`.git`)))return t;{let n=vs(t);if(n===t)throw new ws(`git root for ${t}`);return Td({fs:e,filepath:n})}}async function Ed({fs:e,filepath:t}){try{return J(`fs`,e),J(`filepath`,t),await Td({fs:new q(e),filepath:t})}catch(e){throw e.caller=`git.findRoot`,e}}async function Dd({fs:e,dir:t,gitdir:n=G(t,`.git`),path:r}){try{J(`fs`,e),J(`gitdir`,n),J(`path`,r);let t=new q(e);return await Yl({fs:t,gitdir:await Y({fsp:t,dotgit:n}),path:r})}catch(e){throw e.caller=`git.getConfig`,e}}async function Od({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:G(n,`.git`),defaultBranch:i=`master`}){try{J(`fs`,e),J(`gitdir`,r),t||J(`dir`,n);let a=new q(e);return await od({fs:a,bare:t,dir:n,gitdir:await Y({fsp:a,dotgit:r}),defaultBranch:i})}catch(e){throw e.caller=`git.init`,e}}async function kd({fs:e,cache:t,gitdir:n,oid:r,ancestor:i,depth:a}){let o=await Ku.read({fs:e,gitdir:n});if(!r)throw new Zc(`oid`);if(!i)throw new Zc(`ancestor`);if(r===i)return!1;let s=[r],c=new Set,l=0;for(;s.length;){if(l++===a)throw new qc(a);let r=s.shift(),{type:u,object:d}=await Pc({fs:e,cache:t,gitdir:n,oid:r});if(u!==`commit`)throw new Ts(r,u,`commit`);let f=yl.from(d).parse();for(let e of f.parent)if(e===i)return!0;if(!o.has(r))for(let e of f.parent)c.has(e)||(s.push(e),c.add(e))}return!1}async function Ad({fs:e,dir:t,gitdir:n=G(t,`.git`),remote:r}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e),i=await Y({fsp:t,dotgit:n});return K.listBranches({fs:t,gitdir:i,remote:r})}catch(e){throw e.caller=`git.listBranches`,e}}async function jd({fs:e,gitdir:t,ref:n,cache:r}){if(n){let i=await K.resolve({gitdir:t,fs:e,ref:n}),a=[];return await Md({fs:e,cache:r,gitdir:t,oid:i,filenames:a,prefix:``}),a}else return gs.acquire({fs:e,gitdir:t,cache:r},async function(e){return e.entries.map(e=>e.path)})}async function Md({fs:e,cache:t,gitdir:n,oid:r,filenames:i,prefix:a}){let{tree:o}=await au({fs:e,cache:t,gitdir:n,oid:r});for(let r of o)r.type===`tree`?await Md({fs:e,cache:t,gitdir:n,oid:r.oid,filenames:i,prefix:G(a,r.path)}):i.push(G(a,r.path))}async function Nd({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await jd({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.listFiles`,e}}async function Pd({fs:e,gitdir:t}){let n=await Qs.get({fs:e,gitdir:t}),r=await n.getSubsections(`remote`);return Promise.all(r.map(async e=>({remote:e,url:await n.get(`remote.${e}.url`)})))}async function Fd({fs:e,dir:t,gitdir:n=G(t,`.git`)}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await Pd({fs:t,gitdir:await Y({fsp:t,dotgit:n})})}catch(e){throw e.caller=`git.listRemotes`,e}}async function Id({fs:e,dir:t,gitdir:n=G(t,`.git`)}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e),r=await Y({fsp:t,dotgit:n});return K.listTags({fs:t,gitdir:r})}catch(e){throw e.caller=`git.listTags`,e}}function Ld(e,t){return e.committer.timestamp-t.committer.timestamp}var Rd=`e69de29bb2d1d6434b8b29ae775ad8c2e48c5391`;async function zd({fs:e,cache:t,gitdir:n,oid:r,fileId:i}){if(i===Rd)return;let a=r,o,s=await bl({fs:e,cache:t,gitdir:n,oid:r}),c=s.tree;return i===s.oid?o=s.path:(o=await Bd({fs:e,cache:t,gitdir:n,tree:c,fileId:i,oid:a}),Array.isArray(o)&&(o.length===0?o=void 0:o.length===1&&(o=o[0]))),o}async function Bd({fs:e,cache:t,gitdir:n,tree:r,fileId:i,oid:a,filepaths:o=[],parentPath:s=``}){let c=r.entries().map(function(r){let c;return r.oid===i?(c=G(s,r.path),o.push(c)):r.type===`tree`&&(c=Pc({fs:e,cache:t,gitdir:n,oid:r.oid}).then(function({object:c}){return Bd({fs:e,cache:t,gitdir:n,tree:lc.from(c),fileId:i,oid:a,filepaths:o,parentPath:G(s,r.path)})})),c});return await Promise.all(c),o}async function Vd({fs:e,cache:t,gitdir:n,filepath:r,ref:i,depth:a,since:o,force:s,follow:c}){let l=o===void 0?void 0:Math.floor(o.valueOf()/1e3),u=[],d=await Ku.read({fs:e,gitdir:n}),f=[await eu({fs:e,cache:t,gitdir:n,oid:await K.resolve({fs:e,gitdir:n,ref:i})})],p,m,h;function g(e){h&&r&&u.push(e)}for(;f.length>0;){let i=f.pop();if(l!==void 0&&i.commit.committer.timestamp<=l)break;if(r){let a;try{a=await ru({fs:e,cache:t,gitdir:n,oid:i.commit.tree,filepath:r}),m&&p!==a&&u.push(m),p=a,m=i,h=!0}catch(a){if(a instanceof ws){let o=c&&p;if(o&&(o=await zd({fs:e,cache:t,gitdir:n,oid:i.commit.tree,fileId:p}),o))if(Array.isArray(o)){if(m){let i=await zd({fs:e,cache:t,gitdir:n,oid:m.commit.tree,fileId:p});if(Array.isArray(i))if(o=o.filter(e=>i.indexOf(e)===-1),o.length===1)o=o[0],r=o,m&&u.push(m);else{o=!1,m&&u.push(m);break}}}else r=o,m&&u.push(m);if(!o){if(h&&p&&(u.push(m),!s))break;if(!s&&!c)throw a}m=i,h=!1}else throw a}}else u.push(i);if(a!==void 0&&u.length===a){g(i);break}if(!d.has(i.oid))for(let r of i.commit.parent){let i=await eu({fs:e,cache:t,gitdir:n,oid:r});f.map(e=>e.oid).includes(i.oid)||f.push(i)}f.length===0&&g(i),f.sort((e,t)=>Ld(e.commit,t.commit))}return u}async function Hd({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,ref:i=`HEAD`,depth:a,since:o,force:s,follow:c,cache:l={}}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,i);let t=new q(e);return await Vd({fs:t,cache:l,gitdir:await Y({fsp:t,dotgit:n}),filepath:r,ref:i,depth:a,since:o,force:s,follow:c})}catch(e){throw e.caller=`git.log`,e}}async function Ud({fs:e,onSign:t,dir:n,gitdir:r=G(n,`.git`),ours:i,theirs:a,fastForward:o=!0,fastForwardOnly:s=!1,dryRun:c=!1,noUpdateBranch:l=!1,abortOnConflict:u=!0,message:d,author:f,committer:p,signingKey:m,cache:h={},mergeDriver:g,allowUnrelatedHistories:_=!1}){try{J(`fs`,e),m&&J(`onSign`,t);let v=new q(e),y=await Y({fsp:v,dotgit:r}),b=await Zl({fs:v,gitdir:y,author:f});if(!b&&(!s||!o))throw new Xc(`author`);let x=await Ql({fs:v,gitdir:y,author:b,committer:p});if(!x&&(!s||!o))throw new Xc(`committer`);return await Sd({fs:v,cache:h,dir:n,gitdir:y,ours:i,theirs:a,fastForward:o,fastForwardOnly:s,dryRun:c,noUpdateBranch:l,abortOnConflict:u,message:d,author:b,committer:x,signingKey:m,onSign:t,mergeDriver:g,allowUnrelatedHistories:_})}catch(e){throw e.caller=`git.merge`,e}}var Wd={commit:16,tree:32,blob:48,tag:64,ofs_delta:96,ref_delta:112};async function Gd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),oids:i}){let a=new zo.default,o=[];function s(e,t){let n=Buffer.from(e,t);o.push(n),a.update(n)}async function c({stype:e,object:t}){let n=Wd[e],r=t.length,i=r>15?128:0,a=r&15;r>>>=4;let o=(i|n|a).toString(16);for(s(o,`hex`);i;)i=r>127?128:0,o=i|r&127,s(Pu(2,o),`hex`),r>>>=7;s(Buffer.from(await Hl(t)))}s(`PACK`),s(`00000002`,`hex`),s(Pu(8,i.length),`hex`);for(let n of i){let{type:i,object:a}=await Pc({fs:e,cache:t,gitdir:r,oid:n});await c({write:s,object:a,stype:i})}let l=a.digest();return o.push(l),o}async function Kd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:c=G(s,`.git`),ref:l,url:u,remote:d,remoteRef:f,prune:p=!1,pruneTags:m=!1,fastForward:h=!0,fastForwardOnly:g=!1,corsProxy:_,singleBranch:v,headers:y={},author:b,committer:x,signingKey:S,cache:C={}}){try{J(`fs`,e),J(`gitdir`,c);let w=new q(e),T=await Y({fsp:w,dotgit:c}),E=await Zl({fs:w,gitdir:T,author:b});if(!E)throw new Xc(`author`);let D=await Ql({fs:w,gitdir:T,author:E,committer:x});if(!D)throw new Xc(`committer`);return await Cd({fs:w,cache:C,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:T,ref:l,url:u,remote:d,remoteRef:f,fastForward:h,fastForwardOnly:g,corsProxy:_,singleBranch:v,headers:y,author:E,committer:D,signingKey:S,prune:p,pruneTags:m})}catch(e){throw e.caller=`git.pull`,e}}async function qd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),start:i,finish:a}){let o=await Ku.read({fs:e,gitdir:r}),s=new Set,c=new Set;for(let t of i)s.add(await K.resolve({fs:e,gitdir:r,ref:t}));for(let t of a)try{let n=await K.resolve({fs:e,gitdir:r,ref:t});c.add(n)}catch{}let l=new Set;async function u(n){l.add(n);let{type:i,object:a}=await Pc({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=gl.from(a).headers().object;return u(e)}if(i!==`commit`)throw new Ts(n,i,`commit`);if(!o.has(n))for(n of yl.from(a).headers().parent)!c.has(n)&&!l.has(n)&&await u(n)}for(let e of s)await u(e);return l}async function Jd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),oids:i}){let a=new Set;async function o(n){if(a.has(n))return;a.add(n);let{type:i,object:s}=await Pc({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=gl.from(s).headers().object;await o(e)}else if(i===`commit`){let e=yl.from(s).headers().tree;await o(e)}else if(i===`tree`){let e=lc.from(s);for(let t of e)t.type===`blob`&&a.add(t.oid),t.type===`tree`&&await o(t.oid)}}for(let e of i)await o(e);return a}async function Yd(e){let t={},n=``,r=Fu.streamReader(e),i=await r();for(;i!==!0;)i!==null&&(n+=i.toString(`utf8`)+`
785
+ `),await e.write(r+`/HEAD`,`ref: refs/heads/${i}\n`)}async function dd({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,onPostCheckout:c,dir:l,gitdir:u,url:d,corsProxy:f,ref:p,remote:m,depth:h,since:g,exclude:_,relative:v,singleBranch:y,noCheckout:b,noTags:x,headers:S,nonBlocking:C,batchSize:w=100}){try{if(await ud({fs:e,gitdir:u}),await pu({fs:e,gitdir:u,remote:m,url:d,force:!1}),f){let t=await nc.get({fs:e,gitdir:u});await t.set(`http.corsProxy`,f),await nc.save({fs:e,gitdir:u,config:t})}let{defaultBranch:T,fetchHead:E}=await ld({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:u,ref:p,remote:m,corsProxy:f,depth:h,since:g,exclude:_,relative:v,singleBranch:y,headers:S,tags:!x});if(E===null)return;p||=T,p=p.replace(`refs/heads/`,``),await bu({fs:e,cache:t,onProgress:r,onPostCheckout:c,dir:l,gitdir:u,ref:p,remote:m,noCheckout:b,nonBlocking:C,batchSize:w})}catch(t){throw await e.rmdir(u,{recursive:!0,maxRetries:10}).catch(()=>void 0),t}}async function fd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:s,dir:c,gitdir:l=G(c,`.git`),url:u,corsProxy:d=void 0,ref:f=void 0,remote:p=`origin`,depth:m=void 0,since:h=void 0,exclude:g=[],relative:_=!1,singleBranch:v=!1,noCheckout:y=!1,noTags:b=!1,headers:x={},cache:S={},nonBlocking:C=!1,batchSize:w=100}){try{J(`fs`,e),J(`http`,t),J(`gitdir`,l),y||J(`dir`,c),J(`url`,u);let T=new q(e);return await dd({fs:T,cache:S,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:s,dir:c,gitdir:await Y({fsp:T,dotgit:l}),url:u,corsProxy:d,ref:f,remote:p,depth:m,since:h,exclude:g,relative:_,singleBranch:v,noCheckout:y,noTags:b,headers:x,nonBlocking:C,batchSize:w})}catch(e){throw e.caller=`git.clone`,e}}async function pd({fs:e,onSign:t,dir:n,gitdir:r=G(n,`.git`),message:i,author:a,committer:o,signingKey:s,amend:c=!1,dryRun:l=!1,noUpdateBranch:u=!1,ref:d,parent:f,tree:p,cache:m={}}){try{J(`fs`,e),c||J(`message`,i),s&&J(`onSign`,t);let n=new q(e);return await au({fs:n,cache:m,onSign:t,gitdir:await Y({fsp:n,dotgit:r}),message:i,author:a,committer:o,signingKey:s,amend:c,dryRun:l,noUpdateBranch:u,ref:d,parent:f,tree:p})}catch(e){throw e.caller=`git.commit`,e}}async function md({fs:e,dir:t,gitdir:n=G(t,`.git`),fullname:r=!1,test:i=!1}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await Mu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),fullname:r,test:i})}catch(e){throw e.caller=`git.currentBranch`,e}}async function hd({fs:e,gitdir:t,ref:n}){if(n=n.startsWith(`refs/heads/`)?n:`refs/heads/${n}`,!await K.exists({fs:e,gitdir:t,ref:n}))throw new Os(n);let r=await K.expand({fs:e,gitdir:t,ref:n});if(r===await Mu({fs:e,gitdir:t,fullname:!0})){let n=await K.resolve({fs:e,gitdir:t,ref:r});await K.writeRef({fs:e,gitdir:t,ref:`HEAD`,value:n})}await K.deleteRef({fs:e,gitdir:t,ref:r});let i=ju(n),a=await nc.get({fs:e,gitdir:t});await a.deleteSection(`branch`,i),await nc.save({fs:e,gitdir:t,config:a})}async function gd({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r}){try{J(`fs`,e),J(`ref`,r);let t=new q(e);return await hd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteBranch`,e}}async function _d({fs:e,gitdir:t,remote:n}){let r=await nc.get({fs:e,gitdir:t});await r.deleteSection(`remote`,n),await nc.save({fs:e,gitdir:t,config:r})}async function vd({fs:e,dir:t,gitdir:n=G(t,`.git`),remote:r}){try{J(`fs`,e),J(`remote`,r);let t=new q(e);return await _d({fs:t,gitdir:await Y({fsp:t,dotgit:n}),remote:r})}catch(e){throw e.caller=`git.deleteRemote`,e}}async function yd({fs:e,gitdir:t,ref:n}){n=n.startsWith(`refs/tags/`)?n:`refs/tags/${n}`,await K.deleteRef({fs:e,gitdir:t,ref:n})}async function bd({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r}){try{J(`fs`,e),J(`ref`,r);let t=new q(e);return await yd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteTag`,e}}async function xd({fs:e,gitdir:t,oid:n}){let r=n.slice(0,2);return(await e.readdir(`${t}/objects/${r}`)).map(e=>`${r}${e}`).filter(e=>e.startsWith(n))}async function Sd({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i}){let a=[],o=await e.readdir(G(n,`objects/pack`));o=o.filter(e=>e.endsWith(`.idx`));for(let s of o){let o=await Fc({fs:e,cache:t,filename:`${n}/objects/pack/${s}`,getExternalRefDelta:i});if(o.error)throw new W(o.error);for(let e of o.offsets.keys())e.startsWith(r)&&a.push(e)}return a}async function Cd({fs:e,cache:t,gitdir:n,oid:r}){let i=r=>Rc({fs:e,cache:t,gitdir:n,oid:r}),a=await xd({fs:e,gitdir:n,oid:r}),o=await Sd({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i});for(let e of o)a.indexOf(e)===-1&&a.push(e);if(a.length===1)return a[0];throw a.length>1?new Bc(`oids`,r,a):new Os(`an object matching "${r}"`)}async function wd({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await Cd({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.expandOid`,e}}async function Td({fs:e,cache:t,gitdir:n,oids:r}){let i={},a=r.length,o=r.map((e,t)=>({index:t,oid:e}));for(;o.length;){let r=new Set;for(let{oid:e,index:t}of o)i[e]||(i[e]=new Set),i[e].add(t),i[e].size===a&&r.add(e);if(r.size>0)return[...r];let s=new Map;for(let{oid:r,index:a}of o)try{let{object:o}=await Rc({fs:e,cache:t,gitdir:n,oid:r}),{parent:c}=Cl.from(o).parseHeaders();for(let e of c)(!i[e]||!i[e].has(a))&&s.set(e+`:`+a,{oid:e,index:a})}catch{}o=Array.from(s.values())}return[]}async function Ed({fs:e,cache:t,dir:n,gitdir:r,ours:i,theirs:a,fastForward:o=!0,fastForwardOnly:s=!1,dryRun:c=!1,noUpdateBranch:l=!1,abortOnConflict:u=!0,message:d,author:f,committer:p,signingKey:m,onSign:h,mergeDriver:g,allowUnrelatedHistories:_=!1}){i===void 0&&(i=await Mu({fs:e,gitdir:r,fullname:!0})),i=await K.expand({fs:e,gitdir:r,ref:i}),a=await K.expand({fs:e,gitdir:r,ref:a});let v=await K.resolve({fs:e,gitdir:r,ref:i}),y=await K.resolve({fs:e,gitdir:r,ref:a}),b=await Td({fs:e,cache:t,gitdir:r,oids:[v,y]});if(b.length!==1)if(b.length===0&&_)b.push(`4b825dc642cb6eb9a060e54bf8d69288fbee4904`);else throw new Qc;let x=b[0];if(x===y)return{oid:v,alreadyMerged:!0};if(o&&x===v)return!c&&!l&&await K.writeRef({fs:e,gitdir:r,ref:i,value:y}),{oid:y,fastForward:!0};{if(s)throw new Kc;let o=await bs.acquire({fs:e,gitdir:r,cache:t,allowUnmerged:!1},async o=>Ou({fs:e,cache:t,dir:n,gitdir:r,index:o,ourOid:v,theirOid:y,baseOid:x,ourName:ju(i),baseName:`base`,theirName:ju(a),dryRun:c,abortOnConflict:u,mergeDriver:g}));if(o instanceof $c)throw o;return d||=`Merge branch '${ju(a)}' into ${ju(i)}`,{oid:await au({fs:e,cache:t,gitdir:r,message:d,ref:i,tree:o,parent:[v,y],author:f,committer:p,signingKey:m,onSign:h,dryRun:c,noUpdateBranch:l}),tree:o,mergeCommit:!0}}}async function Dd({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,dir:c,gitdir:l,ref:u,url:d,remote:f,remoteRef:p,prune:m,pruneTags:h,fastForward:g,fastForwardOnly:_,corsProxy:v,singleBranch:y,headers:b,author:x,committer:S,signingKey:C}){try{if(!u){let t=await Mu({fs:e,gitdir:l});if(!t)throw new tl(`ref`);u=t}let{fetchHead:w,fetchHeadDescription:T}=await ld({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:l,corsProxy:v,ref:u,url:d,remote:f,remoteRef:p,singleBranch:y,headers:b,prune:m,pruneTags:h});await Ed({fs:e,cache:t,gitdir:l,ours:u,theirs:w,fastForward:g,fastForwardOnly:_,message:`Merge ${T}`,author:x,committer:S,signingKey:C,dryRun:!1,noUpdateBranch:!1}),await bu({fs:e,cache:t,onProgress:r,dir:c,gitdir:l,ref:u,remote:f,noCheckout:!1})}catch(e){throw e.caller=`git.pull`,e}}async function Od({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:c=G(s,`.git`),ref:l,remote:u,remoteRef:d,url:f,corsProxy:p,depth:m=null,since:h=null,exclude:g=[],relative:_=!1,tags:v=!1,singleBranch:y=!1,headers:b={},prune:x=!1,pruneTags:S=!1,cache:C={}}){try{J(`fs`,e),J(`http`,t),J(`gitdir`,c);let s=new q(e);return await ld({fs:s,cache:C,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,gitdir:await Y({fsp:s,dotgit:c}),ref:l,remote:u,remoteRef:d,url:f,corsProxy:p,depth:m,since:h,exclude:g,relative:_,tags:v,singleBranch:y,headers:b,prune:x,pruneTags:S})}catch(e){throw e.caller=`git.fetch`,e}}async function kd({fs:e,filepath:t}){if(await e.exists(G(t,`.git`)))return t;{let n=Ss(t);if(n===t)throw new Os(`git root for ${t}`);return kd({fs:e,filepath:n})}}async function Ad({fs:e,filepath:t}){try{return J(`fs`,e),J(`filepath`,t),await kd({fs:new q(e),filepath:t})}catch(e){throw e.caller=`git.findRoot`,e}}async function jd({fs:e,dir:t,gitdir:n=G(t,`.git`),path:r}){try{J(`fs`,e),J(`gitdir`,n),J(`path`,r);let t=new q(e);return await $l({fs:t,gitdir:await Y({fsp:t,dotgit:n}),path:r})}catch(e){throw e.caller=`git.getConfig`,e}}async function Md({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:G(n,`.git`),defaultBranch:i=`master`}){try{J(`fs`,e),J(`gitdir`,r),t||J(`dir`,n);let a=new q(e);return await ud({fs:a,bare:t,dir:n,gitdir:await Y({fsp:a,dotgit:r}),defaultBranch:i})}catch(e){throw e.caller=`git.init`,e}}async function Nd({fs:e,cache:t,gitdir:n,oid:r,ancestor:i,depth:a}){let o=await Xu.read({fs:e,gitdir:n});if(!r)throw new tl(`oid`);if(!i)throw new tl(`ancestor`);if(r===i)return!1;let s=[r],c=new Set,l=0;for(;s.length;){if(l++===a)throw new Zc(a);let r=s.shift(),{type:u,object:d}=await Rc({fs:e,cache:t,gitdir:n,oid:r});if(u!==`commit`)throw new ks(r,u,`commit`);let f=Cl.from(d).parse();for(let e of f.parent)if(e===i)return!0;if(!o.has(r))for(let e of f.parent)c.has(e)||(s.push(e),c.add(e))}return!1}async function Pd({fs:e,dir:t,gitdir:n=G(t,`.git`),remote:r}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e),i=await Y({fsp:t,dotgit:n});return K.listBranches({fs:t,gitdir:i,remote:r})}catch(e){throw e.caller=`git.listBranches`,e}}async function Fd({fs:e,gitdir:t,ref:n,cache:r}){if(n){let i=await K.resolve({gitdir:t,fs:e,ref:n}),a=[];return await Id({fs:e,cache:r,gitdir:t,oid:i,filenames:a,prefix:``}),a}else return bs.acquire({fs:e,gitdir:t,cache:r},async function(e){return e.entries.map(e=>e.path)})}async function Id({fs:e,cache:t,gitdir:n,oid:r,filenames:i,prefix:a}){let{tree:o}=await lu({fs:e,cache:t,gitdir:n,oid:r});for(let r of o)r.type===`tree`?await Id({fs:e,cache:t,gitdir:n,oid:r.oid,filenames:i,prefix:G(a,r.path)}):i.push(G(a,r.path))}async function Ld({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await Fd({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.listFiles`,e}}async function Rd({fs:e,gitdir:t}){let n=await nc.get({fs:e,gitdir:t}),r=await n.getSubsections(`remote`);return Promise.all(r.map(async e=>({remote:e,url:await n.get(`remote.${e}.url`)})))}async function zd({fs:e,dir:t,gitdir:n=G(t,`.git`)}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await Rd({fs:t,gitdir:await Y({fsp:t,dotgit:n})})}catch(e){throw e.caller=`git.listRemotes`,e}}async function Bd({fs:e,dir:t,gitdir:n=G(t,`.git`)}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e),r=await Y({fsp:t,dotgit:n});return K.listTags({fs:t,gitdir:r})}catch(e){throw e.caller=`git.listTags`,e}}function Vd(e,t){return e.committer.timestamp-t.committer.timestamp}var Hd=`e69de29bb2d1d6434b8b29ae775ad8c2e48c5391`;async function Ud({fs:e,cache:t,gitdir:n,oid:r,fileId:i}){if(i===Hd)return;let a=r,o,s=await wl({fs:e,cache:t,gitdir:n,oid:r}),c=s.tree;return i===s.oid?o=s.path:(o=await Wd({fs:e,cache:t,gitdir:n,tree:c,fileId:i,oid:a}),Array.isArray(o)&&(o.length===0?o=void 0:o.length===1&&(o=o[0]))),o}async function Wd({fs:e,cache:t,gitdir:n,tree:r,fileId:i,oid:a,filepaths:o=[],parentPath:s=``}){let c=r.entries().map(function(r){let c;return r.oid===i?(c=G(s,r.path),o.push(c)):r.type===`tree`&&(c=Rc({fs:e,cache:t,gitdir:n,oid:r.oid}).then(function({object:c}){return Wd({fs:e,cache:t,gitdir:n,tree:pc.from(c),fileId:i,oid:a,filepaths:o,parentPath:G(s,r.path)})})),c});return await Promise.all(c),o}async function Gd({fs:e,cache:t,gitdir:n,filepath:r,ref:i,depth:a,since:o,force:s,follow:c}){let l=o===void 0?void 0:Math.floor(o.valueOf()/1e3),u=[],d=await Xu.read({fs:e,gitdir:n}),f=[await iu({fs:e,cache:t,gitdir:n,oid:await K.resolve({fs:e,gitdir:n,ref:i})})],p,m,h;function g(e){h&&r&&u.push(e)}for(;f.length>0;){let i=f.pop();if(l!==void 0&&i.commit.committer.timestamp<=l)break;if(r){let a;try{a=await su({fs:e,cache:t,gitdir:n,oid:i.commit.tree,filepath:r}),m&&p!==a&&u.push(m),p=a,m=i,h=!0}catch(a){if(a instanceof Os){let o=c&&p;if(o&&(o=await Ud({fs:e,cache:t,gitdir:n,oid:i.commit.tree,fileId:p}),o))if(Array.isArray(o)){if(m){let i=await Ud({fs:e,cache:t,gitdir:n,oid:m.commit.tree,fileId:p});if(Array.isArray(i))if(o=o.filter(e=>i.indexOf(e)===-1),o.length===1)o=o[0],r=o,m&&u.push(m);else{o=!1,m&&u.push(m);break}}}else r=o,m&&u.push(m);if(!o){if(h&&p&&(u.push(m),!s))break;if(!s&&!c)throw a}m=i,h=!1}else throw a}}else u.push(i);if(a!==void 0&&u.length===a){g(i);break}if(!d.has(i.oid))for(let r of i.commit.parent){let i=await iu({fs:e,cache:t,gitdir:n,oid:r});f.map(e=>e.oid).includes(i.oid)||f.push(i)}f.length===0&&g(i),f.sort((e,t)=>Vd(e.commit,t.commit))}return u}async function Kd({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,ref:i=`HEAD`,depth:a,since:o,force:s,follow:c,cache:l={}}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,i);let t=new q(e);return await Gd({fs:t,cache:l,gitdir:await Y({fsp:t,dotgit:n}),filepath:r,ref:i,depth:a,since:o,force:s,follow:c})}catch(e){throw e.caller=`git.log`,e}}async function qd({fs:e,onSign:t,dir:n,gitdir:r=G(n,`.git`),ours:i,theirs:a,fastForward:o=!0,fastForwardOnly:s=!1,dryRun:c=!1,noUpdateBranch:l=!1,abortOnConflict:u=!0,message:d,author:f,committer:p,signingKey:m,cache:h={},mergeDriver:g,allowUnrelatedHistories:_=!1}){try{J(`fs`,e),m&&J(`onSign`,t);let v=new q(e),y=await Y({fsp:v,dotgit:r}),b=await tu({fs:v,gitdir:y,author:f});if(!b&&(!s||!o))throw new el(`author`);let x=await nu({fs:v,gitdir:y,author:b,committer:p});if(!x&&(!s||!o))throw new el(`committer`);return await Ed({fs:v,cache:h,dir:n,gitdir:y,ours:i,theirs:a,fastForward:o,fastForwardOnly:s,dryRun:c,noUpdateBranch:l,abortOnConflict:u,message:d,author:b,committer:x,signingKey:m,onSign:t,mergeDriver:g,allowUnrelatedHistories:_})}catch(e){throw e.caller=`git.merge`,e}}var Jd={commit:16,tree:32,blob:48,tag:64,ofs_delta:96,ref_delta:112};async function Yd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),oids:i}){let a=new Uo.default,o=[];function s(e,t){let n=Buffer.from(e,t);o.push(n),a.update(n)}async function c({stype:e,object:t}){let n=Jd[e],r=t.length,i=r>15?128:0,a=r&15;r>>>=4;let o=(i|n|a).toString(16);for(s(o,`hex`);i;)i=r>127?128:0,o=i|r&127,s(Ru(2,o),`hex`),r>>>=7;s(Buffer.from(await Kl(t)))}s(`PACK`),s(`00000002`,`hex`),s(Ru(8,i.length),`hex`);for(let n of i){let{type:i,object:a}=await Rc({fs:e,cache:t,gitdir:r,oid:n});await c({write:s,object:a,stype:i})}let l=a.digest();return o.push(l),o}async function Xd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:c=G(s,`.git`),ref:l,url:u,remote:d,remoteRef:f,prune:p=!1,pruneTags:m=!1,fastForward:h=!0,fastForwardOnly:g=!1,corsProxy:_,singleBranch:v,headers:y={},author:b,committer:x,signingKey:S,cache:C={}}){try{J(`fs`,e),J(`gitdir`,c);let w=new q(e),T=await Y({fsp:w,dotgit:c}),E=await tu({fs:w,gitdir:T,author:b});if(!E)throw new el(`author`);let D=await nu({fs:w,gitdir:T,author:E,committer:x});if(!D)throw new el(`committer`);return await Dd({fs:w,cache:C,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:T,ref:l,url:u,remote:d,remoteRef:f,fastForward:h,fastForwardOnly:g,corsProxy:_,singleBranch:v,headers:y,author:E,committer:D,signingKey:S,prune:p,pruneTags:m})}catch(e){throw e.caller=`git.pull`,e}}async function Zd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),start:i,finish:a}){let o=await Xu.read({fs:e,gitdir:r}),s=new Set,c=new Set;for(let t of i)s.add(await K.resolve({fs:e,gitdir:r,ref:t}));for(let t of a)try{let n=await K.resolve({fs:e,gitdir:r,ref:t});c.add(n)}catch{}let l=new Set;async function u(n){l.add(n);let{type:i,object:a}=await Rc({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=bl.from(a).headers().object;return u(e)}if(i!==`commit`)throw new ks(n,i,`commit`);if(!o.has(n))for(n of Cl.from(a).headers().parent)!c.has(n)&&!l.has(n)&&await u(n)}for(let e of s)await u(e);return l}async function Qd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),oids:i}){let a=new Set;async function o(n){if(a.has(n))return;a.add(n);let{type:i,object:s}=await Rc({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=bl.from(s).headers().object;await o(e)}else if(i===`commit`){let e=Cl.from(s).headers().tree;await o(e)}else if(i===`tree`){let e=pc.from(s);for(let t of e)t.type===`blob`&&a.add(t.oid),t.type===`tree`&&await o(t.oid)}}for(let e of i)await o(e);return a}async function $d(e){let t={},n=``,r=zu.streamReader(e),i=await r();for(;i!==!0;)i!==null&&(n+=i.toString(`utf8`)+`
786
786
  `),i=await r();let a=n.toString(`utf8`).split(`
787
- `);if(i=a.shift(),!i.startsWith(`unpack `))throw new $c(`unpack ok" or "unpack [error message]`,i);t.ok=i===`unpack ok`,t.ok||(t.error=i.slice(7)),t.refs={};for(let e of a){if(e.trim()===``)continue;let n=e.slice(0,2),r=e.slice(3),i=r.indexOf(` `);i===-1&&(i=r.length);let a=r.slice(0,i),o=r.slice(i+1);t.refs[a]={ok:n===`ok`,error:o}}return t}async function Xd({capabilities:e=[],triplets:t=[]}){let n=[],r=`\x00 ${e.join(` `)}`;for(let e of t)n.push(Fu.encode(`${e.oldoid} ${e.oid} ${e.fullRef}${r}\n`)),r=``;return n.push(Fu.flush()),n}async function Zd({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,onPrePush:c,gitdir:l,ref:u,remoteRef:d,remote:f,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={}}){let v=u||await Ou({fs:e,gitdir:l});if(v===void 0)throw new Zc(`ref`);let y=await Qs.get({fs:e,gitdir:l});f=f||await y.get(`branch.${v}.pushRemote`)||await y.get(`remote.pushDefault`)||await y.get(`branch.${v}.remote`)||`origin`;let b=p||await y.get(`remote.${f}.pushurl`)||await y.get(`remote.${f}.url`);if(b===void 0)throw new Zc(`remote OR url`);let x=d||await y.get(`branch.${v}.merge`);if(b===void 0)throw new Zc(`remoteRef`);g===void 0&&(g=await y.get(`http.corsProxy`));let S=await K.expand({fs:e,gitdir:l,ref:v}),C=h?`0000000000000000000000000000000000000000`:await K.resolve({fs:e,gitdir:l,ref:S}),w=Uu.getRemoteHelperFor({url:b}),T=await w.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:g,service:`git-receive-pack`,url:b,headers:_,protocolVersion:1}),E=T.auth,D;if(!x)D=S;else try{D=await K.expandAgainstMap({ref:x,map:T.refs})}catch(e){if(e instanceof ws)D=x.startsWith(`refs/`)?x:`refs/heads/${x}`;else throw e}let O=T.refs.get(D)||`0000000000000000000000000000000000000000`;if(c&&!await c({remote:f,url:b,localRef:{ref:h?`(delete)`:S,oid:C},remoteRef:{ref:D,oid:O}}))throw new al;let k=!T.capabilities.has(`no-thin`),ee=new Set;if(!h){let n=[...T.refs.values()],r=new Set;if(O!==`0000000000000000000000000000000000000000`){let i=await xd({fs:e,cache:t,gitdir:l,oids:[C,O]});for(let e of i)n.push(e);k&&(r=await Jd({fs:e,cache:t,gitdir:l,oids:i}))}if(n.includes(C)||(ee=await Jd({fs:e,cache:t,gitdir:l,oids:await qd({fs:e,cache:t,gitdir:l,start:[C],finish:n})})),k){try{let n=await K.resolve({fs:e,gitdir:l,ref:`refs/remotes/${f}/HEAD`,depth:2}),{oid:i}=await K.resolveAgainstMap({ref:n.replace(`refs/remotes/${f}/`,``),fullref:n,map:T.refs}),a=[i];for(let n of await Jd({fs:e,cache:t,gitdir:l,oids:a}))r.add(n)}catch{}for(let e of r)ee.delete(e)}if(C===O&&(m=!0),!m){if(S.startsWith(`refs/tags`)&&O!==`0000000000000000000000000000000000000000`)throw new el(`tag-exists`);if(C!==`0000000000000000000000000000000000000000`&&O!==`0000000000000000000000000000000000000000`&&!await kd({fs:e,cache:t,gitdir:l,oid:C,ancestor:O,depth:-1}))throw new el(`not-fast-forward`)}}let A=await Xd({capabilities:Zu([...T.capabilities],[`report-status`,`side-band-64k`,`agent=${Qu.agent}`]),triplets:[{oldoid:O,oid:C,fullRef:D}]}),j=h?[]:await Gd({fs:e,cache:t,gitdir:l,oids:[...ee]}),te=await w.connect({http:n,onProgress:r,corsProxy:g,service:`git-receive-pack`,url:b,auth:E,headers:_,body:[...A,...j]}),{packfile:ne,progress:re}=await nd.demux(te.body);i&&ju(td(re),async e=>{await i(e)});let ie=await Yd(ne);if(te.headers&&(ie.headers=te.headers),f&&ie.ok&&ie.refs[D].ok&&!S.startsWith(`refs/tags`)){let t=`refs/remotes/${f}/${D.replace(`refs/heads`,``)}`;h?await K.deleteRef({fs:e,gitdir:l,ref:t}):await K.writeRef({fs:e,gitdir:l,ref:t,value:C})}if(ie.ok&&Object.values(ie.refs).every(e=>e.ok))return ie;throw new Uc(Object.entries(ie.refs).filter(([e,t])=>!t.ok).map(([e,t])=>`\n - ${e}: ${t.error}`).join(``),ie)}async function Qd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,dir:c,gitdir:l=G(c,`.git`),ref:u,remoteRef:d,remote:f=`origin`,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={},cache:v={}}){try{J(`fs`,e),J(`http`,t),J(`gitdir`,l);let c=new q(e);return await Zd({fs:c,cache:v,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,gitdir:await Y({fsp:c,dotgit:l}),ref:u,remoteRef:d,remote:f,url:p,force:m,delete:h,corsProxy:g,headers:_})}catch(e){throw e.caller=`git.push`,e}}async function $d({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await Pc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=gl.from(a).parse().object,$d({fs:e,cache:t,gitdir:n,oid:r});if(i!==`blob`)throw new Ts(r,i,`blob`);return{oid:r,blob:new Uint8Array(a)}}async function ef({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){return i!==void 0&&(r=await ru({fs:e,cache:t,gitdir:n,oid:r,filepath:i})),await $d({fs:e,cache:t,gitdir:n,oid:r})}async function tf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,filepath:i,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await ef({fs:t,cache:a,gitdir:await Y({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readBlob`,e}}async function nf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await eu({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.readCommit`,e}}async function rf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,filepath:i=void 0,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await au({fs:t,cache:a,gitdir:await Y({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readTree`,e}}async function af({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`filepath`,r);let t=new q(e),a=await Y({fsp:t,dotgit:n});await gs.acquire({fs:t,gitdir:a,cache:i},async function(e){e.delete({filepath:r})})}catch(e){throw e.caller=`git.remove`,e}}async function of({gitdir:e,type:t,object:n}){return rs(uc.wrap({type:t,object:n}))}async function sf({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,ref:i,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`filepath`,r);let o=new q(e),s=await Y({fsp:o,dotgit:n}),c,l;try{c=await K.resolve({fs:o,gitdir:s,ref:i||`HEAD`})}catch(e){if(i)throw e}if(c)try{c=await ru({fs:o,cache:a,gitdir:s,oid:c,filepath:r})}catch{c=null}let u={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:0,uid:0,gid:0,size:0},d=t&&await o.read(G(t,r));d&&(l=await of({gitdir:s,type:`blob`,object:d}),c===l&&(u=await o.lstat(G(t,r)))),await gs.acquire({fs:o,gitdir:s,cache:a},async function(e){e.delete({filepath:r}),c&&e.insert({filepath:r,stats:u,oid:c})})}catch(e){throw e.caller=`git.reset`,e}}async function cf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,depth:i}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e),a=await Y({fsp:t,dotgit:n});return await K.resolve({fs:t,gitdir:a,ref:r,depth:i})}catch(e){throw e.caller=`git.resolveRef`,e}}async function lf({fs:e,dir:t,gitdir:n=G(t,`.git`),path:r,value:i,append:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`path`,r);let t=new q(e),o=await Y({fsp:t,dotgit:n}),s=await Qs.get({fs:t,gitdir:o});a?await s.append(r,i):await s.set(r,i),await Qs.save({fs:t,gitdir:o,config:s})}catch(e){throw e.caller=`git.setConfig`,e}}async function uf({fs:e,gitdir:t,commit:n}){return await Gl({fs:e,gitdir:t,type:`commit`,object:yl.from(n).toObject(),format:`content`})}async function df({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r=`HEAD`,filepaths:i=[`.`],filter:a,cache:o={},ignored:s=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let c=new q(e);return await kl({fs:c,cache:o,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:[Sl({ref:r}),wl(),Cs()],map:async function(e,[n,r,o]){if(!n&&!o&&r&&!s&&await zl.isIgnored({fs:c,dir:t,filepath:e})||!i.some(t=>hu(e,t)))return null;if(a&&!a(e))return;let[l,u,d]=await Promise.all([n&&n.type(),r&&r.type(),o&&o.type()]),f=[l,u,d].includes(`blob`);if((l===`tree`||l===`special`)&&!f)return;if(l===`commit`)return null;if((u===`tree`||u===`special`)&&!f)return;if(d===`commit`)return null;if((d===`tree`||d===`special`)&&!f)return;let p=l===`blob`?await n.oid():void 0,m=d===`blob`?await o.oid():void 0,h;l!==`blob`&&u===`blob`&&d!==`blob`?h=`42`:u===`blob`&&(h=await r.oid());let g=[void 0,p,h,m],_=g.map(e=>g.indexOf(e));return _.shift(),[e,..._]}})}catch(e){throw e.caller=`git.statusMatrix`,e}}async function ff({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,object:i,force:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e);if(r===void 0)throw new Zc(`ref`);r=r.startsWith(`refs/tags/`)?r:`refs/tags/${r}`;let o=await Y({fsp:t,dotgit:n}),s=await K.resolve({fs:t,gitdir:o,ref:i||`HEAD`});if(!a&&await K.exists({fs:t,gitdir:o,ref:r}))throw new Fc(`tag`,r);await K.writeRef({fs:t,gitdir:o,ref:r,value:s})}catch(e){throw e.caller=`git.tag`,e}}function pf(){try{return Qu.version}catch(e){throw e.caller=`git.version`,e}}async function mf({fs:e,dir:t,gitdir:n=G(t,`.git`),trees:r,map:i,reduce:a,iterate:o,cache:s={}}){try{J(`fs`,e),J(`gitdir`,n),J(`trees`,r);let c=new q(e);return await kl({fs:c,cache:s,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:r,map:i,reduce:a,iterate:o})}catch(e){throw e.caller=`git.walk`,e}}async function hf({fs:e,dir:t,gitdir:n=G(t,`.git`),blob:r}){try{J(`fs`,e),J(`gitdir`,n),J(`blob`,r);let t=new q(e);return await Gl({fs:t,gitdir:await Y({fsp:t,dotgit:n}),type:`blob`,object:r,format:`content`})}catch(e){throw e.caller=`git.writeBlob`,e}}async function gf({fs:e,dir:t,gitdir:n=G(t,`.git`),commit:r}){try{J(`fs`,e),J(`gitdir`,n),J(`commit`,r);let t=new q(e);return await uf({fs:t,gitdir:await Y({fsp:t,dotgit:n}),commit:r})}catch(e){throw e.caller=`git.writeCommit`,e}}async function _f({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,value:i,force:a=!1,symbolic:o=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r),J(`value`,i);let t=new q(e);if(!cu(r,!0))throw new Kc(r,Wo.default.clean(r));let s=await Y({fsp:t,dotgit:n});if(!a&&await K.exists({fs:t,gitdir:s,ref:r}))throw new Fc(`ref`,r);o?await K.writeSymbolicRef({fs:t,gitdir:s,ref:r,value:i}):(i=await K.resolve({fs:t,gitdir:s,ref:i}),await K.writeRef({fs:t,gitdir:s,ref:r,value:i}))}catch(e){throw e.caller=`git.writeRef`,e}}async function vf({fs:e,dir:t,gitdir:n=G(t,`.git`),tree:r}){try{J(`fs`,e),J(`gitdir`,n),J(`tree`,r);let t=new q(e);return await ou({fs:t,gitdir:await Y({fsp:t,dotgit:n}),tree:r})}catch(e){throw e.caller=`git.writeTree`,e}}function yf(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function bf(){return{request:async e=>{let{url:t,method:n=`GET`,headers:r={},body:i,onProgress:a}=e,o;if(i){let e=[];for await(let t of i)e.push(t);let t=e.reduce((e,t)=>e+t.length,0);o=new Uint8Array(t);let n=0;for(let t of e)o.set(t,n),n+=t.length}let s,c=r[`content-type`]??`application/octet-stream`,l=o?new Blob([o.buffer],{type:c}):void 0;if(yf())s=await fetch(t,{method:n,headers:r,body:l});else{let e={...r,"X-Target-URL":t};if(r[`content-type`]&&(e[`Content-Type`]=r[`content-type`]),s=await fetch(`/api/fetch-proxy`,{method:n,headers:e,body:l}),s.status===502||s.status===400){let e=await s.text(),t=`Proxy error ${s.status}`;try{t=JSON.parse(e).error??t}catch{}throw Error(t)}}let u={};s.headers.forEach((e,t)=>{u[t]=e});let d=s.body,f;if(d){let e=d.getReader(),t=0;f={[Symbol.asyncIterator](){return this},async next(){let{done:n,value:r}=await e.read();return n?{done:!0,value:void 0}:(t+=r.length,a&&a({phase:`Receiving`,loaded:t,total:parseInt(u[`content-length`]??`0`,10)||t}),{done:!1,value:r})}}}return{url:s.url||t,method:n,headers:u,body:f,statusCode:s.status,statusMessage:s.statusText}}}}var xf=bf();function Sf(e,t){let n=e.length,r=t.length;if(n===0&&r===0)return[];if(n===0)return t.map(e=>({type:`insert`,line:e}));if(r===0)return e.map(e=>({type:`delete`,line:e}));let i=n+r,a=i,o=2*i+1,s=[],c=Array(o).fill(0),l=-1;outer:for(let o=0;o<=i;o++){s.push(c.slice());for(let i=-o;i<=o;i+=2){let s;s=i===-o||i!==o&&c[i-1+a]<c[i+1+a]?c[i+1+a]:c[i-1+a]+1;let u=s-i;for(;s<n&&u<r&&e[s]===t[u];)s++,u++;if(c[i+a]=s,s>=n&&u>=r){l=o;break outer}}}l===-1&&(l=i);let u=[],d=n,f=r;for(let n=l;n>0;n--){let r=s[n],i=d-f,o;o=i===-n||i!==n&&r[i-1+a]<r[i+1+a]?i+1:i-1;let c=r[o+a],l=c-o;for(;d>c&&f>l;)d--,f--,u.push({type:`equal`,line:e[d]});d===c&&f>l?(f--,u.push({type:`insert`,line:t[f]})):f===l&&d>c&&(d--,u.push({type:`delete`,line:e[d]}))}for(;d>0&&f>0;)d--,f--,u.push({type:`equal`,line:e[d]});return u.reverse(),u}function Cf(e,t=3){let n=[],r=[];for(let t=0;t<e.length;t++)e[t].type!==`equal`&&r.push(t);if(r.length===0)return[];let i=0,a=[];for(let e=1;e<r.length;e++)r[e]-r[e-1]>2*t&&(a.push([i,e-1]),i=e);a.push([i,r.length-1]);for(let[i,o]of a){let a=r[i],s=r[o],c=Math.max(0,a-t),l=Math.min(e.length-1,s+t),u=[],d=0,f=0;for(let t=0;t<c;t++)(e[t].type===`equal`||e[t].type===`delete`)&&d++,(e[t].type===`equal`||e[t].type===`insert`)&&f++;let p=d+1,m=f+1,h=0,g=0;for(let t=c;t<=l;t++){let n=e[t];switch(n.type){case`equal`:u.push(` ${n.line}`),h++,g++;break;case`delete`:u.push(`-${n.line}`),h++;break;case`insert`:u.push(`+${n.line}`),g++;break}}n.push({oldStart:p,oldCount:h,newStart:m,newCount:g,lines:u})}return n}function wf(e){let{oldContent:t,newContent:n,oldName:r,newName:i,color:a=!0}=e;if(t===n)return``;let o=t.split(`
787
+ `);if(i=a.shift(),!i.startsWith(`unpack `))throw new rl(`unpack ok" or "unpack [error message]`,i);t.ok=i===`unpack ok`,t.ok||(t.error=i.slice(7)),t.refs={};for(let e of a){if(e.trim()===``)continue;let n=e.slice(0,2),r=e.slice(3),i=r.indexOf(` `);i===-1&&(i=r.length);let a=r.slice(0,i),o=r.slice(i+1);t.refs[a]={ok:n===`ok`,error:o}}return t}async function ef({capabilities:e=[],triplets:t=[]}){let n=[],r=`\x00 ${e.join(` `)}`;for(let e of t)n.push(zu.encode(`${e.oldoid} ${e.oid} ${e.fullRef}${r}\n`)),r=``;return n.push(zu.flush()),n}async function tf({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,onPrePush:c,gitdir:l,ref:u,remoteRef:d,remote:f,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={}}){let v=u||await Mu({fs:e,gitdir:l});if(v===void 0)throw new tl(`ref`);let y=await nc.get({fs:e,gitdir:l});f=f||await y.get(`branch.${v}.pushRemote`)||await y.get(`remote.pushDefault`)||await y.get(`branch.${v}.remote`)||`origin`;let b=p||await y.get(`remote.${f}.pushurl`)||await y.get(`remote.${f}.url`);if(b===void 0)throw new tl(`remote OR url`);let x=d||await y.get(`branch.${v}.merge`);if(b===void 0)throw new tl(`remoteRef`);g===void 0&&(g=await y.get(`http.corsProxy`));let S=await K.expand({fs:e,gitdir:l,ref:v}),C=h?`0000000000000000000000000000000000000000`:await K.resolve({fs:e,gitdir:l,ref:S}),w=qu.getRemoteHelperFor({url:b}),T=await w.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:g,service:`git-receive-pack`,url:b,headers:_,protocolVersion:1}),E=T.auth,D;if(!x)D=S;else try{D=await K.expandAgainstMap({ref:x,map:T.refs})}catch(e){if(e instanceof Os)D=x.startsWith(`refs/`)?x:`refs/heads/${x}`;else throw e}let O=T.refs.get(D)||`0000000000000000000000000000000000000000`;if(c&&!await c({remote:f,url:b,localRef:{ref:h?`(delete)`:S,oid:C},remoteRef:{ref:D,oid:O}}))throw new ll;let k=!T.capabilities.has(`no-thin`),ee=new Set;if(!h){let n=[...T.refs.values()],r=new Set;if(O!==`0000000000000000000000000000000000000000`){let i=await Td({fs:e,cache:t,gitdir:l,oids:[C,O]});for(let e of i)n.push(e);k&&(r=await Qd({fs:e,cache:t,gitdir:l,oids:i}))}if(n.includes(C)||(ee=await Qd({fs:e,cache:t,gitdir:l,oids:await Zd({fs:e,cache:t,gitdir:l,start:[C],finish:n})})),k){try{let n=await K.resolve({fs:e,gitdir:l,ref:`refs/remotes/${f}/HEAD`,depth:2}),{oid:i}=await K.resolveAgainstMap({ref:n.replace(`refs/remotes/${f}/`,``),fullref:n,map:T.refs}),a=[i];for(let n of await Qd({fs:e,cache:t,gitdir:l,oids:a}))r.add(n)}catch{}for(let e of r)ee.delete(e)}if(C===O&&(m=!0),!m){if(S.startsWith(`refs/tags`)&&O!==`0000000000000000000000000000000000000000`)throw new il(`tag-exists`);if(C!==`0000000000000000000000000000000000000000`&&O!==`0000000000000000000000000000000000000000`&&!await Nd({fs:e,cache:t,gitdir:l,oid:C,ancestor:O,depth:-1}))throw new il(`not-fast-forward`)}}let A=await ef({capabilities:td([...T.capabilities],[`report-status`,`side-band-64k`,`agent=${nd.agent}`]),triplets:[{oldoid:O,oid:C,fullRef:D}]}),j=h?[]:await Yd({fs:e,cache:t,gitdir:l,oids:[...ee]}),te=await w.connect({http:n,onProgress:r,corsProxy:g,service:`git-receive-pack`,url:b,auth:E,headers:_,body:[...A,...j]}),{packfile:ne,progress:re}=await od.demux(te.body);i&&Fu(ad(re),async e=>{await i(e)});let ie=await $d(ne);if(te.headers&&(ie.headers=te.headers),f&&ie.ok&&ie.refs[D].ok&&!S.startsWith(`refs/tags`)){let t=`refs/remotes/${f}/${D.replace(`refs/heads`,``)}`;h?await K.deleteRef({fs:e,gitdir:l,ref:t}):await K.writeRef({fs:e,gitdir:l,ref:t,value:C})}if(ie.ok&&Object.values(ie.refs).every(e=>e.ok))return ie;throw new qc(Object.entries(ie.refs).filter(([e,t])=>!t.ok).map(([e,t])=>`\n - ${e}: ${t.error}`).join(``),ie)}async function nf({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,dir:c,gitdir:l=G(c,`.git`),ref:u,remoteRef:d,remote:f=`origin`,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={},cache:v={}}){try{J(`fs`,e),J(`http`,t),J(`gitdir`,l);let c=new q(e);return await tf({fs:c,cache:v,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,gitdir:await Y({fsp:c,dotgit:l}),ref:u,remoteRef:d,remote:f,url:p,force:m,delete:h,corsProxy:g,headers:_})}catch(e){throw e.caller=`git.push`,e}}async function rf({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await Rc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=bl.from(a).parse().object,rf({fs:e,cache:t,gitdir:n,oid:r});if(i!==`blob`)throw new ks(r,i,`blob`);return{oid:r,blob:new Uint8Array(a)}}async function af({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){return i!==void 0&&(r=await su({fs:e,cache:t,gitdir:n,oid:r,filepath:i})),await rf({fs:e,cache:t,gitdir:n,oid:r})}async function of({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,filepath:i,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await af({fs:t,cache:a,gitdir:await Y({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readBlob`,e}}async function sf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await iu({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.readCommit`,e}}async function cf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,filepath:i=void 0,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await lu({fs:t,cache:a,gitdir:await Y({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readTree`,e}}async function lf({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`filepath`,r);let t=new q(e),a=await Y({fsp:t,dotgit:n});await bs.acquire({fs:t,gitdir:a,cache:i},async function(e){e.delete({filepath:r})})}catch(e){throw e.caller=`git.remove`,e}}async function uf({gitdir:e,type:t,object:n}){return ss(mc.wrap({type:t,object:n}))}async function df({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,ref:i,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`filepath`,r);let o=new q(e),s=await Y({fsp:o,dotgit:n}),c,l;try{c=await K.resolve({fs:o,gitdir:s,ref:i||`HEAD`})}catch(e){if(i)throw e}if(c)try{c=await su({fs:o,cache:a,gitdir:s,oid:c,filepath:r})}catch{c=null}let u={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:0,uid:0,gid:0,size:0},d=t&&await o.read(G(t,r));d&&(l=await uf({gitdir:s,type:`blob`,object:d}),c===l&&(u=await o.lstat(G(t,r)))),await bs.acquire({fs:o,gitdir:s,cache:a},async function(e){e.delete({filepath:r}),c&&e.insert({filepath:r,stats:u,oid:c})})}catch(e){throw e.caller=`git.reset`,e}}async function ff({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,depth:i}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e),a=await Y({fsp:t,dotgit:n});return await K.resolve({fs:t,gitdir:a,ref:r,depth:i})}catch(e){throw e.caller=`git.resolveRef`,e}}async function pf({fs:e,dir:t,gitdir:n=G(t,`.git`),path:r,value:i,append:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`path`,r);let t=new q(e),o=await Y({fsp:t,dotgit:n}),s=await nc.get({fs:t,gitdir:o});a?await s.append(r,i):await s.set(r,i),await nc.save({fs:t,gitdir:o,config:s})}catch(e){throw e.caller=`git.setConfig`,e}}async function mf({fs:e,gitdir:t,commit:n}){return await Yl({fs:e,gitdir:t,type:`commit`,object:Cl.from(n).toObject(),format:`content`})}async function hf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r=`HEAD`,filepaths:i=[`.`],filter:a,cache:o={},ignored:s=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let c=new q(e);return await Nl({fs:c,cache:o,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:[El({ref:r}),Ol(),Ds()],map:async function(e,[n,r,o]){if(!n&&!o&&r&&!s&&await Ul.isIgnored({fs:c,dir:t,filepath:e})||!i.some(t=>yu(e,t)))return null;if(a&&!a(e))return;let[l,u,d]=await Promise.all([n&&n.type(),r&&r.type(),o&&o.type()]),f=[l,u,d].includes(`blob`);if((l===`tree`||l===`special`)&&!f)return;if(l===`commit`)return null;if((u===`tree`||u===`special`)&&!f)return;if(d===`commit`)return null;if((d===`tree`||d===`special`)&&!f)return;let p=l===`blob`?await n.oid():void 0,m=d===`blob`?await o.oid():void 0,h;l!==`blob`&&u===`blob`&&d!==`blob`?h=`42`:u===`blob`&&(h=await r.oid());let g=[void 0,p,h,m],_=g.map(e=>g.indexOf(e));return _.shift(),[e,..._]}})}catch(e){throw e.caller=`git.statusMatrix`,e}}async function gf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,object:i,force:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e);if(r===void 0)throw new tl(`ref`);r=r.startsWith(`refs/tags/`)?r:`refs/tags/${r}`;let o=await Y({fsp:t,dotgit:n}),s=await K.resolve({fs:t,gitdir:o,ref:i||`HEAD`});if(!a&&await K.exists({fs:t,gitdir:o,ref:r}))throw new zc(`tag`,r);await K.writeRef({fs:t,gitdir:o,ref:r,value:s})}catch(e){throw e.caller=`git.tag`,e}}function _f(){try{return nd.version}catch(e){throw e.caller=`git.version`,e}}async function vf({fs:e,dir:t,gitdir:n=G(t,`.git`),trees:r,map:i,reduce:a,iterate:o,cache:s={}}){try{J(`fs`,e),J(`gitdir`,n),J(`trees`,r);let c=new q(e);return await Nl({fs:c,cache:s,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:r,map:i,reduce:a,iterate:o})}catch(e){throw e.caller=`git.walk`,e}}async function yf({fs:e,dir:t,gitdir:n=G(t,`.git`),blob:r}){try{J(`fs`,e),J(`gitdir`,n),J(`blob`,r);let t=new q(e);return await Yl({fs:t,gitdir:await Y({fsp:t,dotgit:n}),type:`blob`,object:r,format:`content`})}catch(e){throw e.caller=`git.writeBlob`,e}}async function bf({fs:e,dir:t,gitdir:n=G(t,`.git`),commit:r}){try{J(`fs`,e),J(`gitdir`,n),J(`commit`,r);let t=new q(e);return await mf({fs:t,gitdir:await Y({fsp:t,dotgit:n}),commit:r})}catch(e){throw e.caller=`git.writeCommit`,e}}async function xf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,value:i,force:a=!1,symbolic:o=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r),J(`value`,i);let t=new q(e);if(!fu(r,!0))throw new Xc(r,Jo.default.clean(r));let s=await Y({fsp:t,dotgit:n});if(!a&&await K.exists({fs:t,gitdir:s,ref:r}))throw new zc(`ref`,r);o?await K.writeSymbolicRef({fs:t,gitdir:s,ref:r,value:i}):(i=await K.resolve({fs:t,gitdir:s,ref:i}),await K.writeRef({fs:t,gitdir:s,ref:r,value:i}))}catch(e){throw e.caller=`git.writeRef`,e}}async function Sf({fs:e,dir:t,gitdir:n=G(t,`.git`),tree:r}){try{J(`fs`,e),J(`gitdir`,n),J(`tree`,r);let t=new q(e);return await uu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),tree:r})}catch(e){throw e.caller=`git.writeTree`,e}}function Cf(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function wf(){return{request:async e=>{let{url:t,method:n=`GET`,headers:r={},body:i,onProgress:a}=e,o;if(i){let e=[];for await(let t of i)e.push(t);let t=e.reduce((e,t)=>e+t.length,0);o=new Uint8Array(t);let n=0;for(let t of e)o.set(t,n),n+=t.length}let s,c=r[`content-type`]??`application/octet-stream`,l=o?new Blob([o.buffer],{type:c}):void 0;if(Cf())s=await fetch(t,{method:n,headers:r,body:l});else{let e={...r,"X-Target-URL":t};if(r[`content-type`]&&(e[`Content-Type`]=r[`content-type`]),s=await fetch(`/api/fetch-proxy`,{method:n,headers:e,body:l}),s.status===502||s.status===400){let e=await s.text(),t=`Proxy error ${s.status}`;try{t=JSON.parse(e).error??t}catch{}throw Error(t)}}let u={};s.headers.forEach((e,t)=>{u[t]=e});let d=s.body,f;if(d){let e=d.getReader(),t=0;f={[Symbol.asyncIterator](){return this},async next(){let{done:n,value:r}=await e.read();return n?{done:!0,value:void 0}:(t+=r.length,a&&a({phase:`Receiving`,loaded:t,total:parseInt(u[`content-length`]??`0`,10)||t}),{done:!1,value:r})}}}return{url:s.url||t,method:n,headers:u,body:f,statusCode:s.status,statusMessage:s.statusText}}}}var Tf=wf();function Ef(e,t){let n=e.length,r=t.length;if(n===0&&r===0)return[];if(n===0)return t.map(e=>({type:`insert`,line:e}));if(r===0)return e.map(e=>({type:`delete`,line:e}));let i=n+r,a=i,o=2*i+1,s=[],c=Array(o).fill(0),l=-1;outer:for(let o=0;o<=i;o++){s.push(c.slice());for(let i=-o;i<=o;i+=2){let s;s=i===-o||i!==o&&c[i-1+a]<c[i+1+a]?c[i+1+a]:c[i-1+a]+1;let u=s-i;for(;s<n&&u<r&&e[s]===t[u];)s++,u++;if(c[i+a]=s,s>=n&&u>=r){l=o;break outer}}}l===-1&&(l=i);let u=[],d=n,f=r;for(let n=l;n>0;n--){let r=s[n],i=d-f,o;o=i===-n||i!==n&&r[i-1+a]<r[i+1+a]?i+1:i-1;let c=r[o+a],l=c-o;for(;d>c&&f>l;)d--,f--,u.push({type:`equal`,line:e[d]});d===c&&f>l?(f--,u.push({type:`insert`,line:t[f]})):f===l&&d>c&&(d--,u.push({type:`delete`,line:e[d]}))}for(;d>0&&f>0;)d--,f--,u.push({type:`equal`,line:e[d]});return u.reverse(),u}function Df(e,t=3){let n=[],r=[];for(let t=0;t<e.length;t++)e[t].type!==`equal`&&r.push(t);if(r.length===0)return[];let i=0,a=[];for(let e=1;e<r.length;e++)r[e]-r[e-1]>2*t&&(a.push([i,e-1]),i=e);a.push([i,r.length-1]);for(let[i,o]of a){let a=r[i],s=r[o],c=Math.max(0,a-t),l=Math.min(e.length-1,s+t),u=[],d=0,f=0;for(let t=0;t<c;t++)(e[t].type===`equal`||e[t].type===`delete`)&&d++,(e[t].type===`equal`||e[t].type===`insert`)&&f++;let p=d+1,m=f+1,h=0,g=0;for(let t=c;t<=l;t++){let n=e[t];switch(n.type){case`equal`:u.push(` ${n.line}`),h++,g++;break;case`delete`:u.push(`-${n.line}`),h++;break;case`insert`:u.push(`+${n.line}`),g++;break}}n.push({oldStart:p,oldCount:h,newStart:m,newCount:g,lines:u})}return n}function Of(e){let{oldContent:t,newContent:n,oldName:r,newName:i,color:a=!0}=e;if(t===n)return``;let o=t.split(`
788
788
  `),s=n.split(`
789
- `);o.length>0&&o[o.length-1]===``&&o.pop(),s.length>0&&s[s.length-1]===``&&s.pop();let c=Cf(Sf(o,s));if(c.length===0)return``;let l=a?`\x1B[31m`:``,u=a?`\x1B[32m`:``,d=a?`\x1B[36m`:``,f=a?`\x1B[1m`:``,p=a?`\x1B[0m`:``,m=``;m+=`${f}diff --git a/${r} b/${i}${p}\n`,m+=`${f}--- a/${r}${p}\n`,m+=`${f}+++ b/${i}${p}\n`;for(let e of c){m+=`${d}@@ -${e.oldStart},${e.oldCount} +${e.newStart},${e.newCount} @@${p}\n`;for(let t of e.lines)t.startsWith(`+`)?m+=`${u}${t}${p}\n`:t.startsWith(`-`)?m+=`${l}${t}${p}\n`:m+=`${t}\n`}return m}function Tf(e,t){if(e===t)return{insertions:0,deletions:0};let n=e.split(`
789
+ `);o.length>0&&o[o.length-1]===``&&o.pop(),s.length>0&&s[s.length-1]===``&&s.pop();let c=Df(Ef(o,s));if(c.length===0)return``;let l=a?`\x1B[31m`:``,u=a?`\x1B[32m`:``,d=a?`\x1B[36m`:``,f=a?`\x1B[1m`:``,p=a?`\x1B[0m`:``,m=``;m+=`${f}diff --git a/${r} b/${i}${p}\n`,m+=`${f}--- a/${r}${p}\n`,m+=`${f}+++ b/${i}${p}\n`;for(let e of c){m+=`${d}@@ -${e.oldStart},${e.oldCount} +${e.newStart},${e.newCount} @@${p}\n`;for(let t of e.lines)t.startsWith(`+`)?m+=`${u}${t}${p}\n`:t.startsWith(`-`)?m+=`${l}${t}${p}\n`:m+=`${t}\n`}return m}function kf(e,t){if(e===t)return{insertions:0,deletions:0};let n=e.split(`
790
790
  `),r=t.split(`
791
- `);n.length>0&&n[n.length-1]===``&&n.pop(),r.length>0&&r[r.length-1]===``&&r.pop();let i=Sf(n,r),a=0,o=0;for(let e of i)e.type===`insert`&&a++,e.type===`delete`&&o++;return{insertions:a,deletions:o}}var Ef=class e{static globalFsByDbName=new Map;lfs;corsProxy;authorName;authorEmail;globalDbName;githubToken;githubTokenLoaded=!1;constructor(e){this.options=e,this.lfs=e.fs.getLightningFS(),this.corsProxy=e.corsProxy,this.authorName=e.authorName??`User`,this.authorEmail=e.authorEmail??`user@example.com`,this.globalDbName=e.globalDbName??`slicc-fs-global`}getOnAuth(){if(!this.githubToken)return;let e=this.githubToken;return()=>({username:`x-access-token`,password:e})}getGlobalFs(){let t=e.globalFsByDbName.get(this.globalDbName);if(t)return t;let n=I.create({dbName:this.globalDbName});return e.globalFsByDbName.set(this.globalDbName,n),n}async ensureGithubTokenLoaded(){if(!this.githubTokenLoaded){this.githubTokenLoaded=!0;try{this.githubToken=(await(await this.getGlobalFs()).readTextFile(`/workspace/.git/github-token`)).trim()||void 0}catch{this.githubToken=void 0}}}async setGithubToken(e){let t=e.trim(),n=await this.getGlobalFs();if(!t){try{await n.rm(`/workspace/.git/github-token`)}catch{}this.githubToken=void 0,this.githubTokenLoaded=!0;return}await n.writeFile(`/workspace/.git/github-token`,t),this.githubToken=t,this.githubTokenLoaded=!0}async execute(e,t){if(e.length===0)return this.help();let[n,...r]=e;try{switch(await this.ensureGithubTokenLoaded(),n){case`init`:return this.init(t,r);case`clone`:return this.clone(t,r);case`add`:return this.add(t,r);case`status`:return this.status(t,r);case`commit`:return this.commit(t,r);case`log`:return this.log(t,r);case`branch`:return this.branch(t,r);case`checkout`:return this.checkout(t,r);case`diff`:return this.diff(t,r);case`show`:return this.show(t,r);case`remote`:return this.remote(t,r);case`fetch`:return this.fetch(t,r);case`pull`:return this.pull(t,r);case`push`:return this.push(t,r);case`merge`:return this.merge(t,r);case`reset`:return this.reset(t,r);case`config`:return this.config(t,r);case`tag`:return this.tag(t,r);case`ls-files`:return this.lsFiles(t,r);case`show-ref`:return this.showRef(t,r);case`stash`:return this.stash(t,r);case`rm`:return this.rm(t,r);case`mv`:return this.mv(t,r);case`rev-parse`:return this.revParse(t,r);case`help`:case`--help`:case`-h`:return this.help();case`version`:case`--version`:return this.version();default:return{stdout:``,stderr:`git: '${n}' is not a git command. See 'git help'.\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`fatal: ${e instanceof Error?e.message:String(e)}\n`,exitCode:128}}}version(){return{stdout:`git version 2.43.0 (isomorphic-git ${pf()})\n`,stderr:``,exitCode:0}}help(){return{stdout:`usage: git <command> [<args>]
791
+ `);n.length>0&&n[n.length-1]===``&&n.pop(),r.length>0&&r[r.length-1]===``&&r.pop();let i=Ef(n,r),a=0,o=0;for(let e of i)e.type===`insert`&&a++,e.type===`delete`&&o++;return{insertions:a,deletions:o}}var Af=class e{static globalFsByDbName=new Map;lfs;corsProxy;authorName;authorEmail;globalDbName;githubToken;githubTokenLoaded=!1;constructor(e){this.options=e,this.lfs=e.fs.getLightningFS(),this.corsProxy=e.corsProxy,this.authorName=e.authorName??`User`,this.authorEmail=e.authorEmail??`user@example.com`,this.globalDbName=e.globalDbName??`slicc-fs-global`}getOnAuth(){if(!this.githubToken)return;let e=this.githubToken;return()=>({username:`x-access-token`,password:e})}getGlobalFs(){let t=e.globalFsByDbName.get(this.globalDbName);if(t)return t;let n=I.create({dbName:this.globalDbName});return e.globalFsByDbName.set(this.globalDbName,n),n}async ensureGithubTokenLoaded(){if(!this.githubTokenLoaded){this.githubTokenLoaded=!0;try{this.githubToken=(await(await this.getGlobalFs()).readTextFile(`/workspace/.git/github-token`)).trim()||void 0}catch{this.githubToken=void 0}}}async setGithubToken(e){let t=e.trim(),n=await this.getGlobalFs();if(!t){try{await n.rm(`/workspace/.git/github-token`)}catch{}this.githubToken=void 0,this.githubTokenLoaded=!0;return}await n.writeFile(`/workspace/.git/github-token`,t),this.githubToken=t,this.githubTokenLoaded=!0}async execute(e,t){if(e.length===0)return this.help();let[n,...r]=e;try{switch(await this.ensureGithubTokenLoaded(),n){case`init`:return this.init(t,r);case`clone`:return this.clone(t,r);case`add`:return this.add(t,r);case`status`:return this.status(t,r);case`commit`:return this.commit(t,r);case`log`:return this.log(t,r);case`branch`:return this.branch(t,r);case`checkout`:return this.checkout(t,r);case`diff`:return this.diff(t,r);case`show`:return this.show(t,r);case`remote`:return this.remote(t,r);case`fetch`:return this.fetch(t,r);case`pull`:return this.pull(t,r);case`push`:return this.push(t,r);case`merge`:return this.merge(t,r);case`reset`:return this.reset(t,r);case`config`:return this.config(t,r);case`tag`:return this.tag(t,r);case`ls-files`:return this.lsFiles(t,r);case`show-ref`:return this.showRef(t,r);case`stash`:return this.stash(t,r);case`rm`:return this.rm(t,r);case`mv`:return this.mv(t,r);case`rev-parse`:return this.revParse(t,r);case`help`:case`--help`:case`-h`:return this.help();case`version`:case`--version`:return this.version();default:return{stdout:``,stderr:`git: '${n}' is not a git command. See 'git help'.\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`fatal: ${e instanceof Error?e.message:String(e)}\n`,exitCode:128}}}version(){return{stdout:`git version 2.43.0 (isomorphic-git ${_f()})\n`,stderr:``,exitCode:0}}help(){return{stdout:`usage: git <command> [<args>]
792
792
 
793
793
  Available commands:
794
794
  init Initialize a new repository
@@ -816,12 +816,12 @@ Available commands:
816
816
  config Get and set repository options
817
817
  rev-parse Pick out and massage parameters
818
818
 
819
- `,stderr:``,exitCode:0}}async init(e,t){let n=this.parseArg(t,`--initial-branch`,`-b`)??`main`;return await Od({fs:this.lfs,dir:e,defaultBranch:n}),{stdout:`Initialized empty Git repository in ${e}/.git/\n`,stderr:``,exitCode:0}}async clone(e,t){if(t.length===0)return{stdout:``,stderr:`fatal: You must specify a repository to clone.
820
- `,exitCode:128};let n=t[0],r=t[1];if(!r){let e=n.match(/\/([^\/]+?)(\.git)?$/);r=e?e[1]:`repo`}let i=r.startsWith(`/`)?r:`${e}/${r}`,a=this.parseArg(t,`--depth`),o=this.parseArg(t,`--branch`,`-b`),s=this.parseBooleanFlag(t,`--single-branch`,!0),c=`Cloning into '${r}'...\n`;await cd({fs:this.lfs,http:xf,dir:i,url:n,corsProxy:this.corsProxy,depth:a?parseInt(a,10):1,ref:o,singleBranch:s,noCheckout:!1,cache:{},onAuth:this.getOnAuth(),onProgress:e=>{e.phase===`Receiving objects`&&(c+=`Receiving objects: ${e.loaded}/${e.total}\n`)}});try{let e=await Nd({fs:this.lfs,dir:i});e.length>0&&(c+=`Checked out ${e.length} files.\n`)}catch{}return{stdout:c+`done.
819
+ `,stderr:``,exitCode:0}}async init(e,t){let n=this.parseArg(t,`--initial-branch`,`-b`)??`main`;return await Md({fs:this.lfs,dir:e,defaultBranch:n}),{stdout:`Initialized empty Git repository in ${e}/.git/\n`,stderr:``,exitCode:0}}async clone(e,t){if(t.length===0)return{stdout:``,stderr:`fatal: You must specify a repository to clone.
820
+ `,exitCode:128};let n=t[0],r=t[1];if(!r){let e=n.match(/\/([^\/]+?)(\.git)?$/);r=e?e[1]:`repo`}let i=r.startsWith(`/`)?r:`${e}/${r}`,a=this.parseArg(t,`--depth`),o=this.parseArg(t,`--branch`,`-b`),s=this.parseBooleanFlag(t,`--single-branch`,!0),c=`Cloning into '${r}'...\n`;await fd({fs:this.lfs,http:Tf,dir:i,url:n,corsProxy:this.corsProxy,depth:a?parseInt(a,10):1,ref:o,singleBranch:s,noCheckout:!1,cache:{},onAuth:this.getOnAuth(),onProgress:e=>{e.phase===`Receiving objects`&&(c+=`Receiving objects: ${e.loaded}/${e.total}\n`)}});try{let e=await Ld({fs:this.lfs,dir:i});e.length>0&&(c+=`Checked out ${e.length} files.\n`)}catch{}return{stdout:c+`done.
821
821
  `,stderr:``,exitCode:0}}async add(e,t){let n=t.includes(`-A`)||t.includes(`--all`),r=t.includes(`-u`)||t.includes(`--update`),i=t.includes(`-f`)||t.includes(`--force`),a=t.filter(e=>!e.startsWith(`-`));if(!n&&!r&&a.length===0)return{stdout:``,stderr:`Nothing specified, nothing added.
822
- `,exitCode:0};if(n){let t=await df({fs:this.lfs,dir:e});for(let[n,,r,a]of t)r!==a&&(r===0?await af({fs:this.lfs,dir:e,filepath:n}):await ql({fs:this.lfs,dir:e,filepath:n,force:i}))}else if(a.includes(`.`)){let t=await df({fs:this.lfs,dir:e});for(let[n,,r,a]of t)r!==a&&r!==0&&await ql({fs:this.lfs,dir:e,filepath:n,force:i})}else if(r){let t=await df({fs:this.lfs,dir:e});for(let[n,r,a,o]of t)r!==0&&a!==o&&(a===0?await af({fs:this.lfs,dir:e,filepath:n}):await ql({fs:this.lfs,dir:e,filepath:n,force:i}))}else for(let t of a)await ql({fs:this.lfs,dir:e,filepath:t,force:i});return{stdout:``,stderr:``,exitCode:0}}async status(e,t){let n=t.includes(`--short`)||t.includes(`-s`),r=t.includes(`--porcelain`);if(n||r)return this.statusShort(e);let i=``;try{let t=await ud({fs:this.lfs,dir:e});i+=`On branch ${t??`(no branch)`}\n\n`}catch{i+=`Not on any branch.
822
+ `,exitCode:0};if(n){let t=await hf({fs:this.lfs,dir:e});for(let[n,,r,a]of t)r!==a&&(r===0?await lf({fs:this.lfs,dir:e,filepath:n}):await Zl({fs:this.lfs,dir:e,filepath:n,force:i}))}else if(a.includes(`.`)){let t=await hf({fs:this.lfs,dir:e});for(let[n,,r,a]of t)r!==a&&r!==0&&await Zl({fs:this.lfs,dir:e,filepath:n,force:i})}else if(r){let t=await hf({fs:this.lfs,dir:e});for(let[n,r,a,o]of t)r!==0&&a!==o&&(a===0?await lf({fs:this.lfs,dir:e,filepath:n}):await Zl({fs:this.lfs,dir:e,filepath:n,force:i}))}else for(let t of a)await Zl({fs:this.lfs,dir:e,filepath:t,force:i});return{stdout:``,stderr:``,exitCode:0}}async status(e,t){let n=t.includes(`--short`)||t.includes(`-s`),r=t.includes(`--porcelain`);if(n||r)return this.statusShort(e);let i=``;try{let t=await md({fs:this.lfs,dir:e});i+=`On branch ${t??`(no branch)`}\n\n`}catch{i+=`Not on any branch.
823
823
 
824
- `}let a=await df({fs:this.lfs,dir:e}),o=[],s=[],c=[];for(let[e,t,n,r]of a)t===0&&n===2&&r===0?c.push(e):r===2||t===1&&r===0&&n===0?o.push(e):n!==r&&n!==0?s.push(e):t===1&&n===0&&r===1&&s.push(e+` (deleted)`);if(o.length>0){i+=`Changes to be committed:
824
+ `}let a=await hf({fs:this.lfs,dir:e}),o=[],s=[],c=[];for(let[e,t,n,r]of a)t===0&&n===2&&r===0?c.push(e):r===2||t===1&&r===0&&n===0?o.push(e):n!==r&&n!==0?s.push(e):t===1&&n===0&&r===1&&s.push(e+` (deleted)`);if(o.length>0){i+=`Changes to be committed:
825
825
  `,i+=` (use "git restore --staged <file>..." to unstage)
826
826
 
827
827
  `;for(let e of o)i+=`\t\x1b[32m${e}\x1b[0m\n`;i+=`
@@ -834,53 +834,53 @@ Available commands:
834
834
 
835
835
  `;for(let e of c)i+=`\t\x1b[31m${e}\x1b[0m\n`;i+=`
836
836
  `}return o.length===0&&s.length===0&&c.length===0&&(i+=`nothing to commit, working tree clean
837
- `),{stdout:i,stderr:``,exitCode:0}}async statusShort(e){let t=await df({fs:this.lfs,dir:e}),n=``;for(let[e,r,i,a]of t){let t=` `,o=` `;if(r===0&&i===2&&a===0)t=`?`,o=`?`;else if(r===0&&i===2&&a===2)t=`A`;else if(r===0&&i===2&&a===3)t=`A`,o=`M`;else if(r===1&&i===2&&a===1)o=`M`;else if(r===1&&i===2&&a===2)t=`M`;else if(r===1&&i===2&&a===3)t=`M`,o=`M`;else if(r===1&&i===0&&a===0)t=`D`;else if(r===1&&i===0&&a===1)o=`D`;else if(r===1&&i===1&&a===1)continue;else continue;n+=`${t}${o} ${e}\n`}return{stdout:n,stderr:``,exitCode:0}}async commit(e,t){let n=this.expandCombinedFlags(t),r=this.parseArg(n,`-m`,`--message`);if(!r)return{stdout:``,stderr:"error: switch `m` requires a value\n",exitCode:1};let i=n.includes(`--amend`),a=n.includes(`-a`)||n.includes(`--all`),o=n.includes(`--allow-empty`);if(a&&await this.stageTrackedChanges(e),!o&&!i&&!(await df({fs:this.lfs,dir:e})).some(([,e,,t])=>t!==e))return{stdout:``,stderr:`nothing to commit, working tree clean
838
- `,exitCode:1};let s=(await ld({fs:this.lfs,dir:e,message:r,author:{name:this.authorName,email:this.authorEmail},amend:i,noUpdateBranch:void 0})).slice(0,7);return{stdout:`[${await ud({fs:this.lfs,dir:e})??`HEAD`} ${s}] ${r}\n`,stderr:``,exitCode:0}}async stageTrackedChanges(e){let t=await df({fs:this.lfs,dir:e});for(let[n,r,i,a]of t)r!==0&&i!==a&&(i===0?await af({fs:this.lfs,dir:e,filepath:n}):await ql({fs:this.lfs,dir:e,filepath:n}))}expandCombinedFlags(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith(`-`)&&!r.startsWith(`--`)&&r.length>2&&!r.includes(`=`)){let e=r.slice(1);for(let n of e)t.push(`-${n}`)}else t.push(r)}return t}async log(e,t){let n=this.parseArg(t,`-n`,`--max-count`),r=t.includes(`--oneline`),i=t.includes(`--stat`),a=t.includes(`--reverse`),o=t.includes(`--all`),s=this.parseArg(t,`--format`,`--pretty`),c=this.parseArg(t,`--author`),l=this.parseArg(t,`--grep`),u=t.indexOf(`--follow`),d=u===-1?void 0:t[u+1],f;f=o?await this.logAllBranches(e,n?parseInt(n,10):void 0):await Hd({fs:this.lfs,dir:e,depth:n?parseInt(n,10):10,...d?{filepath:d,follow:!0}:{}}),c&&(f=f.filter(e=>e.commit.author.name.includes(c))),l&&(f=f.filter(e=>e.commit.message.includes(l))),a&&(f=f.slice().reverse());let p=``;for(let t of f){let{commit:n,oid:a}=t;s?p+=this.formatLogEntry(a,n,s)+`
837
+ `),{stdout:i,stderr:``,exitCode:0}}async statusShort(e){let t=await hf({fs:this.lfs,dir:e}),n=``;for(let[e,r,i,a]of t){let t=` `,o=` `;if(r===0&&i===2&&a===0)t=`?`,o=`?`;else if(r===0&&i===2&&a===2)t=`A`;else if(r===0&&i===2&&a===3)t=`A`,o=`M`;else if(r===1&&i===2&&a===1)o=`M`;else if(r===1&&i===2&&a===2)t=`M`;else if(r===1&&i===2&&a===3)t=`M`,o=`M`;else if(r===1&&i===0&&a===0)t=`D`;else if(r===1&&i===0&&a===1)o=`D`;else if(r===1&&i===1&&a===1)continue;else continue;n+=`${t}${o} ${e}\n`}return{stdout:n,stderr:``,exitCode:0}}async commit(e,t){let n=this.expandCombinedFlags(t),r=this.parseArg(n,`-m`,`--message`);if(!r)return{stdout:``,stderr:"error: switch `m` requires a value\n",exitCode:1};let i=n.includes(`--amend`),a=n.includes(`-a`)||n.includes(`--all`),o=n.includes(`--allow-empty`);if(a&&await this.stageTrackedChanges(e),!o&&!i&&!(await hf({fs:this.lfs,dir:e})).some(([,e,,t])=>t!==e))return{stdout:``,stderr:`nothing to commit, working tree clean
838
+ `,exitCode:1};let s=(await pd({fs:this.lfs,dir:e,message:r,author:{name:this.authorName,email:this.authorEmail},amend:i,noUpdateBranch:void 0})).slice(0,7);return{stdout:`[${await md({fs:this.lfs,dir:e})??`HEAD`} ${s}] ${r}\n`,stderr:``,exitCode:0}}async stageTrackedChanges(e){let t=await hf({fs:this.lfs,dir:e});for(let[n,r,i,a]of t)r!==0&&i!==a&&(i===0?await lf({fs:this.lfs,dir:e,filepath:n}):await Zl({fs:this.lfs,dir:e,filepath:n}))}expandCombinedFlags(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith(`-`)&&!r.startsWith(`--`)&&r.length>2&&!r.includes(`=`)){let e=r.slice(1);for(let n of e)t.push(`-${n}`)}else t.push(r)}return t}async log(e,t){let n=this.parseArg(t,`-n`,`--max-count`),r=t.includes(`--oneline`),i=t.includes(`--stat`),a=t.includes(`--reverse`),o=t.includes(`--all`),s=this.parseArg(t,`--format`,`--pretty`),c=this.parseArg(t,`--author`),l=this.parseArg(t,`--grep`),u=t.indexOf(`--follow`),d=u===-1?void 0:t[u+1],f;f=o?await this.logAllBranches(e,n?parseInt(n,10):void 0):await Kd({fs:this.lfs,dir:e,depth:n?parseInt(n,10):10,...d?{filepath:d,follow:!0}:{}}),c&&(f=f.filter(e=>e.commit.author.name.includes(c))),l&&(f=f.filter(e=>e.commit.message.includes(l))),a&&(f=f.slice().reverse());let p=``;for(let t of f){let{commit:n,oid:a}=t;s?p+=this.formatLogEntry(a,n,s)+`
839
839
  `:r?p+=`\x1b[33m${a.slice(0,7)}\x1b[0m ${n.message.split(`
840
840
  `)[0]}\n`:(p+=`\x1b[33mcommit ${a}\x1b[0m\n`,p+=`Author: ${n.author.name} <${n.author.email}>\n`,p+=`Date: ${new Date(n.author.timestamp*1e3).toLocaleString()}\n\n`,p+=` ${n.message.replace(/\n/g,`
841
- `)}\n\n`),i&&(p+=await this.logStatForCommit(e,t))}return{stdout:p,stderr:``,exitCode:0}}async logAllBranches(e,t){let n=await Ad({fs:this.lfs,dir:e}),r=new Set,i=[];for(let a of n)try{let n=await Hd({fs:this.lfs,dir:e,ref:a,depth:t??50});for(let e of n)r.has(e.oid)||(r.add(e.oid),i.push(e))}catch{}return i.sort((e,t)=>t.commit.author.timestamp-e.commit.author.timestamp),t?i.slice(0,t):i}formatLogEntry(e,t,n){let r=new Date(t.author.timestamp*1e3);return n.replace(/%H/g,e).replace(/%h/g,e.slice(0,7)).replace(/%s/g,t.message.split(`
842
- `)[0]).replace(/%an/g,t.author.name).replace(/%ae/g,t.author.email).replace(/%ad/g,r.toLocaleString()).replace(/%ar/g,this.relativeDate(r))}relativeDate(e){let t=Date.now()-e.getTime(),n=Math.floor(t/1e3),r=Math.floor(n/60),i=Math.floor(r/60),a=Math.floor(i/24),o=Math.floor(a/7),s=Math.floor(a/30),c=Math.floor(a/365);return n<60?`${n} seconds ago`:r<60?`${r} minute${r===1?``:`s`} ago`:i<24?`${i} hour${i===1?``:`s`} ago`:a<7?`${a} day${a===1?``:`s`} ago`:o<4?`${o} week${o===1?``:`s`} ago`:s<12?`${s} month${s===1?``:`s`} ago`:`${c} year${c===1?``:`s`} ago`}async logStatForCommit(e,t){let{commit:n,oid:r}=t,i=n.parent.length>0?n.parent[0]:void 0;return i?(await this.diffCommits(e,i,r,{nameOnly:!1,stat:!0})).stdout:await this.diffInitialCommit(e,r,!0)}async branch(e,t){let n=t.includes(`-d`)||t.includes(`-D`)||t.includes(`--delete`),r=t.includes(`-a`)||t.includes(`--all`),i=t.find(e=>!e.startsWith(`-`));if(n&&i)return await fd({fs:this.lfs,dir:e,ref:i}),{stdout:`Deleted branch ${i}\n`,stderr:``,exitCode:0};if(i&&!n)return await mu({fs:this.lfs,dir:e,ref:i}),{stdout:``,stderr:``,exitCode:0};let a=await Ad({fs:this.lfs,dir:e}),o=await ud({fs:this.lfs,dir:e}),s=``;for(let e of a)e===o?s+=`* \x1b[32m${e}\x1b[0m\n`:s+=` ${e}\n`;if(r)try{let t=await Ad({fs:this.lfs,dir:e,remote:`origin`});for(let e of t)s+=` \x1b[31mremotes/origin/${e}\x1b[0m\n`}catch{}return{stdout:s,stderr:``,exitCode:0}}async checkout(e,t){let n=t.includes(`-b`),r=t.indexOf(`--`);if(r!==-1){let n=t.slice(r+1);if(n.length===0)return{stdout:``,stderr:`error: you must specify path(s) to restore
843
- `,exitCode:1};let i=t.slice(0,r).filter(e=>!e.startsWith(`-`))[0];return this.checkoutFiles(e,n,i)}let i=t.find(e=>!e.startsWith(`-`));return i?n?(await mu({fs:this.lfs,dir:e,ref:i,checkout:!0}),{stdout:`Switched to a new branch '${i}'\n`,stderr:``,exitCode:0}):(await xu({fs:this.lfs,dir:e,ref:i}),{stdout:`Switched to branch '${i}'\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`error: you must specify path(s) or a branch to checkout
844
- `,exitCode:1}}async checkoutFiles(e,t,n){let r=n??`HEAD`,i=await cf({fs:this.lfs,dir:e,ref:r});for(let n of t){let{blob:t}=await tf({fs:this.lfs,dir:e,oid:i,filepath:n}),r=n.lastIndexOf(`/`);r!==-1&&await this.options.fs.mkdir(`${e}/${n.slice(0,r)}`,{recursive:!0}),await this.options.fs.writeFile(`${e}/${n}`,t),await ql({fs:this.lfs,dir:e,filepath:n})}return{stdout:``,stderr:``,exitCode:0}}async diff(e,t){let n=t.includes(`--staged`)||t.includes(`--cached`),r=t.includes(`--name-only`),i=t.includes(`--stat`),a=t.filter(e=>!e.startsWith(`-`));if(a.length>=2)return this.diffCommits(e,a[0],a[1],{nameOnly:r,stat:i});let o=[];if(n)await mf({fs:this.lfs,dir:e,trees:[Sl({ref:`HEAD`}),Cs()],map:async(t,[n,r])=>{if(t===`.`||t.startsWith(`.git`))return;let i=n?await n.type():void 0,a=r?await r.type():void 0;if(i===`tree`||a===`tree`)return;let s=n?await n.oid():void 0,c=r?await r.oid():void 0;if(s===c)return;let l=``;if(s)try{let{blob:t}=await tf({fs:this.lfs,dir:e,oid:s});l=new TextDecoder().decode(t)}catch{}let u=``;if(c)try{let{blob:t}=await tf({fs:this.lfs,dir:e,oid:c});u=new TextDecoder().decode(t)}catch{}o.push({filepath:t,oldContent:l,newContent:u})}});else{let t=new Map;await mf({fs:this.lfs,dir:e,trees:[Cs()],map:async(e,[n])=>{if(e===`.`||e.startsWith(`.git`)||!n||await n.type()!==`blob`)return;let r=await n.oid();r&&t.set(e,r)}});for(let[n,r]of t){let t=``;try{let{blob:n}=await tf({fs:this.lfs,dir:e,oid:r});t=new TextDecoder().decode(n)}catch{}let i=``;try{i=await this.options.fs.readTextFile(`${e}/${n}`)}catch{}t!==i&&o.push({filepath:n,oldContent:t,newContent:i})}}if(o.length===0)return{stdout:``,stderr:``,exitCode:0};if(r)return{stdout:o.map(e=>e.filepath).join(`
841
+ `)}\n\n`),i&&(p+=await this.logStatForCommit(e,t))}return{stdout:p,stderr:``,exitCode:0}}async logAllBranches(e,t){let n=await Pd({fs:this.lfs,dir:e}),r=new Set,i=[];for(let a of n)try{let n=await Kd({fs:this.lfs,dir:e,ref:a,depth:t??50});for(let e of n)r.has(e.oid)||(r.add(e.oid),i.push(e))}catch{}return i.sort((e,t)=>t.commit.author.timestamp-e.commit.author.timestamp),t?i.slice(0,t):i}formatLogEntry(e,t,n){let r=new Date(t.author.timestamp*1e3);return n.replace(/%H/g,e).replace(/%h/g,e.slice(0,7)).replace(/%s/g,t.message.split(`
842
+ `)[0]).replace(/%an/g,t.author.name).replace(/%ae/g,t.author.email).replace(/%ad/g,r.toLocaleString()).replace(/%ar/g,this.relativeDate(r))}relativeDate(e){let t=Date.now()-e.getTime(),n=Math.floor(t/1e3),r=Math.floor(n/60),i=Math.floor(r/60),a=Math.floor(i/24),o=Math.floor(a/7),s=Math.floor(a/30),c=Math.floor(a/365);return n<60?`${n} seconds ago`:r<60?`${r} minute${r===1?``:`s`} ago`:i<24?`${i} hour${i===1?``:`s`} ago`:a<7?`${a} day${a===1?``:`s`} ago`:o<4?`${o} week${o===1?``:`s`} ago`:s<12?`${s} month${s===1?``:`s`} ago`:`${c} year${c===1?``:`s`} ago`}async logStatForCommit(e,t){let{commit:n,oid:r}=t,i=n.parent.length>0?n.parent[0]:void 0;return i?(await this.diffCommits(e,i,r,{nameOnly:!1,stat:!0})).stdout:await this.diffInitialCommit(e,r,!0)}async branch(e,t){let n=t.includes(`-d`)||t.includes(`-D`)||t.includes(`--delete`),r=t.includes(`-a`)||t.includes(`--all`),i=t.find(e=>!e.startsWith(`-`));if(n&&i)return await gd({fs:this.lfs,dir:e,ref:i}),{stdout:`Deleted branch ${i}\n`,stderr:``,exitCode:0};if(i&&!n)return await vu({fs:this.lfs,dir:e,ref:i}),{stdout:``,stderr:``,exitCode:0};let a=await Pd({fs:this.lfs,dir:e}),o=await md({fs:this.lfs,dir:e}),s=``;for(let e of a)e===o?s+=`* \x1b[32m${e}\x1b[0m\n`:s+=` ${e}\n`;if(r)try{let t=await Pd({fs:this.lfs,dir:e,remote:`origin`});for(let e of t)s+=` \x1b[31mremotes/origin/${e}\x1b[0m\n`}catch{}return{stdout:s,stderr:``,exitCode:0}}async checkout(e,t){let n=t.includes(`-b`),r=t.indexOf(`--`);if(r!==-1){let n=t.slice(r+1);if(n.length===0)return{stdout:``,stderr:`error: you must specify path(s) to restore
843
+ `,exitCode:1};let i=t.slice(0,r).filter(e=>!e.startsWith(`-`))[0];return this.checkoutFiles(e,n,i)}let i=t.find(e=>!e.startsWith(`-`));return i?n?(await vu({fs:this.lfs,dir:e,ref:i,checkout:!0}),{stdout:`Switched to a new branch '${i}'\n`,stderr:``,exitCode:0}):(await Tu({fs:this.lfs,dir:e,ref:i}),{stdout:`Switched to branch '${i}'\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`error: you must specify path(s) or a branch to checkout
844
+ `,exitCode:1}}async checkoutFiles(e,t,n){let r=n??`HEAD`,i=await ff({fs:this.lfs,dir:e,ref:r});for(let n of t){let{blob:t}=await of({fs:this.lfs,dir:e,oid:i,filepath:n}),r=n.lastIndexOf(`/`);r!==-1&&await this.options.fs.mkdir(`${e}/${n.slice(0,r)}`,{recursive:!0}),await this.options.fs.writeFile(`${e}/${n}`,t),await Zl({fs:this.lfs,dir:e,filepath:n})}return{stdout:``,stderr:``,exitCode:0}}async diff(e,t){let n=t.includes(`--staged`)||t.includes(`--cached`),r=t.includes(`--name-only`),i=t.includes(`--stat`),a=t.filter(e=>!e.startsWith(`-`));if(a.length>=2)return this.diffCommits(e,a[0],a[1],{nameOnly:r,stat:i});let o=[];if(n)await vf({fs:this.lfs,dir:e,trees:[El({ref:`HEAD`}),Ds()],map:async(t,[n,r])=>{if(t===`.`||t.startsWith(`.git`))return;let i=n?await n.type():void 0,a=r?await r.type():void 0;if(i===`tree`||a===`tree`)return;let s=n?await n.oid():void 0,c=r?await r.oid():void 0;if(s===c)return;let l=``;if(s)try{let{blob:t}=await of({fs:this.lfs,dir:e,oid:s});l=new TextDecoder().decode(t)}catch{}let u=``;if(c)try{let{blob:t}=await of({fs:this.lfs,dir:e,oid:c});u=new TextDecoder().decode(t)}catch{}o.push({filepath:t,oldContent:l,newContent:u})}});else{let t=new Map;await vf({fs:this.lfs,dir:e,trees:[Ds()],map:async(e,[n])=>{if(e===`.`||e.startsWith(`.git`)||!n||await n.type()!==`blob`)return;let r=await n.oid();r&&t.set(e,r)}});for(let[n,r]of t){let t=``;try{let{blob:n}=await of({fs:this.lfs,dir:e,oid:r});t=new TextDecoder().decode(n)}catch{}let i=``;try{i=await this.options.fs.readTextFile(`${e}/${n}`)}catch{}t!==i&&o.push({filepath:n,oldContent:t,newContent:i})}}if(o.length===0)return{stdout:``,stderr:``,exitCode:0};if(r)return{stdout:o.map(e=>e.filepath).join(`
845
845
  `)+`
846
- `,stderr:``,exitCode:0};if(i)return this.formatDiffStat(o);let s=``;for(let e of o)s+=wf({oldContent:e.oldContent,newContent:e.newContent,oldName:e.filepath,newName:e.filepath});return{stdout:s,stderr:``,exitCode:0}}async diffCommits(e,t,n,r){let i=t,a=n;try{i=await bd({fs:this.lfs,dir:e,oid:t})}catch{try{i=await cf({fs:this.lfs,dir:e,ref:t})}catch{}}try{a=await bd({fs:this.lfs,dir:e,oid:n})}catch{try{a=await cf({fs:this.lfs,dir:e,ref:n})}catch{}}let o=[];if(await mf({fs:this.lfs,dir:e,trees:[Sl({ref:i}),Sl({ref:a})],map:async(e,[t,n])=>{if(e===`.`)return;let r=t?await t.type():void 0,i=n?await n.type():void 0;if(r===`tree`||i===`tree`||(t?await t.oid():void 0)===(n?await n.oid():void 0))return;let a=t?await t.content():void 0,s=n?await n.content():void 0,c=a?new TextDecoder().decode(a):``,l=s?new TextDecoder().decode(s):``;o.push({filepath:e,oldContent:c,newContent:l})}}),o.length===0)return{stdout:``,stderr:``,exitCode:0};if(r.nameOnly)return{stdout:o.map(e=>e.filepath).join(`
846
+ `,stderr:``,exitCode:0};if(i)return this.formatDiffStat(o);let s=``;for(let e of o)s+=Of({oldContent:e.oldContent,newContent:e.newContent,oldName:e.filepath,newName:e.filepath});return{stdout:s,stderr:``,exitCode:0}}async diffCommits(e,t,n,r){let i=t,a=n;try{i=await wd({fs:this.lfs,dir:e,oid:t})}catch{try{i=await ff({fs:this.lfs,dir:e,ref:t})}catch{}}try{a=await wd({fs:this.lfs,dir:e,oid:n})}catch{try{a=await ff({fs:this.lfs,dir:e,ref:n})}catch{}}let o=[];if(await vf({fs:this.lfs,dir:e,trees:[El({ref:i}),El({ref:a})],map:async(e,[t,n])=>{if(e===`.`)return;let r=t?await t.type():void 0,i=n?await n.type():void 0;if(r===`tree`||i===`tree`||(t?await t.oid():void 0)===(n?await n.oid():void 0))return;let a=t?await t.content():void 0,s=n?await n.content():void 0,c=a?new TextDecoder().decode(a):``,l=s?new TextDecoder().decode(s):``;o.push({filepath:e,oldContent:c,newContent:l})}}),o.length===0)return{stdout:``,stderr:``,exitCode:0};if(r.nameOnly)return{stdout:o.map(e=>e.filepath).join(`
847
847
  `)+`
848
- `,stderr:``,exitCode:0};if(r.stat)return this.formatDiffStat(o);let s=``;for(let e of o)s+=wf({oldContent:e.oldContent,newContent:e.newContent,oldName:e.filepath,newName:e.filepath});return{stdout:s,stderr:``,exitCode:0}}formatDiffStat(e){let t=`\x1B[0m`,n=``,r=0,i=0,a=0,o=e.map(e=>{let t=Tf(e.oldContent,e.newContent);return e.filepath.length>a&&(a=e.filepath.length),r+=t.insertions,i+=t.deletions,{filepath:e.filepath,...t}});for(let e of o){let r=e.insertions+e.deletions,i=`${`+`.repeat(e.insertions)}${t}${`-`.repeat(e.deletions)}${t}`;n+=` ${e.filepath.padEnd(a)} | ${String(r).padStart(4)} ${i}\n`}return n+=` ${e.length} file${e.length===1?``:`s`} changed`,r>0&&(n+=`, ${r} insertion${r===1?``:`s`}(+)`),i>0&&(n+=`, ${i} deletion${i===1?``:`s`}(-)`),n+=`
849
- `,{stdout:n,stderr:``,exitCode:0}}async show(e,t){let n=t.includes(`--stat`),r=this.parseArg(t,`--format`,`--pretty`),i=new Set([`--format`,`--pretty`]),a;for(let e=0;e<t.length;e++){let n=t[e];if(n.startsWith(`-`)){i.has(n)&&e++;continue}a=n;break}if(a&&a.includes(`:`))return await this.showFileAtCommit(e,a);let o=a??`HEAD`,s;try{s=await cf({fs:this.lfs,dir:e,ref:o})}catch{try{s=await bd({fs:this.lfs,dir:e,oid:o})}catch{return{stdout:``,stderr:`fatal: bad object ${o}\n`,exitCode:128}}}let{commit:c}=await nf({fs:this.lfs,dir:e,oid:s}),l=this.formatShowHeader(s,c,r),u=c.parent.length>0?c.parent[0]:void 0;if(u){let t=await this.diffCommits(e,u,s,{nameOnly:!1,stat:n});l+=t.stdout}else{let t=await this.diffInitialCommit(e,s,n);l+=t}return{stdout:l,stderr:``,exitCode:0}}async showFileAtCommit(e,t){let n=t.indexOf(`:`),r=t.slice(0,n)||`HEAD`,i=t.slice(n+1),a=await cf({fs:this.lfs,dir:e,ref:r}),o=await tf({fs:this.lfs,dir:e,oid:a,filepath:i});return{stdout:new TextDecoder().decode(o.blob),stderr:``,exitCode:0}}formatShowHeader(e,t,n){if(n)return n.replace(/%H/g,e).replace(/%h/g,e.slice(0,7)).replace(/%s/g,t.message.split(`
848
+ `,stderr:``,exitCode:0};if(r.stat)return this.formatDiffStat(o);let s=``;for(let e of o)s+=Of({oldContent:e.oldContent,newContent:e.newContent,oldName:e.filepath,newName:e.filepath});return{stdout:s,stderr:``,exitCode:0}}formatDiffStat(e){let t=`\x1B[0m`,n=``,r=0,i=0,a=0,o=e.map(e=>{let t=kf(e.oldContent,e.newContent);return e.filepath.length>a&&(a=e.filepath.length),r+=t.insertions,i+=t.deletions,{filepath:e.filepath,...t}});for(let e of o){let r=e.insertions+e.deletions,i=`${`+`.repeat(e.insertions)}${t}${`-`.repeat(e.deletions)}${t}`;n+=` ${e.filepath.padEnd(a)} | ${String(r).padStart(4)} ${i}\n`}return n+=` ${e.length} file${e.length===1?``:`s`} changed`,r>0&&(n+=`, ${r} insertion${r===1?``:`s`}(+)`),i>0&&(n+=`, ${i} deletion${i===1?``:`s`}(-)`),n+=`
849
+ `,{stdout:n,stderr:``,exitCode:0}}async show(e,t){let n=t.includes(`--stat`),r=this.parseArg(t,`--format`,`--pretty`),i=new Set([`--format`,`--pretty`]),a;for(let e=0;e<t.length;e++){let n=t[e];if(n.startsWith(`-`)){i.has(n)&&e++;continue}a=n;break}if(a&&a.includes(`:`))return await this.showFileAtCommit(e,a);let o=a??`HEAD`,s;try{s=await ff({fs:this.lfs,dir:e,ref:o})}catch{try{s=await wd({fs:this.lfs,dir:e,oid:o})}catch{return{stdout:``,stderr:`fatal: bad object ${o}\n`,exitCode:128}}}let{commit:c}=await sf({fs:this.lfs,dir:e,oid:s}),l=this.formatShowHeader(s,c,r),u=c.parent.length>0?c.parent[0]:void 0;if(u){let t=await this.diffCommits(e,u,s,{nameOnly:!1,stat:n});l+=t.stdout}else{let t=await this.diffInitialCommit(e,s,n);l+=t}return{stdout:l,stderr:``,exitCode:0}}async showFileAtCommit(e,t){let n=t.indexOf(`:`),r=t.slice(0,n)||`HEAD`,i=t.slice(n+1),a=await ff({fs:this.lfs,dir:e,ref:r}),o=await of({fs:this.lfs,dir:e,oid:a,filepath:i});return{stdout:new TextDecoder().decode(o.blob),stderr:``,exitCode:0}}formatShowHeader(e,t,n){if(n)return n.replace(/%H/g,e).replace(/%h/g,e.slice(0,7)).replace(/%s/g,t.message.split(`
850
850
  `)[0]).replace(/%an/g,t.author.name).replace(/%ae/g,t.author.email).replace(/%ad/g,new Date(t.author.timestamp*1e3).toLocaleString())+`
851
851
  `;let r=`\x1b[33mcommit ${e}\x1b[0m\n`;return r+=`Author: ${t.author.name} <${t.author.email}>\n`,r+=`Date: ${new Date(t.author.timestamp*1e3).toLocaleString()}\n\n`,r+=` ${t.message.replace(/\n/g,`
852
- `)}\n\n`,r}async diffInitialCommit(e,t,n){let r=[];if(await mf({fs:this.lfs,dir:e,trees:[Sl({ref:t})],map:async(e,[t])=>{if(e===`.`||!t||await t.type()!==`blob`)return;let n=await t.content();n&&r.push({filepath:e,content:new TextDecoder().decode(n)})}}),r.length===0)return``;if(n){let e=r.map(e=>({filepath:e.filepath,oldContent:``,newContent:e.content}));return this.formatDiffStat(e).stdout}let i=``;for(let e of r)i+=wf({oldContent:``,newContent:e.content,oldName:e.filepath,newName:e.filepath});return i}async remote(e,t){let[n,...r]=t;if(n===`add`&&r.length>=2){let[t,n]=r;return await uu({fs:this.lfs,dir:e,remote:t,url:n}),{stdout:``,stderr:``,exitCode:0}}if(n===`remove`||n===`rm`){let t=r[0];if(t)return await md({fs:this.lfs,dir:e,remote:t}),{stdout:``,stderr:``,exitCode:0}}let i=t.includes(`-v`)||t.includes(`--verbose`),a=await Fd({fs:this.lfs,dir:e}),o=``;for(let{remote:e,url:t}of a)i?(o+=`${e}\t${t} (fetch)\n`,o+=`${e}\t${t} (push)\n`):o+=`${e}\n`;return{stdout:o,stderr:``,exitCode:0}}async fetch(e,t){let n=t.find(e=>!e.startsWith(`-`))??`origin`,r=t.includes(`--prune`)||t.includes(`-p`),i=`Fetching ${n}\n`,a=await wd({fs:this.lfs,http:xf,dir:e,remote:n,corsProxy:this.corsProxy,prune:r,onAuth:this.getOnAuth(),onProgress:e=>{i+=`${e.phase}: ${e.loaded}/${e.total}\n`}});return a.fetchHead&&(i+=`From ${n}\n`,i+=` ${a.fetchHead.slice(0,7)}..${a.fetchHeadDescription??``}\n`),{stdout:i,stderr:``,exitCode:0}}async pull(e,t){let n=t.find(e=>!e.startsWith(`-`))??`origin`,r=`Pulling from ${n}...\n`;return await Kd({fs:this.lfs,http:xf,dir:e,remote:n,corsProxy:this.corsProxy,author:{name:this.authorName,email:this.authorEmail},onAuth:this.getOnAuth(),onProgress:e=>{r+=`${e.phase}: ${e.loaded}/${e.total}\n`}}),r+=`Already up to date.
853
- `,{stdout:r,stderr:``,exitCode:0}}async push(e,t){let n=t.includes(`-f`)||t.includes(`--force`),r=t.includes(`-u`)||t.includes(`--set-upstream`),i=t.filter(e=>!e.startsWith(`-`)),a=i[0]??`origin`,o=i[1]??await ud({fs:this.lfs,dir:e}),s=`Pushing to ${a}...\n`,c=await Qd({fs:this.lfs,http:xf,dir:e,remote:a,ref:o??void 0,corsProxy:this.corsProxy,force:n,onAuth:this.getOnAuth(),onProgress:e=>{s+=`${e.phase}: ${e.loaded}/${e.total}\n`}});if(c.ok)s+=`To ${a}\n`,s+=` ${o} -> ${o}\n`,r&&o&&(await lf({fs:this.lfs,dir:e,path:`branch.${o}.remote`,value:a}),await lf({fs:this.lfs,dir:e,path:`branch.${o}.merge`,value:`refs/heads/${o}`}),s+=`Branch '${o}' set up to track remote branch '${o}' from '${a}'.\n`);else return{stdout:``,stderr:`error: failed to push to '${a}': ${c.error}\n`,exitCode:1};return{stdout:s,stderr:``,exitCode:0}}async merge(e,t){let n=t.includes(`--no-ff`),r=t.includes(`--ff-only`),i=t.find(e=>!e.startsWith(`-`));if(!i)return{stdout:``,stderr:`fatal: No branch specified to merge.
854
- `,exitCode:128};try{let t=await Ud({fs:this.lfs,dir:e,ours:await ud({fs:this.lfs,dir:e})??void 0,theirs:i,fastForward:!n,fastForwardOnly:r,author:{name:this.authorName,email:this.authorEmail},abortOnConflict:!0});return t.alreadyMerged?{stdout:`Already up to date.
855
- `,stderr:``,exitCode:0}:t.fastForward?(await xu({fs:this.lfs,dir:e,ref:await ud({fs:this.lfs,dir:e})??`HEAD`}),{stdout:`Updating..${t.oid?t.oid.slice(0,7):``}\nFast-forward\n`,stderr:``,exitCode:0}):t.mergeCommit?(await xu({fs:this.lfs,dir:e,ref:await ud({fs:this.lfs,dir:e})??`HEAD`}),{stdout:`Merge made by the 'ort' strategy.
852
+ `)}\n\n`,r}async diffInitialCommit(e,t,n){let r=[];if(await vf({fs:this.lfs,dir:e,trees:[El({ref:t})],map:async(e,[t])=>{if(e===`.`||!t||await t.type()!==`blob`)return;let n=await t.content();n&&r.push({filepath:e,content:new TextDecoder().decode(n)})}}),r.length===0)return``;if(n){let e=r.map(e=>({filepath:e.filepath,oldContent:``,newContent:e.content}));return this.formatDiffStat(e).stdout}let i=``;for(let e of r)i+=Of({oldContent:``,newContent:e.content,oldName:e.filepath,newName:e.filepath});return i}async remote(e,t){let[n,...r]=t;if(n===`add`&&r.length>=2){let[t,n]=r;return await mu({fs:this.lfs,dir:e,remote:t,url:n}),{stdout:``,stderr:``,exitCode:0}}if(n===`remove`||n===`rm`){let t=r[0];if(t)return await vd({fs:this.lfs,dir:e,remote:t}),{stdout:``,stderr:``,exitCode:0}}let i=t.includes(`-v`)||t.includes(`--verbose`),a=await zd({fs:this.lfs,dir:e}),o=``;for(let{remote:e,url:t}of a)i?(o+=`${e}\t${t} (fetch)\n`,o+=`${e}\t${t} (push)\n`):o+=`${e}\n`;return{stdout:o,stderr:``,exitCode:0}}async fetch(e,t){let n=t.find(e=>!e.startsWith(`-`))??`origin`,r=t.includes(`--prune`)||t.includes(`-p`),i=`Fetching ${n}\n`,a=await Od({fs:this.lfs,http:Tf,dir:e,remote:n,corsProxy:this.corsProxy,prune:r,onAuth:this.getOnAuth(),onProgress:e=>{i+=`${e.phase}: ${e.loaded}/${e.total}\n`}});return a.fetchHead&&(i+=`From ${n}\n`,i+=` ${a.fetchHead.slice(0,7)}..${a.fetchHeadDescription??``}\n`),{stdout:i,stderr:``,exitCode:0}}async pull(e,t){let n=t.find(e=>!e.startsWith(`-`))??`origin`,r=`Pulling from ${n}...\n`;return await Xd({fs:this.lfs,http:Tf,dir:e,remote:n,corsProxy:this.corsProxy,author:{name:this.authorName,email:this.authorEmail},onAuth:this.getOnAuth(),onProgress:e=>{r+=`${e.phase}: ${e.loaded}/${e.total}\n`}}),r+=`Already up to date.
853
+ `,{stdout:r,stderr:``,exitCode:0}}async push(e,t){let n=t.includes(`-f`)||t.includes(`--force`),r=t.includes(`-u`)||t.includes(`--set-upstream`),i=t.filter(e=>!e.startsWith(`-`)),a=i[0]??`origin`,o=i[1]??await md({fs:this.lfs,dir:e}),s=`Pushing to ${a}...\n`,c=await nf({fs:this.lfs,http:Tf,dir:e,remote:a,ref:o??void 0,corsProxy:this.corsProxy,force:n,onAuth:this.getOnAuth(),onProgress:e=>{s+=`${e.phase}: ${e.loaded}/${e.total}\n`}});if(c.ok)s+=`To ${a}\n`,s+=` ${o} -> ${o}\n`,r&&o&&(await pf({fs:this.lfs,dir:e,path:`branch.${o}.remote`,value:a}),await pf({fs:this.lfs,dir:e,path:`branch.${o}.merge`,value:`refs/heads/${o}`}),s+=`Branch '${o}' set up to track remote branch '${o}' from '${a}'.\n`);else return{stdout:``,stderr:`error: failed to push to '${a}': ${c.error}\n`,exitCode:1};return{stdout:s,stderr:``,exitCode:0}}async merge(e,t){let n=t.includes(`--no-ff`),r=t.includes(`--ff-only`),i=t.find(e=>!e.startsWith(`-`));if(!i)return{stdout:``,stderr:`fatal: No branch specified to merge.
854
+ `,exitCode:128};try{let t=await qd({fs:this.lfs,dir:e,ours:await md({fs:this.lfs,dir:e})??void 0,theirs:i,fastForward:!n,fastForwardOnly:r,author:{name:this.authorName,email:this.authorEmail},abortOnConflict:!0});return t.alreadyMerged?{stdout:`Already up to date.
855
+ `,stderr:``,exitCode:0}:t.fastForward?(await Tu({fs:this.lfs,dir:e,ref:await md({fs:this.lfs,dir:e})??`HEAD`}),{stdout:`Updating..${t.oid?t.oid.slice(0,7):``}\nFast-forward\n`,stderr:``,exitCode:0}):t.mergeCommit?(await Tu({fs:this.lfs,dir:e,ref:await md({fs:this.lfs,dir:e})??`HEAD`}),{stdout:`Merge made by the 'ort' strategy.
856
856
  `,stderr:``,exitCode:0}):{stdout:`Merge complete.
857
857
  `,stderr:``,exitCode:0}}catch(e){if(e instanceof Error&&e.name===`MergeConflictError`){let t=e.data?.filepaths??[],n=`Auto-merging failed. Fix conflicts and then commit the result.
858
858
  `;if(t.length>0){n+=`CONFLICT (content): Merge conflict in:
859
859
  `;for(let e of t)n+=` ${e}\n`}return{stdout:``,stderr:n,exitCode:1}}if(e instanceof Error&&e.name===`MergeNotSupportedError`)return{stdout:``,stderr:`fatal: merge is not possible because you have unmerged files.
860
860
  `,exitCode:128};if(e instanceof Error&&e.name===`FastForwardError`)return{stdout:``,stderr:`fatal: Not possible to fast-forward, aborting.
861
- `,exitCode:128};throw e}}async tag(e,t){let n=t.includes(`-d`)||t.includes(`--delete`),r=this.parseArg(t,`-l`,`--list`),i=t.includes(`-a`)||t.includes(`--annotate`),a=this.parseArg(t,`-m`,`--message`),o=t.includes(`-f`)||t.includes(`--force`),s=new Set([`-l`,`--list`,`-m`,`--message`]),c=[];for(let e=0;e<t.length;e++){let n=t[e];if(n.startsWith(`-`)){s.has(n)&&e++;continue}c.push(n)}if(n){let t=c[0];return t?(await gd({fs:this.lfs,dir:e,ref:t}),{stdout:`Deleted tag '${t}'\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`fatal: tag name required
862
- `,exitCode:128}}if(r!==void 0||c.length===0){let t=await Id({fs:this.lfs,dir:e}),n=t,i=r||void 0;if(i){let e=RegExp(`^`+i.replace(/\*/g,`.*`)+`$`);n=t.filter(t=>e.test(t))}return{stdout:n.map(e=>`${e}\n`).join(``),stderr:``,exitCode:0}}let l=c[0],u=c[1];return i||a?await fu({fs:this.lfs,dir:e,ref:l,message:a??l,object:u,tagger:{name:this.authorName,email:this.authorEmail,timestamp:Math.floor(Date.now()/1e3),timezoneOffset:0},force:o}):await ff({fs:this.lfs,dir:e,ref:l,object:u,force:o}),{stdout:``,stderr:``,exitCode:0}}async lsFiles(e,t){let n=t.includes(`--modified`)||t.includes(`-m`),r=t.includes(`--others`)||t.includes(`-o`),i=t.includes(`--deleted`)||t.includes(`-d`),a=await df({fs:this.lfs,dir:e}),o=[];for(let[e,t,s,c]of a)r?t===0&&c===0&&s===2&&o.push(e):n?s!==0&&s!==c&&t!==0&&o.push(e):i?s===0&&(t!==0||c!==0)&&o.push(e):(c!==0||t!==0)&&(s===0&&c===0&&t!==0||(c===0?t!==0&&s!==0&&o.push(e):o.push(e)));return o.sort(),{stdout:o.map(e=>`${e}\n`).join(``),stderr:``,exitCode:0}}async showRef(e,t){let n=t.includes(`--heads`),r=t.includes(`--tags`),i=t.find(e=>!e.startsWith(`-`)),a=``;if(!r){let t=await Ad({fs:this.lfs,dir:e});for(let n of t){let t=await cf({fs:this.lfs,dir:e,ref:n}),r=`refs/heads/${n}`;i&&!r.includes(i)||(a+=`${t} ${r}\n`)}}if(!n){let t=await Id({fs:this.lfs,dir:e});for(let n of t){let t=await cf({fs:this.lfs,dir:e,ref:n}),r=`refs/tags/${n}`;i&&!r.includes(i)||(a+=`${t} ${r}\n`)}}return{stdout:a,stderr:``,exitCode:0}}async config(e,t){let n=t.includes(`--list`)||t.includes(`-l`),r=t.includes(`--unset`),i=t.includes(`--global`),a=t.find(e=>!e.startsWith(`-`)&&e.includes(`.`));if(n)return this.configList(e,i);if(r){if(!a)return{stdout:``,stderr:`error: key required for --unset
861
+ `,exitCode:128};throw e}}async tag(e,t){let n=t.includes(`-d`)||t.includes(`--delete`),r=this.parseArg(t,`-l`,`--list`),i=t.includes(`-a`)||t.includes(`--annotate`),a=this.parseArg(t,`-m`,`--message`),o=t.includes(`-f`)||t.includes(`--force`),s=new Set([`-l`,`--list`,`-m`,`--message`]),c=[];for(let e=0;e<t.length;e++){let n=t[e];if(n.startsWith(`-`)){s.has(n)&&e++;continue}c.push(n)}if(n){let t=c[0];return t?(await bd({fs:this.lfs,dir:e,ref:t}),{stdout:`Deleted tag '${t}'\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`fatal: tag name required
862
+ `,exitCode:128}}if(r!==void 0||c.length===0){let t=await Bd({fs:this.lfs,dir:e}),n=t,i=r||void 0;if(i){let e=RegExp(`^`+i.replace(/\*/g,`.*`)+`$`);n=t.filter(t=>e.test(t))}return{stdout:n.map(e=>`${e}\n`).join(``),stderr:``,exitCode:0}}let l=c[0],u=c[1];return i||a?await gu({fs:this.lfs,dir:e,ref:l,message:a??l,object:u,tagger:{name:this.authorName,email:this.authorEmail,timestamp:Math.floor(Date.now()/1e3),timezoneOffset:0},force:o}):await gf({fs:this.lfs,dir:e,ref:l,object:u,force:o}),{stdout:``,stderr:``,exitCode:0}}async lsFiles(e,t){let n=t.includes(`--modified`)||t.includes(`-m`),r=t.includes(`--others`)||t.includes(`-o`),i=t.includes(`--deleted`)||t.includes(`-d`),a=await hf({fs:this.lfs,dir:e}),o=[];for(let[e,t,s,c]of a)r?t===0&&c===0&&s===2&&o.push(e):n?s!==0&&s!==c&&t!==0&&o.push(e):i?s===0&&(t!==0||c!==0)&&o.push(e):(c!==0||t!==0)&&(s===0&&c===0&&t!==0||(c===0?t!==0&&s!==0&&o.push(e):o.push(e)));return o.sort(),{stdout:o.map(e=>`${e}\n`).join(``),stderr:``,exitCode:0}}async showRef(e,t){let n=t.includes(`--heads`),r=t.includes(`--tags`),i=t.find(e=>!e.startsWith(`-`)),a=``;if(!r){let t=await Pd({fs:this.lfs,dir:e});for(let n of t){let t=await ff({fs:this.lfs,dir:e,ref:n}),r=`refs/heads/${n}`;i&&!r.includes(i)||(a+=`${t} ${r}\n`)}}if(!n){let t=await Bd({fs:this.lfs,dir:e});for(let n of t){let t=await ff({fs:this.lfs,dir:e,ref:n}),r=`refs/tags/${n}`;i&&!r.includes(i)||(a+=`${t} ${r}\n`)}}return{stdout:a,stderr:``,exitCode:0}}async config(e,t){let n=t.includes(`--list`)||t.includes(`-l`),r=t.includes(`--unset`),i=t.includes(`--global`),a=t.find(e=>!e.startsWith(`-`)&&e.includes(`.`));if(n)return this.configList(e,i);if(r){if(!a)return{stdout:``,stderr:`error: key required for --unset
863
863
  `,exitCode:1};if(a===`credential.token`||a===`github.token`)return await this.setGithubToken(``),{stdout:``,stderr:``,exitCode:0};if(i){let e=await this.getGlobalFs();try{let t=await e.readTextFile(`/workspace/.gitconfig`),n=this.removeConfigKey(t,a);await e.writeFile(`/workspace/.gitconfig`,n)}catch{}}else try{let t=`${e}/.git/config`,n=await this.options.fs.readTextFile(t),r=this.removeConfigKey(n,a);await this.options.fs.writeFile(t,r)}catch{}return{stdout:``,stderr:``,exitCode:0}}if(!a)return{stdout:``,stderr:`usage: git config [--global] [--list] [--unset] <key> [<value>]
864
- `,exitCode:1};let o=t.indexOf(a),s;for(let e=o+1;e<t.length;e++)if(!t[e].startsWith(`-`)){s=t[e];break}if(s!==void 0)return a===`credential.token`||a===`github.token`?(await this.setGithubToken(s),{stdout:``,stderr:``,exitCode:0}):(i?await this.setGlobalConfig(a,s):await lf({fs:this.lfs,dir:e,path:a,value:s}),a===`user.name`&&(this.authorName=s),a===`user.email`&&(this.authorEmail=s),{stdout:``,stderr:``,exitCode:0});if(a===`credential.token`||a===`github.token`)return{stdout:this.githubToken?`${this.githubToken}\n`:``,stderr:``,exitCode:+!this.githubToken};let c;return i?c=await this.getGlobalConfig(a):(c=await Dd({fs:this.lfs,dir:e,path:a}),c||=await this.getGlobalConfig(a)),{stdout:c?`${c}\n`:``,stderr:``,exitCode:+!c}}async configList(e,t){let n=``;if(!t)try{let t=`${e}/.git/config`,r=await this.options.fs.readTextFile(t);n+=this.parseGitConfigToList(r)}catch{}try{let e=await(await this.getGlobalFs()).readTextFile(`/workspace/.gitconfig`);n+=this.parseGitConfigToList(e)}catch{}return{stdout:n,stderr:``,exitCode:0}}parseGitConfigToList(e){let t=``,n=``,r=``;for(let i of e.split(`
864
+ `,exitCode:1};let o=t.indexOf(a),s;for(let e=o+1;e<t.length;e++)if(!t[e].startsWith(`-`)){s=t[e];break}if(s!==void 0)return a===`credential.token`||a===`github.token`?(await this.setGithubToken(s),{stdout:``,stderr:``,exitCode:0}):(i?await this.setGlobalConfig(a,s):await pf({fs:this.lfs,dir:e,path:a,value:s}),a===`user.name`&&(this.authorName=s),a===`user.email`&&(this.authorEmail=s),{stdout:``,stderr:``,exitCode:0});if(a===`credential.token`||a===`github.token`)return{stdout:this.githubToken?`${this.githubToken}\n`:``,stderr:``,exitCode:+!this.githubToken};let c;return i?c=await this.getGlobalConfig(a):(c=await jd({fs:this.lfs,dir:e,path:a}),c||=await this.getGlobalConfig(a)),{stdout:c?`${c}\n`:``,stderr:``,exitCode:+!c}}async configList(e,t){let n=``;if(!t)try{let t=`${e}/.git/config`,r=await this.options.fs.readTextFile(t);n+=this.parseGitConfigToList(r)}catch{}try{let e=await(await this.getGlobalFs()).readTextFile(`/workspace/.gitconfig`);n+=this.parseGitConfigToList(e)}catch{}return{stdout:n,stderr:``,exitCode:0}}parseGitConfigToList(e){let t=``,n=``,r=``;for(let i of e.split(`
865
865
  `)){let e=i.trim();if(!e||e.startsWith(`#`)||e.startsWith(`;`))continue;let a=e.match(/^\[(\w+)(?:\s+"([^"]*)")?\]$/);if(a){n=a[1].toLowerCase(),r=a[2]??``;continue}let o=e.match(/^(\w+)\s*=\s*(.*)$/);if(o&&n){let e=o[1],i=o[2].trim(),a=r?`${n}.${r}.${e}`:`${n}.${e}`;t+=`${a}=${i}\n`}}return t}removeConfigKey(e,t){let n=t.split(`.`),r=n.pop(),i=n.join(`.`),a=e.split(`
866
866
  `),o=[],s=``;for(let e of a){let t=e.trim(),n=t.match(/^\[(\w+)(?:\s+"([^"]*)")?\]$/);if(n){let t=n[1].toLowerCase(),r=n[2]??``;s=r?`${t}.${r}`:t,o.push(e);continue}if(s===i){let e=t.match(/^(\w+)\s*=/);if(e&&e[1]===r)continue}o.push(e)}return o.join(`
867
867
  `)}async setGlobalConfig(e,t){let n=await this.getGlobalFs(),r=`/workspace/.gitconfig`,i=``;try{i=await n.readTextFile(r)}catch{}let a=e.split(`.`),o=a.pop(),s=a.join(`.`),c=i.split(`
868
868
  `),l=``,u=!1,d=!1;for(let e=0;e<c.length;e++){let n=c[e].trim(),r=n.match(/^\[(\w+)(?:\s+"([^"]*)")?\]$/);if(r){let e=r[1].toLowerCase(),t=r[2]??``;l=t?`${e}.${t}`:e,l===s&&(d=!0);continue}if(l===s){let r=n.match(/^(\w+)\s*=/);if(r&&r[1]===o){c[e]=`\t${o} = ${t}`,u=!0;break}}}if(u){await n.writeFile(r,c.join(`
869
869
  `));return}if(d){for(let e=c.length-1;e>=0;e--){let n=c[e].trim().match(/^\[(\w+)(?:\s+"([^"]*)")?\]$/);if(n){let r=n[1].toLowerCase(),i=n[2]??``;if((i?`${r}.${i}`:r)===s){c.splice(e+1,0,`\t${o} = ${t}`);break}}}await n.writeFile(r,c.join(`
870
870
  `));return}let f=s.split(`.`),p;p=f.length>1?`[${f[0]} "${f.slice(1).join(`.`)}"]`:`[${s}]`;let m=i?i.trimEnd()+`\n${p}\n\t${o} = ${t}\n`:`${p}\n\t${o} = ${t}\n`;await n.writeFile(r,m)}async getGlobalConfig(e){let t=await this.getGlobalFs();try{let n=await t.readTextFile(`/workspace/.gitconfig`),r=e.split(`.`),i=r.pop(),a=r.join(`.`),o=``;for(let e of n.split(`
871
- `)){let t=e.trim(),n=t.match(/^\[(\w+)(?:\s+"([^"]*)")?\]$/);if(n){let e=n[1].toLowerCase(),t=n[2]??``;o=t?`${e}.${t}`:e;continue}if(o===a){let e=t.match(/^(\w+)\s*=\s*(.*)$/);if(e&&e[1]===i)return e[2].trim()}}}catch{}}async reset(e,t){let n=t.includes(`--soft`),r=t.includes(`--hard`),i=t.includes(`--mixed`),a=t.filter(e=>!e.startsWith(`-`)),o=n||r||i;if(!o&&a.length===0){let t=await df({fs:this.lfs,dir:e});for(let[n,r,,i]of t)i!==r&&await sf({fs:this.lfs,dir:e,filepath:n});return{stdout:``,stderr:``,exitCode:0}}if(!o){let t=a.filter(e=>e!==`HEAD`);if(t.length===0){let t=await df({fs:this.lfs,dir:e});for(let[n,r,,i]of t)i!==r&&await sf({fs:this.lfs,dir:e,filepath:n});return{stdout:``,stderr:``,exitCode:0}}for(let n of t)await sf({fs:this.lfs,dir:e,filepath:n});return{stdout:``,stderr:``,exitCode:0}}let s=a[0]??`HEAD`,c=await cf({fs:this.lfs,dir:e,ref:s}),l=await ud({fs:this.lfs,dir:e,fullname:!0});if(!l)return{stdout:``,stderr:`fatal: not on a branch, cannot reset
872
- `,exitCode:128};if(await _f({fs:this.lfs,dir:e,ref:l,value:c,force:!0}),n)return{stdout:`HEAD is now at ${c.slice(0,7)}\n`,stderr:``,exitCode:0};let u=new Set(await Nd({fs:this.lfs,dir:e}));for(let t of u)await af({fs:this.lfs,dir:e,filepath:t});return await this.resetIndexToCommit(e,c),r&&await this.resetWorkdirToCommit(e,c,u),{stdout:`HEAD is now at ${c.slice(0,7)}\n`,stderr:``,exitCode:0}}async resetIndexToCommit(e,t){let{tree:n}=await rf({fs:this.lfs,dir:e,oid:t});await this.addTreeToIndex(e,t,n,``)}async addTreeToIndex(e,t,n,r){for(let i of n){let n=r?`${r}/${i.path}`:i.path;if(i.type===`blob`)await sf({fs:this.lfs,dir:e,filepath:n,ref:t});else if(i.type===`tree`){let{tree:r}=await rf({fs:this.lfs,dir:e,oid:i.oid});await this.addTreeToIndex(e,t,r,n)}}}async resetWorkdirToCommit(e,t,n){let r=new Set,{tree:i}=await rf({fs:this.lfs,dir:e,oid:t});await this.collectTreeFiles(e,i,``,r);for(let n of r){let{blob:r}=await tf({fs:this.lfs,dir:e,oid:t,filepath:n}),i=n.lastIndexOf(`/`);i!==-1&&await this.options.fs.mkdir(`${e}/${n.slice(0,i)}`,{recursive:!0}),await this.options.fs.writeFile(`${e}/${n}`,r)}for(let t of n)if(!r.has(t))try{await this.options.fs.rm(`${e}/${t}`)}catch{}}async collectTreeFiles(e,t,n,r){for(let i of t){let t=n?`${n}/${i.path}`:i.path;if(i.type===`blob`)r.add(t);else if(i.type===`tree`){let{tree:n}=await rf({fs:this.lfs,dir:e,oid:i.oid});await this.collectTreeFiles(e,n,t,r)}}}async stash(e,t){let n=t[0];if(!n||n.startsWith(`-`))return this.stashPush(e,t);switch(n){case`push`:case`save`:return this.stashPush(e,t.slice(1));case`pop`:return this.stashPop(e);case`list`:return this.stashList(e);case`drop`:return this.stashDrop(e,t.slice(1));case`show`:return this.stashShow(e);default:return{stdout:``,stderr:`error: unknown subcommand: ${n}\n`,exitCode:1}}}async stashPush(e,t){let n=await ud({fs:this.lfs,dir:e})??`HEAD`,r;try{r=await cf({fs:this.lfs,dir:e,ref:`HEAD`})}catch{return{stdout:``,stderr:`fatal: cannot stash without a HEAD commit
873
- `,exitCode:128}}let i=await Nd({fs:this.lfs,dir:e,ref:`HEAD`}),a=await Nd({fs:this.lfs,dir:e}),o=new Set([...i,...a]),s=await df({fs:this.lfs,dir:e});for(let[e,t,,n]of s)t===0&&n!==0&&o.add(e);let c=[],l=[];for(let t of o){let n=i.includes(t),a;try{a=await this.options.fs.readTextFile(`${e}/${t}`)}catch{}if(n){let{blob:n}=await tf({fs:this.lfs,dir:e,oid:r,filepath:t}),i=new TextDecoder().decode(n);if(a===void 0)c.push({file:t,inHead:!0,existsInWorkdir:!1});else if(a!==i){c.push({file:t,inHead:!0,existsInWorkdir:!0});let n=await hf({fs:this.lfs,dir:e,blob:new TextEncoder().encode(a)});l.push({filepath:t,oid:n})}else{let r=await hf({fs:this.lfs,dir:e,blob:n});l.push({filepath:t,oid:r})}}else if(a!==void 0){c.push({file:t,inHead:!1,existsInWorkdir:!0});let n=await hf({fs:this.lfs,dir:e,blob:new TextEncoder().encode(a)});l.push({filepath:t,oid:n})}}if(c.length===0)return{stdout:``,stderr:`No local changes to save
874
- `,exitCode:1};let u=await this.buildTreeFromEntries(e,l),d=[r];try{let t=await cf({fs:this.lfs,dir:e,ref:`refs/stash`});d.push(t)}catch{}let{commit:f}=await nf({fs:this.lfs,dir:e,oid:r}),p=`WIP on ${n}: ${r.slice(0,7)} ${f.message.split(`
875
- `)[0]}`,m=await gf({fs:this.lfs,dir:e,commit:{tree:u,parent:d,author:{name:this.authorName,email:this.authorEmail,timestamp:Math.floor(Date.now()/1e3),timezoneOffset:0},committer:{name:this.authorName,email:this.authorEmail,timestamp:Math.floor(Date.now()/1e3),timezoneOffset:0},message:p}});await _f({fs:this.lfs,dir:e,ref:`refs/stash`,value:m,force:!0});for(let t of c)if(t.inHead){let{blob:n}=await tf({fs:this.lfs,dir:e,oid:r,filepath:t.file});await this.options.fs.writeFile(`${e}/${t.file}`,n),await sf({fs:this.lfs,dir:e,filepath:t.file,ref:r})}else{try{await this.options.fs.rm(`${e}/${t.file}`)}catch{}try{await af({fs:this.lfs,dir:e,filepath:t.file})}catch{}}return{stdout:`Saved working directory and index state ${p}\n`,stderr:``,exitCode:0}}async buildTreeFromEntries(e,t){let n=new Map;for(let{filepath:e,oid:r}of t){let t=e.split(`/`),i=n;for(let e=0;e<t.length-1;e++){let n=i.get(t[e]);(!n||n.type!==`tree`)&&(n={type:`tree`,children:new Map},i.set(t[e],n)),i=n.children}i.set(t[t.length-1],{type:`blob`,oid:r,mode:`100644`})}let r=async t=>{let n=[];for(let[e,i]of t)if(i.type===`blob`)n.push({mode:i.mode,path:e,oid:i.oid,type:`blob`});else{let t=await r(i.children);n.push({mode:`040000`,path:e,oid:t,type:`tree`})}return await vf({fs:this.lfs,dir:e,tree:n})};return r(n)}async stashPop(e){let t;try{t=await cf({fs:this.lfs,dir:e,ref:`refs/stash`})}catch{return{stdout:``,stderr:`error: No stash entries found.
876
- `,exitCode:1}}let{commit:n}=await nf({fs:this.lfs,dir:e,oid:t}),r=await cf({fs:this.lfs,dir:e,ref:`HEAD`});return await this.restoreStashTree(e,n.tree,r),n.parent.length>1?await _f({fs:this.lfs,dir:e,ref:`refs/stash`,value:n.parent[1],force:!0}):await this.deleteRef(e,`refs/stash`),{stdout:`Dropped refs/stash@{0} (${t.slice(0,7)})\n`,stderr:``,exitCode:0}}async restoreStashTree(e,t,n){let r=new Map,i=async(t,n)=>{let{tree:a}=await rf({fs:this.lfs,dir:e,oid:t});for(let t of a){let a=n?`${n}/${t.path}`:t.path;if(t.type===`blob`){let{blob:n}=await tf({fs:this.lfs,dir:e,oid:t.oid});r.set(a,n)}else t.type===`tree`&&await i(t.oid,a)}};await i(t,``);let a=new Set;try{let t=await Nd({fs:this.lfs,dir:e,ref:`HEAD`});for(let e of t)a.add(e)}catch{}for(let[t,i]of r){let r=t.lastIndexOf(`/`);r!==-1&&await this.options.fs.mkdir(`${e}/${t.slice(0,r)}`,{recursive:!0}),await this.options.fs.writeFile(`${e}/${t}`,i);let o=new TextDecoder().decode(i),s;if(a.has(t))try{let{blob:r}=await tf({fs:this.lfs,dir:e,oid:n,filepath:t});s=new TextDecoder().decode(r)}catch{}s!==o&&await ql({fs:this.lfs,dir:e,filepath:t})}for(let t of a)if(!r.has(t)){try{await this.options.fs.rm(`${e}/${t}`)}catch{}await af({fs:this.lfs,dir:e,filepath:t})}}async stashList(e){let t=``,n=0;try{let r=await cf({fs:this.lfs,dir:e,ref:`refs/stash`});for(;r;){let{commit:i}=await nf({fs:this.lfs,dir:e,oid:r});if(t+=`stash@{${n}}: ${i.message}\n`,n++,i.parent.length>1)r=i.parent[1];else break}}catch{}return{stdout:t,stderr:``,exitCode:0}}async stashDrop(e,t){let n=0,r=t.find(e=>e.startsWith(`stash@{`));if(r){let e=r.match(/stash@\{(\d+)\}/);e&&(n=parseInt(e[1],10))}let i;try{i=await cf({fs:this.lfs,dir:e,ref:`refs/stash`})}catch{return{stdout:``,stderr:`error: No stash entries found.
877
- `,exitCode:1}}if(n===0){let{commit:t}=await nf({fs:this.lfs,dir:e,oid:i});return t.parent.length>1?await _f({fs:this.lfs,dir:e,ref:`refs/stash`,value:t.parent[1],force:!0}):await this.deleteRef(e,`refs/stash`),{stdout:`Dropped refs/stash@{0} (${i.slice(0,7)})\n`,stderr:``,exitCode:0}}let a=[],o=i;for(let t=0;t<n;t++){let{commit:t}=await nf({fs:this.lfs,dir:e,oid:o});if(a.push({oid:o,commit:t}),t.parent.length<=1)return{stdout:``,stderr:`error: stash@{${n}} not found\n`,exitCode:1};o=t.parent[1]}let s=o,{commit:c}=await nf({fs:this.lfs,dir:e,oid:s}),l=c.parent.length>1?c.parent[1]:void 0;for(let t=a.length-1;t>=0;t--){let n=a[t],r=[n.commit.parent[0]];l&&r.push(l),l=await gf({fs:this.lfs,dir:e,commit:{...n.commit,parent:r}})}return l?await _f({fs:this.lfs,dir:e,ref:`refs/stash`,value:l,force:!0}):await this.deleteRef(e,`refs/stash`),{stdout:`Dropped refs/stash@{${n}} (${s.slice(0,7)})\n`,stderr:``,exitCode:0}}async stashShow(e){let t;try{t=await cf({fs:this.lfs,dir:e,ref:`refs/stash`})}catch{return{stdout:``,stderr:`error: No stash entries found.
878
- `,exitCode:1}}let{commit:n}=await nf({fs:this.lfs,dir:e,oid:t}),r=n.parent[0];return this.diffCommits(e,r,t,{nameOnly:!1,stat:!0})}async deleteRef(e,t){try{await this.lfs.unlink(`${e}/.git/${t}`)}catch{}}async rm(e,t){let n=t.includes(`--cached`),r=t.includes(`-r`)||t.includes(`-R`)||t.includes(`--recursive`),i=t.filter(e=>!e.startsWith(`-`));if(i.length===0)return{stdout:``,stderr:`fatal: No pathspec given. Which files should I remove?
879
- `,exitCode:128};for(let t of i){let i=t.startsWith(`/`)?t:`${e}/${t}`,a=!1;try{a=(await this.options.fs.stat(i)).type===`directory`}catch{}if(a){if(!r)return{stdout:``,stderr:`fatal: not removing '${t}' recursively without -r\n`,exitCode:128};let i=(await Nd({fs:this.lfs,dir:e})).filter(e=>e===t||e.startsWith(t+`/`));for(let t of i)if(await af({fs:this.lfs,dir:e,filepath:t}),!n)try{await this.options.fs.rm(`${e}/${t}`)}catch{}}else if(await af({fs:this.lfs,dir:e,filepath:t}),!n)try{await this.options.fs.rm(i)}catch{}}return{stdout:``,stderr:``,exitCode:0}}async mv(e,t){let n=t.filter(e=>!e.startsWith(`-`));if(n.length<2)return{stdout:``,stderr:`fatal: usage: git mv <source> <destination>
880
- `,exitCode:128};let r=n[0],i=n[1],a=r.startsWith(`/`)?r:`${e}/${r}`,o=i.startsWith(`/`)?i:`${e}/${i}`,s;try{s=await this.options.fs.readFile(a,{encoding:`binary`})}catch{return{stdout:``,stderr:`fatal: bad source, source=${r}, destination=${i}\n`,exitCode:128}}let c=o.lastIndexOf(`/`);return c!==-1&&await this.options.fs.mkdir(o.slice(0,c),{recursive:!0}),await this.options.fs.writeFile(o,s),await this.options.fs.rm(a),await ql({fs:this.lfs,dir:e,filepath:i}),await af({fs:this.lfs,dir:e,filepath:r}),{stdout:``,stderr:``,exitCode:0}}async revParse(e,t){if(t.includes(`--show-toplevel`))try{return{stdout:`${await Ed({fs:this.lfs,filepath:e})}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`fatal: not a git repository
881
- `,exitCode:128}}if(t.includes(`--is-inside-work-tree`))try{return await Ed({fs:this.lfs,filepath:e}),{stdout:`true
871
+ `)){let t=e.trim(),n=t.match(/^\[(\w+)(?:\s+"([^"]*)")?\]$/);if(n){let e=n[1].toLowerCase(),t=n[2]??``;o=t?`${e}.${t}`:e;continue}if(o===a){let e=t.match(/^(\w+)\s*=\s*(.*)$/);if(e&&e[1]===i)return e[2].trim()}}}catch{}}async reset(e,t){let n=t.includes(`--soft`),r=t.includes(`--hard`),i=t.includes(`--mixed`),a=t.filter(e=>!e.startsWith(`-`)),o=n||r||i;if(!o&&a.length===0){let t=await hf({fs:this.lfs,dir:e});for(let[n,r,,i]of t)i!==r&&await df({fs:this.lfs,dir:e,filepath:n});return{stdout:``,stderr:``,exitCode:0}}if(!o){let t=a.filter(e=>e!==`HEAD`);if(t.length===0){let t=await hf({fs:this.lfs,dir:e});for(let[n,r,,i]of t)i!==r&&await df({fs:this.lfs,dir:e,filepath:n});return{stdout:``,stderr:``,exitCode:0}}for(let n of t)await df({fs:this.lfs,dir:e,filepath:n});return{stdout:``,stderr:``,exitCode:0}}let s=a[0]??`HEAD`,c=await ff({fs:this.lfs,dir:e,ref:s}),l=await md({fs:this.lfs,dir:e,fullname:!0});if(!l)return{stdout:``,stderr:`fatal: not on a branch, cannot reset
872
+ `,exitCode:128};if(await xf({fs:this.lfs,dir:e,ref:l,value:c,force:!0}),n)return{stdout:`HEAD is now at ${c.slice(0,7)}\n`,stderr:``,exitCode:0};let u=new Set(await Ld({fs:this.lfs,dir:e}));for(let t of u)await lf({fs:this.lfs,dir:e,filepath:t});return await this.resetIndexToCommit(e,c),r&&await this.resetWorkdirToCommit(e,c,u),{stdout:`HEAD is now at ${c.slice(0,7)}\n`,stderr:``,exitCode:0}}async resetIndexToCommit(e,t){let{tree:n}=await cf({fs:this.lfs,dir:e,oid:t});await this.addTreeToIndex(e,t,n,``)}async addTreeToIndex(e,t,n,r){for(let i of n){let n=r?`${r}/${i.path}`:i.path;if(i.type===`blob`)await df({fs:this.lfs,dir:e,filepath:n,ref:t});else if(i.type===`tree`){let{tree:r}=await cf({fs:this.lfs,dir:e,oid:i.oid});await this.addTreeToIndex(e,t,r,n)}}}async resetWorkdirToCommit(e,t,n){let r=new Set,{tree:i}=await cf({fs:this.lfs,dir:e,oid:t});await this.collectTreeFiles(e,i,``,r);for(let n of r){let{blob:r}=await of({fs:this.lfs,dir:e,oid:t,filepath:n}),i=n.lastIndexOf(`/`);i!==-1&&await this.options.fs.mkdir(`${e}/${n.slice(0,i)}`,{recursive:!0}),await this.options.fs.writeFile(`${e}/${n}`,r)}for(let t of n)if(!r.has(t))try{await this.options.fs.rm(`${e}/${t}`)}catch{}}async collectTreeFiles(e,t,n,r){for(let i of t){let t=n?`${n}/${i.path}`:i.path;if(i.type===`blob`)r.add(t);else if(i.type===`tree`){let{tree:n}=await cf({fs:this.lfs,dir:e,oid:i.oid});await this.collectTreeFiles(e,n,t,r)}}}async stash(e,t){let n=t[0];if(!n||n.startsWith(`-`))return this.stashPush(e,t);switch(n){case`push`:case`save`:return this.stashPush(e,t.slice(1));case`pop`:return this.stashPop(e);case`list`:return this.stashList(e);case`drop`:return this.stashDrop(e,t.slice(1));case`show`:return this.stashShow(e);default:return{stdout:``,stderr:`error: unknown subcommand: ${n}\n`,exitCode:1}}}async stashPush(e,t){let n=await md({fs:this.lfs,dir:e})??`HEAD`,r;try{r=await ff({fs:this.lfs,dir:e,ref:`HEAD`})}catch{return{stdout:``,stderr:`fatal: cannot stash without a HEAD commit
873
+ `,exitCode:128}}let i=await Ld({fs:this.lfs,dir:e,ref:`HEAD`}),a=await Ld({fs:this.lfs,dir:e}),o=new Set([...i,...a]),s=await hf({fs:this.lfs,dir:e});for(let[e,t,,n]of s)t===0&&n!==0&&o.add(e);let c=[],l=[];for(let t of o){let n=i.includes(t),a;try{a=await this.options.fs.readTextFile(`${e}/${t}`)}catch{}if(n){let{blob:n}=await of({fs:this.lfs,dir:e,oid:r,filepath:t}),i=new TextDecoder().decode(n);if(a===void 0)c.push({file:t,inHead:!0,existsInWorkdir:!1});else if(a!==i){c.push({file:t,inHead:!0,existsInWorkdir:!0});let n=await yf({fs:this.lfs,dir:e,blob:new TextEncoder().encode(a)});l.push({filepath:t,oid:n})}else{let r=await yf({fs:this.lfs,dir:e,blob:n});l.push({filepath:t,oid:r})}}else if(a!==void 0){c.push({file:t,inHead:!1,existsInWorkdir:!0});let n=await yf({fs:this.lfs,dir:e,blob:new TextEncoder().encode(a)});l.push({filepath:t,oid:n})}}if(c.length===0)return{stdout:``,stderr:`No local changes to save
874
+ `,exitCode:1};let u=await this.buildTreeFromEntries(e,l),d=[r];try{let t=await ff({fs:this.lfs,dir:e,ref:`refs/stash`});d.push(t)}catch{}let{commit:f}=await sf({fs:this.lfs,dir:e,oid:r}),p=`WIP on ${n}: ${r.slice(0,7)} ${f.message.split(`
875
+ `)[0]}`,m=await bf({fs:this.lfs,dir:e,commit:{tree:u,parent:d,author:{name:this.authorName,email:this.authorEmail,timestamp:Math.floor(Date.now()/1e3),timezoneOffset:0},committer:{name:this.authorName,email:this.authorEmail,timestamp:Math.floor(Date.now()/1e3),timezoneOffset:0},message:p}});await xf({fs:this.lfs,dir:e,ref:`refs/stash`,value:m,force:!0});for(let t of c)if(t.inHead){let{blob:n}=await of({fs:this.lfs,dir:e,oid:r,filepath:t.file});await this.options.fs.writeFile(`${e}/${t.file}`,n),await df({fs:this.lfs,dir:e,filepath:t.file,ref:r})}else{try{await this.options.fs.rm(`${e}/${t.file}`)}catch{}try{await lf({fs:this.lfs,dir:e,filepath:t.file})}catch{}}return{stdout:`Saved working directory and index state ${p}\n`,stderr:``,exitCode:0}}async buildTreeFromEntries(e,t){let n=new Map;for(let{filepath:e,oid:r}of t){let t=e.split(`/`),i=n;for(let e=0;e<t.length-1;e++){let n=i.get(t[e]);(!n||n.type!==`tree`)&&(n={type:`tree`,children:new Map},i.set(t[e],n)),i=n.children}i.set(t[t.length-1],{type:`blob`,oid:r,mode:`100644`})}let r=async t=>{let n=[];for(let[e,i]of t)if(i.type===`blob`)n.push({mode:i.mode,path:e,oid:i.oid,type:`blob`});else{let t=await r(i.children);n.push({mode:`040000`,path:e,oid:t,type:`tree`})}return await Sf({fs:this.lfs,dir:e,tree:n})};return r(n)}async stashPop(e){let t;try{t=await ff({fs:this.lfs,dir:e,ref:`refs/stash`})}catch{return{stdout:``,stderr:`error: No stash entries found.
876
+ `,exitCode:1}}let{commit:n}=await sf({fs:this.lfs,dir:e,oid:t}),r=await ff({fs:this.lfs,dir:e,ref:`HEAD`});return await this.restoreStashTree(e,n.tree,r),n.parent.length>1?await xf({fs:this.lfs,dir:e,ref:`refs/stash`,value:n.parent[1],force:!0}):await this.deleteRef(e,`refs/stash`),{stdout:`Dropped refs/stash@{0} (${t.slice(0,7)})\n`,stderr:``,exitCode:0}}async restoreStashTree(e,t,n){let r=new Map,i=async(t,n)=>{let{tree:a}=await cf({fs:this.lfs,dir:e,oid:t});for(let t of a){let a=n?`${n}/${t.path}`:t.path;if(t.type===`blob`){let{blob:n}=await of({fs:this.lfs,dir:e,oid:t.oid});r.set(a,n)}else t.type===`tree`&&await i(t.oid,a)}};await i(t,``);let a=new Set;try{let t=await Ld({fs:this.lfs,dir:e,ref:`HEAD`});for(let e of t)a.add(e)}catch{}for(let[t,i]of r){let r=t.lastIndexOf(`/`);r!==-1&&await this.options.fs.mkdir(`${e}/${t.slice(0,r)}`,{recursive:!0}),await this.options.fs.writeFile(`${e}/${t}`,i);let o=new TextDecoder().decode(i),s;if(a.has(t))try{let{blob:r}=await of({fs:this.lfs,dir:e,oid:n,filepath:t});s=new TextDecoder().decode(r)}catch{}s!==o&&await Zl({fs:this.lfs,dir:e,filepath:t})}for(let t of a)if(!r.has(t)){try{await this.options.fs.rm(`${e}/${t}`)}catch{}await lf({fs:this.lfs,dir:e,filepath:t})}}async stashList(e){let t=``,n=0;try{let r=await ff({fs:this.lfs,dir:e,ref:`refs/stash`});for(;r;){let{commit:i}=await sf({fs:this.lfs,dir:e,oid:r});if(t+=`stash@{${n}}: ${i.message}\n`,n++,i.parent.length>1)r=i.parent[1];else break}}catch{}return{stdout:t,stderr:``,exitCode:0}}async stashDrop(e,t){let n=0,r=t.find(e=>e.startsWith(`stash@{`));if(r){let e=r.match(/stash@\{(\d+)\}/);e&&(n=parseInt(e[1],10))}let i;try{i=await ff({fs:this.lfs,dir:e,ref:`refs/stash`})}catch{return{stdout:``,stderr:`error: No stash entries found.
877
+ `,exitCode:1}}if(n===0){let{commit:t}=await sf({fs:this.lfs,dir:e,oid:i});return t.parent.length>1?await xf({fs:this.lfs,dir:e,ref:`refs/stash`,value:t.parent[1],force:!0}):await this.deleteRef(e,`refs/stash`),{stdout:`Dropped refs/stash@{0} (${i.slice(0,7)})\n`,stderr:``,exitCode:0}}let a=[],o=i;for(let t=0;t<n;t++){let{commit:t}=await sf({fs:this.lfs,dir:e,oid:o});if(a.push({oid:o,commit:t}),t.parent.length<=1)return{stdout:``,stderr:`error: stash@{${n}} not found\n`,exitCode:1};o=t.parent[1]}let s=o,{commit:c}=await sf({fs:this.lfs,dir:e,oid:s}),l=c.parent.length>1?c.parent[1]:void 0;for(let t=a.length-1;t>=0;t--){let n=a[t],r=[n.commit.parent[0]];l&&r.push(l),l=await bf({fs:this.lfs,dir:e,commit:{...n.commit,parent:r}})}return l?await xf({fs:this.lfs,dir:e,ref:`refs/stash`,value:l,force:!0}):await this.deleteRef(e,`refs/stash`),{stdout:`Dropped refs/stash@{${n}} (${s.slice(0,7)})\n`,stderr:``,exitCode:0}}async stashShow(e){let t;try{t=await ff({fs:this.lfs,dir:e,ref:`refs/stash`})}catch{return{stdout:``,stderr:`error: No stash entries found.
878
+ `,exitCode:1}}let{commit:n}=await sf({fs:this.lfs,dir:e,oid:t}),r=n.parent[0];return this.diffCommits(e,r,t,{nameOnly:!1,stat:!0})}async deleteRef(e,t){try{await this.lfs.unlink(`${e}/.git/${t}`)}catch{}}async rm(e,t){let n=t.includes(`--cached`),r=t.includes(`-r`)||t.includes(`-R`)||t.includes(`--recursive`),i=t.filter(e=>!e.startsWith(`-`));if(i.length===0)return{stdout:``,stderr:`fatal: No pathspec given. Which files should I remove?
879
+ `,exitCode:128};for(let t of i){let i=t.startsWith(`/`)?t:`${e}/${t}`,a=!1;try{a=(await this.options.fs.stat(i)).type===`directory`}catch{}if(a){if(!r)return{stdout:``,stderr:`fatal: not removing '${t}' recursively without -r\n`,exitCode:128};let i=(await Ld({fs:this.lfs,dir:e})).filter(e=>e===t||e.startsWith(t+`/`));for(let t of i)if(await lf({fs:this.lfs,dir:e,filepath:t}),!n)try{await this.options.fs.rm(`${e}/${t}`)}catch{}}else if(await lf({fs:this.lfs,dir:e,filepath:t}),!n)try{await this.options.fs.rm(i)}catch{}}return{stdout:``,stderr:``,exitCode:0}}async mv(e,t){let n=t.filter(e=>!e.startsWith(`-`));if(n.length<2)return{stdout:``,stderr:`fatal: usage: git mv <source> <destination>
880
+ `,exitCode:128};let r=n[0],i=n[1],a=r.startsWith(`/`)?r:`${e}/${r}`,o=i.startsWith(`/`)?i:`${e}/${i}`,s;try{s=await this.options.fs.readFile(a,{encoding:`binary`})}catch{return{stdout:``,stderr:`fatal: bad source, source=${r}, destination=${i}\n`,exitCode:128}}let c=o.lastIndexOf(`/`);return c!==-1&&await this.options.fs.mkdir(o.slice(0,c),{recursive:!0}),await this.options.fs.writeFile(o,s),await this.options.fs.rm(a),await Zl({fs:this.lfs,dir:e,filepath:i}),await lf({fs:this.lfs,dir:e,filepath:r}),{stdout:``,stderr:``,exitCode:0}}async revParse(e,t){if(t.includes(`--show-toplevel`))try{return{stdout:`${await Ad({fs:this.lfs,filepath:e})}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`fatal: not a git repository
881
+ `,exitCode:128}}if(t.includes(`--is-inside-work-tree`))try{return await Ad({fs:this.lfs,filepath:e}),{stdout:`true
882
882
  `,stderr:``,exitCode:0}}catch{return{stdout:`false
883
- `,stderr:``,exitCode:0}}let n=t.find(e=>!e.startsWith(`-`))??`HEAD`;try{return{stdout:`${await cf({fs:this.lfs,dir:e,ref:n})}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`fatal: ambiguous argument '${n}'\n`,exitCode:128}}}parseArg(e,...t){for(let n of t){let t=e.indexOf(n);if(t!==-1&&e[t+1])return e[t+1];for(let t of e)if(t.startsWith(`${n}=`))return t.slice(n.length+1)}}parseBooleanFlag(e,t,n){let r=`--no-${t.slice(2)}`,i=n;for(let n of e)n===t&&(i=!0),n===r&&(i=!1);return i}},X=n(`playwright-teleport`),Df=null,Of=null;function kf(e){Df=e}function Af(e){Of=e}function jf(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}function Mf(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}var Nf=[`playwright-cli`,`playwright`,`puppeteer`],Pf=new WeakMap,Ff=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`]);function If(e){return e.toISOString().replace(/:/g,`-`)}function Lf(e,t){let n=Pf.get(e);n||(n=new WeakMap,Pf.set(e,n));let r=n.get(t);return r||(r={snapshots:new Map,appTabId:null,harRecorder:null,sessionDirsCreated:!1,teleportWatchers:new Map},n.set(t,r)),r}function Rf(e){return e instanceof L||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}var zf=`function(text) {
883
+ `,stderr:``,exitCode:0}}let n=t.find(e=>!e.startsWith(`-`))??`HEAD`;try{return{stdout:`${await ff({fs:this.lfs,dir:e,ref:n})}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`fatal: ambiguous argument '${n}'\n`,exitCode:128}}}parseArg(e,...t){for(let n of t){let t=e.indexOf(n);if(t!==-1&&e[t+1])return e[t+1];for(let t of e)if(t.startsWith(`${n}=`))return t.slice(n.length+1)}}parseBooleanFlag(e,t,n){let r=`--no-${t.slice(2)}`,i=n;for(let n of e)n===t&&(i=!0),n===r&&(i=!1);return i}},X=n(`playwright-teleport`),jf=null,Mf=null;function Nf(e){jf=e}function Pf(e){Mf=e}function Ff(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}function If(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}var Lf=[`playwright-cli`,`playwright`,`puppeteer`],Rf=new WeakMap,zf=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`]);function Bf(e){return e.toISOString().replace(/:/g,`-`)}function Vf(e,t){let n=Rf.get(e);n||(n=new WeakMap,Rf.set(e,n));let r=n.get(t);return r||(r={snapshots:new Map,appTabId:null,harRecorder:null,sessionDirsCreated:!1,teleportWatchers:new Map},n.set(t,r)),r}function Hf(e){return e instanceof L||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}var Uf=`function(text) {
884
884
  const el = this;
885
885
  const tag = el.tagName;
886
886
  const proto = tag === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
@@ -892,11 +892,11 @@ Available commands:
892
892
  }
893
893
  el.dispatchEvent(new Event('input', { bubbles: true }));
894
894
  el.dispatchEvent(new Event('change', { bubbles: true }));
895
- }`,Bf=`function() {
895
+ }`,Wf=`function() {
896
896
  const el = this;
897
897
  if (el.isContentEditable) return el.textContent || '';
898
898
  return el.value ?? '';
899
- }`,Vf=`function() {
899
+ }`,Gf=`function() {
900
900
  const el = this;
901
901
  if (!(el instanceof HTMLElement)) return false;
902
902
  el.focus();
@@ -920,15 +920,15 @@ Available commands:
920
920
  return true;
921
921
  }
922
922
  return false;
923
- }`;async function Hf(e){let t=await e.evaluate(`JSON.stringify({ href: location.href, hostname: location.hostname, pathname: location.pathname })`);return JSON.parse(t)}async function Uf(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!Rf(e))throw e}t.sessionDirsCreated=!0}}async function Wf(e,t,n,r){try{return await e.withTab(r,async()=>{let n=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:r,title:i}=JSON.parse(n),a=Jf(await e.getAccessibilityTree(),new Map,new Map,{value:0}).join(`
923
+ }`;async function Kf(e){let t=await e.evaluate(`JSON.stringify({ href: location.href, hostname: location.hostname, pathname: location.pathname })`);return JSON.parse(t)}async function qf(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!Hf(e))throw e}t.sessionDirsCreated=!0}}async function Jf(e,t,n,r){try{return await e.withTab(r,async()=>{let n=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:r,title:i}=JSON.parse(n),a=Qf(await e.getAccessibilityTree(),new Map,new Map,{value:0}).join(`
924
924
  `),o=[`Page URL: ${r}`,`Page Title: ${i}`,``,a].join(`
925
- `),s=`/.playwright/snapshots/page-${If(new Date)}.yml`;return await t.writeFile(s,o),s})}catch{return null}}async function Gf(e,t,n){await Uf(e,t);let r=new Date().toISOString(),i=`playwright-cli ${n.command}${n.args.length?` `+n.args.join(` `):``}`,a=n.result.exitCode===0?n.result.stdout.trim()||`OK`:`Error: ${n.result.stderr.trim()}`,o=[`### ${i}`,`- **Time**: ${r}`];if(n.tabUrl||n.targetId){let e=n.tabUrl?`${n.tabUrl}${n.targetId?` (targetId: ${n.targetId})`:``}`:`targetId: ${n.targetId}`;o.push(`- **Tab**: ${e}`)}o.push(`- **Result**: ${a}`),n.snapshotPath&&o.push(``,`[Snapshot](${n.snapshotPath})`),o.push(`---`,``);let s=o.join(`
925
+ `),s=`/.playwright/snapshots/page-${Bf(new Date)}.yml`;return await t.writeFile(s,o),s})}catch{return null}}async function Yf(e,t,n){await qf(e,t);let r=new Date().toISOString(),i=`playwright-cli ${n.command}${n.args.length?` `+n.args.join(` `):``}`,a=n.result.exitCode===0?n.result.stdout.trim()||`OK`:`Error: ${n.result.stderr.trim()}`,o=[`### ${i}`,`- **Time**: ${r}`];if(n.tabUrl||n.targetId){let e=n.tabUrl?`${n.tabUrl}${n.targetId?` (targetId: ${n.targetId})`:``}`:`targetId: ${n.targetId}`;o.push(`- **Tab**: ${e}`)}o.push(`- **Result**: ${a}`),n.snapshotPath&&o.push(``,`[Snapshot](${n.snapshotPath})`),o.push(`---`,``);let s=o.join(`
926
926
  `)+`
927
- `,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}function Kf(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`)}function qf(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Jf(e,t,n,r,i=``,a=``){let o=[],s=me(e.role,`unknown`).toLowerCase(),c=me(e.name),l=me(e.value),u=![`none`,`presentation`,`generic`,`rootwebarea`].includes(s)&&(c||s===`textbox`||s===`button`||s===`link`||s===`checkbox`||s===`radio`),d=``;if(u){d=a+`e${++r.value}`,e.backendNodeId&&n.set(d,e.backendNodeId);let i=qf(c),o=``;o=s===`button`&&c?`button[aria-label="${i}"], button[title="${i}"]`:s===`link`&&c?`a[aria-label="${i}"], a[title="${i}"]`:s===`textbox`?c?`input[aria-label="${i}"], textarea[aria-label="${i}"], [contenteditable][aria-label="${i}"], input[placeholder="${i}"], textarea[placeholder="${i}"], [contenteditable][placeholder="${i}"], input[title="${i}"], textarea[title="${i}"], [contenteditable][title="${i}"]`:`input, textarea, [contenteditable]`:s===`checkbox`?`input[type="checkbox"]`:s===`radio`?`input[type="radio"]`:c?`[aria-label="${i}"], [title="${i}"]`:`[role="${s}"]`,t.set(d,o)}let f=`${i}- ${s}`;if(c&&(f+=` "${Kf(c)}"`),d&&(f+=` [ref=${d}]`),l&&(f+=`: "${Kf(l)}"`),o.push(f),e.children)for(let s of e.children)o.push(...Jf(s,t,n,r,i+` `,a));return o}async function Yf(e,t){if(t.appTabId)return;let n=await e.listPages(),r=typeof window<`u`?window.location.origin:`http://localhost:5710`,i=n.find(e=>e.url.startsWith(r)&&!e.url.includes(`/preview/`));i&&(t.appTabId=i.targetId)}function Xf(e,t){return t===e.appTabId}function Zf(e){let t=e.url.trim(),n=e.title.trim();return n===`Omnibox Popup`||t.startsWith(`chrome://`)||t.startsWith(`chrome-search://`)||t.startsWith(`chrome-untrusted://`)||t.startsWith(`devtools://`)||t.length===0&&/popup$/i.test(n)}function Qf(e,t){return!Xf(e,t.targetId)&&!Zf(t)}async function $f(e,t){return await Yf(e,t),(typeof e.listAllTargets==`function`?await e.listAllTargets():await e.listPages()).filter(e=>Qf(t,e))}async function ep(e,t,n,r){await e.attachToPage(n);let i=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:a,title:o}=JSON.parse(i),s=await e.getAccessibilityTree(),c=new Map,l=new Map,u=new Map,d=Jf(s,c,l,{value:0}).join(`
927
+ `,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}function Xf(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`)}function Zf(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Qf(e,t,n,r,i=``,a=``){let o=[],s=me(e.role,`unknown`).toLowerCase(),c=me(e.name),l=me(e.value),u=![`none`,`presentation`,`generic`,`rootwebarea`].includes(s)&&(c||s===`textbox`||s===`button`||s===`link`||s===`checkbox`||s===`radio`),d=``;if(u){d=a+`e${++r.value}`,e.backendNodeId&&n.set(d,e.backendNodeId);let i=Zf(c),o=``;o=s===`button`&&c?`button[aria-label="${i}"], button[title="${i}"]`:s===`link`&&c?`a[aria-label="${i}"], a[title="${i}"]`:s===`textbox`?c?`input[aria-label="${i}"], textarea[aria-label="${i}"], [contenteditable][aria-label="${i}"], input[placeholder="${i}"], textarea[placeholder="${i}"], [contenteditable][placeholder="${i}"], input[title="${i}"], textarea[title="${i}"], [contenteditable][title="${i}"]`:`input, textarea, [contenteditable]`:s===`checkbox`?`input[type="checkbox"]`:s===`radio`?`input[type="radio"]`:c?`[aria-label="${i}"], [title="${i}"]`:`[role="${s}"]`,t.set(d,o)}let f=`${i}- ${s}`;if(c&&(f+=` "${Xf(c)}"`),d&&(f+=` [ref=${d}]`),l&&(f+=`: "${Xf(l)}"`),o.push(f),e.children)for(let s of e.children)o.push(...Qf(s,t,n,r,i+` `,a));return o}async function $f(e,t){if(t.appTabId)return;let n=await e.listPages(),r=typeof window<`u`?window.location.origin:`http://localhost:5710`,i=n.find(e=>e.url.startsWith(r)&&!e.url.includes(`/preview/`));i&&(t.appTabId=i.targetId)}function ep(e,t){return t===e.appTabId}function tp(e){let t=e.url.trim(),n=e.title.trim();return n===`Omnibox Popup`||t.startsWith(`chrome://`)||t.startsWith(`chrome-search://`)||t.startsWith(`chrome-untrusted://`)||t.startsWith(`devtools://`)||t.length===0&&/popup$/i.test(n)}function np(e,t){return!ep(e,t.targetId)&&!tp(t)}async function rp(e,t){return await $f(e,t),(typeof e.listAllTargets==`function`?await e.listAllTargets():await e.listPages()).filter(e=>np(t,e))}async function ip(e,t,n,r){await e.attachToPage(n);let i=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:a,title:o}=JSON.parse(i),s=await e.getAccessibilityTree(),c=new Map,l=new Map,u=new Map,d=Qf(s,c,l,{value:0}).join(`
928
928
  `);if(!r?.noIframes&&typeof e.getFrameTree==`function`)try{let t=(await e.getFrameTree()).filter(e=>e.parentFrameId);if(t.length>0){let n=0,r=d.split(`
929
- `),i=[],o=new Set;for(let s of r){i.push(s);let r=s.match(/^(\s*)- iframe\s/);if(!r)continue;let d=s.match(/:\s*"([^"]+)"\s*$/);if(!d)continue;let f=d[1],p=t.find(e=>{if(o.has(e.frameId))return!1;try{let t=new URL(e.url),n=new URL(f,a),r=n.origin+n.pathname.replace(/\/$/,``)+n.search;return t.origin+t.pathname.replace(/\/$/,``)+t.search===r}catch{return e.url===f}});if(!p)continue;o.add(p.frameId),n++;let m=`f${n}`,h=r[1]+` `;try{let t=await e.getAccessibilityTreeForFrame(p.frameId),n=new Map,r=new Map,a=Jf(t,n,r,{value:0},h,m);for(let[e,t]of n)c.set(e,t),u.set(e,p.frameId);for(let[e,t]of r)l.set(e,t),u.set(e,p.frameId);i.push(...a)}catch{}}d=i.join(`
929
+ `),i=[],o=new Set;for(let s of r){i.push(s);let r=s.match(/^(\s*)- iframe\s/);if(!r)continue;let d=s.match(/:\s*"([^"]+)"\s*$/);if(!d)continue;let f=d[1],p=t.find(e=>{if(o.has(e.frameId))return!1;try{let t=new URL(e.url),n=new URL(f,a),r=n.origin+n.pathname.replace(/\/$/,``)+n.search;return t.origin+t.pathname.replace(/\/$/,``)+t.search===r}catch{return e.url===f}});if(!p)continue;o.add(p.frameId),n++;let m=`f${n}`,h=r[1]+` `;try{let t=await e.getAccessibilityTreeForFrame(p.frameId),n=new Map,r=new Map,a=Qf(t,n,r,{value:0},h,m);for(let[e,t]of n)c.set(e,t),u.set(e,p.frameId);for(let[e,t]of r)l.set(e,t),u.set(e,p.frameId);i.push(...a)}catch{}}d=i.join(`
930
930
  `)}}catch{}let f={url:a,title:o,refToSelector:c,refToBackendNodeId:l,refToFrameId:u,content:d,timestamp:Date.now()};return t.snapshots.set(n,f),{snapshot:f,output:[`Page URL: ${a}`,`Page Title: ${o}`,``,d].join(`
931
- `)}}function tp(e){let t=new Map;for(let n of e){let e=n.domain??`unknown`;t.set(e,(t.get(e)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]).map(([e,t])=>`${t} ${e}`).join(`, `)}var np={origin:``,localStorage:{},sessionStorage:{}};function rp(e){return Object.keys(e.localStorage).length+Object.keys(e.sessionStorage).length}function ip(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}function ap(e){try{return new URL(`/favicon.ico`,e).toString()}catch{return e}}function op(e,t,n){let r=ip(t);if(t&&r===e)return t;let i=ip(n);return n&&i===e?n:e||(t??n)}async function sp(e,t){let n=await e.evaluate(`(() => {
931
+ `)}}function ap(e){let t=new Map;for(let n of e){let e=n.domain??`unknown`;t.set(e,(t.get(e)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]).map(([e,t])=>`${t} ${e}`).join(`, `)}var op={origin:``,localStorage:{},sessionStorage:{}};function sp(e){return Object.keys(e.localStorage).length+Object.keys(e.sessionStorage).length}function cp(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}function lp(e){try{return new URL(`/favicon.ico`,e).toString()}catch{return e}}function up(e,t,n){let r=cp(t);if(t&&r===e)return t;let i=cp(n);return n&&i===e?n:e||(t??n)}async function dp(e,t){let n=await e.evaluate(`(() => {
932
932
  const collect = (storage) => {
933
933
  const items = {};
934
934
  for (let i = 0; i < storage.length; i++) {
@@ -942,7 +942,7 @@ Available commands:
942
942
  localStorage: collect(window.localStorage),
943
943
  sessionStorage: collect(window.sessionStorage),
944
944
  });
945
- })()`);if(typeof n!=`string`||n.length===0)return X.warn(`Teleport storage capture returned non-string result`,{label:t,type:typeof n}),np;try{let e=JSON.parse(n);return{origin:typeof e.origin==`string`?e.origin:``,localStorage:e.localStorage??{},sessionStorage:e.sessionStorage??{}}}catch(e){return X.warn(`Could not parse teleport storage snapshot`,{label:t,error:String(e)}),np}}function cp(e){return`(() => {
945
+ })()`);if(typeof n!=`string`||n.length===0)return X.warn(`Teleport storage capture returned non-string result`,{label:t,type:typeof n}),op;try{let e=JSON.parse(n);return{origin:typeof e.origin==`string`?e.origin:``,localStorage:e.localStorage??{},sessionStorage:e.sessionStorage??{}}}catch(e){return X.warn(`Could not parse teleport storage snapshot`,{label:t,error:String(e)}),op}}function fp(e){return`(() => {
946
946
  const snapshot = ${JSON.stringify(e)};
947
947
  if (!snapshot.origin || window.location.origin !== snapshot.origin) return;
948
948
  const markerKey = '__slicc_teleport_storage_applied__:' + snapshot.origin;
@@ -958,7 +958,7 @@ Available commands:
958
958
  apply(window.localStorage, snapshot.localStorage || {});
959
959
  apply(window.sessionStorage, snapshot.sessionStorage || {});
960
960
  try { window.sessionStorage.setItem(markerKey, '1'); } catch {}
961
- })();`}function lp(e){return`(() => {
961
+ })();`}function pp(e){return`(() => {
962
962
  const snapshot = ${JSON.stringify(e)};
963
963
  if (!snapshot.origin || globalThis.location.origin !== snapshot.origin) {
964
964
  throw new Error('Teleport storage origin mismatch');
@@ -976,11 +976,11 @@ Available commands:
976
976
  localStorageCount: Object.keys(snapshot.localStorage || {}).length,
977
977
  sessionStorageCount: Object.keys(snapshot.sessionStorage || {}).length,
978
978
  });
979
- })();`}async function up(e,t,n){let r=rp(t);if(r===0)return;let i=await e.evaluate(lp(t));X.info(`Applied teleport storage snapshot on current page`,{target:n,totalEntries:r,resultType:typeof i}),X.debug(`Applied teleport storage snapshot details`,{target:n,origin:t.origin||`(unknown)`,totalEntries:r,resultType:typeof i})}async function dp(e,t,n,r){let i=rp(t);if(i===0)return null;let a=await e.sendCDP(`Page.addScriptToEvaluateOnNewDocument`,{source:cp(t)}),o=typeof a.identifier==`string`?a.identifier:null;return X.info(`Installed teleport storage init script`,{target:r,totalEntries:i,hasIdentifier:!!o}),X.debug(`Installed teleport storage init script details`,{target:r,origin:t.origin||`(unknown)`,localStorageCount:Object.keys(t.localStorage).length,sessionStorageCount:Object.keys(t.sessionStorage).length,hasIdentifier:!!o}),o?async()=>{try{await e.attachToPage(n),await e.sendCDP(`Page.removeScriptToEvaluateOnNewDocument`,{identifier:o})}catch(e){X.warn(`Failed to remove teleport storage init script`,{target:r,error:String(e)})}}:null}async function fp(e){let t=await e.evaluate(`(() => JSON.stringify({
979
+ })();`}async function mp(e,t,n){let r=sp(t);if(r===0)return;let i=await e.evaluate(pp(t));X.info(`Applied teleport storage snapshot on current page`,{target:n,totalEntries:r,resultType:typeof i}),X.debug(`Applied teleport storage snapshot details`,{target:n,origin:t.origin||`(unknown)`,totalEntries:r,resultType:typeof i})}async function hp(e,t,n,r){let i=sp(t);if(i===0)return null;let a=await e.sendCDP(`Page.addScriptToEvaluateOnNewDocument`,{source:fp(t)}),o=typeof a.identifier==`string`?a.identifier:null;return X.info(`Installed teleport storage init script`,{target:r,totalEntries:i,hasIdentifier:!!o}),X.debug(`Installed teleport storage init script details`,{target:r,origin:t.origin||`(unknown)`,localStorageCount:Object.keys(t.localStorage).length,sessionStorageCount:Object.keys(t.sessionStorage).length,hasIdentifier:!!o}),o?async()=>{try{await e.attachToPage(n),await e.sendCDP(`Page.removeScriptToEvaluateOnNewDocument`,{identifier:o})}catch(e){X.warn(`Failed to remove teleport storage init script`,{target:r,error:String(e)})}}:null}async function gp(e){let t=await e.evaluate(`(() => JSON.stringify({
980
980
  url: window.location.href,
981
981
  title: document.title || '',
982
982
  bodySnippet: document.body?.innerText?.replace(/s+/g, ' ').trim().slice(0, 500) || '(empty)',
983
- }))()`);if(typeof t!=`string`||t.length===0)return{url:``,title:``,bodySnippet:`(unavailable)`};try{let e=JSON.parse(t);return{url:typeof e.url==`string`?e.url:``,title:typeof e.title==`string`?e.title:``,bodySnippet:typeof e.bodySnippet==`string`&&e.bodySnippet.length>0?e.bodySnippet:`(empty)`}}catch{return{url:``,title:``,bodySnippet:`(unparseable)`}}}function pp(e){return/callback|authorize\/resume|error/i.test(e)}async function mp(e,t,n){try{let r=await fp(e),i=`${n}:${r.url}:${r.title}`;if(t.lastFollowerDiagnosticKey===i)return;t.lastFollowerDiagnosticKey=i,X.debug(`Teleport follower diagnostics`,{reason:n,url:r.url,title:r.title,bodySnippet:r.bodySnippet})}catch(e){X.warn(`Could not capture teleport follower diagnostics`,{reason:n,error:String(e)})}}async function hp(e,t){let n=e.removeFollowerStorageScript;if(n){e.removeFollowerStorageScript=null;try{await n(),X.info(`Removed follower teleport storage init script`,{reason:t})}catch(e){X.warn(`Failed to remove follower teleport storage init script`,{reason:t,error:String(e)})}}}async function gp(e,t){if(X.warn(`Teleport timed out`,{timeoutMs:t.timeoutMs,phase:t.phase}),X.debug(`Teleport timeout details`,{timeoutMs:t.timeoutMs,phase:t.phase,followerTargetId:t.followerTargetId}),t.phase=`timedOut`,t.followerTargetId){try{await e.attachToPage(t.followerTargetId),await mp(e,t,`timeout`)}catch(e){X.warn(`Could not attach to follower for timeout diagnostics`,{error:String(e)})}await hp(t,`timeout`)}if(_p(t),t.followerTargetId)try{await e.closePage(t.followerTargetId)}catch(e){X.warn(`Failed to close follower tab after timeout`,{error:String(e)})}t.rejectBlock?.(Error(`Teleport timed out after ${Math.round(t.timeoutMs/1e3)}s — human did not complete auth`))}function _p(e){X.info(`Cleaning up teleport watcher`,{phase:e.phase,hadPoll:!!e.pollInterval,hadTimeout:!!e.timeoutTimer,hadListener:!!e.cleanupListener}),e.pollInterval&&=(clearInterval(e.pollInterval),void 0),e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.cleanupListener&&=(e.cleanupListener(),void 0)}function vp(e,t,n,r,i,a,o,s){X.info(`Arming teleport watcher`,{timeoutMs:i,runtimeSelection:a?`explicit`:`auto`}),X.debug(`Arming teleport watcher details`,{startPattern:n.source,returnPattern:r.source,timeoutMs:i,runtimeId:a??`auto`,originalUrl:o});let c={startPattern:n,returnPattern:r,timeoutMs:i,runtimeId:a,phase:`armed`,leaderTargetId:s,originalLeaderUrl:o};return c.completionPromise=new Promise((e,t)=>{c.resolveBlock=e,c.rejectBlock=t}),c.completionPromise.catch(()=>{}),c.pollInterval=setInterval(async()=>{if(c.phase!==`armed`)return;let r=c.leaderTargetId;if(r)try{await e.attachToPage(r);let i=await e.evaluate(`window.location.href`),a=typeof i==`string`?i:String(i);X.debug(`Polling leader tab URL`,{targetId:r,href:a,startPattern:n.source}),n.test(a)&&(X.info(`Teleport start pattern matched on leader`),X.debug(`Teleport start pattern matched on leader details`,{targetId:r,href:a,startPattern:n.source}),yp(e,t,c,a))}catch(e){X.warn(`Error polling leader tab URL`,{targetId:r,error:String(e)})}},1e3),s&&t.teleportWatchers.set(s,c),c}async function yp(e,t,n,r){if(n.phase===`armed`){n.phase=`teleporting`,X.info(`Teleport triggered`),X.debug(`Teleport trigger details`,{triggerUrl:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0);try{let i=[],a=np;try{i=(await e.sendCDP(`Network.getCookies`,{})).cookies??[],X.info(`Captured leader cookies for follower`,{count:i.length})}catch(e){X.warn(`Could not capture leader cookies`,{error:String(e)})}try{a=await sp(e,`leader`),X.info(`Captured leader storage for follower`,{totalEntries:rp(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),X.debug(`Captured leader storage for follower details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){X.warn(`Could not capture leader storage`,{error:String(e)})}let o=n.runtimeId;if(!o){let e=Df?.();if(!e)throw Error(`No follower selection available — not connected to a tray`);let t=e();if(!t)throw Error(`No followers connected to teleport to`);o=t.runtimeId}X.info(`Selected follower for teleport`),X.debug(`Selected follower for teleport details`,{runtimeId:o});let s=await e.createRemotePage(o,`about:blank`),c=s.includes(`:`)?s:`${o}:${s}`;if(n.followerTargetId=c,X.info(`Opened follower tab for teleport`),X.debug(`Opened follower tab for teleport details`,{followerTargetId:c}),await e.attachToPage(c),X.info(`Attached to follower tab for teleport`),X.debug(`Attached to follower tab for teleport details`,{followerTargetId:c}),await e.sendCDP(`Page.enable`),i.length>0)try{await e.sendCDP(`Network.setCookies`,{cookies:i}),X.info(`Injected leader cookies into follower`,{count:i.length})}catch(e){X.warn(`Could not inject leader cookies into follower`,{error:String(e)})}let l=r;n.removeFollowerStorageScript=await dp(e,a,c,`follower`),X.info(`Navigating follower to intercepted auth URL`),X.debug(`Navigating follower to intercepted auth URL details`,{url:l,originalLeaderUrl:n.originalLeaderUrl,triggerUrl:r,storageOrigin:a.origin||`(unknown)`}),await e.sendCDP(`Page.navigate`,{url:l}),X.info(`Starting teleport timeout timer`,{timeoutMs:n.timeoutMs}),n.timeoutTimer=setTimeout(()=>{(n.phase===`teleporting`||n.phase===`waitingForAuth`||n.phase===`waitingForReturn`)&&gp(e,n)},n.timeoutMs),n.phase=`waitingForAuth`,X.info(`Teleport waiting for follower auth redirect`),X.debug(`Teleport waiting for follower auth redirect details`,{startPattern:n.startPattern.source}),n.pollInterval=setInterval(async()=>{if(!(n.phase!==`waitingForAuth`&&n.phase!==`waitingForReturn`))try{await e.attachToPage(c);let r=await e.evaluate(`window.location.href`),i=typeof r==`string`?r:String(r);if(!i)return;if(n.lastFollowerUrl!==i&&(n.lastFollowerUrl=i,X.debug(`Follower teleport navigation`,{href:i,phase:n.phase})),n.phase===`waitingForAuth`){n.startPattern.test(i)?(n.phase=`waitingForReturn`,X.info(`Follower reached auth provider; waiting for return pattern`),X.debug(`Follower reached auth provider details`,{href:i,startPattern:n.startPattern.source})):X.debug(`Waiting for auth redirect on follower`,{href:i,startPattern:n.startPattern.source});return}X.debug(`Polling follower tab URL for return`,{href:i,returnPattern:n.returnPattern.source}),pp(i)&&await mp(e,n,`waiting-for-return`),n.returnPattern.test(i)&&(X.info(`Follower return pattern matched after auth`),X.debug(`Follower return pattern matched after auth details`,{href:i,returnPattern:n.returnPattern.source}),bp(e,t,n,o))}catch(e){X.warn(`Error polling follower tab URL`,{error:String(e)})}},1e3)}catch(e){X.error(`Teleport trigger failed`,{error:String(e)}),await hp(n,`trigger-error`),n.phase=`done`,_p(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}async function bp(e,t,n,r){if(!(n.phase!==`teleporting`&&n.phase!==`waitingForReturn`)){n.phase=`capturing`,X.info(`Capturing auth state from follower`),X.debug(`Capturing auth state from follower details`,{followerTargetId:n.followerTargetId,runtimeId:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0),n.timeoutTimer&&=(clearTimeout(n.timeoutTimer),void 0);try{X.info(`Waiting for redirect chain to settle (2s)`),await new Promise(e=>setTimeout(e,2e3)),await e.attachToPage(n.followerTargetId);let t;try{let n=await e.evaluate(`window.location.href`);t=typeof n==`string`?n:String(n),X.debug(`Captured final URL from follower`,{finalUrl:t})}catch(e){X.warn(`Could not read follower URL (may be mid-navigation)`,{error:String(e)})}try{let t=await e.evaluate(`document.body?.innerText?.substring(0, 500) || "(empty)"`);X.debug(`Follower page content at capture time`,{bodyText:t})}catch(e){X.warn(`Could not read follower page content`,{error:String(e)})}let i=(await e.sendCDP(`Network.getCookies`)).cookies??[],a=i.length>0?tp(i):`none`;X.info(`Captured cookies from follower`,{count:i.length}),X.debug(`Captured cookies from follower details`,{count:i.length,domains:a});let o=np;try{o=await sp(e,`follower`),X.info(`Captured follower storage for leader`,{totalEntries:rp(o),localStorageCount:Object.keys(o.localStorage).length,sessionStorageCount:Object.keys(o.sessionStorage).length}),X.debug(`Captured follower storage for leader details`,{origin:o.origin||`(unknown)`,localStorageCount:Object.keys(o.localStorage).length,sessionStorageCount:Object.keys(o.sessionStorage).length})}catch(e){X.warn(`Could not capture follower storage`,{error:String(e)})}let s=rp(o);await mp(e,n,`capture`),await hp(n,`capture`);try{await e.closePage(n.followerTargetId),X.info(`Closed follower tab after teleport`),X.debug(`Closed follower tab after teleport details`,{followerTargetId:n.followerTargetId})}catch(e){X.warn(`Failed to close follower tab`,{error:String(e)})}let c=n.leaderTargetId,l=o.origin||``,u=op(l,n.originalLeaderUrl,t),d=ip(n.originalLeaderUrl),f=!!l&&d!==l,p=f?ap(l):null;if(c)if(await e.attachToPage(c),i.length>0&&(await e.sendCDP(`Network.setCookies`,{cookies:i}),X.info(`Injected cookies into leader tab`,{count:i.length}),X.debug(`Injected cookies into leader tab details`,{count:i.length,leaderTargetId:c})),f&&p){X.info(`Hydrating leader storage origin before landing`,{storageEntries:s}),X.debug(`Hydrating leader storage origin before landing details`,{hydrationUrl:p,landingUrl:u,originalLeaderUrl:n.originalLeaderUrl,finalUrl:t,leaderTargetId:c,storageOrigin:l,storageEntries:s});try{await e.navigate(p),await up(e,o,`leader`),u&&u!==p&&await e.navigate(u)}catch(t){X.warn(`Direct leader origin hydration failed, falling back to init-script replay`,{error:String(t)}),X.debug(`Direct leader origin hydration fallback details`,{hydrationUrl:p,landingUrl:u,error:String(t)});let n=await dp(e,o,c,`leader`);try{u&&await e.navigate(u)}finally{await n?.()}}}else{let r=await dp(e,o,c,`leader`);try{u&&(X.info(`Navigating leader after auth-state injection`,{hasLandingUrl:!0,storageEntries:s}),X.debug(`Navigating leader after auth-state injection details`,{landingUrl:u,originalLeaderUrl:n.originalLeaderUrl,finalUrl:t,leaderTargetId:c,storageOrigin:o.origin||`(unknown)`,storageEntries:s}),await e.navigate(u))}finally{await r?.()}}else X.warn(`No leader tab available for auth-state injection`);n.phase=`done`,_p(n);let m=i.length>0?` (${tp(i)})`:``,h=s>0?` + ${s} storage entr${s===1?`y`:`ies`}`:``,g=u?` (navigated to ${u})`:``,_=`Teleported ${i.length} cookie(s)${m}${h} from ${r}${g}`;X.info(`Teleport completed successfully`,{cookieCount:i.length,storageEntries:s,landed:!!u}),X.debug(`Teleport completed successfully details`,{result:_}),n.resolveBlock?.(_)}catch(e){X.error(`Teleport auth-state capture failed`,{error:String(e)}),await hp(n,`capture-error`),n.phase=`done`,_p(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}function xp(e){return`Usage: ${e} <command> [args...]
983
+ }))()`);if(typeof t!=`string`||t.length===0)return{url:``,title:``,bodySnippet:`(unavailable)`};try{let e=JSON.parse(t);return{url:typeof e.url==`string`?e.url:``,title:typeof e.title==`string`?e.title:``,bodySnippet:typeof e.bodySnippet==`string`&&e.bodySnippet.length>0?e.bodySnippet:`(empty)`}}catch{return{url:``,title:``,bodySnippet:`(unparseable)`}}}function _p(e){return/callback|authorize\/resume|error/i.test(e)}async function vp(e,t,n){try{let r=await gp(e),i=`${n}:${r.url}:${r.title}`;if(t.lastFollowerDiagnosticKey===i)return;t.lastFollowerDiagnosticKey=i,X.debug(`Teleport follower diagnostics`,{reason:n,url:r.url,title:r.title,bodySnippet:r.bodySnippet})}catch(e){X.warn(`Could not capture teleport follower diagnostics`,{reason:n,error:String(e)})}}async function yp(e,t){let n=e.removeFollowerStorageScript;if(n){e.removeFollowerStorageScript=null;try{await n(),X.info(`Removed follower teleport storage init script`,{reason:t})}catch(e){X.warn(`Failed to remove follower teleport storage init script`,{reason:t,error:String(e)})}}}async function bp(e,t){if(X.warn(`Teleport timed out`,{timeoutMs:t.timeoutMs,phase:t.phase}),X.debug(`Teleport timeout details`,{timeoutMs:t.timeoutMs,phase:t.phase,followerTargetId:t.followerTargetId}),t.phase=`timedOut`,t.followerTargetId){try{await e.attachToPage(t.followerTargetId),await vp(e,t,`timeout`)}catch(e){X.warn(`Could not attach to follower for timeout diagnostics`,{error:String(e)})}await yp(t,`timeout`)}if(xp(t),t.followerTargetId)try{await e.closePage(t.followerTargetId)}catch(e){X.warn(`Failed to close follower tab after timeout`,{error:String(e)})}t.rejectBlock?.(Error(`Teleport timed out after ${Math.round(t.timeoutMs/1e3)}s — human did not complete auth`))}function xp(e){X.info(`Cleaning up teleport watcher`,{phase:e.phase,hadPoll:!!e.pollInterval,hadTimeout:!!e.timeoutTimer,hadListener:!!e.cleanupListener}),e.pollInterval&&=(clearInterval(e.pollInterval),void 0),e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.cleanupListener&&=(e.cleanupListener(),void 0)}function Sp(e,t,n,r,i,a,o,s){X.info(`Arming teleport watcher`,{timeoutMs:i,runtimeSelection:a?`explicit`:`auto`}),X.debug(`Arming teleport watcher details`,{startPattern:n.source,returnPattern:r.source,timeoutMs:i,runtimeId:a??`auto`,originalUrl:o});let c={startPattern:n,returnPattern:r,timeoutMs:i,runtimeId:a,phase:`armed`,leaderTargetId:s,originalLeaderUrl:o};return c.completionPromise=new Promise((e,t)=>{c.resolveBlock=e,c.rejectBlock=t}),c.completionPromise.catch(()=>{}),c.pollInterval=setInterval(async()=>{if(c.phase!==`armed`)return;let r=c.leaderTargetId;if(r)try{await e.attachToPage(r);let i=await e.evaluate(`window.location.href`),a=typeof i==`string`?i:String(i);X.debug(`Polling leader tab URL`,{targetId:r,href:a,startPattern:n.source}),n.test(a)&&(X.info(`Teleport start pattern matched on leader`),X.debug(`Teleport start pattern matched on leader details`,{targetId:r,href:a,startPattern:n.source}),Cp(e,t,c,a))}catch(e){X.warn(`Error polling leader tab URL`,{targetId:r,error:String(e)})}},1e3),s&&t.teleportWatchers.set(s,c),c}async function Cp(e,t,n,r){if(n.phase===`armed`){n.phase=`teleporting`,X.info(`Teleport triggered`),X.debug(`Teleport trigger details`,{triggerUrl:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0);try{let i=[],a=op;try{i=(await e.sendCDP(`Network.getCookies`,{})).cookies??[],X.info(`Captured leader cookies for follower`,{count:i.length})}catch(e){X.warn(`Could not capture leader cookies`,{error:String(e)})}try{a=await dp(e,`leader`),X.info(`Captured leader storage for follower`,{totalEntries:sp(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),X.debug(`Captured leader storage for follower details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){X.warn(`Could not capture leader storage`,{error:String(e)})}let o=n.runtimeId;if(!o){let e=jf?.();if(!e)throw Error(`No follower selection available — not connected to a tray`);let t=e();if(!t)throw Error(`No followers connected to teleport to`);o=t.runtimeId}X.info(`Selected follower for teleport`),X.debug(`Selected follower for teleport details`,{runtimeId:o});let s=await e.createRemotePage(o,`about:blank`),c=s.includes(`:`)?s:`${o}:${s}`;if(n.followerTargetId=c,X.info(`Opened follower tab for teleport`),X.debug(`Opened follower tab for teleport details`,{followerTargetId:c}),await e.attachToPage(c),X.info(`Attached to follower tab for teleport`),X.debug(`Attached to follower tab for teleport details`,{followerTargetId:c}),await e.sendCDP(`Page.enable`),i.length>0)try{await e.sendCDP(`Network.setCookies`,{cookies:i}),X.info(`Injected leader cookies into follower`,{count:i.length})}catch(e){X.warn(`Could not inject leader cookies into follower`,{error:String(e)})}let l=r;n.removeFollowerStorageScript=await hp(e,a,c,`follower`),X.info(`Navigating follower to intercepted auth URL`),X.debug(`Navigating follower to intercepted auth URL details`,{url:l,originalLeaderUrl:n.originalLeaderUrl,triggerUrl:r,storageOrigin:a.origin||`(unknown)`}),await e.sendCDP(`Page.navigate`,{url:l}),X.info(`Starting teleport timeout timer`,{timeoutMs:n.timeoutMs}),n.timeoutTimer=setTimeout(()=>{(n.phase===`teleporting`||n.phase===`waitingForAuth`||n.phase===`waitingForReturn`)&&bp(e,n)},n.timeoutMs),n.phase=`waitingForAuth`,X.info(`Teleport waiting for follower auth redirect`),X.debug(`Teleport waiting for follower auth redirect details`,{startPattern:n.startPattern.source}),n.pollInterval=setInterval(async()=>{if(!(n.phase!==`waitingForAuth`&&n.phase!==`waitingForReturn`))try{await e.attachToPage(c);let r=await e.evaluate(`window.location.href`),i=typeof r==`string`?r:String(r);if(!i)return;if(n.lastFollowerUrl!==i&&(n.lastFollowerUrl=i,X.debug(`Follower teleport navigation`,{href:i,phase:n.phase})),n.phase===`waitingForAuth`){n.startPattern.test(i)?(n.phase=`waitingForReturn`,X.info(`Follower reached auth provider; waiting for return pattern`),X.debug(`Follower reached auth provider details`,{href:i,startPattern:n.startPattern.source})):X.debug(`Waiting for auth redirect on follower`,{href:i,startPattern:n.startPattern.source});return}X.debug(`Polling follower tab URL for return`,{href:i,returnPattern:n.returnPattern.source}),_p(i)&&await vp(e,n,`waiting-for-return`),n.returnPattern.test(i)&&(X.info(`Follower return pattern matched after auth`),X.debug(`Follower return pattern matched after auth details`,{href:i,returnPattern:n.returnPattern.source}),wp(e,t,n,o))}catch(e){X.warn(`Error polling follower tab URL`,{error:String(e)})}},1e3)}catch(e){X.error(`Teleport trigger failed`,{error:String(e)}),await yp(n,`trigger-error`),n.phase=`done`,xp(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}async function wp(e,t,n,r){if(!(n.phase!==`teleporting`&&n.phase!==`waitingForReturn`)){n.phase=`capturing`,X.info(`Capturing auth state from follower`),X.debug(`Capturing auth state from follower details`,{followerTargetId:n.followerTargetId,runtimeId:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0),n.timeoutTimer&&=(clearTimeout(n.timeoutTimer),void 0);try{X.info(`Waiting for redirect chain to settle (2s)`),await new Promise(e=>setTimeout(e,2e3)),await e.attachToPage(n.followerTargetId);let t;try{let n=await e.evaluate(`window.location.href`);t=typeof n==`string`?n:String(n),X.debug(`Captured final URL from follower`,{finalUrl:t})}catch(e){X.warn(`Could not read follower URL (may be mid-navigation)`,{error:String(e)})}try{let t=await e.evaluate(`document.body?.innerText?.substring(0, 500) || "(empty)"`);X.debug(`Follower page content at capture time`,{bodyText:t})}catch(e){X.warn(`Could not read follower page content`,{error:String(e)})}let i=(await e.sendCDP(`Network.getCookies`)).cookies??[],a=i.length>0?ap(i):`none`;X.info(`Captured cookies from follower`,{count:i.length}),X.debug(`Captured cookies from follower details`,{count:i.length,domains:a});let o=op;try{o=await dp(e,`follower`),X.info(`Captured follower storage for leader`,{totalEntries:sp(o),localStorageCount:Object.keys(o.localStorage).length,sessionStorageCount:Object.keys(o.sessionStorage).length}),X.debug(`Captured follower storage for leader details`,{origin:o.origin||`(unknown)`,localStorageCount:Object.keys(o.localStorage).length,sessionStorageCount:Object.keys(o.sessionStorage).length})}catch(e){X.warn(`Could not capture follower storage`,{error:String(e)})}let s=sp(o);await vp(e,n,`capture`),await yp(n,`capture`);try{await e.closePage(n.followerTargetId),X.info(`Closed follower tab after teleport`),X.debug(`Closed follower tab after teleport details`,{followerTargetId:n.followerTargetId})}catch(e){X.warn(`Failed to close follower tab`,{error:String(e)})}let c=n.leaderTargetId,l=o.origin||``,u=up(l,n.originalLeaderUrl,t),d=cp(n.originalLeaderUrl),f=!!l&&d!==l,p=f?lp(l):null;if(c)if(await e.attachToPage(c),i.length>0&&(await e.sendCDP(`Network.setCookies`,{cookies:i}),X.info(`Injected cookies into leader tab`,{count:i.length}),X.debug(`Injected cookies into leader tab details`,{count:i.length,leaderTargetId:c})),f&&p){X.info(`Hydrating leader storage origin before landing`,{storageEntries:s}),X.debug(`Hydrating leader storage origin before landing details`,{hydrationUrl:p,landingUrl:u,originalLeaderUrl:n.originalLeaderUrl,finalUrl:t,leaderTargetId:c,storageOrigin:l,storageEntries:s});try{await e.navigate(p),await mp(e,o,`leader`),u&&u!==p&&await e.navigate(u)}catch(t){X.warn(`Direct leader origin hydration failed, falling back to init-script replay`,{error:String(t)}),X.debug(`Direct leader origin hydration fallback details`,{hydrationUrl:p,landingUrl:u,error:String(t)});let n=await hp(e,o,c,`leader`);try{u&&await e.navigate(u)}finally{await n?.()}}}else{let r=await hp(e,o,c,`leader`);try{u&&(X.info(`Navigating leader after auth-state injection`,{hasLandingUrl:!0,storageEntries:s}),X.debug(`Navigating leader after auth-state injection details`,{landingUrl:u,originalLeaderUrl:n.originalLeaderUrl,finalUrl:t,leaderTargetId:c,storageOrigin:o.origin||`(unknown)`,storageEntries:s}),await e.navigate(u))}finally{await r?.()}}else X.warn(`No leader tab available for auth-state injection`);n.phase=`done`,xp(n);let m=i.length>0?` (${ap(i)})`:``,h=s>0?` + ${s} storage entr${s===1?`y`:`ies`}`:``,g=u?` (navigated to ${u})`:``,_=`Teleported ${i.length} cookie(s)${m}${h} from ${r}${g}`;X.info(`Teleport completed successfully`,{cookieCount:i.length,storageEntries:s,landed:!!u}),X.debug(`Teleport completed successfully details`,{result:_}),n.resolveBlock?.(_)}catch(e){X.error(`Teleport auth-state capture failed`,{error:String(e)}),await yp(n,`capture-error`),n.phase=`done`,xp(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}function Tp(e){return`Usage: ${e} <command> [args...]
984
984
 
985
985
  Commands:
986
986
  open [url|/vfs/path] [--foreground|--fg] [--runtime=<id>]
@@ -1055,17 +1055,17 @@ Commands:
1055
1055
  sessionstorage-clear Clear all sessionStorage
1056
1056
  help Show this help message
1057
1057
 
1058
- Aliases: ${Nf.filter(t=>t!==e).join(`, `)}`}function Sp(e){let t=[],n={};for(let r of e)if(r.startsWith(`--`)&&r.includes(`=`)){let e=r.indexOf(`=`);n[r.slice(2,e)]=r.slice(e+1)}else r.startsWith(`--`)?n[r.slice(2)]=`true`:t.push(r);return{positional:t,flags:n}}function Z(e){let t=e.tab;return t?{targetId:t}:{error:`Error: --tab <targetId> is required. Run 'playwright-cli tab-list' to get tab IDs.
1059
- `}}function Cp(e,t,n){let r=xp(e),i=t?Lf(t,n):null;return z(e,async a=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`)return{stdout:r+`
1060
- `,stderr:``,exitCode:0};if(!t||!i)return{stdout:``,stderr:`${e}: browser APIs are unavailable in this environment\n`,exitCode:1};let o=a[0],s=a.slice(1),{positional:c,flags:l}=Sp(s),u;try{switch(o){case`teleport`:{if(l.list===`true`){X.info(`Listing available follower runtimes`);let e=Of?.();if(!e){u={stdout:``,stderr:`teleport: not connected to a tray
1058
+ Aliases: ${Lf.filter(t=>t!==e).join(`, `)}`}function Ep(e){let t=[],n={};for(let r of e)if(r.startsWith(`--`)&&r.includes(`=`)){let e=r.indexOf(`=`);n[r.slice(2,e)]=r.slice(e+1)}else r.startsWith(`--`)?n[r.slice(2)]=`true`:t.push(r);return{positional:t,flags:n}}function Z(e){let t=e.tab;return t?{targetId:t}:{error:`Error: --tab <targetId> is required. Run 'playwright-cli tab-list' to get tab IDs.
1059
+ `}}function Dp(e,t,n){let r=Tp(e),i=t?Vf(t,n):null;return z(e,async a=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`)return{stdout:r+`
1060
+ `,stderr:``,exitCode:0};if(!t||!i)return{stdout:``,stderr:`${e}: browser APIs are unavailable in this environment\n`,exitCode:1};let o=a[0],s=a.slice(1),{positional:c,flags:l}=Ep(s),u;try{switch(o){case`teleport`:{if(l.list===`true`){X.info(`Listing available follower runtimes`);let e=Mf?.();if(!e){u={stdout:``,stderr:`teleport: not connected to a tray
1061
1061
  `,exitCode:1};break}let t=e();if(t.length===0){u={stdout:`No followers connected to the tray.
1062
1062
  `,stderr:``,exitCode:0};break}let n=[`Available runtimes for teleport:`];for(let e of t){let t=[e.runtimeId];if(e.floatType&&t.push(`[${e.floatType}]`),e.runtime&&t.push(`(${e.runtime})`),e.lastActivity){let n=Math.round((Date.now()-e.lastActivity)/1e3);t.push(`active ${n}s ago`)}n.push(` ${t.join(` `)}`)}u={stdout:n.join(`
1063
1063
  `)+`
1064
- `,stderr:``,exitCode:0};break}if(l.off===`true`){let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}X.info(`Disarming teleport watcher via --off`,{targetId:e.targetId});let t=i.teleportWatchers.get(e.targetId);t&&(_p(t),i.teleportWatchers.delete(e.targetId)),u={stdout:`Teleport watcher disarmed
1064
+ `,stderr:``,exitCode:0};break}if(l.off===`true`){let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}X.info(`Disarming teleport watcher via --off`,{targetId:e.targetId});let t=i.teleportWatchers.get(e.targetId);t&&(xp(t),i.teleportWatchers.delete(e.targetId)),u={stdout:`Teleport watcher disarmed
1065
1065
  `,stderr:``,exitCode:0};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=l.start||l[`teleport-start`],r=l.return||l[`teleport-return`];if(!n||!r){u={stdout:``,stderr:`teleport requires --start <regex> and --return <regex>
1066
1066
  `,exitCode:1};break}let a,o;try{a=new RegExp(n)}catch{u={stdout:``,stderr:`Invalid regex for --start: ${n}\n`,exitCode:1};break}try{o=new RegExp(r)}catch{u={stdout:``,stderr:`Invalid regex for --return: ${r}\n`,exitCode:1};break}let s=l.timeout?parseInt(l.timeout,10):300;if(isNaN(s)||s<=0){u={stdout:``,stderr:`--timeout must be a positive number
1067
- `,exitCode:1};break}let c=l.runtime,d=i.teleportWatchers.get(e.targetId);d&&(X.info(`Disarming existing teleport watcher before re-arming`,{targetId:e.targetId}),_p(d),i.teleportWatchers.delete(e.targetId));let f;try{await t.attachToPage(e.targetId);let n=await t.evaluate(`window.location.href`);f=typeof n==`string`?n:String(n)}catch{}X.info(`Arming teleport via explicit subcommand`,{targetId:e.targetId,timeoutSec:s,runtimeSelection:c?`explicit`:`auto`}),X.debug(`Arming teleport via explicit subcommand details`,{targetId:e.targetId,startPattern:n,returnPattern:r,timeoutSec:s,runtimeId:c??`auto`,leaderUrl:f}),vp(t,i,a,o,s*1e3,c,f,e.targetId),u={stdout:`Teleport armed on tab ${e.targetId}. Will trigger when URL matches ${n}\n`,stderr:``,exitCode:0};break}case`open`:case`tab-new`:{let e=c[0]||`about:blank`,n=l.runtime;await Yf(t,i);let r;r=n?await t.createRemotePage(n,e):await t.createPage(e);let a=l[`teleport-start`],o=l[`teleport-return`];if(a&&o){X.info(`Arming teleport via open/tab-new flags`),X.debug(`Arming teleport via open/tab-new flags details`,{targetId:r,startPattern:a,returnPattern:o});let n,s;try{n=new RegExp(a)}catch{u={stdout:``,stderr:`Invalid regex for --teleport-start: ${a}\n`,exitCode:1};break}try{s=new RegExp(o)}catch{u={stdout:``,stderr:`Invalid regex for --teleport-return: ${o}\n`,exitCode:1};break}let c=l.timeout?parseInt(l.timeout,10):300,d=i.teleportWatchers.get(r);d&&(_p(d),i.teleportWatchers.delete(r)),vp(t,i,n,s,c*1e3,l[`teleport-runtime`],e,r)}u={stdout:`Opened ${e} in new tab [targetId: ${r}]\n`,stderr:``,exitCode:0};break}case`goto`:case`navigate`:{if(c.length===0){u={stdout:``,stderr:`goto requires a URL
1068
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>(await t.navigate(c[0]),!0)),i.snapshots.delete(e.targetId);let n=l[`teleport-start`],r=l[`teleport-return`];if(n&&r){X.info(`Arming teleport via goto/navigate flags`),X.debug(`Arming teleport via goto/navigate flags details`,{targetId:e.targetId,startPattern:n,returnPattern:r});let a,o;try{a=new RegExp(n)}catch{u={stdout:``,stderr:`Invalid regex for --teleport-start: ${n}\n`,exitCode:1};break}try{o=new RegExp(r)}catch{u={stdout:``,stderr:`Invalid regex for --teleport-return: ${r}\n`,exitCode:1};break}let s=l.timeout?parseInt(l.timeout,10):300,d=i.teleportWatchers.get(e.targetId);d&&(_p(d),i.teleportWatchers.delete(e.targetId)),vp(t,i,a,o,s*1e3,l[`teleport-runtime`],c[0],e.targetId)}u={stdout:`Navigated to ${c[0]}\n`,stderr:``,exitCode:0};break}case`snapshot`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let r=l[`no-iframes`]===`true`,{output:a}=await t.withTab(e.targetId,async()=>await ep(t,i,e.targetId,{noIframes:r}));if(l.filename){await n.writeFile(l.filename,a),u={stdout:`Snapshot saved to ${l.filename}\n`,stderr:``,exitCode:0};break}u={stdout:a+`
1067
+ `,exitCode:1};break}let c=l.runtime,d=i.teleportWatchers.get(e.targetId);d&&(X.info(`Disarming existing teleport watcher before re-arming`,{targetId:e.targetId}),xp(d),i.teleportWatchers.delete(e.targetId));let f;try{await t.attachToPage(e.targetId);let n=await t.evaluate(`window.location.href`);f=typeof n==`string`?n:String(n)}catch{}X.info(`Arming teleport via explicit subcommand`,{targetId:e.targetId,timeoutSec:s,runtimeSelection:c?`explicit`:`auto`}),X.debug(`Arming teleport via explicit subcommand details`,{targetId:e.targetId,startPattern:n,returnPattern:r,timeoutSec:s,runtimeId:c??`auto`,leaderUrl:f}),Sp(t,i,a,o,s*1e3,c,f,e.targetId),u={stdout:`Teleport armed on tab ${e.targetId}. Will trigger when URL matches ${n}\n`,stderr:``,exitCode:0};break}case`open`:case`tab-new`:{let e=c[0]||`about:blank`,n=l.runtime;await $f(t,i);let r;r=n?await t.createRemotePage(n,e):await t.createPage(e);let a=l[`teleport-start`],o=l[`teleport-return`];if(a&&o){X.info(`Arming teleport via open/tab-new flags`),X.debug(`Arming teleport via open/tab-new flags details`,{targetId:r,startPattern:a,returnPattern:o});let n,s;try{n=new RegExp(a)}catch{u={stdout:``,stderr:`Invalid regex for --teleport-start: ${a}\n`,exitCode:1};break}try{s=new RegExp(o)}catch{u={stdout:``,stderr:`Invalid regex for --teleport-return: ${o}\n`,exitCode:1};break}let c=l.timeout?parseInt(l.timeout,10):300,d=i.teleportWatchers.get(r);d&&(xp(d),i.teleportWatchers.delete(r)),Sp(t,i,n,s,c*1e3,l[`teleport-runtime`],e,r)}u={stdout:`Opened ${e} in new tab [targetId: ${r}]\n`,stderr:``,exitCode:0};break}case`goto`:case`navigate`:{if(c.length===0){u={stdout:``,stderr:`goto requires a URL
1068
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>(await t.navigate(c[0]),!0)),i.snapshots.delete(e.targetId);let n=l[`teleport-start`],r=l[`teleport-return`];if(n&&r){X.info(`Arming teleport via goto/navigate flags`),X.debug(`Arming teleport via goto/navigate flags details`,{targetId:e.targetId,startPattern:n,returnPattern:r});let a,o;try{a=new RegExp(n)}catch{u={stdout:``,stderr:`Invalid regex for --teleport-start: ${n}\n`,exitCode:1};break}try{o=new RegExp(r)}catch{u={stdout:``,stderr:`Invalid regex for --teleport-return: ${r}\n`,exitCode:1};break}let s=l.timeout?parseInt(l.timeout,10):300,d=i.teleportWatchers.get(e.targetId);d&&(xp(d),i.teleportWatchers.delete(e.targetId)),Sp(t,i,a,o,s*1e3,l[`teleport-runtime`],c[0],e.targetId)}u={stdout:`Navigated to ${c[0]}\n`,stderr:``,exitCode:0};break}case`snapshot`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let r=l[`no-iframes`]===`true`,{output:a}=await t.withTab(e.targetId,async()=>await ip(t,i,e.targetId,{noIframes:r}));if(l.filename){await n.writeFile(l.filename,a),u={stdout:`Snapshot saved to ${l.filename}\n`,stderr:``,exitCode:0};break}u={stdout:a+`
1069
1069
  `,stderr:``,exitCode:0};break}case`frames`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}u={stdout:await t.withTab(e.targetId,async()=>`Frames in current tab:\n${(await t.getFrameTree()).map(e=>{let t=e.parentFrameId?`child`:`main`,n=e.parentFrameId?` (parent: ${e.parentFrameId})`:``;return` [${t}] ${e.frameId}${n} - ${e.url}`}).join(`
1070
1070
  `)}`)+`
1071
1071
  `,stderr:``,exitCode:0};break}case`screenshot`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}u={stdout:await t.withTab(e.targetId,async()=>{let r;if(c[0]&&c[0].startsWith(`e`)){let n=i.snapshots.get(e.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let a=n.refToBackendNodeId.get(c[0]);if(a){let e=t.getTransport(),n=t.getSessionId();await e.send(`DOM.enable`,{},n),await e.send(`Runtime.enable`,{},n);let i=(await e.send(`DOM.resolveNode`,{backendNodeId:a},n)).object;if(i?.objectId){let t=(await e.send(`Runtime.callFunctionOn`,{objectId:i.objectId,functionDeclaration:`function() {
@@ -1078,9 +1078,9 @@ Aliases: ${Nf.filter(t=>t!==e).join(`, `)}`}function Sp(e){let t=[],n={};for(let
1078
1078
  el.scrollIntoView({ block: 'center' });
1079
1079
  const r = el.getBoundingClientRect();
1080
1080
  return JSON.stringify({ x: r.x + window.scrollX, y: r.y + window.scrollY, width: r.width, height: r.height });
1081
- })()`);i&&(r=JSON.parse(i))}}let a=l[`max-width`]?parseInt(l[`max-width`],10):void 0,o=await t.screenshot({fullPage:l.fullPage===`true`,...r?{clip:r}:{},...a?{maxWidth:a}:{}}),s=l.filename||`/tmp/screenshot-${Date.now()}.png`,u=Mf(o);await n.writeFile(s,u);try{await Uf(n,i);let e=`/.playwright/screenshots/screenshot-${If(new Date)}.png`;await n.writeFile(e,u)}catch{}return`Screenshot saved to ${s} (${Math.round(u.length/1024)} KB)`})+`
1081
+ })()`);i&&(r=JSON.parse(i))}}let a=l[`max-width`]?parseInt(l[`max-width`],10):void 0,o=await t.screenshot({fullPage:l.fullPage===`true`,...r?{clip:r}:{},...a?{maxWidth:a}:{}}),s=l.filename||`/tmp/screenshot-${Date.now()}.png`,u=If(o);await n.writeFile(s,u);try{await qf(n,i);let e=`/.playwright/screenshots/screenshot-${Bf(new Date)}.png`;await n.writeFile(e,u)}catch{}return`Screenshot saved to ${s} (${Math.round(u.length/1024)} KB)`})+`
1082
1082
  `,stderr:``,exitCode:0};break}case`click`:{if(c.length===0){u={stdout:``,stderr:`click requires a ref (e.g. e5)
1083
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let r=i.snapshots.get(e.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:a}=jf(n),o=r.refToFrameId?.get(n);if(a&&o){let a=r.refToSelector.get(n);if(!a)throw Error(`Unknown ref "${n}" in iframe`);let s=a.split(`,`)[0].trim();return await t.evaluateInFrame(o,`(function() {
1083
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let r=i.snapshots.get(e.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:a}=Ff(n),o=r.refToFrameId?.get(n);if(a&&o){let a=r.refToSelector.get(n);if(!a)throw Error(`Unknown ref "${n}" in iframe`);let s=a.split(`,`)[0].trim();return await t.evaluateInFrame(o,`(function() {
1084
1084
  var el = document.querySelector(${JSON.stringify(s)});
1085
1085
  if (!el) throw new Error('Element not found in iframe for ref ${n}');
1086
1086
  el.scrollIntoView({ block: 'center' });
@@ -1088,7 +1088,7 @@ Aliases: ${Nf.filter(t=>t!==e).join(`, `)}`}function Sp(e){let t=[],n={};for(let
1088
1088
  })()`),i.snapshots.delete(e.targetId),`Clicked ${n} (in iframe)`}let s=r.refToBackendNodeId.get(n);if(s)return await t.clickByBackendNodeId(s),i.snapshots.delete(e.targetId),`Clicked ${n}`;let c=r.refToSelector.get(n);if(!c)throw Error(`Unknown ref "${n}". Available: ${[...r.refToSelector.keys()].slice(0,10).join(`, `)}...`);return await t.click(c),i.snapshots.delete(e.targetId),`Clicked ${n}`})+`
1089
1089
  `,stderr:``,exitCode:0};break}case`type`:{if(c.length===0){u={stdout:``,stderr:`type requires text
1090
1090
  `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c.join(` `);await t.withTab(e.targetId,async()=>{await t.type(n)}),u={stdout:`Typed: ${n}\n`,stderr:``,exitCode:0};break}case`fill`:{if(c.length<2){u={stdout:``,stderr:`fill requires <ref> <text>
1091
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0],r=c.slice(1).join(` `);u={stdout:await t.withTab(e.targetId,async()=>{let a=i.snapshots.get(e.targetId);if(!a)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:o}=jf(n),s=a.refToFrameId?.get(n);if(o&&s){let o=a.refToSelector.get(n);if(!o)throw Error(`Unknown ref "${n}" in iframe`);let c=o.split(`,`)[0].trim();return await t.evaluateInFrame(s,`(function() {
1091
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0],r=c.slice(1).join(` `);u={stdout:await t.withTab(e.targetId,async()=>{let a=i.snapshots.get(e.targetId);if(!a)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:o}=Ff(n),s=a.refToFrameId?.get(n);if(o&&s){let o=a.refToSelector.get(n);if(!o)throw Error(`Unknown ref "${n}" in iframe`);let c=o.split(`,`)[0].trim();return await t.evaluateInFrame(s,`(function() {
1092
1092
  var el = document.querySelector(${JSON.stringify(c)});
1093
1093
  if (!el) throw new Error('Element not found in iframe for ref ${n}');
1094
1094
  el.scrollIntoView({ block: 'center' });
@@ -1097,20 +1097,20 @@ Aliases: ${Nf.filter(t=>t!==e).join(`, `)}`}function Sp(e){let t=[],n={};for(let
1097
1097
  el.value = ${JSON.stringify(r)};
1098
1098
  el.dispatchEvent(new Event('input', { bubbles: true }));
1099
1099
  el.dispatchEvent(new Event('change', { bubbles: true }));
1100
- })()`),i.snapshots.delete(e.targetId),`Filled ${n} with: ${r} (in iframe)`}let c=a.refToBackendNodeId.get(n);if(c){await t.clickByBackendNodeId(c);let a=t.getTransport(),o=t.getSessionId();await a.send(`DOM.enable`,{},o),await a.send(`Runtime.enable`,{},o);let s=(await a.send(`DOM.resolveNode`,{backendNodeId:c},o)).object;return s?.objectId&&await a.send(`Runtime.callFunctionOn`,{objectId:s.objectId,functionDeclaration:Vf,returnByValue:!0},o),await t.type(r),s?.objectId&&((await a.send(`Runtime.callFunctionOn`,{objectId:s.objectId,functionDeclaration:Bf,returnByValue:!0},o)).result?.value??``)!==r&&await a.send(`Runtime.callFunctionOn`,{objectId:s.objectId,functionDeclaration:zf,arguments:[{value:r}],returnByValue:!0},o),i.snapshots.delete(e.targetId),`Filled ${n} with: ${r}`}let l=a.refToSelector.get(n);if(!l)throw Error(`Unknown ref "${n}"`);return await t.click(l),await t.evaluate(`(function() {
1100
+ })()`),i.snapshots.delete(e.targetId),`Filled ${n} with: ${r} (in iframe)`}let c=a.refToBackendNodeId.get(n);if(c){await t.clickByBackendNodeId(c);let a=t.getTransport(),o=t.getSessionId();await a.send(`DOM.enable`,{},o),await a.send(`Runtime.enable`,{},o);let s=(await a.send(`DOM.resolveNode`,{backendNodeId:c},o)).object;return s?.objectId&&await a.send(`Runtime.callFunctionOn`,{objectId:s.objectId,functionDeclaration:Gf,returnByValue:!0},o),await t.type(r),s?.objectId&&((await a.send(`Runtime.callFunctionOn`,{objectId:s.objectId,functionDeclaration:Wf,returnByValue:!0},o)).result?.value??``)!==r&&await a.send(`Runtime.callFunctionOn`,{objectId:s.objectId,functionDeclaration:Uf,arguments:[{value:r}],returnByValue:!0},o),i.snapshots.delete(e.targetId),`Filled ${n} with: ${r}`}let l=a.refToSelector.get(n);if(!l)throw Error(`Unknown ref "${n}"`);return await t.click(l),await t.evaluate(`(function() {
1101
1101
  const el = document.querySelector(${JSON.stringify(l)});
1102
1102
  if (el) {
1103
- return (${Vf}).call(el);
1103
+ return (${Gf}).call(el);
1104
1104
  }
1105
1105
  return false;
1106
1106
  })()`),await t.type(r),await t.evaluate(`(function() {
1107
1107
  const el = document.querySelector(${JSON.stringify(l.split(`,`)[0].trim())});
1108
1108
  if (!el) return '';
1109
- return (${Bf}).call(el);
1109
+ return (${Wf}).call(el);
1110
1110
  })()`)!==r&&await t.evaluate(`(function() {
1111
1111
  const el = document.querySelector(${JSON.stringify(l.split(`,`)[0].trim())});
1112
1112
  if (!el) return;
1113
- (${zf}).call(el, ${JSON.stringify(r)});
1113
+ (${Uf}).call(el, ${JSON.stringify(r)});
1114
1114
  })()`),i.snapshots.delete(e.targetId),`Filled ${n} with: ${r}`})+`
1115
1115
  `,stderr:``,exitCode:0};break}case`eval`:{if(c.length===0){u={stdout:``,stderr:`eval requires an expression
1116
1116
  `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c.join(` `);u={stdout:(await t.withTab(e.targetId,async()=>{let e=await t.evaluate(n);return typeof e==`string`?e:JSON.stringify(e,null,2)})??`undefined`)+`
@@ -1120,32 +1120,32 @@ Aliases: ${Nf.filter(t=>t!==e).join(`, `)}`}function Sp(e){let t=[],n={};for(let
1120
1120
  `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];await t.withTab(e.targetId,async()=>{let e=t.getTransport(),r=t.getSessionId();await e.send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:n},r),await e.send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:n},r)}),u={stdout:`Pressed ${n}\n`,stderr:``,exitCode:0};break}case`go-back`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.evaluate(`history.back()`)}),i.snapshots.delete(e.targetId),u={stdout:`Navigated back
1121
1121
  `,stderr:``,exitCode:0};break}case`go-forward`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.evaluate(`history.forward()`)}),i.snapshots.delete(e.targetId),u={stdout:`Navigated forward
1122
1122
  `,stderr:``,exitCode:0};break}case`reload`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.sendCDP(`Page.reload`)}),u={stdout:`Reloaded
1123
- `,stderr:``,exitCode:0};break}case`tab-list`:{let e=await $f(t,i);if(e.length===0){u={stdout:`No tabs open
1123
+ `,stderr:``,exitCode:0};break}case`tab-list`:{let e=await rp(t,i);if(e.length===0){u={stdout:`No tabs open
1124
1124
  `,stderr:``,exitCode:0};break}u={stdout:e.map(e=>{let t=!!e.active,n=e.targetId.includes(`:`),r=t?` (active)`:``,i=n?` [remote:${e.targetId.substring(0,e.targetId.indexOf(`:`))}]`:``;return`[${e.targetId}] ${e.url} "${e.title}"${r}${i}`}).join(`
1125
1125
  `)+`
1126
1126
  `,stderr:``,exitCode:0};break}case`tab-close`:case`close`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.closePage(e.targetId),i.snapshots.delete(e.targetId),i.teleportWatchers.delete(e.targetId),u={stdout:`Closed tab ${e.targetId}\n`,stderr:``,exitCode:0};break}case`dblclick`:{if(c.length===0){u={stdout:``,stderr:`dblclick requires a ref (e.g. e5)
1127
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0],r=c[1]||`left`;u={stdout:await t.withTab(e.targetId,async()=>{let a=i.snapshots.get(e.targetId);if(!a)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:o}=jf(n),s=a.refToFrameId?.get(n);if(o&&s){let r=a.refToSelector.get(n);if(!r)throw Error(`Unknown ref "${n}" in iframe`);let o=r.split(`,`)[0].trim();return await t.evaluateInFrame(s,`(function() {
1127
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0],r=c[1]||`left`;u={stdout:await t.withTab(e.targetId,async()=>{let a=i.snapshots.get(e.targetId);if(!a)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:o}=Ff(n),s=a.refToFrameId?.get(n);if(o&&s){let r=a.refToSelector.get(n);if(!r)throw Error(`Unknown ref "${n}" in iframe`);let o=r.split(`,`)[0].trim();return await t.evaluateInFrame(s,`(function() {
1128
1128
  var el = document.querySelector(${JSON.stringify(o)});
1129
1129
  if (!el) throw new Error('Element not found in iframe for ref ${n}');
1130
1130
  el.scrollIntoView({ block: 'center' });
1131
1131
  el.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
1132
1132
  })()`),i.snapshots.delete(e.targetId),`Double-clicked ${n} (in iframe)`}let c=a.refToBackendNodeId.get(n);if(!c)throw Error(`Unknown ref "${n}"`);return await t.dblclickByBackendNodeId(c,r),i.snapshots.delete(e.targetId),`Double-clicked ${n}`})+`
1133
1133
  `,stderr:``,exitCode:0};break}case`hover`:{if(c.length===0){u={stdout:``,stderr:`hover requires a ref (e.g. e5)
1134
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let r=i.snapshots.get(e.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:a}=jf(n),o=r.refToFrameId?.get(n);if(a&&o){let e=r.refToSelector.get(n);if(!e)throw Error(`Unknown ref "${n}" in iframe`);let i=e.split(`,`)[0].trim();return await t.evaluateInFrame(o,`(function() {
1134
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let r=i.snapshots.get(e.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:a}=Ff(n),o=r.refToFrameId?.get(n);if(a&&o){let e=r.refToSelector.get(n);if(!e)throw Error(`Unknown ref "${n}" in iframe`);let i=e.split(`,`)[0].trim();return await t.evaluateInFrame(o,`(function() {
1135
1135
  var el = document.querySelector(${JSON.stringify(i)});
1136
1136
  if (!el) throw new Error('Element not found in iframe for ref ${n}');
1137
1137
  el.scrollIntoView({ block: 'center' });
1138
1138
  el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
1139
1139
  })()`),`Hovered ${n} (in iframe)`}let s=r.refToBackendNodeId.get(n);if(!s)throw Error(`Unknown ref "${n}"`);return await t.hoverByBackendNodeId(s),`Hovered ${n}`})+`
1140
1140
  `,stderr:``,exitCode:0};break}case`select`:{if(c.length<2){u={stdout:``,stderr:`select requires <ref> <value>
1141
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0],r=c.slice(1).join(` `);u={stdout:await t.withTab(e.targetId,async()=>{let a=i.snapshots.get(e.targetId);if(!a)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:o}=jf(n),s=a.refToFrameId?.get(n);if(o&&s){let o=a.refToSelector.get(n);if(!o)throw Error(`Unknown ref "${n}" in iframe`);let c=o.split(`,`)[0].trim();return await t.evaluateInFrame(s,`(function() {
1141
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0],r=c.slice(1).join(` `);u={stdout:await t.withTab(e.targetId,async()=>{let a=i.snapshots.get(e.targetId);if(!a)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:o}=Ff(n),s=a.refToFrameId?.get(n);if(o&&s){let o=a.refToSelector.get(n);if(!o)throw Error(`Unknown ref "${n}" in iframe`);let c=o.split(`,`)[0].trim();return await t.evaluateInFrame(s,`(function() {
1142
1142
  var el = document.querySelector(${JSON.stringify(c)});
1143
1143
  if (!el) throw new Error('Element not found in iframe for ref ${n}');
1144
1144
  el.value = ${JSON.stringify(r)};
1145
1145
  el.dispatchEvent(new Event('change', { bubbles: true }));
1146
1146
  })()`),i.snapshots.delete(e.targetId),`Selected "${r}" on ${n} (in iframe)`}let c=a.refToBackendNodeId.get(n);if(!c)throw Error(`Unknown ref "${n}"`);return await t.selectByBackendNodeId(c,r),i.snapshots.delete(e.targetId),`Selected "${r}" on ${n}`})+`
1147
1147
  `,stderr:``,exitCode:0};break}case`check`:{if(c.length===0){u={stdout:``,stderr:`check requires a ref (e.g. e5)
1148
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let r=i.snapshots.get(e.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:a}=jf(n),o=r.refToFrameId?.get(n);if(a&&o){let a=r.refToSelector.get(n);if(!a)throw Error(`Unknown ref "${n}" in iframe`);let s=a.split(`,`)[0].trim();return await t.evaluateInFrame(o,`(function() {
1148
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let r=i.snapshots.get(e.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:a}=Ff(n),o=r.refToFrameId?.get(n);if(a&&o){let a=r.refToSelector.get(n);if(!a)throw Error(`Unknown ref "${n}" in iframe`);let s=a.split(`,`)[0].trim();return await t.evaluateInFrame(o,`(function() {
1149
1149
  var el = document.querySelector(${JSON.stringify(s)});
1150
1150
  if (!el) throw new Error('Element not found in iframe for ref ${n}');
1151
1151
  if (!el.checked) {
@@ -1155,7 +1155,7 @@ Aliases: ${Nf.filter(t=>t!==e).join(`, `)}`}function Sp(e){let t=[],n={};for(let
1155
1155
  }
1156
1156
  })()`),i.snapshots.delete(e.targetId),`Checked ${n} (in iframe)`}let s=r.refToBackendNodeId.get(n);if(!s)throw Error(`Unknown ref "${n}"`);let c=await t.setCheckedByBackendNodeId(s,!0);return c===`toggled`&&i.snapshots.delete(e.targetId),c===`already`?`${n} already checked`:`Checked ${n}`})+`
1157
1157
  `,stderr:``,exitCode:0};break}case`uncheck`:{if(c.length===0){u={stdout:``,stderr:`uncheck requires a ref (e.g. e5)
1158
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let r=i.snapshots.get(e.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:a}=jf(n),o=r.refToFrameId?.get(n);if(a&&o){let a=r.refToSelector.get(n);if(!a)throw Error(`Unknown ref "${n}" in iframe`);let s=a.split(`,`)[0].trim();return await t.evaluateInFrame(o,`(function() {
1158
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let r=i.snapshots.get(e.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:a}=Ff(n),o=r.refToFrameId?.get(n);if(a&&o){let a=r.refToSelector.get(n);if(!a)throw Error(`Unknown ref "${n}" in iframe`);let s=a.split(`,`)[0].trim();return await t.evaluateInFrame(o,`(function() {
1159
1159
  var el = document.querySelector(${JSON.stringify(s)});
1160
1160
  if (!el) throw new Error('Element not found in iframe for ref ${n}');
1161
1161
  if (el.checked) {
@@ -1175,8 +1175,8 @@ Aliases: ${Nf.filter(t=>t!==e).join(`, `)}`}function Sp(e){let t=[],n={};for(let
1175
1175
  `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}let n=c[0];u={stdout:await t.withTab(e.targetId,async()=>{let e=((await t.sendCDP(`Network.getCookies`)).cookies??[]).filter(e=>e.name===n);if(e.length===0)throw Error(`Cookie "${n}" not found`);return e.map(e=>`${e.name}=${e.value}\tDomain=${e.domain}\tPath=${e.path}\tSecure=${e.secure}\tHttpOnly=${e.httpOnly}\tExpires=${e.expires}`).join(`
1176
1176
  `)})+`
1177
1177
  `,stderr:``,exitCode:0};break}case`cookie-set`:{if(c.length<2){u={stdout:``,stderr:`cookie-set requires <name> <value>
1178
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{let e=await Hf(t),n={name:c[0],value:c[1]};l.domain&&(n.domain=l.domain),l.path&&(n.path=l.path),l.secure===`true`&&(n.secure=!0),l.httpOnly===`true`&&(n.httpOnly=!0),l.expires&&(n.expires=parseFloat(l.expires)),!n.domain&&!n.path&&(n.url=e.href),await t.sendCDP(`Network.setCookie`,n)}),u={stdout:`Cookie "${c[0]}" set\n`,stderr:``,exitCode:0};break}case`cookie-delete`:{if(c.length===0){u={stdout:``,stderr:`cookie-delete requires a cookie name
1179
- `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{let e={name:c[0]};l.domain&&(e.domain=l.domain),l.path&&(e.path=l.path),!e.domain&&!e.path&&(e.url=(await Hf(t)).href),await t.sendCDP(`Network.deleteCookies`,e)}),u={stdout:`Cookie "${c[0]}" deleted\n`,stderr:``,exitCode:0};break}case`cookie-clear`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.sendCDP(`Network.clearBrowserCookies`)}),u={stdout:`All cookies cleared
1178
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{let e=await Kf(t),n={name:c[0],value:c[1]};l.domain&&(n.domain=l.domain),l.path&&(n.path=l.path),l.secure===`true`&&(n.secure=!0),l.httpOnly===`true`&&(n.httpOnly=!0),l.expires&&(n.expires=parseFloat(l.expires)),!n.domain&&!n.path&&(n.url=e.href),await t.sendCDP(`Network.setCookie`,n)}),u={stdout:`Cookie "${c[0]}" set\n`,stderr:``,exitCode:0};break}case`cookie-delete`:{if(c.length===0){u={stdout:``,stderr:`cookie-delete requires a cookie name
1179
+ `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{let e={name:c[0]};l.domain&&(e.domain=l.domain),l.path&&(e.path=l.path),!e.domain&&!e.path&&(e.url=(await Kf(t)).href),await t.sendCDP(`Network.deleteCookies`,e)}),u={stdout:`Cookie "${c[0]}" deleted\n`,stderr:``,exitCode:0};break}case`cookie-clear`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.sendCDP(`Network.clearBrowserCookies`)}),u={stdout:`All cookies cleared
1180
1180
  `,stderr:``,exitCode:0};break}case`localstorage-list`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}u={stdout:await t.withTab(e.targetId,async()=>{let e=await t.evaluate(`JSON.stringify(Object.entries(localStorage))`),n=JSON.parse(e);return n.length===0?`No localStorage entries`:n.map(([e,t])=>`${e}=${t}`).join(`
1181
1181
  `)})+`
1182
1182
  `,stderr:``,exitCode:0};break}case`localstorage-get`:{if(c.length===0){u={stdout:``,stderr:`localstorage-get requires a key
@@ -1191,11 +1191,11 @@ Aliases: ${Nf.filter(t=>t!==e).join(`, `)}`}function Sp(e){let t=[],n={};for(let
1191
1191
  `,stderr:``,exitCode:0};break}case`sessionstorage-set`:{if(c.length<2){u={stdout:``,stderr:`sessionstorage-set requires <key> <value>
1192
1192
  `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.evaluate(`sessionStorage.setItem(${JSON.stringify(c[0])}, ${JSON.stringify(c.slice(1).join(` `))})`)}),u={stdout:`sessionStorage "${c[0]}" set\n`,stderr:``,exitCode:0};break}case`sessionstorage-delete`:{if(c.length===0){u={stdout:``,stderr:`sessionstorage-delete requires a key
1193
1193
  `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.evaluate(`sessionStorage.removeItem(${JSON.stringify(c[0])})`)}),u={stdout:`sessionStorage "${c[0]}" deleted\n`,stderr:``,exitCode:0};break}case`sessionstorage-clear`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.evaluate(`sessionStorage.clear()`)}),u={stdout:`sessionStorage cleared
1194
- `,stderr:``,exitCode:0};break}case`record`:{let e=c[0]||`about:blank`,r=l.filter;await Yf(t,i);let a=await t.createPage(e),o=t.getTransport(),s=(await o.send(`Target.attachToTarget`,{targetId:a,flatten:!0})).sessionId;i.harRecorder||=new ge(o,n);let d=await i.harRecorder.startRecording(a,s,r);u={stdout:`Recording started (targetId: ${a}, recordingId: ${d}) at ${e}\nHAR saved to /recordings/${d}/\n`,stderr:``,exitCode:0};break}case`stop-recording`:{if(c.length===0){u={stdout:``,stderr:`stop-recording requires a recordingId
1195
- `,exitCode:1};break}let e=c[0];if(!i.harRecorder){u={stdout:``,stderr:`Recording not found: ${e}\n`,exitCode:1};break}u={stdout:`Recording stopped. HAR files saved to ${await i.harRecorder.stopRecording(e)}\n`,stderr:``,exitCode:0};break}default:u={stdout:``,stderr:`Unknown command: ${o}\nRun "playwright-cli help" for usage.\n`,exitCode:1};break}}catch(e){u={stdout:``,stderr:`Error: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let d=l.tab??null,f=null;Ff.has(o)&&u.exitCode===0&&d&&(f=await Wf(t,n,i,d));try{await Gf(n,i,{command:o,args:s,result:u,snapshotPath:f,targetId:d})}catch{}return u})}var wp=new Map([[`File operations`,[`ls`,`cat`,`head`,`tail`,`wc`,`touch`,`mkdir`,`rm`,`cp`,`mv`,`ln`,`chmod`,`stat`,`readlink`]],[`Text processing`,[`grep`,`sed`,`awk`,`sort`,`uniq`,`cut`,`tr`,`tee`,`diff`]],[`Search`,[`find`,`rg`]],[`Navigation & paths`,[`pwd`,`basename`,`dirname`,`tree`,`du`,`cd`]],[`Archives`,[`zip`,`unzip`,`pdftk`,`pdf`]],[`Media`,[`convert`,`magick`]],[`Audio`,[`say`,`afplay`,`chime`]],[`Environment & shell`,[`echo`,`printf`,`env`,`printenv`,`export`,`alias`,`unalias`,`history`,`clear`,`true`,`false`,`bash`,`sh`,`commands`,`which`,`uname`,`man`,`host`,`oauth-token`,`secret`,`nuke`,`models`,`cost`]],[`Data processing`,[`xargs`,`jq`,`base64`,`date`]],[`Network`,[`curl`,`wget`,`html-to-markdown`]],[`Version control`,[`git`]],[`Languages`,[`node`,`python`,`python3`,`sqlite3`]],[`Skills`,[`skill`,`upskill`]],[`Browser & UI`,[`serve`,`open`,`imgcat`,...Nf,`webhook`]],[`Filesystem`,[`mount`,`fswatch`]]]);function Tp(e,t=[]){let n=[],r=new Set(e);n.push(`Available commands:
1196
- `);let i=[];for(let[e,t]of wp){let i=t.filter(e=>r.has(e));if(i.length>0){n.push(` ${e}:`),n.push(` ${i.join(`, `)}\n`);for(let e of i)r.delete(e)}}for(let e of r)i.push(e);return i.length>0&&(n.push(` Other:`),n.push(` ${i.sort().join(`, `)}\n`)),t.length>0&&(n.push(` User scripts (.jsh):`),n.push(` ${t.sort().join(`, `)}\n`)),n.push(`Use '<command> --help' for details on a specific command.`),n.join(`
1194
+ `,stderr:``,exitCode:0};break}case`record`:{let e=c[0]||`about:blank`,r=l.filter;await $f(t,i);let a=await t.createPage(e),o=t.getTransport(),s=(await o.send(`Target.attachToTarget`,{targetId:a,flatten:!0})).sessionId;i.harRecorder||=new ge(o,n);let d=await i.harRecorder.startRecording(a,s,r);u={stdout:`Recording started (targetId: ${a}, recordingId: ${d}) at ${e}\nHAR saved to /recordings/${d}/\n`,stderr:``,exitCode:0};break}case`stop-recording`:{if(c.length===0){u={stdout:``,stderr:`stop-recording requires a recordingId
1195
+ `,exitCode:1};break}let e=c[0];if(!i.harRecorder){u={stdout:``,stderr:`Recording not found: ${e}\n`,exitCode:1};break}u={stdout:`Recording stopped. HAR files saved to ${await i.harRecorder.stopRecording(e)}\n`,stderr:``,exitCode:0};break}default:u={stdout:``,stderr:`Unknown command: ${o}\nRun "playwright-cli help" for usage.\n`,exitCode:1};break}}catch(e){u={stdout:``,stderr:`Error: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let d=l.tab??null,f=null;zf.has(o)&&u.exitCode===0&&d&&(f=await Jf(t,n,i,d));try{await Yf(n,i,{command:o,args:s,result:u,snapshotPath:f,targetId:d})}catch{}return u})}var Op=new Map([[`File operations`,[`ls`,`cat`,`head`,`tail`,`wc`,`touch`,`mkdir`,`rm`,`cp`,`mv`,`ln`,`chmod`,`stat`,`readlink`]],[`Text processing`,[`grep`,`sed`,`awk`,`sort`,`uniq`,`cut`,`tr`,`tee`,`diff`]],[`Search`,[`find`,`rg`]],[`Navigation & paths`,[`pwd`,`basename`,`dirname`,`tree`,`du`,`cd`]],[`Archives`,[`zip`,`unzip`,`pdftk`,`pdf`]],[`Media`,[`convert`,`magick`]],[`Audio`,[`say`,`afplay`,`chime`]],[`Environment & shell`,[`echo`,`printf`,`env`,`printenv`,`export`,`alias`,`unalias`,`history`,`clear`,`true`,`false`,`bash`,`sh`,`commands`,`which`,`uname`,`man`,`host`,`oauth-token`,`secret`,`nuke`,`models`,`cost`]],[`Data processing`,[`xargs`,`jq`,`base64`,`date`]],[`Network`,[`curl`,`wget`,`html-to-markdown`]],[`Version control`,[`git`]],[`Languages`,[`node`,`python`,`python3`,`sqlite3`]],[`Skills`,[`skill`,`upskill`]],[`Browser & UI`,[`serve`,`open`,`imgcat`,...Lf,`webhook`]],[`Filesystem`,[`mount`,`fswatch`]]]);function kp(e,t=[]){let n=[],r=new Set(e);n.push(`Available commands:
1196
+ `);let i=[];for(let[e,t]of Op){let i=t.filter(e=>r.has(e));if(i.length>0){n.push(` ${e}:`),n.push(` ${i.join(`, `)}\n`);for(let e of i)r.delete(e)}}for(let e of r)i.push(e);return i.length>0&&(n.push(` Other:`),n.push(` ${i.sort().join(`, `)}\n`)),t.length>0&&(n.push(` User scripts (.jsh):`),n.push(` ${t.sort().join(`, `)}\n`)),n.push(`Use '<command> --help' for details on a specific command.`),n.join(`
1197
1197
  `)+`
1198
- `}function Ep(e={}){return z(`commands`,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return{stdout:`commands - display available commands
1198
+ `}function Ap(e={}){return z(`commands`,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return{stdout:`commands - display available commands
1199
1199
 
1200
1200
  Usage: commands [command]
1201
1201
 
@@ -1206,7 +1206,7 @@ If a command name is provided, shows help for that command.
1206
1206
  Otherwise, lists all available commands.
1207
1207
 
1208
1208
  Note: This is an enhanced version of 'help' that shows all custom commands.
1209
- `,stderr:``,exitCode:0};if(t.length>0&&n.exec){let e=t[0];return n.exec(`${e} --help`,{cwd:n.cwd})}return{stdout:Tp(n.getRegisteredCommands?.()??[],await e.getJshCommands?.()??[]),stderr:``,exitCode:0}})}function Dp(e){let t=e.toLowerCase();return t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`JPEG`:t.endsWith(`.png`)?`PNG`:t.endsWith(`.gif`)?`GIF`:t.endsWith(`.webp`)?`WEBP`:t.endsWith(`.bmp`)?`BMP`:t.endsWith(`.tiff`)||t.endsWith(`.tif`)?`TIFF`:t.endsWith(`.avif`)?`AVIF`:`PNG`}function Op(){return{stdout:`usage: convert [input] [operations...] [output]
1209
+ `,stderr:``,exitCode:0};if(t.length>0&&n.exec){let e=t[0];return n.exec(`${e} --help`,{cwd:n.cwd})}return{stdout:kp(n.getRegisteredCommands?.()??[],await e.getJshCommands?.()??[]),stderr:``,exitCode:0}})}function jp(e){let t=e.toLowerCase();return t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`JPEG`:t.endsWith(`.png`)?`PNG`:t.endsWith(`.gif`)?`GIF`:t.endsWith(`.webp`)?`WEBP`:t.endsWith(`.bmp`)?`BMP`:t.endsWith(`.tiff`)||t.endsWith(`.tif`)?`TIFF`:t.endsWith(`.avif`)?`AVIF`:`PNG`}function Mp(){return{stdout:`usage: convert [input] [operations...] [output]
1210
1210
 
1211
1211
  Operations:
1212
1212
  -resize WxH resize to width x height
@@ -1221,7 +1221,7 @@ Examples:
1221
1221
  convert photo.png -resize 50% smaller.png
1222
1222
  convert image.jpg -rotate 90 -quality 85 rotated.jpg
1223
1223
  convert input.png -crop 100x100+50+50 cropped.png
1224
- `,stderr:``,exitCode:0}}function kp(e=`convert`){return z(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Op();let r=[],i=[],a=0;for(;a<t.length;){let n=t[a];if(n===`-resize`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -resize\n`,exitCode:1};i.push({type:`resize`,value:t[a+1]}),a+=2}else if(n===`-rotate`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -rotate\n`,exitCode:1};i.push({type:`rotate`,value:t[a+1]}),a+=2}else if(n===`-crop`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -crop\n`,exitCode:1};i.push({type:`crop`,value:t[a+1]}),a+=2}else if(n===`-quality`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -quality\n`,exitCode:1};i.push({type:`quality`,value:t[a+1]}),a+=2}else if(n.startsWith(`-`))return{stdout:``,stderr:`${e}: unsupported option ${n}\n`,exitCode:1};else r.push(n),a++}if(r.length!==2)return{stdout:``,stderr:`${e}: expected exactly one input file and one output file\n`,exitCode:1};let o=r[0],s=r[1];try{let e=n.fs.resolvePath(n.cwd,o),t=await n.fs.readFileBuffer(e),r=await Ye(),a=null;if(await r.ImageMagick.read(t,async e=>{for(let t of i)switch(t.type){case`resize`:{let n=t.value.match(/^(\d+)%$/);if(n){let t=parseInt(n[1],10),r=Math.round(e.width*t/100),i=Math.round(e.height*t/100);e.resize(r,i)}else{let n=t.value.endsWith(`!`),i=(n?t.value.slice(0,-1):t.value).split(`x`);if(i.length===2){let t=parseInt(i[0],10),a=parseInt(i[1],10);if(n){let n=new r.MagickGeometry(t,a);n.ignoreAspectRatio=!0,e.resize(n)}else e.resize(t,a)}else throw Error(`Invalid resize format: ${t.value}`)}break}case`rotate`:{let n=parseFloat(t.value);if(isNaN(n))throw Error(`Invalid rotation degrees: ${t.value}`);e.rotate(n);break}case`crop`:{if(!t.value.match(/^(\d+)x(\d+)\+(\d+)\+(\d+)$/))throw Error(`Invalid crop format: ${t.value} (expected WxH+X+Y)`);let n=new r.MagickGeometry(t.value);e.crop(n);break}case`quality`:{let n=parseInt(t.value,10);if(isNaN(n)||n<0||n>100)throw Error(`Invalid quality: ${t.value} (must be 0-100)`);e.quality=n;break}}let t=Dp(s);e.write(t,e=>{a=e})}),!a)throw Error(`Failed to generate output image`);let c=n.fs.resolvePath(n.cwd,s);return await n.fs.writeFile(c,a),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}var Ap=n(`tray-leader`),jp=`leader-tray-session`,Mp=3e4,Np=1e4,Pp={state:`inactive`,session:null,error:null};function Fp(){return{...Pp,session:Pp.session?{...Pp.session}:null}}function Ip(e){Pp={...e,session:e.session?{...e.session}:null}}var Lp=class{constructor(e=jp){this.key=e}async load(){return Rp(await Fe(this.key))}async save(e){await Ve(this.key,JSON.stringify(e))}async clear(){await Ve(this.key,``)}};function Rp(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t.workerBaseUrl!=`string`||typeof t.trayId!=`string`||typeof t.createdAt!=`string`||typeof t.controllerId!=`string`||typeof t.controllerUrl!=`string`||typeof t.joinUrl!=`string`||typeof t.webhookUrl!=`string`||typeof t.runtime!=`string`?null:{workerBaseUrl:t.workerBaseUrl,trayId:t.trayId,createdAt:t.createdAt,controllerId:t.controllerId,controllerUrl:t.controllerUrl,joinUrl:t.joinUrl,webhookUrl:t.webhookUrl,leaderKey:typeof t.leaderKey==`string`?t.leaderKey:void 0,leaderWebSocketUrl:typeof t.leaderWebSocketUrl==`string`?t.leaderWebSocketUrl:null,runtime:t.runtime}}catch{return null}}var zp=class{store;fetchImpl;webSocketFactory;pingIntervalMs;connectTimeoutMs;socket=null;pingTimer=null;currentSession=null;constructor(e){this.options=e,this.store=e.store??new Lp,this.fetchImpl=e.fetchImpl??Up(),this.webSocketFactory=e.webSocketFactory??(e=>new WebSocket(e)),this.pingIntervalMs=e.pingIntervalMs??Mp,this.connectTimeoutMs=e.connectTimeoutMs??Np}async start(){if(this.currentSession&&this.socket)return Ip({state:`leader`,session:this.currentSession,error:null}),this.currentSession;Ip({state:`connecting`,session:null,error:null}),this.currentSession=null;try{let e=await this.store.load(),t=e?.workerBaseUrl===this.options.workerBaseUrl?e:null,n=await this.attachWithRecovery(t);this.currentSession=n;let r=await this.openLeaderSocket(n.leaderWebSocketUrl);return this.socket=r,this.startPingLoop(r),Ip({state:`leader`,session:n,error:null}),Ap.info(`Leader joined tray`,{trayId:n.trayId,controllerId:n.controllerId,runtime:n.runtime}),n}catch(e){throw Ip({state:`error`,session:this.currentSession,error:e instanceof Error?e.message:String(e)}),e}}stop(){if(this.pingTimer&&=(clearInterval(this.pingTimer),null),this.socket){try{this.socket.close()}catch{}this.socket=null}this.currentSession=null,Ip({state:`inactive`,session:null,error:null})}async clearSession(){await this.store.clear()}sendControlMessage(e){if(!this.socket)throw Error(`Tray leader WebSocket is not connected`);this.socket.send(JSON.stringify(e))}async attachWithRecovery(e){try{return await this.claimLeaderSession(e)}catch(t){if(!e||!Vp(t))throw t;return Ap.warn(`Stored tray session is stale, creating a fresh tray`,{trayId:e.trayId,error:t instanceof Error?t.message:String(t)}),await this.store.clear(),this.claimLeaderSession(null)}}async claimLeaderSession(e){let t=e??await this.createTraySession(),n=await this.fetchJson(t.controllerUrl,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:t.controllerId,leaderKey:t.leaderKey,runtime:this.options.runtime})});if(n.role!==`leader`||!n.leaderKey||!n.websocket?.url)throw Error(`Tray attach did not return leader access for controller ${n.controllerId}`);let r={...t,trayId:n.trayId,controllerId:n.controllerId,leaderKey:n.leaderKey,leaderWebSocketUrl:n.websocket.url,runtime:this.options.runtime};return await this.store.save(r),r}async createTraySession(){let e=await this.fetchJson(p(this.options.workerBaseUrl,`tray`),{method:`POST`});return{workerBaseUrl:this.options.workerBaseUrl,trayId:e.trayId,createdAt:e.createdAt,controllerId:crypto.randomUUID(),controllerUrl:e.capabilities.controller.url,joinUrl:e.capabilities.join.url,webhookUrl:e.capabilities.webhook.url,runtime:this.options.runtime}}async openLeaderSocket(e){return await new Promise((t,n)=>{let r=this.webSocketFactory(e),i=!1,a=setTimeout(()=>{o(`Tray leader WebSocket timed out after ${this.connectTimeoutMs}ms waiting for leader.connected`);try{r.close(1e3,`leader.connected timeout`)}catch{}},this.connectTimeoutMs),o=e=>{i||(i=!0,clearTimeout(a),n(Error(e)))};r.addEventListener(`message`,e=>{let n=Hp(e.data);if(n){if(n.type===`leader.connected`){i||(i=!0,clearTimeout(a),t(r));return}if(n.type===`pong`){Ap.debug(`Tray leader heartbeat acknowledged`,{trayId:this.currentSession?.trayId});return}this.options.onControlMessage?.(n)}}),r.addEventListener(`close`,()=>o(`Tray leader WebSocket closed before leader.connected`)),r.addEventListener(`error`,()=>o(`Tray leader WebSocket failed before leader.connected`))})}startPingLoop(e){this.pingTimer&&clearInterval(this.pingTimer);let t=()=>{try{e.send(JSON.stringify({type:`ping`}))}catch{this.stop()}};t(),this.pingTimer=setInterval(t,this.pingIntervalMs),e.addEventListener(`close`,()=>this.stop()),e.addEventListener(`error`,()=>this.stop())}async fetchJson(e,t){let n=await this.fetchImpl(e,t);if(!n.ok)throw await Bp.fromResponse(n);return await n.json()}},Bp=class e extends Error{constructor(e,t,n){super(n),this.status=e,this.code=t,this.name=`LeaderTrayHttpError`}static async fromResponse(t){try{let n=await t.json();return new e(t.status,n.code??null,n.error??`Tray request failed (${t.status})`)}catch{return new e(t.status,null,`Tray request failed (${t.status})`)}}};function Vp(e){return e instanceof Bp&&[403,404,410].includes(e.status)}function Hp(e){if(typeof e!=`string`)return null;try{return JSON.parse(e)}catch{return null}}function Up(e=fetch){return typeof chrome<`u`&&chrome?.runtime?.id?e:async(t,n={})=>{let r=typeof t==`string`?t:t.toString();try{if(new URL(r).origin===window.location.origin)return e(r,{...n,cache:`no-store`})}catch{}let i=new Headers(n.headers);i.set(`X-Target-URL`,r);let a=await e(`/api/fetch-proxy`,{...n,headers:i,cache:`no-store`});if(a.status===400||a.status===502){let e=`Proxy error ${a.status}`;try{e=(await a.json()).error??e}catch{}throw Error(e)}return a}}var Wp=null;function Gp(e){Wp=e}function Kp(){return Wp?.()??[]}var qp=null;function Jp(e){qp=e}function Yp(){return qp??void 0}function Xp(){return{stdout:`host - display or manage the current tray host status
1224
+ `,stderr:``,exitCode:0}}function Np(e=`convert`){return z(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Mp();let r=[],i=[],a=0;for(;a<t.length;){let n=t[a];if(n===`-resize`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -resize\n`,exitCode:1};i.push({type:`resize`,value:t[a+1]}),a+=2}else if(n===`-rotate`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -rotate\n`,exitCode:1};i.push({type:`rotate`,value:t[a+1]}),a+=2}else if(n===`-crop`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -crop\n`,exitCode:1};i.push({type:`crop`,value:t[a+1]}),a+=2}else if(n===`-quality`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -quality\n`,exitCode:1};i.push({type:`quality`,value:t[a+1]}),a+=2}else if(n.startsWith(`-`))return{stdout:``,stderr:`${e}: unsupported option ${n}\n`,exitCode:1};else r.push(n),a++}if(r.length!==2)return{stdout:``,stderr:`${e}: expected exactly one input file and one output file\n`,exitCode:1};let o=r[0],s=r[1];try{let e=n.fs.resolvePath(n.cwd,o),t=await n.fs.readFileBuffer(e),r=await Ye(),a=null;if(await r.ImageMagick.read(t,async e=>{for(let t of i)switch(t.type){case`resize`:{let n=t.value.match(/^(\d+)%$/);if(n){let t=parseInt(n[1],10),r=Math.round(e.width*t/100),i=Math.round(e.height*t/100);e.resize(r,i)}else{let n=t.value.endsWith(`!`),i=(n?t.value.slice(0,-1):t.value).split(`x`);if(i.length===2){let t=parseInt(i[0],10),a=parseInt(i[1],10);if(n){let n=new r.MagickGeometry(t,a);n.ignoreAspectRatio=!0,e.resize(n)}else e.resize(t,a)}else throw Error(`Invalid resize format: ${t.value}`)}break}case`rotate`:{let n=parseFloat(t.value);if(isNaN(n))throw Error(`Invalid rotation degrees: ${t.value}`);e.rotate(n);break}case`crop`:{if(!t.value.match(/^(\d+)x(\d+)\+(\d+)\+(\d+)$/))throw Error(`Invalid crop format: ${t.value} (expected WxH+X+Y)`);let n=new r.MagickGeometry(t.value);e.crop(n);break}case`quality`:{let n=parseInt(t.value,10);if(isNaN(n)||n<0||n>100)throw Error(`Invalid quality: ${t.value} (must be 0-100)`);e.quality=n;break}}let t=jp(s);e.write(t,e=>{a=e})}),!a)throw Error(`Failed to generate output image`);let c=n.fs.resolvePath(n.cwd,s);return await n.fs.writeFile(c,a),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}var Pp=n(`tray-leader`),Fp=`leader-tray-session`,Ip=3e4,Lp=1e4,Rp={state:`inactive`,session:null,error:null};function zp(){return{...Rp,session:Rp.session?{...Rp.session}:null}}function Bp(e){Rp={...e,session:e.session?{...e.session}:null}}var Vp=class{constructor(e=Fp){this.key=e}async load(){return Hp(await Fe(this.key))}async save(e){await Ve(this.key,JSON.stringify(e))}async clear(){await Ve(this.key,``)}};function Hp(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t.workerBaseUrl!=`string`||typeof t.trayId!=`string`||typeof t.createdAt!=`string`||typeof t.controllerId!=`string`||typeof t.controllerUrl!=`string`||typeof t.joinUrl!=`string`||typeof t.webhookUrl!=`string`||typeof t.runtime!=`string`?null:{workerBaseUrl:t.workerBaseUrl,trayId:t.trayId,createdAt:t.createdAt,controllerId:t.controllerId,controllerUrl:t.controllerUrl,joinUrl:t.joinUrl,webhookUrl:t.webhookUrl,leaderKey:typeof t.leaderKey==`string`?t.leaderKey:void 0,leaderWebSocketUrl:typeof t.leaderWebSocketUrl==`string`?t.leaderWebSocketUrl:null,runtime:t.runtime}}catch{return null}}var Up=class{store;fetchImpl;webSocketFactory;pingIntervalMs;connectTimeoutMs;socket=null;pingTimer=null;currentSession=null;constructor(e){this.options=e,this.store=e.store??new Vp,this.fetchImpl=e.fetchImpl??qp(),this.webSocketFactory=e.webSocketFactory??(e=>new WebSocket(e)),this.pingIntervalMs=e.pingIntervalMs??Ip,this.connectTimeoutMs=e.connectTimeoutMs??Lp}async start(){if(this.currentSession&&this.socket)return Bp({state:`leader`,session:this.currentSession,error:null}),this.currentSession;Bp({state:`connecting`,session:null,error:null}),this.currentSession=null;try{let e=await this.store.load(),t=e?.workerBaseUrl===this.options.workerBaseUrl?e:null,n=await this.attachWithRecovery(t);this.currentSession=n;let r=await this.openLeaderSocket(n.leaderWebSocketUrl);return this.socket=r,this.startPingLoop(r),Bp({state:`leader`,session:n,error:null}),Pp.info(`Leader joined tray`,{trayId:n.trayId,controllerId:n.controllerId,runtime:n.runtime}),n}catch(e){throw Bp({state:`error`,session:this.currentSession,error:e instanceof Error?e.message:String(e)}),e}}stop(){if(this.pingTimer&&=(clearInterval(this.pingTimer),null),this.socket){try{this.socket.close()}catch{}this.socket=null}this.currentSession=null,Bp({state:`inactive`,session:null,error:null})}async clearSession(){await this.store.clear()}sendControlMessage(e){if(!this.socket)throw Error(`Tray leader WebSocket is not connected`);this.socket.send(JSON.stringify(e))}async attachWithRecovery(e){try{return await this.claimLeaderSession(e)}catch(t){if(!e||!Gp(t))throw t;return Pp.warn(`Stored tray session is stale, creating a fresh tray`,{trayId:e.trayId,error:t instanceof Error?t.message:String(t)}),await this.store.clear(),this.claimLeaderSession(null)}}async claimLeaderSession(e){let t=e??await this.createTraySession(),n=await this.fetchJson(t.controllerUrl,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:t.controllerId,leaderKey:t.leaderKey,runtime:this.options.runtime})});if(n.role!==`leader`||!n.leaderKey||!n.websocket?.url)throw Error(`Tray attach did not return leader access for controller ${n.controllerId}`);let r={...t,trayId:n.trayId,controllerId:n.controllerId,leaderKey:n.leaderKey,leaderWebSocketUrl:n.websocket.url,runtime:this.options.runtime};return await this.store.save(r),r}async createTraySession(){let e=await this.fetchJson(p(this.options.workerBaseUrl,`tray`),{method:`POST`});return{workerBaseUrl:this.options.workerBaseUrl,trayId:e.trayId,createdAt:e.createdAt,controllerId:crypto.randomUUID(),controllerUrl:e.capabilities.controller.url,joinUrl:e.capabilities.join.url,webhookUrl:e.capabilities.webhook.url,runtime:this.options.runtime}}async openLeaderSocket(e){return await new Promise((t,n)=>{let r=this.webSocketFactory(e),i=!1,a=setTimeout(()=>{o(`Tray leader WebSocket timed out after ${this.connectTimeoutMs}ms waiting for leader.connected`);try{r.close(1e3,`leader.connected timeout`)}catch{}},this.connectTimeoutMs),o=e=>{i||(i=!0,clearTimeout(a),n(Error(e)))};r.addEventListener(`message`,e=>{let n=Kp(e.data);if(n){if(n.type===`leader.connected`){i||(i=!0,clearTimeout(a),t(r));return}if(n.type===`pong`){Pp.debug(`Tray leader heartbeat acknowledged`,{trayId:this.currentSession?.trayId});return}this.options.onControlMessage?.(n)}}),r.addEventListener(`close`,()=>o(`Tray leader WebSocket closed before leader.connected`)),r.addEventListener(`error`,()=>o(`Tray leader WebSocket failed before leader.connected`))})}startPingLoop(e){this.pingTimer&&clearInterval(this.pingTimer);let t=()=>{try{e.send(JSON.stringify({type:`ping`}))}catch{this.stop()}};t(),this.pingTimer=setInterval(t,this.pingIntervalMs),e.addEventListener(`close`,()=>this.stop()),e.addEventListener(`error`,()=>this.stop())}async fetchJson(e,t){let n=await this.fetchImpl(e,t);if(!n.ok)throw await Wp.fromResponse(n);return await n.json()}},Wp=class e extends Error{constructor(e,t,n){super(n),this.status=e,this.code=t,this.name=`LeaderTrayHttpError`}static async fromResponse(t){try{let n=await t.json();return new e(t.status,n.code??null,n.error??`Tray request failed (${t.status})`)}catch{return new e(t.status,null,`Tray request failed (${t.status})`)}}};function Gp(e){return e instanceof Wp&&[403,404,410].includes(e.status)}function Kp(e){if(typeof e!=`string`)return null;try{return JSON.parse(e)}catch{return null}}function qp(e=fetch){return typeof chrome<`u`&&chrome?.runtime?.id?e:async(t,n={})=>{let r=typeof t==`string`?t:t.toString();try{if(new URL(r).origin===window.location.origin)return e(r,{...n,cache:`no-store`})}catch{}let i=new Headers(n.headers);i.set(`X-Target-URL`,r);let a=await e(`/api/fetch-proxy`,{...n,headers:i,cache:`no-store`});if(a.status===400||a.status===502){let e=`Proxy error ${a.status}`;try{e=(await a.json()).error??e}catch{}throw Error(e)}return a}}var Jp=null;function Yp(e){Jp=e}function Xp(){return Jp?.()??[]}var Zp=null;function Qp(e){Zp=e}function $p(){return Zp??void 0}function em(){return{stdout:`host - display or manage the current tray host status
1225
1225
 
1226
1226
  Usage: host [reset]
1227
1227
 
@@ -1229,22 +1229,22 @@ Shows the current tray state (leader or follower) and, when available, the join
1229
1229
 
1230
1230
  Subcommands:
1231
1231
  reset Disconnect all followers and create a fresh tray session with a new join URL
1232
- `,stderr:``,exitCode:0}}function Zp(e){if(e<60)return`${e}s ago`;let t=Math.floor(e/60);if(t<60)return`${t}m ago`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}h ago`:`${n}h ${r}m ago`}function Qp(e,t){let n=[`status: ${e.state}`];if(e.session?n.push(`join_url: ${e.session.joinUrl}`):n.push(`join_url: unavailable`),e.error&&n.push(`error: ${e.error}`),t.length>0){n.push(`followers:`);for(let e of t){let t=[e.runtimeId];if(e.runtime&&t.push(`(${e.runtime})`),e.connectedAt){let n=Math.round((Date.now()-new Date(e.connectedAt).getTime())/1e3);t.push(`connected ${Zp(n)}`)}n.push(` - ${t.join(` `)}`)}}return`${n.join(`
1233
- `)}\n`}function $p(e){let t=[`status: follower (${e.state})`];if(e.joinUrl&&t.push(`join_url: ${e.joinUrl}`),e.state===`connecting`){if(e.connectingSince!=null){let n=Math.round((Date.now()-e.connectingSince)/1e3);t.push(`connecting_for: ${Zp(n).replace(` ago`,``)}`)}e.attachAttempts>0&&t.push(`attach_attempts: ${e.attachAttempts}`),e.lastAttachCode&&t.push(`last_code: ${e.lastAttachCode}`)}if(e.state===`connected`&&e.lastPingTime!=null){let n=Math.round((Date.now()-e.lastPingTime)/1e3);t.push(`last_ping: ${n}s ago`)}return e.state===`reconnecting`&&e.reconnectAttempts>0&&t.push(`reconnect_attempts: ${e.reconnectAttempts}`),e.lastError&&t.push(`last_error: ${e.lastError}`),e.error&&t.push(`error: ${e.error}`),`${t.join(`
1234
- `)}\n`}function em(e={}){let t=e.getStatus??Fp,n=e.getFollowerStatus??m,r=e.getFollowers??Kp;return z(`host`,async i=>{if(i.includes(`--help`)||i.includes(`-h`))return Xp();if(i[0]===`reset`)return tm(n,t,e.resetTray??Yp());if(i.length>0)return{stdout:``,stderr:`host: unsupported arguments
1235
- `,exitCode:1};let a=n();return a.state===`inactive`?{stdout:Qp(t(),r()),stderr:``,exitCode:0}:{stdout:$p(a),stderr:``,exitCode:0}})}async function tm(e,t,n){if(e().state!==`inactive`)return{stdout:``,stderr:`host reset: only the leader can reset the tray session
1232
+ `,stderr:``,exitCode:0}}function tm(e){if(e<60)return`${e}s ago`;let t=Math.floor(e/60);if(t<60)return`${t}m ago`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}h ago`:`${n}h ${r}m ago`}function nm(e,t){let n=[`status: ${e.state}`];if(e.session?n.push(`join_url: ${e.session.joinUrl}`):n.push(`join_url: unavailable`),e.error&&n.push(`error: ${e.error}`),t.length>0){n.push(`followers:`);for(let e of t){let t=[e.runtimeId];if(e.runtime&&t.push(`(${e.runtime})`),e.connectedAt){let n=Math.round((Date.now()-new Date(e.connectedAt).getTime())/1e3);t.push(`connected ${tm(n)}`)}n.push(` - ${t.join(` `)}`)}}return`${n.join(`
1233
+ `)}\n`}function rm(e){let t=[`status: follower (${e.state})`];if(e.joinUrl&&t.push(`join_url: ${e.joinUrl}`),e.state===`connecting`){if(e.connectingSince!=null){let n=Math.round((Date.now()-e.connectingSince)/1e3);t.push(`connecting_for: ${tm(n).replace(` ago`,``)}`)}e.attachAttempts>0&&t.push(`attach_attempts: ${e.attachAttempts}`),e.lastAttachCode&&t.push(`last_code: ${e.lastAttachCode}`)}if(e.state===`connected`&&e.lastPingTime!=null){let n=Math.round((Date.now()-e.lastPingTime)/1e3);t.push(`last_ping: ${n}s ago`)}return e.state===`reconnecting`&&e.reconnectAttempts>0&&t.push(`reconnect_attempts: ${e.reconnectAttempts}`),e.lastError&&t.push(`last_error: ${e.lastError}`),e.error&&t.push(`error: ${e.error}`),`${t.join(`
1234
+ `)}\n`}function im(e={}){let t=e.getStatus??zp,n=e.getFollowerStatus??m,r=e.getFollowers??Xp;return z(`host`,async i=>{if(i.includes(`--help`)||i.includes(`-h`))return em();if(i[0]===`reset`)return am(n,t,e.resetTray??$p());if(i.length>0)return{stdout:``,stderr:`host: unsupported arguments
1235
+ `,exitCode:1};let a=n();return a.state===`inactive`?{stdout:nm(t(),r()),stderr:``,exitCode:0}:{stdout:rm(a),stderr:``,exitCode:0}})}async function am(e,t,n){if(e().state!==`inactive`)return{stdout:``,stderr:`host reset: only the leader can reset the tray session
1236
1236
  `,exitCode:1};let r=t();if(r.state!==`leader`&&r.state!==`error`)return{stdout:``,stderr:`host reset: no active tray session to reset
1237
1237
  `,exitCode:1};if(!n)return{stdout:``,stderr:`host reset: tray reset is not available in this environment
1238
1238
  `,exitCode:1};try{return{stdout:`Tray session reset. All followers disconnected.
1239
- `+Qp(await n(),[]),stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host reset: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function nm(){return{stdout:`imgcat - preview image and video files in the preview tab
1239
+ `+nm(await n(),[]),stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host reset: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function om(){return{stdout:`imgcat - preview image and video files in the preview tab
1240
1240
 
1241
1241
  Usage: imgcat <path> [path...]
1242
1242
 
1243
1243
  Options:
1244
1244
  -h, --help Show this help message
1245
- `,stderr:``,exitCode:0}}function rm(e={}){return z(`imgcat`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return nm();if(typeof window>`u`||typeof document>`u`)return{stdout:``,stderr:`imgcat: browser APIs are unavailable in this environment
1245
+ `,stderr:``,exitCode:0}}function sm(e={}){return z(`imgcat`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return om();if(typeof window>`u`||typeof document>`u`)return{stdout:``,stderr:`imgcat: browser APIs are unavailable in this environment
1246
1246
  `,exitCode:1};if(!e.onMediaPreview)return{stdout:``,stderr:`imgcat: terminal preview is unavailable
1247
- `,exitCode:1};let r=[];for(let e of t){let t=n.fs.resolvePath(n.cwd,e);if(!(await n.fs.stat(t)).isFile)return{stdout:``,stderr:`imgcat: not a file: ${e}\n`,exitCode:1};let a=i(t);if(!c(a))return{stdout:``,stderr:`imgcat: unsupported media type: ${e}\n`,exitCode:1};let o=await n.fs.readFileBuffer(t),s=new Uint8Array(o.byteLength);s.set(o),r.push({path:t,mimeType:a,bytes:s})}try{return await e.onMediaPreview(r),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`imgcat: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var im=`https://sql.js.org/dist/`,am=`https://cdn.jsdelivr.net/pyodide/v0.27.7/full/`,om=`v20.0.0-js-shim`,sm=`
1247
+ `,exitCode:1};let r=[];for(let e of t){let t=n.fs.resolvePath(n.cwd,e);if(!(await n.fs.stat(t)).isFile)return{stdout:``,stderr:`imgcat: not a file: ${e}\n`,exitCode:1};let a=i(t);if(!c(a))return{stdout:``,stderr:`imgcat: unsupported media type: ${e}\n`,exitCode:1};let o=await n.fs.readFileBuffer(t),s=new Uint8Array(o.byteLength);s.set(o),r.push({path:t,mimeType:a,bytes:s})}try{return await e.onMediaPreview(r),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`imgcat: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var cm=`https://sql.js.org/dist/`,lm=`https://cdn.jsdelivr.net/pyodide/v0.27.7/full/`,um=`v20.0.0-js-shim`,dm=`
1248
1248
  import sys
1249
1249
  import traceback
1250
1250
 
@@ -1264,10 +1264,10 @@ except SystemExit as exc:
1264
1264
  except BaseException:
1265
1265
  traceback.print_exc()
1266
1266
  __slicc_exit_code = 1
1267
- `,cm=null,lm=null,um=Object.create(null),dm=class extends Error{constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function fm(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function pm(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}function mm(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function hm(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function gm(e,t){return e===`/`?t.startsWith(`/`):t===e||t.startsWith(`${e}/`)}function _m(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function vm(e){return e==null?``:e instanceof Uint8Array?`x'${_m(e)}'`:String(e)}function ym(e){return i(e)}function bm(e){let t=typeof chrome<`u`&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost:5710`}${n}`}function xm(e){return e.length===0||e.startsWith(`/`)?!1:!e.split(`/`).some(e=>e===`..`)}function Sm(e,t){return R(`${e}/${t}`)}function Cm(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function wm(e,t){let n=import.meta.resolve;if(typeof n==`function`)try{return new URL(`./`,n(e))}catch{}return new URL(t,import.meta.url)}async function Tm(){return cm||=(async()=>{let t=(await v(()=>import(`./sql-wasm-Cx-UtEsl.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1,2]))).default,n=typeof window>`u`?wm(`sql.js/dist/sql-wasm.js`,`../../../../../node_modules/sql.js/dist/`).toString():im;return t({locateFile:e=>`${n}${e}`})})(),cm}var Em=typeof chrome<`u`&&!!chrome?.runtime?.id;async function Dm(){return lm||=(async()=>{let{loadPyodide:e}=await v(async()=>{let{loadPyodide:e}=await import(`./pyodide-CDyS-YOW.js`);return{loadPyodide:e}},__vite__mapDeps([3,1,4])),t;return t=typeof window>`u`?decodeURIComponent(wm(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname):Em?chrome.runtime.getURL(`pyodide/`):am,e({indexURL:t,fullStdLib:!1})})(),lm}var Om=new Set([`http`,`https`,`net`,`tls`,`dgram`,`dns`,`cluster`,`worker_threads`,`child_process`,`crypto`,`os`,`stream`,`zlib`,`vm`,`v8`,`perf_hooks`,`readline`,`repl`,`tty`,`inspector`]);function km(e){let t=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,n=new Set,r;for(;(r=t.exec(e))!==null;)n.add(r[2]);return[...n]}function Am(){return{stdout:`usage: node -e <code> [args...]
1268
- `,stderr:``,exitCode:0}}function jm(){return{stdout:`${om}\n`,stderr:``,exitCode:0}}function Mm(){return z(`node`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return Am();if(e.includes(`--version`)||e.includes(`-v`))return jm();let n=``,r=`<stdin>`,i=[`node`];if(e.length>0&&(e[0]===`-e`||e[0]===`--eval`)){if(!e[1])return{stdout:``,stderr:`node: option requires an argument -- eval
1267
+ `,fm=null,pm=null,mm=Object.create(null),hm=class extends Error{constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function gm(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function _m(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}function vm(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function ym(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function bm(e,t){return e===`/`?t.startsWith(`/`):t===e||t.startsWith(`${e}/`)}function xm(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Sm(e){return e==null?``:e instanceof Uint8Array?`x'${xm(e)}'`:String(e)}function Cm(e){return i(e)}function wm(e){let t=typeof chrome<`u`&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost:5710`}${n}`}function Tm(e){return e.length===0||e.startsWith(`/`)?!1:!e.split(`/`).some(e=>e===`..`)}function Em(e,t){return R(`${e}/${t}`)}function Dm(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Om(e,t){let n=import.meta.resolve;if(typeof n==`function`)try{return new URL(`./`,n(e))}catch{}return new URL(t,import.meta.url)}async function km(){return fm||=(async()=>{let t=(await v(()=>import(`./sql-wasm-Cx-UtEsl.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1,2]))).default,n=typeof window>`u`?Om(`sql.js/dist/sql-wasm.js`,`../../../../../node_modules/sql.js/dist/`).toString():cm;return t({locateFile:e=>`${n}${e}`})})(),fm}var Am=typeof chrome<`u`&&!!chrome?.runtime?.id;async function jm(){return pm||=(async()=>{let{loadPyodide:e}=await v(async()=>{let{loadPyodide:e}=await import(`./pyodide-CDyS-YOW.js`);return{loadPyodide:e}},__vite__mapDeps([3,1,4])),t;return t=typeof window>`u`?decodeURIComponent(Om(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname):Am?chrome.runtime.getURL(`pyodide/`):lm,e({indexURL:t,fullStdLib:!1})})(),pm}var Mm=new Set([`http`,`https`,`net`,`tls`,`dgram`,`dns`,`cluster`,`worker_threads`,`child_process`,`crypto`,`os`,`stream`,`zlib`,`vm`,`v8`,`perf_hooks`,`readline`,`repl`,`tty`,`inspector`]);function Nm(e){let t=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,n=new Set,r;for(;(r=t.exec(e))!==null;)n.add(r[2]);return[...n]}function Pm(){return{stdout:`usage: node -e <code> [args...]
1268
+ `,stderr:``,exitCode:0}}function Fm(){return{stdout:`${um}\n`,stderr:``,exitCode:0}}function Im(){return z(`node`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return Pm();if(e.includes(`--version`)||e.includes(`-v`))return Fm();let n=``,r=`<stdin>`,i=[`node`];if(e.length>0&&(e[0]===`-e`||e[0]===`--eval`)){if(!e[1])return{stdout:``,stderr:`node: option requires an argument -- eval
1269
1269
  `,exitCode:9};n=e[1],r=`[eval]`,i=[`node`,...e.slice(2)]}else if(e.length>0&&!e[0].startsWith(`-`)){let a=e[0],o=t.fs.resolvePath(t.cwd,a);if(!await t.fs.exists(o))return{stdout:``,stderr:`node: cannot find module '${a}'\n`,exitCode:1};n=await t.fs.readFile(o),r=a,i=[`node`,a,...e.slice(1)]}else if(t.stdin.trim().length>0)n=t.stdin,r=`<stdin>`,i=[`node`];else if(e.length>0)return{stdout:``,stderr:`node: unsupported option '${e[0]}'\n`,exitCode:9};else return{stdout:``,stderr:`node: REPL mode is not supported in this environment; use node -e "code"
1270
- `,exitCode:9};let a=[],o=[],s=e=>{a.push(typeof e==`string`?e:String(e))},c=e=>{o.push(typeof e==`string`?e:String(e))},l={log:(...e)=>s(`${e.map(Cm).join(` `)}\n`),info:(...e)=>s(`${e.map(Cm).join(` `)}\n`),warn:(...e)=>c(`${e.map(Cm).join(` `)}\n`),error:(...e)=>c(`${e.map(Cm).join(` `)}\n`)},u={argv:i,env:Object.fromEntries(t.env.entries()),cwd:()=>t.cwd,exit:e=>{throw new dm(Number.isFinite(e)?Number(e):0)},stdout:{write:s},stderr:{write:c}},d={readFile:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readFile(n)},readFileBinary:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readFileBuffer(n)},writeFile:async(e,n)=>{let r=t.fs.resolvePath(t.cwd,e);await t.fs.writeFile(r,n)},writeFileBinary:async(e,n)=>{let r=t.fs.resolvePath(t.cwd,e),i=new Uint8Array(n.byteLength);i.set(n),await t.fs.writeFile(r,i)},readDir:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readdir(n)},exists:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.exists(n)},fetchToFile:async(e,n)=>{if(typeof fetch>`u`)throw Error(`fetch is not available in this runtime`);let r=await fetch(e);if(!r.ok)throw Error(`fetch ${r.status} ${r.statusText}`);let i=new Uint8Array(await r.arrayBuffer()),a=t.fs.resolvePath(t.cwd,n);return await t.fs.writeFile(a,i),i.byteLength}},f=async e=>{if(!t.exec)throw Error(`exec is not available in this runtime`);let n=await t.exec(e,{cwd:t.cwd});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}},p=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!p){let e=km(n),t=new Set([`fs`,`process`,`buffer`]),r=e.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!t.has(e)&&!Om.has(e)),i=um.__requireCache??=Object.create(null),a=r.filter(e=>!(e in i));if(a.length>0){let e=await Promise.allSettled(a.map(async e=>{let t=await v(()=>import(`https://esm.sh/`+e),[]);i[e]=t&&typeof t==`object`&&`default`in t?t.default:t}));for(let t=0;t<e.length;t++)if(e[t].status===`rejected`){let n=e[t].reason;c(`Warning: failed to pre-load require('${a[t]}'): ${n instanceof Error?n.message:String(n)}\n`)}}}let m=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return d;if(t===`process`)return u;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=um.__requireCache;if(t&&`path`in t)return t.path;if(t&&e in t)return t[e];throw Error(`require('${e}'): path module not pre-loaded. Add require('path') as a static import.`)}if(Om.has(t))throw Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${{http:` Use fetch() instead.`,https:` Use fetch() instead.`,child_process:` Use exec() which is available as a shell bridge.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`}[t]||``}`);let n=um.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal or await import('https://esm.sh/${e}') directly.`)},h={exports:{},filename:r};try{if(p){let e=`
1270
+ `,exitCode:9};let a=[],o=[],s=e=>{a.push(typeof e==`string`?e:String(e))},c=e=>{o.push(typeof e==`string`?e:String(e))},l={log:(...e)=>s(`${e.map(Dm).join(` `)}\n`),info:(...e)=>s(`${e.map(Dm).join(` `)}\n`),warn:(...e)=>c(`${e.map(Dm).join(` `)}\n`),error:(...e)=>c(`${e.map(Dm).join(` `)}\n`)},u={argv:i,env:Object.fromEntries(t.env.entries()),cwd:()=>t.cwd,exit:e=>{throw new hm(Number.isFinite(e)?Number(e):0)},stdout:{write:s},stderr:{write:c}},d={readFile:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readFile(n)},readFileBinary:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readFileBuffer(n)},writeFile:async(e,n)=>{let r=t.fs.resolvePath(t.cwd,e);await t.fs.writeFile(r,n)},writeFileBinary:async(e,n)=>{let r=t.fs.resolvePath(t.cwd,e),i=new Uint8Array(n.byteLength);i.set(n),await t.fs.writeFile(r,i)},readDir:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readdir(n)},exists:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.exists(n)},fetchToFile:async(e,n)=>{if(typeof fetch>`u`)throw Error(`fetch is not available in this runtime`);let r=await fetch(e);if(!r.ok)throw Error(`fetch ${r.status} ${r.statusText}`);let i=new Uint8Array(await r.arrayBuffer()),a=t.fs.resolvePath(t.cwd,n);return await t.fs.writeFile(a,i),i.byteLength}},f=async e=>{if(!t.exec)throw Error(`exec is not available in this runtime`);let n=await t.exec(e,{cwd:t.cwd});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}},p=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!p){let e=Nm(n),t=new Set([`fs`,`process`,`buffer`]),r=e.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!t.has(e)&&!Mm.has(e)),i=mm.__requireCache??=Object.create(null),a=r.filter(e=>!(e in i));if(a.length>0){let e=await Promise.allSettled(a.map(async e=>{let t=await v(()=>import(`https://esm.sh/`+e),[]);i[e]=t&&typeof t==`object`&&`default`in t?t.default:t}));for(let t=0;t<e.length;t++)if(e[t].status===`rejected`){let n=e[t].reason;c(`Warning: failed to pre-load require('${a[t]}'): ${n instanceof Error?n.message:String(n)}\n`)}}}let m=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return d;if(t===`process`)return u;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=mm.__requireCache;if(t&&`path`in t)return t.path;if(t&&e in t)return t[e];throw Error(`require('${e}'): path module not pre-loaded. Add require('path') as a static import.`)}if(Mm.has(t))throw Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${{http:` Use fetch() instead.`,https:` Use fetch() instead.`,child_process:` Use exec() which is available as a shell bridge.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`}[t]||``}`);let n=mm.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal or await import('https://esm.sh/${e}') directly.`)},h={exports:{},filename:r};try{if(p){let e=`
1271
1271
  const __stdout = [];
1272
1272
  const __stderr = [];
1273
1273
  const __origConsole = { log: console.log, error: console.error, warn: console.warn, info: console.info };
@@ -1372,17 +1372,17 @@ except BaseException:
1372
1372
  console.info = __origConsole.info;
1373
1373
  return { stdout: __stdout.join(''), stderr: __stderr.join('') };
1374
1374
  `,r=document.querySelector(`iframe[data-js-tool]`);r||(r=document.createElement(`iframe`),r.style.display=`none`,r.dataset.jsTool=`true`,r.src=chrome.runtime.getURL(`sandbox.html`),document.body.appendChild(r),await new Promise(e=>{r.addEventListener(`load`,()=>e(),{once:!0})}));let a=`node-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=e=>{let n=e.data;!n||n.type!==`vfs`||(async()=>{try{let e,i=n.args?.[0]?t.fs.resolvePath(t.cwd,n.args[0]):n.args?.[0];switch(n.op){case`readFile`:e=await t.fs.readFile(i);break;case`readFileBinary`:e=await t.fs.readFileBuffer(i);break;case`writeFile`:await t.fs.writeFile(i,n.args[1]),e=!0;break;case`writeFileBinary`:await t.fs.writeFile(i,n.binaryData??new Uint8Array),e=!0;break;case`readDir`:e=await t.fs.readdir(i);break;case`exists`:e=await t.fs.exists(i);break;case`stat`:{let n=await t.fs.stat(i);e={isDirectory:n.isDirectory,isFile:n.isFile,size:n.size};break}case`mkdir`:await t.fs.mkdir(i,{recursive:!0}),e=!0;break;case`rm`:await t.fs.rm(i,{recursive:!0}),e=!0;break}r.contentWindow.postMessage({type:`vfs_response`,id:n.id,result:e},`*`)}catch(e){let t=e instanceof Error?e.message:String(e);r.contentWindow.postMessage({type:`vfs_response`,id:n.id,error:t},`*`)}})()};window.addEventListener(`message`,o);let s=e=>{let t=e.data;!t||t.type!==`shell_exec`||(async()=>{try{let e=await f(t.command);r.contentWindow.postMessage({type:`shell_exec_response`,id:t.id,result:e},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);r.contentWindow.postMessage({type:`shell_exec_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,s);let c=e=>{let t=e.data;!t||t.type!==`fetch_proxy`||(async()=>{try{let e={method:t.init?.method??`GET`,cache:`no-store`};t.init?.headers&&(e.headers=t.init.headers),t.init?.body&&![`GET`,`HEAD`].includes(e.method)&&(e.body=t.init.body);let n=await fetch(t.url,e),i=await n.arrayBuffer(),a={};n.headers.forEach((e,t)=>{a[t]=e}),r.contentWindow.postMessage({type:`fetch_proxy_response`,id:t.id,status:n.status,statusText:n.statusText,headers:a,body:new Uint8Array(i)},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);r.contentWindow.postMessage({type:`fetch_proxy_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,c);let l=await new Promise((t,n)=>{let i,o=e=>{if(e.data?.type===`exec_result`&&e.data.id===a)if(window.removeEventListener(`message`,o),clearTimeout(i),e.data.error)t({stdout:``,stderr:e.data.error+`
1375
- `});else try{let n=JSON.parse(e.data.result);t({stdout:n.stdout||``,stderr:n.stderr||``})}catch{t({stdout:e.data.result||``,stderr:``})}};i=setTimeout(()=>{window.removeEventListener(`message`,o),n(Error(`node eval timed out (30s)`))},3e4),window.addEventListener(`message`,o),r.contentWindow.postMessage({type:`exec`,id:a,code:e},`*`)});return window.removeEventListener(`message`,o),window.removeEventListener(`message`,s),window.removeEventListener(`message`,c),{stdout:l.stdout,stderr:l.stderr,exitCode:+!!l.stderr}}let e=Object.getPrototypeOf(async function(){}).constructor;return await new e(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${n}`)(d,u,l,m,h,h.exports,um,f),{stdout:a.join(``),stderr:o.join(``),exitCode:0}}catch(e){if(e instanceof dm)return{stdout:a.join(``),stderr:o.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:a.join(``),stderr:`${o.join(``)}${t}\n`,exitCode:1}}})}var Nm=[`--download`,`-d`,`--view`,`-v`];function Pm(){return{stdout:`usage: open [--download|-d] [--view|-v] <url|path> [url|path...]
1375
+ `});else try{let n=JSON.parse(e.data.result);t({stdout:n.stdout||``,stderr:n.stderr||``})}catch{t({stdout:e.data.result||``,stderr:``})}};i=setTimeout(()=>{window.removeEventListener(`message`,o),n(Error(`node eval timed out (30s)`))},3e4),window.addEventListener(`message`,o),r.contentWindow.postMessage({type:`exec`,id:a,code:e},`*`)});return window.removeEventListener(`message`,o),window.removeEventListener(`message`,s),window.removeEventListener(`message`,c),{stdout:l.stdout,stderr:l.stderr,exitCode:+!!l.stderr}}let e=Object.getPrototypeOf(async function(){}).constructor;return await new e(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${n}`)(d,u,l,m,h,h.exports,mm,f),{stdout:a.join(``),stderr:o.join(``),exitCode:0}}catch(e){if(e instanceof hm)return{stdout:a.join(``),stderr:o.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:a.join(``),stderr:`${o.join(``)}${t}\n`,exitCode:1}}})}var Lm=[`--download`,`-d`,`--view`,`-v`];function Rm(){return{stdout:`usage: open [--download|-d] [--view|-v] <url|path> [url|path...]
1376
1376
 
1377
1377
  VFS paths are served in a new browser tab via the preview service worker.
1378
1378
  URLs (http/https/etc.) are opened directly in a new tab.
1379
1379
  For app directories with a default entry file, prefer serve <dir>.
1380
1380
  --download, -d Force download instead of opening in a tab.
1381
1381
  --view, -v Return image inline so the agent can see it.
1382
- `,stderr:``,exitCode:0}}function Fm(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function Im(){return z(`open`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Pm();if(typeof window>`u`||typeof document>`u`)return{stdout:``,stderr:`open: browser APIs are unavailable in this environment
1383
- `,exitCode:1};let n=e.includes(`--download`)||e.includes(`-d`),r=e.includes(`--view`)||e.includes(`-v`),i=e.filter(e=>!Nm.includes(e));if(i.length===0)return Pm();let a=[];for(let e of i){if(hm(e)){window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${e}`);continue}let i=t.fs.resolvePath(t.cwd,e);if(i.endsWith(`.shtml`)){let e=typeof window<`u`?window.__slicc_sprinkleManager:void 0;if(e){let t=(i.split(`/`).pop()??``).replace(/\.shtml$/,``);try{await e.open(t),a.push(`opened sprinkle ${t} from ${i}`)}catch(e){return{stdout:``,stderr:`open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}else{let e=bm(i);window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${i} → ${e}`)}continue}if(r){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 o=ym(i),s=Fm(new Uint8Array(r));a.push(`${i} (${Math.round(r.byteLength/1024)} KB)\n<img:data:${o};base64,${s}>`)}else if(n){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 o=new Uint8Array(r.byteLength);o.set(r);let s=new Blob([o.buffer],{type:ym(i)}),c=URL.createObjectURL(s),l=document.createElement(`a`);l.href=c,l.download=fm(i)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),a.push(`downloaded ${i}`)}else{let e=bm(i);window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${i} → ${e}`)}}return{stdout:a.join(`
1382
+ `,stderr:``,exitCode:0}}function zm(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function Bm(){return z(`open`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Rm();if(typeof window>`u`||typeof document>`u`)return{stdout:``,stderr:`open: browser APIs are unavailable in this environment
1383
+ `,exitCode:1};let n=e.includes(`--download`)||e.includes(`-d`),r=e.includes(`--view`)||e.includes(`-v`),i=e.filter(e=>!Lm.includes(e));if(i.length===0)return Rm();let a=[];for(let e of i){if(ym(e)){window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${e}`);continue}let i=t.fs.resolvePath(t.cwd,e);if(i.endsWith(`.shtml`)){let e=typeof window<`u`?window.__slicc_sprinkleManager:void 0;if(e){let t=(i.split(`/`).pop()??``).replace(/\.shtml$/,``);try{await e.open(t),a.push(`opened sprinkle ${t} from ${i}`)}catch(e){return{stdout:``,stderr:`open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}else{let e=wm(i);window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${i} → ${e}`)}continue}if(r){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 o=Cm(i),s=zm(new Uint8Array(r));a.push(`${i} (${Math.round(r.byteLength/1024)} KB)\n<img:data:${o};base64,${s}>`)}else if(n){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 o=new Uint8Array(r.byteLength);o.set(r);let s=new Blob([o.buffer],{type:Cm(i)}),c=URL.createObjectURL(s),l=document.createElement(`a`);l.href=c,l.download=gm(i)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),a.push(`downloaded ${i}`)}else{let e=wm(i);window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${i} → ${e}`)}}return{stdout:a.join(`
1384
1384
  `)+`
1385
- `,stderr:``,exitCode:0}})}var Lm=null,Rm=null;async function zm(){return Lm||=v(()=>import(`./es-DlWKrNhH.js`),__vite__mapDeps([5,1,6,2])),Lm}async function Bm(){return Rm||=v(()=>import(`./dist-B3JYrjq2.js`),__vite__mapDeps([7,4])),Rm}function Vm(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 Hm(e){let{range:t,rotation:n}=Vm(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 Um(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 Wm(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
1385
+ `,stderr:``,exitCode:0}})}var Vm=null,Hm=null;async function Um(){return Vm||=v(()=>import(`./es-DlWKrNhH.js`),__vite__mapDeps([5,1,6,2])),Vm}async function Wm(){return Hm||=v(()=>import(`./dist-B3JYrjq2.js`),__vite__mapDeps([7,4])),Hm}function Gm(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 Km(e){let{range:t,rotation:n}=Gm(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 qm(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 Jm(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
1386
1386
 
1387
1387
  Operations:
1388
1388
  dump_data Print metadata (page count, title, author, etc.)
@@ -1406,14 +1406,14 @@ Page ranges:
1406
1406
  1-endright Pages 1 to end, rotated 90° clockwise
1407
1407
  3left Page 3 rotated 270° (counterclockwise)
1408
1408
  1-5down Pages 1-5 rotated 180°
1409
- `,stderr:``,exitCode:0}}function Gm(e=`pdftk`){return z(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Wm();try{let r=[],i=0;for(;i<t.length;){let e=t[i],a=e.match(/^([A-Z])=(.+)$/);if(a){let e=a[1],t=n.fs.resolvePath(n.cwd,a[2]);r.push({handle:e,path:t}),i++;continue}if([`dump_data`,`dump_data_utf8`,`cat`,`rotate`].includes(e))break;if(!e.startsWith(`-`)){let t=n.fs.resolvePath(n.cwd,e);r.push({handle:``,path:t}),i++;continue}break}if(r.length===0)return{stdout:``,stderr:`${e}: no input PDF specified\n`,exitCode:1};let a=t[i];if(i++,!a)return{stdout:``,stderr:`${e}: no operation specified\n`,exitCode:1};if(a===`dump_data`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data only supports a single input file\n`,exitCode:1};let t=await zm(),i=await n.fs.readFileBuffer(r[0].path),a=await t.PDFDocument.load(i),o=[];o.push(`NumberOfPages: ${a.getPageCount()}`);let s=a.getTitle();s&&o.push(`InfoBegin`),s&&o.push(`InfoKey: Title`),s&&o.push(`InfoValue: ${s}`);let c=a.getAuthor();c&&o.push(`InfoBegin`),c&&o.push(`InfoKey: Author`),c&&o.push(`InfoValue: ${c}`);let l=a.getCreator();l&&o.push(`InfoBegin`),l&&o.push(`InfoKey: Creator`),l&&o.push(`InfoValue: ${l}`);let u=a.getProducer();return u&&o.push(`InfoBegin`),u&&o.push(`InfoKey: Producer`),u&&o.push(`InfoValue: ${u}`),{stdout:o.join(`
1409
+ `,stderr:``,exitCode:0}}function Ym(e=`pdftk`){return z(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Jm();try{let r=[],i=0;for(;i<t.length;){let e=t[i],a=e.match(/^([A-Z])=(.+)$/);if(a){let e=a[1],t=n.fs.resolvePath(n.cwd,a[2]);r.push({handle:e,path:t}),i++;continue}if([`dump_data`,`dump_data_utf8`,`cat`,`rotate`].includes(e))break;if(!e.startsWith(`-`)){let t=n.fs.resolvePath(n.cwd,e);r.push({handle:``,path:t}),i++;continue}break}if(r.length===0)return{stdout:``,stderr:`${e}: no input PDF specified\n`,exitCode:1};let a=t[i];if(i++,!a)return{stdout:``,stderr:`${e}: no operation specified\n`,exitCode:1};if(a===`dump_data`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data only supports a single input file\n`,exitCode:1};let t=await Um(),i=await n.fs.readFileBuffer(r[0].path),a=await t.PDFDocument.load(i),o=[];o.push(`NumberOfPages: ${a.getPageCount()}`);let s=a.getTitle();s&&o.push(`InfoBegin`),s&&o.push(`InfoKey: Title`),s&&o.push(`InfoValue: ${s}`);let c=a.getAuthor();c&&o.push(`InfoBegin`),c&&o.push(`InfoKey: Author`),c&&o.push(`InfoValue: ${c}`);let l=a.getCreator();l&&o.push(`InfoBegin`),l&&o.push(`InfoKey: Creator`),l&&o.push(`InfoValue: ${l}`);let u=a.getProducer();return u&&o.push(`InfoBegin`),u&&o.push(`InfoKey: Producer`),u&&o.push(`InfoValue: ${u}`),{stdout:o.join(`
1410
1410
  `)+`
1411
- `,stderr:``,exitCode:0}}if(a===`dump_data_utf8`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data_utf8 only supports a single input file\n`,exitCode:1};let t=await Bm(),i=await n.fs.readFileBuffer(r[0].path);return{stdout:(await t.extractText(i)).text+`
1412
- `,stderr:``,exitCode:0}}if(a===`cat`){let a=await zm(),o=await a.PDFDocument.create(),s=t.slice(i),c=s.indexOf(`output`);if(c===-1)return{stdout:``,stderr:`${e}: cat operation requires 'output <filename>'\n`,exitCode:1};let l=s.slice(0,c),u=s[c+1];if(!u)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let d=n.fs.resolvePath(n.cwd,u),f=new Map;for(let e of r){let t=await n.fs.readFileBuffer(e.path),r=await a.PDFDocument.load(t),i=e.handle||`default`;f.set(i,r)}for(let t of l){if(/^[A-Z]$/.test(t)){let n=f.get(t);if(!n)return{stdout:``,stderr:`${e}: unknown handle '${t}'\n`,exitCode:1};let r=n.getPageCount(),i=Array.from({length:r},(e,t)=>t);(await o.copyPages(n,i)).forEach(e=>o.addPage(e));continue}let n=f.get(r[0].handle||`default`);if(!n)return{stdout:``,stderr:`${e}: no default input document\n`,exitCode:1};let i=n.getPageCount(),s=Hm(t),c=Um(s,i).map(e=>e-1),l=await o.copyPages(n,c);for(let e of l)s.rotation&&e.setRotation(a.degrees(s.rotation)),o.addPage(e)}let p=await o.save();return await n.fs.writeFile(d,p),{stdout:`Created ${u}\n`,stderr:``,exitCode:0}}if(a===`rotate`){if(r.length>1)return{stdout:``,stderr:`${e}: rotate only supports a single input file\n`,exitCode:1};let a=await zm(),o=await n.fs.readFileBuffer(r[0].path),s=await a.PDFDocument.load(o),c=t.slice(i),l=c.indexOf(`output`);if(l===-1)return{stdout:``,stderr:`${e}: rotate operation requires 'output <filename>'\n`,exitCode:1};let u=c.slice(0,l),d=c[l+1];if(!d)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let f=n.fs.resolvePath(n.cwd,d),p=s.getPageCount(),m=new Map;for(let t of u){let n=Hm(t);if(!n.rotation)return{stdout:``,stderr:`${e}: rotation suffix required (right/left/down) for range '${t}'\n`,exitCode:1};let r=Um(n,p);for(let e of r)m.set(e-1,n.rotation)}let h=s.getPages();for(let[e,t]of m.entries()){let n=h[e],r=(n.getRotation().angle+t)%360;n.setRotation(a.degrees(r))}let g=await s.save();return await n.fs.writeFile(f,g),{stdout:`Created ${d}\n`,stderr:``,exitCode:0}}return{stdout:``,stderr:`${e}: unknown operation '${a}'\n`,exitCode:1}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}async function Km(e,t,n){let r=t.FS;function i(e){try{r.stat(e)}catch{r.mkdirTree(e)}}async function a(t){i(t);let n;try{n=await e.readdir(t)}catch{return}for(let o of n){let n=t===`/`?`/${o}`:`${t}/${o}`;try{if((await e.stat(n)).isDirectory)await a(n);else{let a=await e.readFile(n);i(t),r.writeFile(n,a)}}catch{}}}for(let e of n)await a(e)}async function qm(e,t,n){let r=t.FS;async function i(t){let n;try{n=r.readdir(t).filter(e=>e!==`.`&&e!==`..`)}catch{return}for(let a of n){let n=t===`/`?`/${a}`:`${t}/${a}`;try{let a=r.stat(n);if(r.isDir(a.mode))await e.mkdir(n,{recursive:!0}),await i(n);else{let i=new TextDecoder().decode(r.readFile(n));await e.mkdir(t,{recursive:!0}),await e.writeFile(n,i)}}catch{}}}for(let e of n)await i(e)}function Jm(){return{stdout:`usage: python3 [-c code | script.py] [args...]
1413
- `,stderr:``,exitCode:0}}function Ym(){return{stdout:`Python 3.12 (Pyodide)
1414
- `,stderr:``,exitCode:0}}function Xm(e){return z(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return Jm();if(t.includes(`--version`)||t.includes(`-V`))return Ym();let r=``,i=`<stdin>`,a=[`python3`];if(t[0]===`-c`){if(!t[1])return{stdout:``,stderr:`${e}: option requires an argument -- 'c'\n`,exitCode:2};r=t[1],i=`-c`,a=[`-c`,...t.slice(2)]}else if(t.length>0&&!t[0].startsWith(`-`)){let o=t[0],s=n.fs.resolvePath(n.cwd,o);if(!await n.fs.exists(s))return{stdout:``,stderr:`${e}: can't open file '${o}': [Errno 2] No such file or directory\n`,exitCode:2};r=await n.fs.readFile(s),i=o,a=[o,...t.slice(1)]}else if(n.stdin.trim().length>0)r=n.stdin,i=`<stdin>`,a=[`<stdin>`];else if(t.length>0)return{stdout:``,stderr:`${e}: unsupported option '${t[0]}'\n`,exitCode:2};else return{stdout:``,stderr:`${e}: no input provided (use -c CODE, script path, or stdin)\n`,exitCode:2};try{let e=await Dm(),t=[],o=[],s=[n.cwd,`/tmp`];if(i!==`<stdin>`&&i!==`[eval]`){let e=i.includes(`/`)?i.slice(0,i.lastIndexOf(`/`)):n.cwd;s.includes(e)||s.push(e)}await Km(n.fs,e,s);try{e.FS.chdir(n.cwd)}catch{}e.setStdout({batched:e=>t.push(e+`
1411
+ `,stderr:``,exitCode:0}}if(a===`dump_data_utf8`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data_utf8 only supports a single input file\n`,exitCode:1};let t=await Wm(),i=await n.fs.readFileBuffer(r[0].path);return{stdout:(await t.extractText(i)).text+`
1412
+ `,stderr:``,exitCode:0}}if(a===`cat`){let a=await Um(),o=await a.PDFDocument.create(),s=t.slice(i),c=s.indexOf(`output`);if(c===-1)return{stdout:``,stderr:`${e}: cat operation requires 'output <filename>'\n`,exitCode:1};let l=s.slice(0,c),u=s[c+1];if(!u)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let d=n.fs.resolvePath(n.cwd,u),f=new Map;for(let e of r){let t=await n.fs.readFileBuffer(e.path),r=await a.PDFDocument.load(t),i=e.handle||`default`;f.set(i,r)}for(let t of l){if(/^[A-Z]$/.test(t)){let n=f.get(t);if(!n)return{stdout:``,stderr:`${e}: unknown handle '${t}'\n`,exitCode:1};let r=n.getPageCount(),i=Array.from({length:r},(e,t)=>t);(await o.copyPages(n,i)).forEach(e=>o.addPage(e));continue}let n=f.get(r[0].handle||`default`);if(!n)return{stdout:``,stderr:`${e}: no default input document\n`,exitCode:1};let i=n.getPageCount(),s=Km(t),c=qm(s,i).map(e=>e-1),l=await o.copyPages(n,c);for(let e of l)s.rotation&&e.setRotation(a.degrees(s.rotation)),o.addPage(e)}let p=await o.save();return await n.fs.writeFile(d,p),{stdout:`Created ${u}\n`,stderr:``,exitCode:0}}if(a===`rotate`){if(r.length>1)return{stdout:``,stderr:`${e}: rotate only supports a single input file\n`,exitCode:1};let a=await Um(),o=await n.fs.readFileBuffer(r[0].path),s=await a.PDFDocument.load(o),c=t.slice(i),l=c.indexOf(`output`);if(l===-1)return{stdout:``,stderr:`${e}: rotate operation requires 'output <filename>'\n`,exitCode:1};let u=c.slice(0,l),d=c[l+1];if(!d)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let f=n.fs.resolvePath(n.cwd,d),p=s.getPageCount(),m=new Map;for(let t of u){let n=Km(t);if(!n.rotation)return{stdout:``,stderr:`${e}: rotation suffix required (right/left/down) for range '${t}'\n`,exitCode:1};let r=qm(n,p);for(let e of r)m.set(e-1,n.rotation)}let h=s.getPages();for(let[e,t]of m.entries()){let n=h[e],r=(n.getRotation().angle+t)%360;n.setRotation(a.degrees(r))}let g=await s.save();return await n.fs.writeFile(f,g),{stdout:`Created ${d}\n`,stderr:``,exitCode:0}}return{stdout:``,stderr:`${e}: unknown operation '${a}'\n`,exitCode:1}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}async function Xm(e,t,n){let r=t.FS;function i(e){try{r.stat(e)}catch{r.mkdirTree(e)}}async function a(t){i(t);let n;try{n=await e.readdir(t)}catch{return}for(let o of n){let n=t===`/`?`/${o}`:`${t}/${o}`;try{if((await e.stat(n)).isDirectory)await a(n);else{let a=await e.readFile(n);i(t),r.writeFile(n,a)}}catch{}}}for(let e of n)await a(e)}async function Zm(e,t,n){let r=t.FS;async function i(t){let n;try{n=r.readdir(t).filter(e=>e!==`.`&&e!==`..`)}catch{return}for(let a of n){let n=t===`/`?`/${a}`:`${t}/${a}`;try{let a=r.stat(n);if(r.isDir(a.mode))await e.mkdir(n,{recursive:!0}),await i(n);else{let i=new TextDecoder().decode(r.readFile(n));await e.mkdir(t,{recursive:!0}),await e.writeFile(n,i)}}catch{}}}for(let e of n)await i(e)}function Qm(){return{stdout:`usage: python3 [-c code | script.py] [args...]
1413
+ `,stderr:``,exitCode:0}}function $m(){return{stdout:`Python 3.12 (Pyodide)
1414
+ `,stderr:``,exitCode:0}}function eh(e){return z(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return Qm();if(t.includes(`--version`)||t.includes(`-V`))return $m();let r=``,i=`<stdin>`,a=[`python3`];if(t[0]===`-c`){if(!t[1])return{stdout:``,stderr:`${e}: option requires an argument -- 'c'\n`,exitCode:2};r=t[1],i=`-c`,a=[`-c`,...t.slice(2)]}else if(t.length>0&&!t[0].startsWith(`-`)){let o=t[0],s=n.fs.resolvePath(n.cwd,o);if(!await n.fs.exists(s))return{stdout:``,stderr:`${e}: can't open file '${o}': [Errno 2] No such file or directory\n`,exitCode:2};r=await n.fs.readFile(s),i=o,a=[o,...t.slice(1)]}else if(n.stdin.trim().length>0)r=n.stdin,i=`<stdin>`,a=[`<stdin>`];else if(t.length>0)return{stdout:``,stderr:`${e}: unsupported option '${t[0]}'\n`,exitCode:2};else return{stdout:``,stderr:`${e}: no input provided (use -c CODE, script path, or stdin)\n`,exitCode:2};try{let e=await jm(),t=[],o=[],s=[n.cwd,`/tmp`];if(i!==`<stdin>`&&i!==`[eval]`){let e=i.includes(`/`)?i.slice(0,i.lastIndexOf(`/`)):n.cwd;s.includes(e)||s.push(e)}await Xm(n.fs,e,s);try{e.FS.chdir(n.cwd)}catch{}e.setStdout({batched:e=>t.push(e+`
1415
1415
  `)}),e.setStderr({batched:e=>o.push(e+`
1416
- `)});let c=!1;e.setStdin({stdin:()=>c||!n.stdin?null:(c=!0,n.stdin)}),e.globals.set(`__slicc_code`,r),e.globals.set(`__slicc_filename`,i),e.globals.set(`__slicc_argv`,a),await e.runPythonAsync(sm);let l=e.globals.get(`__slicc_exit_code`),u=typeof l==`number`?l:Number(l??1);try{e.runPython(`del __slicc_code, __slicc_filename, __slicc_argv, __slicc_exit_code`)}catch{}return await qm(n.fs,e,s),{stdout:t.join(``),stderr:o.join(``),exitCode:u}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function Zm(){return{stdout:`usage: serve [--entry <relative-path>] [--project] <directory>
1416
+ `)});let c=!1;e.setStdin({stdin:()=>c||!n.stdin?null:(c=!0,n.stdin)}),e.globals.set(`__slicc_code`,r),e.globals.set(`__slicc_filename`,i),e.globals.set(`__slicc_argv`,a),await e.runPythonAsync(dm);let l=e.globals.get(`__slicc_exit_code`),u=typeof l==`number`?l:Number(l??1);try{e.runPython(`del __slicc_code, __slicc_filename, __slicc_argv, __slicc_exit_code`)}catch{}return await Zm(n.fs,e,s),{stdout:t.join(``),stderr:o.join(``),exitCode:u}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function th(){return{stdout:`usage: serve [--entry <relative-path>] [--project] <directory>
1417
1417
 
1418
1418
  Serve a VFS directory in a new browser tab via the preview service worker.
1419
1419
  Defaults to index.html inside the target directory.
@@ -1422,23 +1422,23 @@ Page ranges:
1422
1422
  --project Enable project serve mode. Root-relative paths (/scripts/,
1423
1423
  /styles/, etc.) resolve against the served directory.
1424
1424
  Use this for frameworks like EDS that expect a local dev server.
1425
- `,stderr:``,exitCode:0}}function Qm(e){let t=`index.html`,n,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`--entry`){let n=e[i+1];if(!n)return{entry:t,project:r,error:`serve: missing value for --entry
1425
+ `,stderr:``,exitCode:0}}function nh(e){let t=`index.html`,n,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`--entry`){let n=e[i+1];if(!n)return{entry:t,project:r,error:`serve: missing value for --entry
1426
1426
  `};t=n,i+=1;continue}if(a.startsWith(`--entry=`)){t=a.slice(8);continue}if(a===`--project`){r=!0;continue}if(a.startsWith(`-`))return{entry:t,project:r,error:`serve: unknown option: ${a}\n`};if(n)return{entry:t,project:r,error:`serve: expected a single directory argument
1427
- `};n=a}return{directory:n,entry:t,project:r}}function $m(e,t){return z(`serve`,async(n,r)=>{if(n.length===0||n.includes(`--help`)||n.includes(`-h`))return Zm();let i=typeof window<`u`&&typeof window.open==`function`;if(!e&&!i)return{stdout:``,stderr:`serve: browser APIs are unavailable in this environment
1428
- `,exitCode:1};let a=Qm(n);if(a.error)return{stdout:``,stderr:a.error,exitCode:1};if(!a.directory)return Zm();if(!xm(a.entry))return{stdout:``,stderr:`serve: invalid entry file: ${a.entry}\n`,exitCode:1};let o=r.fs.resolvePath(r.cwd,a.directory),s;try{s=await r.fs.stat(o)}catch{return{stdout:``,stderr:`serve: no such directory: ${a.directory}\n`,exitCode:1}}if(!s.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${a.directory}\n`,exitCode:1};let c=Sm(o,a.entry),l;try{l=await r.fs.stat(c)}catch{return{stdout:``,stderr:`serve: entry file not found: ${c}\n`,exitCode:1}}if(!l.isFile)return{stdout:``,stderr:`serve: entry is not a file: ${c}\n`,exitCode:1};let u=bm(c);if(a.project&&(u+=`?projectRoot=${encodeURIComponent(o)}`),e&&t){let t=await e.createPage(u);return{stdout:`serving ${o} → ${u} (targetId: ${t})\nUse: playwright-cli <command> --tab ${t}\n`,stderr:``,exitCode:0}}return typeof window<`u`&&typeof window.open==`function`&&window.open(u,`_blank`,`noopener,noreferrer`),{stdout:`serving ${o} → ${u}\n`,stderr:``,exitCode:0}})}function eh(){return{stdout:`usage: sqlite3 [database] [sql]
1429
- `,stderr:``,exitCode:0}}function th(e=`sqlite3`){return z(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return eh();let r=`:memory:`,i=t;t.length>0&&!t[0].startsWith(`-`)&&(r=t[0],i=t.slice(1));let a=i.join(` `).trim()||n.stdin.trim();if(!a)return{stdout:``,stderr:`${e}: interactive mode is not supported; provide SQL as argument or stdin\n`,exitCode:1};try{let e=await Tm(),t=r===`:memory:`,i=t?`:memory:`:n.fs.resolvePath(n.cwd,r),o;!t&&await n.fs.exists(i)&&(o=await n.fs.readFileBuffer(i));let s=o?new e.Database(o):new e.Database,c=s.exec(a);t||await n.fs.writeFile(i,s.export()),s.close();let l=[];for(let e of c)for(let t of e.values)l.push(t.map(vm).join(`|`));return{stdout:l.length>0?`${l.join(`
1430
- `)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function nh(){return{stdout:`usage: uname
1431
- `,stderr:``,exitCode:0}}function rh(){return z(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return nh();if(e.length>0)return{stdout:``,stderr:`uname: unsupported arguments
1427
+ `};n=a}return{directory:n,entry:t,project:r}}function rh(e,t){return z(`serve`,async(n,r)=>{if(n.length===0||n.includes(`--help`)||n.includes(`-h`))return th();let i=typeof window<`u`&&typeof window.open==`function`;if(!e&&!i)return{stdout:``,stderr:`serve: browser APIs are unavailable in this environment
1428
+ `,exitCode:1};let a=nh(n);if(a.error)return{stdout:``,stderr:a.error,exitCode:1};if(!a.directory)return th();if(!Tm(a.entry))return{stdout:``,stderr:`serve: invalid entry file: ${a.entry}\n`,exitCode:1};let o=r.fs.resolvePath(r.cwd,a.directory),s;try{s=await r.fs.stat(o)}catch{return{stdout:``,stderr:`serve: no such directory: ${a.directory}\n`,exitCode:1}}if(!s.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${a.directory}\n`,exitCode:1};let c=Em(o,a.entry),l;try{l=await r.fs.stat(c)}catch{return{stdout:``,stderr:`serve: entry file not found: ${c}\n`,exitCode:1}}if(!l.isFile)return{stdout:``,stderr:`serve: entry is not a file: ${c}\n`,exitCode:1};let u=wm(c);if(a.project&&(u+=`?projectRoot=${encodeURIComponent(o)}`),e&&t){let t=await e.createPage(u);return{stdout:`serving ${o} → ${u} (targetId: ${t})\nUse: playwright-cli <command> --tab ${t}\n`,stderr:``,exitCode:0}}return typeof window<`u`&&typeof window.open==`function`&&window.open(u,`_blank`,`noopener,noreferrer`),{stdout:`serving ${o} → ${u}\n`,stderr:``,exitCode:0}})}function ih(){return{stdout:`usage: sqlite3 [database] [sql]
1429
+ `,stderr:``,exitCode:0}}function ah(e=`sqlite3`){return z(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return ih();let r=`:memory:`,i=t;t.length>0&&!t[0].startsWith(`-`)&&(r=t[0],i=t.slice(1));let a=i.join(` `).trim()||n.stdin.trim();if(!a)return{stdout:``,stderr:`${e}: interactive mode is not supported; provide SQL as argument or stdin\n`,exitCode:1};try{let e=await km(),t=r===`:memory:`,i=t?`:memory:`:n.fs.resolvePath(n.cwd,r),o;!t&&await n.fs.exists(i)&&(o=await n.fs.readFileBuffer(i));let s=o?new e.Database(o):new e.Database,c=s.exec(a);t||await n.fs.writeFile(i,s.export()),s.close();let l=[];for(let e of c)for(let t of e.values)l.push(t.map(Sm).join(`|`));return{stdout:l.length>0?`${l.join(`
1430
+ `)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function oh(){return{stdout:`usage: uname
1431
+ `,stderr:``,exitCode:0}}function sh(){return z(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return oh();if(e.length>0)return{stdout:``,stderr:`uname: unsupported arguments
1432
1432
  `,exitCode:1};let t=globalThis.navigator?.userAgent;return typeof t!=`string`||t.length===0?{stdout:``,stderr:`uname: navigator.userAgent is unavailable
1433
- `,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function ih(){return{stdout:`usage: man <topic>
1433
+ `,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function ch(){return{stdout:`usage: man <topic>
1434
1434
 
1435
1435
  Fetches documentation for a given topic from sliccy.com.
1436
- `,stderr:``,exitCode:0}}function ah(e){return e.replace(/<[^>]*>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&nbsp;/g,` `).trimEnd()}function oh(){return z(`man`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return ih();if(e.length===0)return{stdout:``,stderr:`What manual page do you want?
1436
+ `,stderr:``,exitCode:0}}function lh(e){return e.replace(/<[^>]*>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&nbsp;/g,` `).trimEnd()}function uh(){return z(`man`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return ch();if(e.length===0)return{stdout:``,stderr:`What manual page do you want?
1437
1437
  For example, try 'man commands'.
1438
- `,exitCode:1};let t=e.join(`-`),n=`https://www.sliccy.com/man/${t}.plain.html`;try{let e=await fetch(n);return e.status===404?{stdout:``,stderr:`No manual entry for ${t}\n`,exitCode:1}:e.ok?{stdout:ah(await e.text())+`
1439
- `,stderr:``,exitCode:0}:{stdout:``,stderr:`man: failed to fetch manual page for ${t}: ${e.status} ${e.statusText}\n`,exitCode:1}}catch(e){return{stdout:``,stderr:`man: ${e.message||String(e)}\n`,exitCode:1}}})}function sh(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
1440
- `,stderr:``,exitCode:0}}function ch(){return z(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return sh();let n=`.`,r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`-d`){n=e[t+1]??``,t++;continue}if(i.startsWith(`-`))return{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1};r.push(i)}if(r.length<1)return{stdout:``,stderr:`unzip: expected archive path
1441
- `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=M(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!gm(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=pm(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}function lh(){return{stdout:`usage: webhook <command> [options]
1438
+ `,exitCode:1};let t=e.join(`-`),n=`https://www.sliccy.com/man/${t}.plain.html`;try{let e=await fetch(n);return e.status===404?{stdout:``,stderr:`No manual entry for ${t}\n`,exitCode:1}:e.ok?{stdout:lh(await e.text())+`
1439
+ `,stderr:``,exitCode:0}:{stdout:``,stderr:`man: failed to fetch manual page for ${t}: ${e.status} ${e.statusText}\n`,exitCode:1}}catch(e){return{stdout:``,stderr:`man: ${e.message||String(e)}\n`,exitCode:1}}})}function dh(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
1440
+ `,stderr:``,exitCode:0}}function fh(){return z(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return dh();let n=`.`,r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`-d`){n=e[t+1]??``,t++;continue}if(i.startsWith(`-`))return{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1};r.push(i)}if(r.length<1)return{stdout:``,stderr:`unzip: expected archive path
1441
+ `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=M(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!bm(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=_m(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}function ph(){return{stdout:`usage: webhook <command> [options]
1442
1442
 
1443
1443
  Commands:
1444
1444
  create --scoop <name> [--name <name>] [--filter <code>] Create a new webhook endpoint
@@ -1456,12 +1456,12 @@ Examples:
1456
1456
  webhook create --scoop slack-relay --name slack --filter "(e) => ({ text: e.body.text, user: e.body.user })"
1457
1457
  webhook list
1458
1458
  webhook delete abc123
1459
- `,stderr:``,exitCode:0}}async function uh(e,t,n){if(typeof chrome<`u`&&chrome?.runtime?.id)throw Error(`Webhooks are only available in CLI mode (npm run dev:full)`);let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/webhooks${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function dh(){return z(`webhook`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return lh();let t=e[0];try{switch(t){case`create`:{let t=`default`,n,r,i=e.indexOf(`--name`);i!==-1&&e[i+1]&&(t=e[i+1]);let a=e.indexOf(`--filter`);a!==-1&&e[a+1]&&(n=e[a+1]);let o=e.indexOf(`--scoop`);if(o!==-1&&e[o+1]&&(r=e[o+1]),!r)return{stdout:``,stderr:`webhook: --scoop is required (every webhook must route to a scoop)
1460
- `,exitCode:1};let{ok:s,data:c}=await uh(`POST`,``,{name:t,filter:n,scoop:r});if(!s)return{stdout:``,stderr:`webhook: failed to create webhook: ${c.error??`unknown error`}\n`,exitCode:1};let l=c,u=`Created webhook "${l.name}"\nID: ${l.id}\nURL: ${l.url}\n`;return l.scoop&&(u+=`Scoop: ${l.scoop}\n`),l.filter&&(u+=`Filter: ${l.filter}\n`),{stdout:u,stderr:``,exitCode:0}}case`list`:{let{ok:e,data:t}=await uh(`GET`,``);if(!e)return{stdout:``,stderr:`webhook: failed to list webhooks: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No active webhooks
1459
+ `,stderr:``,exitCode:0}}async function mh(e,t,n){if(typeof chrome<`u`&&chrome?.runtime?.id)throw Error(`Webhooks are only available in CLI mode (npm run dev:full)`);let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/webhooks${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function hh(){return z(`webhook`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return ph();let t=e[0];try{switch(t){case`create`:{let t=`default`,n,r,i=e.indexOf(`--name`);i!==-1&&e[i+1]&&(t=e[i+1]);let a=e.indexOf(`--filter`);a!==-1&&e[a+1]&&(n=e[a+1]);let o=e.indexOf(`--scoop`);if(o!==-1&&e[o+1]&&(r=e[o+1]),!r)return{stdout:``,stderr:`webhook: --scoop is required (every webhook must route to a scoop)
1460
+ `,exitCode:1};let{ok:s,data:c}=await mh(`POST`,``,{name:t,filter:n,scoop:r});if(!s)return{stdout:``,stderr:`webhook: failed to create webhook: ${c.error??`unknown error`}\n`,exitCode:1};let l=c,u=`Created webhook "${l.name}"\nID: ${l.id}\nURL: ${l.url}\n`;return l.scoop&&(u+=`Scoop: ${l.scoop}\n`),l.filter&&(u+=`Filter: ${l.filter}\n`),{stdout:u,stderr:``,exitCode:0}}case`list`:{let{ok:e,data:t}=await mh(`GET`,``);if(!e)return{stdout:``,stderr:`webhook: failed to list webhooks: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No active webhooks
1461
1461
  `,stderr:``,exitCode:0};let r=`Active webhooks:
1462
1462
  `;for(let e of n)r+=` ${e.id} ${e.name.padEnd(20)} ${e.url}`,e.scoop&&(r+=` -> ${e.scoop}`),e.filter&&(r+=` [filtered]`),r+=`
1463
1463
  `;return{stdout:r,stderr:``,exitCode:0}}case`delete`:{let t=e[1];if(!t)return{stdout:``,stderr:`webhook: delete requires an ID
1464
- `,exitCode:1};let{ok:n,status:r,data:i}=await uh(`DELETE`,`/${t}`);return n?{stdout:`Deleted webhook "${t}"\n`,stderr:``,exitCode:0}:r===404?{stdout:``,stderr:`webhook: webhook "${t}" not found\n`,exitCode:1}:{stdout:``,stderr:`webhook: failed to delete webhook: ${i.error??`unknown error`}\n`,exitCode:1}}default:return{stdout:``,stderr:`webhook: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`webhook: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function fh(){return{stdout:`usage: crontask <command> [options]
1464
+ `,exitCode:1};let{ok:n,status:r,data:i}=await mh(`DELETE`,`/${t}`);return n?{stdout:`Deleted webhook "${t}"\n`,stderr:``,exitCode:0}:r===404?{stdout:``,stderr:`webhook: webhook "${t}" not found\n`,exitCode:1}:{stdout:``,stderr:`webhook: failed to delete webhook: ${i.error??`unknown error`}\n`,exitCode:1}}default:return{stdout:``,stderr:`webhook: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`webhook: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function gh(){return{stdout:`usage: crontask <command> [options]
1465
1465
 
1466
1466
  Commands:
1467
1467
  create [options] Create a new cron task
@@ -1493,16 +1493,16 @@ Examples:
1493
1493
  crontask create --name every-5min --scoop poller --cron "*/5 * * * *" --filter "() => ({ time: Date.now() })"
1494
1494
  crontask list
1495
1495
  crontask delete abc123
1496
- `,stderr:``,exitCode:0}}var ph=typeof chrome<`u`&&!!chrome?.runtime?.id;function mh(){return globalThis.__slicc_lickManager??null}var hh=null;async function gh(){if(hh)return hh;let{createLickManagerProxy:e}=await v(async()=>{let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-BsVSy3SO.js`);return{createLickManagerProxy:e}},[]);return hh=e(),hh}async function _h(e,t,n){let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/crontasks${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function vh(){return z(`crontask`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return fh();let t=e[0];try{switch(t){case`create`:{let t,n,r,i,a=e.indexOf(`--name`);a!==-1&&e[a+1]&&(t=e[a+1]);let o=e.indexOf(`--cron`);o!==-1&&e[o+1]&&(n=e[o+1]);let s=e.indexOf(`--filter`);s!==-1&&e[s+1]&&(r=e[s+1]);let c=e.indexOf(`--scoop`);if(c!==-1&&e[c+1]&&(i=e[c+1]),!t)return{stdout:``,stderr:`crontask: --name is required
1496
+ `,stderr:``,exitCode:0}}var _h=typeof chrome<`u`&&!!chrome?.runtime?.id;function vh(){return globalThis.__slicc_lickManager??null}var yh=null;async function bh(){if(yh)return yh;let{createLickManagerProxy:e}=await v(async()=>{let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-BsVSy3SO.js`);return{createLickManagerProxy:e}},[]);return yh=e(),yh}async function xh(e,t,n){let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/crontasks${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function Sh(){return z(`crontask`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return gh();let t=e[0];try{switch(t){case`create`:{let t,n,r,i,a=e.indexOf(`--name`);a!==-1&&e[a+1]&&(t=e[a+1]);let o=e.indexOf(`--cron`);o!==-1&&e[o+1]&&(n=e[o+1]);let s=e.indexOf(`--filter`);s!==-1&&e[s+1]&&(r=e[s+1]);let c=e.indexOf(`--scoop`);if(c!==-1&&e[c+1]&&(i=e[c+1]),!t)return{stdout:``,stderr:`crontask: --name is required
1497
1497
  `,exitCode:1};if(!n)return{stdout:``,stderr:`crontask: --cron is required
1498
- `,exitCode:1};if(ph){if(r)return{stdout:``,stderr:`crontask: --filter is not supported in extension mode (CSP restriction)
1499
- `,exitCode:1};let e=mh(),a=e?await e.createCronTask(t,n,i):await(await gh()).createCronTask(t,n,i),o=`Created cron task "${a.name}"\n`;return o+=`ID: ${a.id}\n`,o+=`Cron: ${a.cron}\n`,a.scoop&&(o+=`Scoop: ${a.scoop}\n`),a.nextRun&&(o+=`Next run: ${new Date(a.nextRun).toLocaleString()}\n`),{stdout:o,stderr:``,exitCode:0}}let{ok:l,data:u}=await _h(`POST`,``,{name:t,cron:n,filter:r,scoop:i});if(!l)return{stdout:``,stderr:`crontask: failed to create: ${u.error??`unknown error`}\n`,exitCode:1};let d=u,f=`Created cron task "${d.name}"\n`;return f+=`ID: ${d.id}\n`,f+=`Cron: ${d.cron}\n`,d.scoop&&(f+=`Scoop: ${d.scoop}\n`),d.filter&&(f+=`Filter: ${d.filter}\n`),d.nextRun&&(f+=`Next run: ${new Date(d.nextRun).toLocaleString()}\n`),{stdout:f,stderr:``,exitCode:0}}case`list`:{if(ph){let e=mh(),t=e?e.listCronTasks():await(async()=>{let{listCronTasksAsync:e}=await v(async()=>{let{listCronTasksAsync:e}=await import(`./lick-manager-proxy-BsVSy3SO.js`);return{listCronTasksAsync:e}},[]);return e()})();if(t.length===0)return{stdout:`No active cron tasks
1498
+ `,exitCode:1};if(_h){if(r)return{stdout:``,stderr:`crontask: --filter is not supported in extension mode (CSP restriction)
1499
+ `,exitCode:1};let e=vh(),a=e?await e.createCronTask(t,n,i):await(await bh()).createCronTask(t,n,i),o=`Created cron task "${a.name}"\n`;return o+=`ID: ${a.id}\n`,o+=`Cron: ${a.cron}\n`,a.scoop&&(o+=`Scoop: ${a.scoop}\n`),a.nextRun&&(o+=`Next run: ${new Date(a.nextRun).toLocaleString()}\n`),{stdout:o,stderr:``,exitCode:0}}let{ok:l,data:u}=await xh(`POST`,``,{name:t,cron:n,filter:r,scoop:i});if(!l)return{stdout:``,stderr:`crontask: failed to create: ${u.error??`unknown error`}\n`,exitCode:1};let d=u,f=`Created cron task "${d.name}"\n`;return f+=`ID: ${d.id}\n`,f+=`Cron: ${d.cron}\n`,d.scoop&&(f+=`Scoop: ${d.scoop}\n`),d.filter&&(f+=`Filter: ${d.filter}\n`),d.nextRun&&(f+=`Next run: ${new Date(d.nextRun).toLocaleString()}\n`),{stdout:f,stderr:``,exitCode:0}}case`list`:{if(_h){let e=vh(),t=e?e.listCronTasks():await(async()=>{let{listCronTasksAsync:e}=await v(async()=>{let{listCronTasksAsync:e}=await import(`./lick-manager-proxy-BsVSy3SO.js`);return{listCronTasksAsync:e}},[]);return e()})();if(t.length===0)return{stdout:`No active cron tasks
1500
1500
  `,stderr:``,exitCode:0};let n=`Active cron tasks:
1501
1501
  `;for(let e of t)n+=` ${e.id} ${e.name.padEnd(20)} ${e.cron.padEnd(15)}`,e.scoop&&(n+=` -> ${e.scoop}`),e.filter&&(n+=` [filtered]`),n+=` (${e.status})`,e.nextRun&&(n+=` next: ${new Date(e.nextRun).toLocaleString()}`),n+=`
1502
- `;return{stdout:n,stderr:``,exitCode:0}}let{ok:e,data:t}=await _h(`GET`,``);if(!e)return{stdout:``,stderr:`crontask: failed to list: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No active cron tasks
1502
+ `;return{stdout:n,stderr:``,exitCode:0}}let{ok:e,data:t}=await xh(`GET`,``);if(!e)return{stdout:``,stderr:`crontask: failed to list: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No active cron tasks
1503
1503
  `,stderr:``,exitCode:0};let r=`Active cron tasks:
1504
1504
  `;for(let e of n)r+=` ${e.id} ${e.name.padEnd(20)} ${e.cron.padEnd(15)}`,e.scoop&&(r+=` -> ${e.scoop}`),e.filter&&(r+=` [filtered]`),r+=` (${e.status})`,e.nextRun&&(r+=` next: ${new Date(e.nextRun).toLocaleString()}`),r+=`
1505
- `;return{stdout:r,stderr:``,exitCode:0}}case`delete`:case`kill`:{let n=e[1];if(!n)return{stdout:``,stderr:`crontask: ${t} requires an ID\n`,exitCode:1};if(ph){let e=mh();return(e?await e.deleteCronTask(n):await(await gh()).deleteCronTask(n))?{stdout:`Deleted cron task "${n}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${n}" not found\n`,exitCode:1}}let{ok:r,status:i,data:a}=await _h(`DELETE`,`/${n}`);return r?{stdout:`Deleted cron task "${n}"\n`,stderr:``,exitCode:0}:i===404?{stdout:``,stderr:`crontask: task "${n}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${a.error??`unknown error`}\n`,exitCode:1}}default:return{stdout:``,stderr:`crontask: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var yh=new Map,bh=0;function xh(){return z(`fswatch`,async e=>{let t=e[0];if(!t||t===`--help`)return{stdout:`usage: fswatch <command> [options]
1505
+ `;return{stdout:r,stderr:``,exitCode:0}}case`delete`:case`kill`:{let n=e[1];if(!n)return{stdout:``,stderr:`crontask: ${t} requires an ID\n`,exitCode:1};if(_h){let e=vh();return(e?await e.deleteCronTask(n):await(await bh()).deleteCronTask(n))?{stdout:`Deleted cron task "${n}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${n}" not found\n`,exitCode:1}}let{ok:r,status:i,data:a}=await xh(`DELETE`,`/${n}`);return r?{stdout:`Deleted cron task "${n}"\n`,stderr:``,exitCode:0}:i===404?{stdout:``,stderr:`crontask: task "${n}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${a.error??`unknown error`}\n`,exitCode:1}}default:return{stdout:``,stderr:`crontask: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var Ch=new Map,wh=0;function Th(){return z(`fswatch`,async e=>{let t=e[0];if(!t||t===`--help`)return{stdout:`usage: fswatch <command> [options]
1506
1506
 
1507
1507
  Commands:
1508
1508
  create --path <path> --pattern <glob> [--scoop <name>] [--name <name>] Watch for file changes
@@ -1514,11 +1514,11 @@ Options:
1514
1514
  --pattern <glob> File pattern to match, e.g. "*.md", "*.bsh" (required)
1515
1515
  --scoop <name> Route change events to this scoop as lick events
1516
1516
  --name <name> Human-readable name for the watcher
1517
- `,stderr:``,exitCode:0};if(t===`list`){if(yh.size===0)return{stdout:`No active file watchers.
1518
- `,stderr:``,exitCode:0};let e=``;for(let[,t]of yh)e+=`ID: ${t.id}\n`,e+=` Name: ${t.name}\n`,e+=` Path: ${t.basePath}\n`,e+=` Pattern: ${t.pattern}\n`,t.scoop&&(e+=` Scoop: ${t.scoop}\n`),e+=` Created: ${t.createdAt}\n\n`;return{stdout:e,stderr:``,exitCode:0}}if(t===`delete`){let t=e[1];if(!t)return{stdout:``,stderr:`fswatch: delete requires an ID
1519
- `,exitCode:1};let n=yh.get(t);return n?(n.unsubscribe(),yh.delete(t),{stdout:`Deleted watcher "${n.name}" (${t})\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`fswatch: watcher not found: ${t}\n`,exitCode:1}}if(t===`create`){let t=``,n=``,r=``,i=``;for(let a=1;a<e.length;a++)e[a]===`--path`&&e[a+1]?t=e[++a]:e[a]===`--pattern`&&e[a+1]?n=e[++a]:e[a]===`--scoop`&&e[a+1]?r=e[++a]:e[a]===`--name`&&e[a+1]&&(i=e[++a]);if(!t||!n)return{stdout:``,stderr:`fswatch: --path and --pattern are required
1517
+ `,stderr:``,exitCode:0};if(t===`list`){if(Ch.size===0)return{stdout:`No active file watchers.
1518
+ `,stderr:``,exitCode:0};let e=``;for(let[,t]of Ch)e+=`ID: ${t.id}\n`,e+=` Name: ${t.name}\n`,e+=` Path: ${t.basePath}\n`,e+=` Pattern: ${t.pattern}\n`,t.scoop&&(e+=` Scoop: ${t.scoop}\n`),e+=` Created: ${t.createdAt}\n\n`;return{stdout:e,stderr:``,exitCode:0}}if(t===`delete`){let t=e[1];if(!t)return{stdout:``,stderr:`fswatch: delete requires an ID
1519
+ `,exitCode:1};let n=Ch.get(t);return n?(n.unsubscribe(),Ch.delete(t),{stdout:`Deleted watcher "${n.name}" (${t})\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`fswatch: watcher not found: ${t}\n`,exitCode:1}}if(t===`create`){let t=``,n=``,r=``,i=``;for(let a=1;a<e.length;a++)e[a]===`--path`&&e[a+1]?t=e[++a]:e[a]===`--pattern`&&e[a+1]?n=e[++a]:e[a]===`--scoop`&&e[a+1]?r=e[++a]:e[a]===`--name`&&e[a+1]&&(i=e[++a]);if(!t||!n)return{stdout:``,stderr:`fswatch: --path and --pattern are required
1520
1520
  `,exitCode:1};let a=RegExp(`^`+n.replace(/\./g,`\\.`).replace(/\*/g,`.*`)+`$`),o=e=>{let t=e.split(`/`).pop()??``;return a.test(t)},s=globalThis.__slicc_fs_watcher;if(!s)return{stdout:``,stderr:`fswatch: file system watcher not available
1521
- `,exitCode:1};let c=`fsw-${++bh}`;i||=`${n} in ${t}`;let l=globalThis.__slicc_lick_handler,u=s.watch(t,o,e=>{l&&l({type:`fswatch`,fswatchId:c,fswatchName:i,targetScoop:r,timestamp:new Date().toISOString(),changes:e.map(e=>({type:e.type,path:e.path})),body:{changes:e.map(e=>({type:e.type,path:e.path}))}})});yh.set(c,{id:c,name:i,basePath:t,pattern:n,scoop:r,unsubscribe:u,createdAt:new Date().toISOString()});let d=`Created file watcher "${i}"\n`;return d+=`ID: ${c}\n`,d+=`Path: ${t}\n`,d+=`Pattern: ${n}\n`,r&&(d+=`Scoop: ${r}\n`),{stdout:d,stderr:``,exitCode:0}}return{stdout:``,stderr:`fswatch: unknown command: ${t}\n`,exitCode:1}})}function Sh(){return{stdout:`usage: sprinkle <subcommand> [args]
1521
+ `,exitCode:1};let c=`fsw-${++wh}`;i||=`${n} in ${t}`;let l=globalThis.__slicc_lick_handler,u=s.watch(t,o,e=>{l&&l({type:`fswatch`,fswatchId:c,fswatchName:i,targetScoop:r,timestamp:new Date().toISOString(),changes:e.map(e=>({type:e.type,path:e.path})),body:{changes:e.map(e=>({type:e.type,path:e.path}))}})});Ch.set(c,{id:c,name:i,basePath:t,pattern:n,scoop:r,unsubscribe:u,createdAt:new Date().toISOString()});let d=`Created file watcher "${i}"\n`;return d+=`ID: ${c}\n`,d+=`Path: ${t}\n`,d+=`Pattern: ${n}\n`,r&&(d+=`Scoop: ${r}\n`),{stdout:d,stderr:``,exitCode:0}}return{stdout:``,stderr:`fswatch: unknown command: ${t}\n`,exitCode:1}})}function Eh(){return{stdout:`usage: sprinkle <subcommand> [args]
1522
1522
 
1523
1523
  list List available .shtml sprinkles
1524
1524
  open <name> Open a sprinkle by name
@@ -1528,10 +1528,10 @@ Options:
1528
1528
  chat <html> Show inline HTML in chat (Tool UI)
1529
1529
  Use data-action="name" on buttons for callbacks
1530
1530
  Pipe HTML: echo "<div>...</div>" | sprinkle chat
1531
- `,stderr:``,exitCode:0}}function Ch(){return typeof window>`u`?null:window.__slicc_sprinkleManager??null}function wh(){return z(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return Sh();let n=e[0];if(n===`chat`){let n=e.slice(1).join(` `);if(!n&&t.stdin&&(n=t.stdin),!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
1531
+ `,stderr:``,exitCode:0}}function Dh(){return typeof window>`u`?null:window.__slicc_sprinkleManager??null}function Oh(){return z(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return Eh();let n=e[0];if(n===`chat`){let n=e.slice(1).join(` `);if(!n&&t.stdin&&(n=t.stdin),!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
1532
1532
  `,exitCode:1};let r=await g({html:n,onAction:async(e,t)=>({action:e,data:t})});return r===null?{stdout:``,stderr:`sprinkle chat: not in tool execution context
1533
1533
  `,exitCode:1}:{stdout:JSON.stringify(r)+`
1534
- `,stderr:``,exitCode:0}}let r=Ch();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
1534
+ `,stderr:``,exitCode:0}}let r=Dh();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
1535
1535
  `,exitCode:1};switch(n){case`list`:{await r.refresh();let e=r.available();if(e.length===0)return{stdout:`No .shtml sprinkles found.
1536
1536
  `,stderr:``,exitCode:0};let t=new Set(r.opened());return{stdout:e.map(e=>{let n=t.has(e.name)?` [open]`:``;return` ${e.name}${n} ${e.title} (${e.path})`}).join(`
1537
1537
  `)+`
@@ -1540,7 +1540,7 @@ Options:
1540
1540
  `,exitCode:1}}case`refresh`:{await r.refresh();let e=r.available().length;return{stdout:`Found ${e} sprinkle${e===1?``:`s`}.\n`,stderr:``,exitCode:0}}case`send`:{let t=e[1];if(!t)return{stdout:``,stderr:`sprinkle send: name required
1541
1541
  `,exitCode:1};let n=e.slice(2).join(` `);if(!n)return{stdout:``,stderr:`sprinkle send: JSON data required
1542
1542
  `,exitCode:1};let i;try{i=JSON.parse(n)}catch{return{stdout:``,stderr:`sprinkle send: invalid JSON
1543
- `,exitCode:1}}return r.sendToSprinkle(t,i),{stdout:`Data sent to sprinkle "${t}".\n`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function Th(){return`oauth-token — get an OAuth access token for a provider
1543
+ `,exitCode:1}}return r.sendToSprinkle(t,i),{stdout:`Data sent to sprinkle "${t}".\n`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function kh(){return`oauth-token — get an OAuth access token for a provider
1544
1544
 
1545
1545
  Usage:
1546
1546
  oauth-token <providerId> Get token for a specific provider
@@ -1556,13 +1556,13 @@ on success.
1556
1556
  Examples:
1557
1557
  oauth-token adobe
1558
1558
  curl -H "Authorization: Bearer $(oauth-token adobe)" https://api.corp.com/data
1559
- `}function Eh(){return z(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await v(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-DtthfIx_.js`);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15])),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await v(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./providers-CBTIfSNw.js`);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([16,9,1,4,10,11,12,13,14,15]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Th(),stderr:``,exitCode:0};if(e.includes(`--list`))return Dh(r,a,i,t);let o,s=e.indexOf(`--provider`);if(s>=0){if(o=e[s+1],!o)return{stdout:``,stderr:`oauth-token: --provider requires a value
1559
+ `}function Ah(){return z(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await v(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-DtthfIx_.js`);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15])),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await v(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./providers-CBTIfSNw.js`);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([16,9,1,4,10,11,12,13,14,15]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:kh(),stderr:``,exitCode:0};if(e.includes(`--list`))return jh(r,a,i,t);let o,s=e.indexOf(`--provider`);if(s>=0){if(o=e[s+1],!o)return{stdout:``,stderr:`oauth-token: --provider requires a value
1560
1560
  `,exitCode:1}}else if(e.length>0)o=e[0];else{let e=n(),t=i(e);if(t?.isOAuth&&t.onOAuthLogin)o=e;else if(o=a().find(e=>{let t=i(e);return t?.isOAuth&&t.onOAuthLogin}),!o)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
1561
1561
  `,exitCode:1}}let c=i(o);if(!c)return{stdout:``,stderr:`oauth-token: unknown provider "${o}"\n`,exitCode:1};if(!c.isOAuth||!c.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${o}" is not an OAuth provider\n`,exitCode:1};let l=t(o);if(l&&!l.expired)return{stdout:`${l.token}\n`,stderr:``,exitCode:0};try{let{createOAuthLauncher:e}=await v(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-t9Y4KdOX.js`);return{createOAuthLauncher:e}},[]),n=e();await c.onOAuthLogin(n,()=>{});let r=t(o);return r&&r.token?{stdout:`${r.token}\n`,stderr:``,exitCode:0}:(console.error(`[oauth-token] Provider ${o}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
1562
- `,exitCode:1})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${o}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function Dh(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
1562
+ `,exitCode:1})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${o}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function jh(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
1563
1563
  `,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(`
1564
1564
  `)+`
1565
- `,stderr:``,exitCode:0}}function Oh(){return`secret — manage secrets for the fetch proxy
1565
+ `,stderr:``,exitCode:0}}function Mh(){return`secret — manage secrets for the fetch proxy
1566
1566
 
1567
1567
  Usage:
1568
1568
  secret set <name> --domain <patterns> Show instructions for adding a secret
@@ -1579,19 +1579,19 @@ Examples:
1579
1579
  secret list
1580
1580
  secret delete GITHUB_TOKEN
1581
1581
  secret test GITHUB_TOKEN https://api.github.com/repos
1582
- `}async function kh(e,t,n){if(typeof chrome<`u`&&chrome?.runtime?.id)throw Error(`Secrets CLI is only available in CLI mode`);let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/secrets${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function Ah(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function jh(){return z(`secret`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:Oh(),stderr:``,exitCode:0};let t=e[0];try{switch(t){case`set`:{let t=e[1];if(!t||t.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
1583
- `,exitCode:1};let n=Ah(e),r=n&&n.length>0?n.join(`,`):`<domain1,domain2>`,i=`To add the secret "${t}", use one of the following methods:\n\n`;return i+=` macOS Keychain (swift-server):
1582
+ `}async function Nh(e,t,n){if(typeof chrome<`u`&&chrome?.runtime?.id)throw Error(`Secrets CLI is only available in CLI mode`);let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/secrets${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function Ph(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function Fh(){return z(`secret`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:Mh(),stderr:``,exitCode:0};let t=e[0];try{switch(t){case`set`:{let t=e[1];if(!t||t.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
1583
+ `,exitCode:1};let n=Ph(e),r=n&&n.length>0?n.join(`,`):`<domain1,domain2>`,i=`To add the secret "${t}", use one of the following methods:\n\n`;return i+=` macOS Keychain (swift-server):
1584
1584
  `,i+=` security add-generic-password -s ai.sliccy.slicc -a ${t} -w '<value>' -U -C note -j '${r}'\n\n`,i+=` Environment file (node-server):
1585
1585
  `,i+=` Add to ~/.slicc/secrets.env:
1586
1586
  `,i+=` ${t}=<value>\n`,i+=` ${t}_DOMAINS=${r}\n\n`,i+=`Then restart the server to pick up changes.
1587
- `,{stdout:i,stderr:``,exitCode:0}}case`list`:{let{ok:e,data:t}=await kh(`GET`,``);if(!e)return{stdout:``,stderr:`secret: failed to list secrets: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No secrets stored
1587
+ `,{stdout:i,stderr:``,exitCode:0}}case`list`:{let{ok:e,data:t}=await Nh(`GET`,``);if(!e)return{stdout:``,stderr:`secret: failed to list secrets: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No secrets stored
1588
1588
  `,stderr:``,exitCode:0};let r=Math.max(4,...n.map(e=>e.name.length)),i=`${`NAME`.padEnd(r)} DOMAINS\n`;for(let e of n)i+=`${e.name.padEnd(r)} ${e.domains.join(`, `)}\n`;return{stdout:i,stderr:``,exitCode:0}}case`delete`:{let t=e[1];if(!t)return{stdout:``,stderr:`secret: delete requires a <name>
1589
1589
  `,exitCode:1};let n=`To delete the secret "${t}", use one of the following methods:\n\n`;return n+=` macOS Keychain (swift-server):
1590
1590
  `,n+=` security delete-generic-password -s ai.sliccy.slicc -a ${t}\n\n`,n+=` Environment file (node-server):
1591
1591
  `,n+=` Remove the ${t}= and ${t}_DOMAINS= lines from ~/.slicc/secrets.env\n\n`,n+=`Then restart the server to pick up changes.
1592
1592
  `,{stdout:n,stderr:``,exitCode:0}}case`test`:{let t=e[1],n=e[2];if(!t||!n)return{stdout:``,stderr:`secret: test requires <name> <url>
1593
- `,exitCode:1};let r;try{r=new URL(n).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${n}"\n`,exitCode:1}}let{ok:i,data:a}=await kh(`GET`,``);if(!i)return{stdout:``,stderr:`secret: failed to fetch secrets
1594
- `,exitCode:1};let o=a.find(e=>e.name===t);if(!o)return{stdout:``,stderr:`secret: no secret named "${t}"\n`,exitCode:1};let{isAllowedDomain:s}=await v(async()=>{let{isAllowedDomain:e}=await import(`./secret-masking-CfbASE5x.js`);return{isAllowedDomain:e}},[]);return s(o.domains,r)?{stdout:`✓ ${t} is allowed for ${r}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${t} is NOT allowed for ${r}\n Allowed domains: ${o.domains.join(`, `)}\n`,stderr:``,exitCode:1}}default:return{stdout:``,stderr:`secret: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function Mh(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}var Nh=null;function Ph(e){Nh=e}function Fh(){return Nh?.()??null}function Ih(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=Lh(r),o=Lh(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function Lh(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function Rh(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
1593
+ `,exitCode:1};let r;try{r=new URL(n).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${n}"\n`,exitCode:1}}let{ok:i,data:a}=await Nh(`GET`,``);if(!i)return{stdout:``,stderr:`secret: failed to fetch secrets
1594
+ `,exitCode:1};let o=a.find(e=>e.name===t);if(!o)return{stdout:``,stderr:`secret: no secret named "${t}"\n`,exitCode:1};let{isAllowedDomain:s}=await v(async()=>{let{isAllowedDomain:e}=await import(`./secret-masking-CfbASE5x.js`);return{isAllowedDomain:e}},[]);return s(o.domains,r)?{stdout:`✓ ${t} is allowed for ${r}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${t} is NOT allowed for ${r}\n Allowed domains: ${o.domains.join(`, `)}\n`,stderr:``,exitCode:1}}default:return{stdout:``,stderr:`secret: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function Ih(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}var Lh=null;function Rh(e){Lh=e}function zh(){return Lh?.()??null}function Bh(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=Vh(r),o=Vh(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function Vh(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function Hh(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
1595
1595
 
1596
1596
  Usage:
1597
1597
  rsync [flags] <local-path> <runtime-id>:<remote-path> # push
@@ -1607,21 +1607,21 @@ Examples:
1607
1607
  rsync /workspace follower-abc123:/workspace
1608
1608
  rsync --delete /shared leader:/shared
1609
1609
  rsync follower-abc123:/workspace/project /workspace/project
1610
- `,stderr:``,exitCode:0}}async function zh(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function Bh(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function Vh(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function Hh(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function Uh(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function Wh(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=Mh(await zh(e,i),await Bh(t,o,a),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1610
+ `,stderr:``,exitCode:0}}async function Uh(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function Wh(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function Gh(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function Kh(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function qh(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function Jh(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=Ih(await Uh(e,i),await Wh(t,o,a),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1611
1611
  `)+`
1612
- `,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let s=i+`/`+n,c=a+`/`+n;await Hh(t,o,Uh(c));let l=await t(o,{op:`writeFile`,path:c,content:Kh(await e.readFile(s,{encoding:`binary`})),encoding:`base64`});if(!l[0].ok)return{stdout:r.join(`
1612
+ `,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let s=i+`/`+n,c=a+`/`+n;await Kh(t,o,qh(c));let l=await t(o,{op:`writeFile`,path:c,content:Xh(await e.readFile(s,{encoding:`binary`})),encoding:`base64`});if(!l[0].ok)return{stdout:r.join(`
1613
1613
  `)+`
1614
1614
  `,stderr:`Error writing ${c}: ${l[0].error}\n`,exitCode:1}}for(let e of l.toDelete){let n=a+`/`+e,i=await t(o,{op:`rm`,path:n});if(!i[0].ok)return{stdout:r.join(`
1615
1615
  `)+`
1616
1616
  `,stderr:`Error deleting ${n}: ${i[0].error}\n`,exitCode:1}}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1617
1617
  `)+`
1618
- `,stderr:``,exitCode:0}}async function Gh(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=Mh(await Bh(t,o,a),await zh(e,i),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1618
+ `,stderr:``,exitCode:0}}async function Yh(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=Ih(await Wh(t,o,a),await Uh(e,i),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1619
1619
  `)+`
1620
- `,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=Uh(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=qh(await Vh(t,o,r));await e.writeFile(s,l)}for(let t of l.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1620
+ `,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=qh(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=Zh(await Gh(t,o,r));await e.writeFile(s,l)}for(let t of l.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1621
1621
  `)+`
1622
- `,stderr:``,exitCode:0}}function Kh(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function qh(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 Jh(e={}){let t=e.fs,n=e.getSendFsRequest??Fh;return z(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return Rh();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
1622
+ `,stderr:``,exitCode:0}}function Xh(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Zh(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 Qh(e={}){let t=e.fs,n=e.getSendFsRequest??zh;return z(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return Hh();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
1623
1623
  `,exitCode:1};let r=n();if(!r)return{stdout:``,stderr:`rsync: not connected to a tray — rsync requires a tray connection
1624
- `,exitCode:1};let i=Ih(e);if(`error`in i)return i.error===`__help__`?Rh():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await Wh(t,r,i):await Gh(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var Yh=[`/workspace/skills`];async function Xh(e){let t=new Map;for(let n of Yh)await e.exists(n)&&await Zh(e,n,t);return await Zh(e,`/`,t),t}async function Zh(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.jsh`))continue;let e=Qh(r);n.has(e)||n.set(e,r)}}function Qh(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.jsh`)?t.slice(0,-4):t}function $h(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return z(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
1624
+ `,exitCode:1};let i=Bh(e);if(`error`in i)return i.error===`__help__`?Hh():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await Jh(t,r,i):await Yh(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var $h=[`/workspace/skills`];async function eg(e){let t=new Map;for(let n of $h)await e.exists(n)&&await tg(e,n,t);return await tg(e,`/`,t),t}async function tg(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.jsh`))continue;let e=ng(r);n.has(e)||n.set(e,r)}}function ng(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.jsh`)?t.slice(0,-4):t}function rg(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return z(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
1625
1625
 
1626
1626
  Usage: which <command> [command...]
1627
1627
 
@@ -1631,12 +1631,12 @@ Prints the path of the given command(s).
1631
1631
 
1632
1632
  Exit code 0 if all commands found, 1 if any not found.
1633
1633
  `,stderr:``,exitCode:0};if(e.length===0)return{stdout:``,stderr:`which: missing argument
1634
- `,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=t.scriptCatalog?await t.scriptCatalog.getJshCommands():t.fs?await Xh(t.fs):new Map,o=[],s=!0;for(let t of e)if(i.has(t))o.push(`/usr/bin/${t}`);else{let e=a.get(t);e?o.push(e):s=!1}return{stdout:o.length>0?o.join(`
1634
+ `,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=t.scriptCatalog?await t.scriptCatalog.getJshCommands():t.fs?await eg(t.fs):new Map,o=[],s=!0;for(let t of e)if(i.has(t))o.push(`/usr/bin/${t}`);else{let e=a.get(t);e?o.push(e):s=!1}return{stdout:o.length>0?o.join(`
1635
1635
  `)+`
1636
- `:``,stderr:``,exitCode:+!s}})}async function eg(e,t,n,r){if((await e.fs.stat(t)).isFile)return r[n]=await e.fs.readFileBuffer(t),1;let i=await e.fs.readdir(t),a=0;for(let o of i){let i=mm(t,o),s=n?`${n}/${o}`:o;a+=await eg(e,i,s,r)}return a}function tg(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
1637
- `,stderr:``,exitCode:0}}function ng(){return z(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return tg();let n=!1,r=[];for(let t of e){if(t===`-r`){n=!0;continue}if(t.startsWith(`-`))return{stdout:``,stderr:`zip: unsupported option ${t}\n`,exitCode:1};r.push(t)}if(r.length<2)return{stdout:``,stderr:`zip: expected archive path and at least one input path
1638
- `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=r.slice(1),o={},s=0;for(let e of a){let r=t.fs.resolvePath(t.cwd,e),i=await t.fs.stat(r),a=(e.startsWith(`/`)?e.slice(1):e.replace(/^\.\//,``))||fm(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await eg(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
1639
- `,exitCode:1};let c=P(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function rg(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
1636
+ `:``,stderr:``,exitCode:+!s}})}async function ig(e,t,n,r){if((await e.fs.stat(t)).isFile)return r[n]=await e.fs.readFileBuffer(t),1;let i=await e.fs.readdir(t),a=0;for(let o of i){let i=vm(t,o),s=n?`${n}/${o}`:o;a+=await ig(e,i,s,r)}return a}function ag(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
1637
+ `,stderr:``,exitCode:0}}function og(){return z(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return ag();let n=!1,r=[];for(let t of e){if(t===`-r`){n=!0;continue}if(t.startsWith(`-`))return{stdout:``,stderr:`zip: unsupported option ${t}\n`,exitCode:1};r.push(t)}if(r.length<2)return{stdout:``,stderr:`zip: expected archive path and at least one input path
1638
+ `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=r.slice(1),o={},s=0;for(let e of a){let r=t.fs.resolvePath(t.cwd,e),i=await t.fs.stat(r),a=(e.startsWith(`/`)?e.slice(1):e.replace(/^\.\//,``))||gm(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await ig(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
1639
+ `,exitCode:1};let c=P(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function sg(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
1640
1640
 
1641
1641
  Usage: screencapture [options] <output-file>
1642
1642
 
@@ -1652,57 +1652,57 @@ Examples:
1652
1652
  screencapture screenshot.png # Capture to file
1653
1653
  screencapture -c # Capture to clipboard
1654
1654
  screencapture -v capture.png # Capture and return for agent vision
1655
- `,stderr:``,exitCode:0}}function ig(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function ag(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function og(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>{r.play().then(()=>e()).catch(t)},r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>requestAnimationFrame(e));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),new Promise((n,r)=>{o.toBlob(e=>{e?n(e):r(Error(`Failed to create image blob`))},e,t)})}finally{n.getTracks().forEach(e=>e.stop())}}function sg(){return z(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return rg();if(typeof window>`u`||typeof navigator>`u`||typeof document>`u`)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
1655
+ `,stderr:``,exitCode:0}}function cg(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function lg(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function ug(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>{r.play().then(()=>e()).catch(t)},r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>requestAnimationFrame(e));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),new Promise((n,r)=>{o.toBlob(e=>{e?n(e):r(Error(`Failed to create image blob`))},e,t)})}finally{n.getTracks().forEach(e=>e.stop())}}function dg(){return z(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return sg();if(typeof window>`u`||typeof navigator>`u`||typeof document>`u`)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
1656
1656
  `,exitCode:1};if(!navigator.mediaDevices?.getDisplayMedia)return{stdout:``,stderr:`screencapture: screen capture is not supported in this browser
1657
1657
  `,exitCode:1};let n=e.includes(`--clipboard`)||e.includes(`-c`),r=e.includes(`--view`)||e.includes(`-v`),i=[`--clipboard`,`-c`,`--view`,`-v`,`--help`,`-h`],a=e.indexOf(`--`),o=(a>=0?e.slice(a+1):e.filter(e=>!i.includes(e)))[0];if(!n&&!o)return{stdout:``,stderr:`screencapture: output file required (or use -c for clipboard)
1658
- `,exitCode:1};let s=o||`screenshot.png`,c=ag(s),l=c===`image/png`?1:.92,u;try{u=await og(c,l)}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{stdout:``,stderr:`screencapture: user cancelled or permission denied
1659
- `,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}let d=await u.arrayBuffer(),f=new Uint8Array(d);if(n)try{let e;if(c===`image/png`)e=u;else{let t=new Image,n=URL.createObjectURL(u);try{await new Promise((e,r)=>{t.onload=()=>e(),t.onerror=()=>r(Error(`Failed to load image for conversion`)),t.src=n})}finally{URL.revokeObjectURL(n)}let r=document.createElement(`canvas`);r.width=t.width,r.height=t.height;let i=r.getContext(`2d`);if(!i)throw Error(`Failed to get canvas context`);i.drawImage(t,0,0),e=await new Promise((e,t)=>{r.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}return await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),{stdout:`captured ${Math.round(e.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`screencapture: failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let p=t.fs.resolvePath(t.cwd,s);try{await t.fs.writeFile(p,f)}catch(e){return{stdout:``,stderr:`screencapture: failed to write file: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let m=Math.round(f.length/1024);return r?{stdout:`${p} (${m} KB)\n<img:data:${c};base64,${ig(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${fm(p)}\n`,stderr:``,exitCode:0}})}function cg(e){return e instanceof Error?e.message:String(e)}function lg(){return{stdout:`usage: pbcopy
1658
+ `,exitCode:1};let s=o||`screenshot.png`,c=lg(s),l=c===`image/png`?1:.92,u;try{u=await ug(c,l)}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{stdout:``,stderr:`screencapture: user cancelled or permission denied
1659
+ `,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}let d=await u.arrayBuffer(),f=new Uint8Array(d);if(n)try{let e;if(c===`image/png`)e=u;else{let t=new Image,n=URL.createObjectURL(u);try{await new Promise((e,r)=>{t.onload=()=>e(),t.onerror=()=>r(Error(`Failed to load image for conversion`)),t.src=n})}finally{URL.revokeObjectURL(n)}let r=document.createElement(`canvas`);r.width=t.width,r.height=t.height;let i=r.getContext(`2d`);if(!i)throw Error(`Failed to get canvas context`);i.drawImage(t,0,0),e=await new Promise((e,t)=>{r.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}return await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),{stdout:`captured ${Math.round(e.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`screencapture: failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let p=t.fs.resolvePath(t.cwd,s);try{await t.fs.writeFile(p,f)}catch(e){return{stdout:``,stderr:`screencapture: failed to write file: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let m=Math.round(f.length/1024);return r?{stdout:`${p} (${m} KB)\n<img:data:${c};base64,${cg(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${gm(p)}\n`,stderr:``,exitCode:0}})}function fg(e){return e instanceof Error?e.message:String(e)}function pg(){return{stdout:`usage: pbcopy
1660
1660
 
1661
1661
  Copy stdin to the clipboard.
1662
1662
  Example: echo hello | pbcopy
1663
- `,stderr:``,exitCode:0}}function ug(){return{stdout:`usage: pbpaste
1663
+ `,stderr:``,exitCode:0}}function mg(){return{stdout:`usage: pbpaste
1664
1664
 
1665
1665
  Paste clipboard contents to stdout.
1666
- `,stderr:``,exitCode:0}}function dg(e){return{stdout:`usage: ${e} [-i|-o]\n\n -i Force copy mode (read from stdin)
1666
+ `,stderr:``,exitCode:0}}function hg(e){return{stdout:`usage: ${e} [-i|-o]\n\n -i Force copy mode (read from stdin)
1667
1667
  -o Force paste mode (write to stdout)
1668
1668
  (default) Auto-detect: stdin present = copy, no stdin = paste
1669
- Example: echo hello | ${e}\n Example: ${e} -o > file.txt\n`,stderr:``,exitCode:0}}async function fg(e,t){if(!globalThis.navigator?.clipboard)return{stdout:``,stderr:`${t}: clipboard API is unavailable\n`,exitCode:1};try{return await navigator.clipboard.writeText(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`${t}: failed to write to clipboard: ${cg(e)}\n`,exitCode:1}}}async function pg(e){if(!globalThis.navigator?.clipboard)return{stdout:``,stderr:`${e}: clipboard API is unavailable\n`,exitCode:1};try{return{stdout:await navigator.clipboard.readText(),stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: failed to read from clipboard: ${cg(t)}\n`,exitCode:1}}}function mg(){return z(`pbcopy`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?lg():fg(t.stdin,`pbcopy`))}function hg(){return z(`pbpaste`,async e=>e.includes(`--help`)||e.includes(`-h`)?ug():pg(`pbpaste`))}function gg(e){return z(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return dg(e);let r=t.includes(`-i`),i=t.includes(`-o`);return r&&i?{stdout:``,stderr:`${e}: cannot use both -i and -o\n`,exitCode:1}:i?pg(e):r||n.stdin.length>0?fg(n.stdin,e):pg(e)})}function _g(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [--list] <text>
1669
+ Example: echo hello | ${e}\n Example: ${e} -o > file.txt\n`,stderr:``,exitCode:0}}async function gg(e,t){if(!globalThis.navigator?.clipboard)return{stdout:``,stderr:`${t}: clipboard API is unavailable\n`,exitCode:1};try{return await navigator.clipboard.writeText(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`${t}: failed to write to clipboard: ${fg(e)}\n`,exitCode:1}}}async function _g(e){if(!globalThis.navigator?.clipboard)return{stdout:``,stderr:`${e}: clipboard API is unavailable\n`,exitCode:1};try{return{stdout:await navigator.clipboard.readText(),stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: failed to read from clipboard: ${fg(t)}\n`,exitCode:1}}}function vg(){return z(`pbcopy`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?pg():gg(t.stdin,`pbcopy`))}function yg(){return z(`pbpaste`,async e=>e.includes(`--help`)||e.includes(`-h`)?mg():_g(`pbpaste`))}function bg(e){return z(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return hg(e);let r=t.includes(`-i`),i=t.includes(`-o`);return r&&i?{stdout:``,stderr:`${e}: cannot use both -i and -o\n`,exitCode:1}:i?_g(e):r||n.stdin.length>0?gg(n.stdin,e):_g(e)})}function xg(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [--list] <text>
1670
1670
 
1671
1671
  Speaks the given text using the Web Speech API.
1672
1672
  -v voice Voice name (partial match supported)
1673
1673
  -r rate Speech rate (0.1 to 10, default 1)
1674
1674
  -l lang Language tag (required, BCP 47, e.g. en-US, de-DE, fr-FR)
1675
1675
  --list List available voices
1676
- `,stderr:``,exitCode:0}}var vg=!1,yg=null;function bg(){return vg?Promise.resolve(speechSynthesis.getVoices()):(yg||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){vg=!0,e(t);return}let n=()=>{vg=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),vg=!0,e(speechSynthesis.getVoices())},1e3)}),yg)}function xg(){return z(`say`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return _g();if(typeof window>`u`||typeof speechSynthesis>`u`)return{stdout:``,stderr:`say: Web Speech API unavailable in this environment
1677
- `,exitCode:1};if(e.includes(`--list`))return{stdout:(await bg()).map(e=>`${e.name} (${e.lang})${e.default?` [default]`:``}`).join(`
1676
+ `,stderr:``,exitCode:0}}var Sg=!1,Cg=null;function wg(){return Sg?Promise.resolve(speechSynthesis.getVoices()):(Cg||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){Sg=!0,e(t);return}let n=()=>{Sg=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),Sg=!0,e(speechSynthesis.getVoices())},1e3)}),Cg)}function Tg(){return z(`say`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return xg();if(typeof window>`u`||typeof speechSynthesis>`u`)return{stdout:``,stderr:`say: Web Speech API unavailable in this environment
1677
+ `,exitCode:1};if(e.includes(`--list`))return{stdout:(await wg()).map(e=>`${e.name} (${e.lang})${e.default?` [default]`:``}`).join(`
1678
1678
  `)+`
1679
1679
  `,stderr:``,exitCode:0};let t=null,n=1,r=null,i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===`-v`){if(a+1>=e.length||e[a+1].startsWith(`-`))return{stdout:``,stderr:`say: -v requires a voice name
1680
1680
  `,exitCode:1};t=e[++a]}else if(o===`-r`){if(a+1>=e.length||e[a+1].startsWith(`-`))return{stdout:``,stderr:`say: -r requires a rate value
1681
1681
  `,exitCode:1};if(n=parseFloat(e[++a]),isNaN(n)||n<.1||n>10)return{stdout:``,stderr:`say: rate must be between 0.1 and 10
1682
1682
  `,exitCode:1}}else if(o===`-l`){if(a+1>=e.length||e[a+1].startsWith(`-`))return{stdout:``,stderr:`say: -l requires a language tag
1683
- `,exitCode:1};r=e[++a]}else if(o.startsWith(`-`)&&o!==`--list`)return{stdout:``,stderr:`say: unknown option: ${o}\n`,exitCode:1};else o.startsWith(`-`)||i.push(o)}let a=i.join(` `);if(!a)return _g();if(!r)return{stdout:``,stderr:`say: -l language tag is required
1684
- `,exitCode:1};let o=new SpeechSynthesisUtterance(a);if(o.rate=n,o.lang=r,t){let e=(await bg()).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));if(e)o.voice=e;else return{stdout:``,stderr:`say: voice "${t}" not found. Use --list to see available voices.\n`,exitCode:1}}return new Promise(e=>{o.onend=()=>{e({stdout:``,stderr:``,exitCode:0})},o.onerror=t=>{e({stdout:``,stderr:`say: speech synthesis error: ${t.error}\n`,exitCode:1})},speechSynthesis.speak(o)})})}function Sg(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
1683
+ `,exitCode:1};r=e[++a]}else if(o.startsWith(`-`)&&o!==`--list`)return{stdout:``,stderr:`say: unknown option: ${o}\n`,exitCode:1};else o.startsWith(`-`)||i.push(o)}let a=i.join(` `);if(!a)return xg();if(!r)return{stdout:``,stderr:`say: -l language tag is required
1684
+ `,exitCode:1};let o=new SpeechSynthesisUtterance(a);if(o.rate=n,o.lang=r,t){let e=(await wg()).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));if(e)o.voice=e;else return{stdout:``,stderr:`say: voice "${t}" not found. Use --list to see available voices.\n`,exitCode:1}}return new Promise(e=>{o.onend=()=>{e({stdout:``,stderr:``,exitCode:0})},o.onerror=t=>{e({stdout:``,stderr:`say: speech synthesis error: ${t.error}\n`,exitCode:1})},speechSynthesis.speak(o)})})}function Eg(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
1685
1685
 
1686
1686
  Plays an audio file using the Web Audio API.
1687
1687
  -v volume Volume level (0 to 1, default 1)
1688
1688
  -r rate Playback rate (0.25 to 4, default 1)
1689
- `,stderr:``,exitCode:0}}var Cg=null;function wg(){return(!Cg||Cg.state===`closed`)&&(Cg=new AudioContext),Cg}async function Tg(e,t,n,r){if(typeof window>`u`||typeof AudioContext>`u`)return{stdout:``,stderr:`afplay: Web Audio API unavailable in this environment
1690
- `,exitCode:1};let i=r.fs.resolvePath(r.cwd,e),a;try{a=new Uint8Array(await r.fs.readFileBuffer(i))}catch{return{stdout:``,stderr:`afplay: cannot open ${e}: No such file\n`,exitCode:1}}if(!ym(i).startsWith(`audio/`))return{stdout:``,stderr:`afplay: ${e} is not an audio file\n`,exitCode:1};try{let e=wg();e.state===`suspended`&&await e.resume();let r=new ArrayBuffer(a.byteLength);new Uint8Array(r).set(a);let i=await e.decodeAudioData(r),o=e.createBufferSource();o.buffer=i,o.playbackRate.value=n;let s=e.createGain();return s.gain.value=t,o.connect(s),s.connect(e.destination),new Promise(e=>{o.onended=()=>{e({stdout:``,stderr:``,exitCode:0})},o.start()})}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}}function Eg(){return z(`afplay`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Sg();let n=1,r=1,i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a===`-v`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -v requires a volume value
1689
+ `,stderr:``,exitCode:0}}var Dg=null;function Og(){return(!Dg||Dg.state===`closed`)&&(Dg=new AudioContext),Dg}async function kg(e,t,n,r){if(typeof window>`u`||typeof AudioContext>`u`)return{stdout:``,stderr:`afplay: Web Audio API unavailable in this environment
1690
+ `,exitCode:1};let i=r.fs.resolvePath(r.cwd,e),a;try{a=new Uint8Array(await r.fs.readFileBuffer(i))}catch{return{stdout:``,stderr:`afplay: cannot open ${e}: No such file\n`,exitCode:1}}if(!Cm(i).startsWith(`audio/`))return{stdout:``,stderr:`afplay: ${e} is not an audio file\n`,exitCode:1};try{let e=Og();e.state===`suspended`&&await e.resume();let r=new ArrayBuffer(a.byteLength);new Uint8Array(r).set(a);let i=await e.decodeAudioData(r),o=e.createBufferSource();o.buffer=i,o.playbackRate.value=n;let s=e.createGain();return s.gain.value=t,o.connect(s),s.connect(e.destination),new Promise(e=>{o.onended=()=>{e({stdout:``,stderr:``,exitCode:0})},o.start()})}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}}function Ag(){return z(`afplay`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Eg();let n=1,r=1,i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a===`-v`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -v requires a volume value
1691
1691
  `,exitCode:1};if(n=parseFloat(e[++t]),isNaN(n)||n<0||n>1)return{stdout:``,stderr:`afplay: volume must be between 0 and 1
1692
1692
  `,exitCode:1}}else if(a===`-r`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -r requires a rate value
1693
1693
  `,exitCode:1};if(r=parseFloat(e[++t]),isNaN(r)||r<.25||r>4)return{stdout:``,stderr:`afplay: rate must be between 0.25 and 4
1694
1694
  `,exitCode:1}}else if(a.startsWith(`-`))return{stdout:``,stderr:`afplay: unknown option: ${a}\n`,exitCode:1};else{if(i!==null)return{stdout:``,stderr:`afplay: only one file can be specified
1695
- `,exitCode:1};i=a}}return i?Tg(i,n,r,t):Sg()})}function Dg(){return z(`chime`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`usage: chime
1695
+ `,exitCode:1};i=a}}return i?kg(i,n,r,t):Eg()})}function jg(){return z(`chime`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`usage: chime
1696
1696
 
1697
1697
  Plays a notification chime sound.
1698
1698
  Alias for: afplay /shared/sounds/chime.mp3
1699
- `,stderr:``,exitCode:0}:Tg(`/shared/sounds/chime.mp3`,1,1,t))}function Og(){return z(`debug`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`usage: debug [on|off]
1699
+ `,stderr:``,exitCode:0}:kg(`/shared/sounds/chime.mp3`,1,1,t))}function Mg(){return z(`debug`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`usage: debug [on|off]
1700
1700
 
1701
1701
  Toggle debug tabs (Terminal, Memory) in extension mode.
1702
1702
  Without arguments, shows current state.
1703
1703
  `,stderr:``,exitCode:0};let t=e[0]?.toLowerCase();if(t!==`on`&&t!==`off`&&t!==void 0)return{stdout:``,stderr:`debug: unknown argument '${t}' (use 'on' or 'off')\n`,exitCode:1};if(!t)try{let e=localStorage.getItem(`slicc-hidden-tabs`);return{stdout:`Debug tabs: ${(e?JSON.parse(e):[`terminal`,`memory`]).includes(`terminal`)?`off`:`on`}\n`,stderr:``,exitCode:0}}catch{return{stdout:`Debug tabs: off
1704
1704
  `,stderr:``,exitCode:0}}let n=t===`on`,r=window.__slicc_debug_tabs;if(r)return r(n),{stdout:`Debug tabs ${n?`enabled`:`hidden`}\n`,stderr:``,exitCode:0};try{return chrome.runtime.sendMessage({source:`offscreen`,payload:{type:`debug-tabs`,show:n}}),{stdout:`Debug tabs ${n?`enabled`:`hidden`}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`debug: failed to send toggle message
1705
- `,exitCode:1}}})}var kg=`/.cache/artificial-analysis.json`,Ag=1440*60*1e3,jg=`https://artificialanalysis.ai/api/v2/data/llms/models`;async function Mg(e,t=!1){if(e&&!t)try{let t=await e.readFile(kg),n=JSON.parse(t);if(Date.now()-n.fetchedAt<Ag)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i;try{i=await fetch(jg,{headers:r})}catch{return[]}if(i.status===401||!i.ok)return[];let a;try{a=await i.json()}catch{return[]}let o=(Array.isArray(a)?a:a?.data??a?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&o.length>0){let t={fetchedAt:Date.now(),models:o};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(kg,JSON.stringify(t))}catch{}}return o}function Ng(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function Pg(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=Ng(e),a=t.find(e=>Ng(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function Fg(){return`models - list available LLM models
1705
+ `,exitCode:1}}})}var Ng=`/.cache/artificial-analysis.json`,Pg=1440*60*1e3,Fg=`https://artificialanalysis.ai/api/v2/data/llms/models`;async function Ig(e,t=!1){if(e&&!t)try{let t=await e.readFile(Ng),n=JSON.parse(t);if(Date.now()-n.fetchedAt<Pg)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i;try{i=await fetch(Fg,{headers:r})}catch{return[]}if(i.status===401||!i.ok)return[];let a;try{a=await i.json()}catch{return[]}let o=(Array.isArray(a)?a:a?.data??a?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&o.length>0){let t={fetchedAt:Date.now(),models:o};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(Ng,JSON.stringify(t))}catch{}}return o}function Lg(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function Rg(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=Lg(e),a=t.find(e=>Lg(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function zg(){return`models - list available LLM models
1706
1706
 
1707
1707
  Usage: models [options]
1708
1708
 
@@ -1714,13 +1714,13 @@ Options:
1714
1714
  --refresh Force re-fetch benchmark data from Artificial Analysis
1715
1715
  --no-benchmarks Skip benchmark data enrichment (faster, works offline)
1716
1716
  -h, --help Show this help message
1717
- `}function Ig(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function Lg(e){return`$${e.toFixed(2)}`}var Rg=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function zg(e){let t=`${e.id} ${e.name??``}`;return!Rg.test(t)}function Bg(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 Vg(e){let t=new Map;for(let n of e){let e=Bg(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function Hg(e,t,n,r,i){let a=i?Pg(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 Ug(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=`${Lg(e.cost.input)} / ${Lg(e.cost.output)}`,a=`${Ig(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(`
1717
+ `}function Bg(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function Vg(e){return`$${e.toFixed(2)}`}var Hg=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Ug(e){let t=`${e.id} ${e.name??``}`;return!Hg.test(t)}function Wg(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 Gg(e){let t=new Map;for(let n of e){let e=Wg(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function Kg(e,t,n,r,i){let a=i?Rg(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 qg(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=`${Vg(e.cost.input)} / ${Vg(e.cost.output)}`,a=`${Bg(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(`
1718
1718
  `)+`
1719
- `}function Wg(e){return z(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await v(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-DtthfIx_.js`);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:Fg(),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.
1720
- `,exitCode:1};let y;f||(y=await Mg(e,d),y.length===0&&(y=void 0));let b;if(m){let e=r();if(!e.includes(m))return{stdout:``,stderr:`Unknown provider: ${m}. Available: ${e.join(`, `)}\n`,exitCode:1};b=[m]}else b=l?[...new Set(_.map(e=>e.providerId))]:[h];let x=[],S=[];for(let e of b){let t=a(e).filter(zg);if(t.length===0){if(!l)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>Hg(t,e,g,h,y)).sort((e,t)=>t.cost.input-e.cost.input);if(u||(n=Vg(n)),x.push(...n),!c){let t=i(e);S.push(Ug(t.name,e,n,!!y))}}return c?{stdout:JSON.stringify(x,null,2)+`
1719
+ `}function Jg(e){return z(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await v(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-DtthfIx_.js`);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:zg(),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.
1720
+ `,exitCode:1};let y;f||(y=await Ig(e,d),y.length===0&&(y=void 0));let b;if(m){let e=r();if(!e.includes(m))return{stdout:``,stderr:`Unknown provider: ${m}. Available: ${e.join(`, `)}\n`,exitCode:1};b=[m]}else b=l?[...new Set(_.map(e=>e.providerId))]:[h];let x=[],S=[];for(let e of b){let t=a(e).filter(Ug);if(t.length===0){if(!l)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>Kg(t,e,g,h,y)).sort((e,t)=>t.cost.input-e.cost.input);if(u||(n=Gg(n)),x.push(...n),!c){let t=i(e);S.push(qg(t.name,e,n,!!y))}}return c?{stdout:JSON.stringify(x,null,2)+`
1721
1721
  `,stderr:``,exitCode:0}:(!u&&!c&&S.push(`Showing latest versions only. Use --all-versions to see all.
1722
1722
  `),{stdout:S.join(`
1723
- `),stderr:``,exitCode:0})})}function Gg(){return z(`nuke`,async e=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`Usage: nuke <launch-code>
1723
+ `),stderr:``,exitCode:0})})}function Yg(){return z(`nuke`,async e=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`Usage: nuke <launch-code>
1724
1724
 
1725
1725
  Completely reset the environment by deleting all local data and reloading.
1726
1726
  Destroys the file system, chat history, and scoops database.
@@ -1728,7 +1728,7 @@ Requires the secret launch code to proceed.
1728
1728
  `,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?(indexedDB.databases().then(e=>{for(let t of e)t.name&&indexedDB.deleteDatabase(t.name)}),setTimeout(()=>location.reload(),0),{stdout:`Nuking everything…
1729
1729
  `,stderr:``,exitCode:0}):{stdout:``,stderr:`⚠️ WARNING: this will reset the entire environment, file system, chats, and scoops.
1730
1730
  Run nuke again with the secret launch code to proceed.
1731
- `,exitCode:1})}function Kg(e={}){let t=[Ep({getJshCommands:e.getJshCommands}),em(),$m(e.browserAPI,e.fs),Im(),rm(e),ng(),ch(),th(`sqlite3`),th(`sqllite`),Mm(),Xm(`python3`),Xm(`python`),dh(),vh(),xh(),wh(),Gm(`pdftk`),Gm(`pdf`),kp(`convert`),kp(`magick`),$h({fs:e.fs,scriptCatalog:e.scriptCatalog}),rh(),oh(),Eh(),jh(),Jh({fs:e.fs}),sg(),mg(),hg(),gg(`xclip`),gg(`xsel`),xg(),Eg(),Dg(),Wg(e.fs),Ge(),Gg()];return typeof chrome<`u`&&chrome?.runtime?.id&&t.push(Og()),e.fs&&t.push(...Nf.map(t=>Cp(t,e.browserAPI,e.fs))),t}var qg=new TextDecoder;function Jg(e){return typeof e==`string`?e:qg.decode(e)}function Yg(e){return JSON.parse(Jg(e))}function Xg(e){if(typeof e!=`string`)return e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}var Zg=`https://wry-manatee-359.convex.site/api/v1`,Qg=`https://api.tessl.io`,$g=`/workspace/skills`,e_=`slicc-fs-global`,t_=`/workspace/.git/github-token`,n_=`application/vnd.github.v3+json`,r_=`https://www.sliccy.com/skills/catalog.json`;function i_(e){if(!(!e||!e.trim()))return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function a_(e){return e.map(e=>{let t=e.boost?parseFloat(e.boost):NaN,n=Number.isFinite(t)?t:void 0;return{name:e.name,displayName:e.displayName||e.name,description:e.description||``,source:{repo:e.repo,path:e.path||void 0,skill:e.skill||void 0},affinity:{apps:i_(e.apps),tasks:i_(e.tasks),role:i_(e.role),purpose:i_(e.purpose)},priority:n}})}var o_={apps:3,tasks:2,role:1,purpose:1};function s_(e,t){return e.map(e=>{let n=0,r=[],i=(e.affinity.apps??[]).filter(e=>t.apps.includes(e));i.length&&(n+=i.length*o_.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*o_.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=o_.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=o_.purpose,r.push(`purpose(${t.purpose})`)),n*=e.priority??1,{entry:e,score:n,matchReasons:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)}function c_(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.skill&&(t+=` --skill ${e.skill}`),t}async function l_(e){let t=new Set;try{let n=await e.readDir($g);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}try{let n=await e.readTextFile(`/${N}/${F}`),r=JSON.parse(n);for(let e of r.applied_skills??[])t.add(e.name)}catch{}let n=[`.agents`,`.claude`];try{let r=await e.readDir(`/`);for(let i of r)if(i.type===`directory`)for(let r of n)try{let n=`/${i.name}/${r}/skills`,a=await e.readDir(n);for(let e of a)e.type===`directory`&&t.add(e.name)}catch{}}catch{}return t}var u_;function d_(){return u_||=I.create({dbName:e_}),u_}async function f_(){try{return(await(await d_()).readTextFile(t_)).trim()||void 0}catch{return}}function p_(e,t=n_){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function m_(e){let t=await f_();return{hasToken:!!t,request:(n,r=n_)=>e(n,{headers:p_(t,r)})}}function h_(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}function g_(e){let t=Jg(e);if(!t)return;try{let e=JSON.parse(t);if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}let n=t.trim();if(n)return n.slice(0,200)}function __(e,t,n){let r=g_(e.body),i=r?` GitHub said: ${r}`:``,a=h_(e.headers,`retry-after`),o=h_(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}function v_(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/* and **/.claude/skills/* anywhere in the VFS.
1731
+ `,exitCode:1})}function Xg(e={}){let t=[Ap({getJshCommands:e.getJshCommands}),im(),rh(e.browserAPI,e.fs),Bm(),sm(e),og(),fh(),ah(`sqlite3`),ah(`sqllite`),Im(),eh(`python3`),eh(`python`),hh(),Sh(),Th(),Oh(),Ym(`pdftk`),Ym(`pdf`),Np(`convert`),Np(`magick`),rg({fs:e.fs,scriptCatalog:e.scriptCatalog}),sh(),uh(),Ah(),Fh(),Qh({fs:e.fs}),dg(),vg(),yg(),bg(`xclip`),bg(`xsel`),Tg(),Ag(),jg(),Jg(e.fs),Ge(),Yg()];return typeof chrome<`u`&&chrome?.runtime?.id&&t.push(Mg()),e.fs&&t.push(...Lf.map(t=>Dp(t,e.browserAPI,e.fs))),t}var Zg=`https://wry-manatee-359.convex.site/api/v1`,Qg=`https://api.tessl.io`,$g=`/workspace/skills`,e_=`slicc-fs-global`,t_=`/workspace/.git/github-token`,n_=`application/vnd.github.v3+json`,r_=`https://www.sliccy.com/skills/catalog.json`;function i_(e){if(!(!e||!e.trim()))return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function a_(e){return e.map(e=>{let t=e.boost?parseFloat(e.boost):NaN,n=Number.isFinite(t)?t:void 0;return{name:e.name,displayName:e.displayName||e.name,description:e.description||``,source:{repo:e.repo,path:e.path||void 0,skill:e.skill||void 0},affinity:{apps:i_(e.apps),tasks:i_(e.tasks),role:i_(e.role),purpose:i_(e.purpose)},priority:n}})}var o_={apps:3,tasks:2,role:1,purpose:1};function s_(e,t){return e.map(e=>{let n=0,r=[],i=(e.affinity.apps??[]).filter(e=>t.apps.includes(e));i.length&&(n+=i.length*o_.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*o_.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=o_.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=o_.purpose,r.push(`purpose(${t.purpose})`)),n*=e.priority??1,{entry:e,score:n,matchReasons:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)}function c_(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.skill&&(t+=` --skill ${e.skill}`),t}async function l_(e){let t=new Set;try{let n=await e.readDir($g);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}try{let n=await e.readTextFile(`/${N}/${F}`),r=JSON.parse(n);for(let e of r.applied_skills??[])t.add(e.name)}catch{}let n=[`.agents`,`.claude`];try{let r=await e.readDir(`/`);for(let i of r)if(i.type===`directory`)for(let r of n)try{let n=`/${i.name}/${r}/skills`,a=await e.readDir(n);for(let e of a)e.type===`directory`&&t.add(e.name)}catch{}}catch{}return t}var u_;function d_(){return u_||=I.create({dbName:e_}),u_}async function f_(){try{return(await(await d_()).readTextFile(t_)).trim()||void 0}catch{return}}function p_(e,t=n_){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function m_(e){let t=await f_();return{hasToken:!!t,request:(n,r=n_)=>e(n,{headers:p_(t,r)})}}function h_(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}function g_(e){let t=Ea(e);if(!t)return;try{let e=JSON.parse(t);if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}let n=t.trim();if(n)return n.slice(0,200)}function __(e,t,n){let r=g_(e.body),i=r?` GitHub said: ${r}`:``,a=h_(e.headers,`retry-after`),o=h_(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}function v_(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/* and **/.claude/skills/* anywhere in the VFS.
1732
1732
  `}function y_(){return`Only native /workspace/skills entries are install-managed; compatibility-discovered .agents/.claude skills remain read-only.
1733
1733
  `}function b_(e){switch(e){case`native`:return`native`;case`agents`:return`.agents`;case`claude`:return`.claude`}}function x_(e){return e.source===`native`}function S_(e){return x_(e)?e.installed&&e.installedVersion?`installed (v${e.installedVersion})`:`available`:e.installed&&e.installedVersion?`compatibility (state v${e.installedVersion})`:`compatibility (read-only)`}function C_(e){return x_(e)?`install-managed (/workspace/skills)`:`compatibility-only (read-only)`}function w_(e,t){let n=`${t}:\n\n`;n+=` NAME VERSION SOURCE STATUS
1734
1734
  `,n+=` ─────────────────────────────────────────────────────────────
@@ -1787,13 +1787,13 @@ Examples:
1787
1787
  upskill aemcoder/skills@fix/stateless-tab-targeting --all
1788
1788
  upskill https://clawhub.ai/arun-8687/tavily-search
1789
1789
  upskill tessl:postgres-pro
1790
- `,stderr:``,exitCode:0}}async function O_(e,t){let n=await t(`${Zg}/search?q=${encodeURIComponent(e)}`,{headers:{Accept:`application/json`}});if(n.status!==200)throw Error(`ClawHub returned HTTP ${n.status}`);let r=Yg(n.body);return r.results?r.results.map(e=>({name:e.slug,displayName:e.displayName||e.slug,summary:e.summary||``,source:`clawhub`,qualityScore:null,installHint:`upskill clawhub:${e.slug}`})):[]}function k_(e){let t=e.match(/github\.com\/([^\/?#]+)\/([^\/?#]+)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,``)}:null}async function A_(e,t){let n=await t(`${Qg}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,{headers:{Accept:`application/json`}});if(n.status!==200)throw Error(`Tessl returned HTTP ${n.status}`);let r=Yg(n.body);if(!r.data)return[];let i=new Map;for(let e of r.data){if(e.type!==`skill`)continue;let t=e.attributes,n=k_(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,a=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=i.get(o);if(s&&s.qualityScore!=null&&a!=null&&s.qualityScore>=a)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;i.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:a,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(i.values())}var j_=10;async function M_(e,t,n=1){let[r,i]=await Promise.allSettled([O_(e,t),A_(e,t)]),a=r.status===`fulfilled`?r.value:[],o=i.status===`fulfilled`?i.value:[];if(a.length===0&&o.length===0){let t=``;return r.status===`rejected`&&i.status===`rejected`&&(t=`upskill: both registries failed to respond
1790
+ `,stderr:``,exitCode:0}}async function O_(e,t){let n=await t(`${Zg}/search?q=${encodeURIComponent(e)}`,{headers:{Accept:`application/json`}});if(n.status!==200)throw Error(`ClawHub returned HTTP ${n.status}`);let r=Da(n.body);return r.results?r.results.map(e=>({name:e.slug,displayName:e.displayName||e.slug,summary:e.summary||``,source:`clawhub`,qualityScore:null,installHint:`upskill clawhub:${e.slug}`})):[]}function k_(e){let t=e.match(/github\.com\/([^\/?#]+)\/([^\/?#]+)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,``)}:null}async function A_(e,t){let n=await t(`${Qg}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,{headers:{Accept:`application/json`}});if(n.status!==200)throw Error(`Tessl returned HTTP ${n.status}`);let r=Da(n.body);if(!r.data)return[];let i=new Map;for(let e of r.data){if(e.type!==`skill`)continue;let t=e.attributes,n=k_(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,a=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=i.get(o);if(s&&s.qualityScore!=null&&a!=null&&s.qualityScore>=a)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;i.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:a,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(i.values())}var j_=10;async function M_(e,t,n=1){let[r,i]=await Promise.allSettled([O_(e,t),A_(e,t)]),a=r.status===`fulfilled`?r.value:[],o=i.status===`fulfilled`?i.value:[];if(a.length===0&&o.length===0){let t=``;return r.status===`rejected`&&i.status===`rejected`&&(t=`upskill: both registries failed to respond
1791
1791
  `),{stdout:`No skills found for "${e}"\n\nTry a different search term or browse https://clawhub.ai or https://tessl.io/registry\n`,stderr:t,exitCode:+!!t}}let s=[],c=0,l=0;for(;c<o.length&&c<3;)s.push(o[c++]);for(;l<a.length||c<o.length;)l<a.length&&s.push(a[l++]),c<o.length&&s.push(o[c++]);let u=s.length,d=Math.ceil(u/j_),f=Math.max(1,Math.min(n,d)),p=(f-1)*j_,m=s.slice(p,p+j_),h=`Search results for "${e}" (page ${f}/${d}, ${u} total):\n\n`;for(let e of m){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;h+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(h+=` ${e.summary}\n`),h+=`
1792
1792
  `}return f<d&&(h+=`Showing ${p+1}-${p+m.length} of ${u}. `,h+=`Next page: upskill search ${e} --page ${f+1}\n\n`),h+=`To install:
1793
1793
  `,a.length>0&&(h+=` From ClawHub: upskill clawhub:<slug>
1794
1794
  `),o.length>0&&(h+=` From Tessl: upskill <owner/repo> --skill <name>
1795
- `),{stdout:h,stderr:``,exitCode:0}}async function N_(e,t,n,r=!1,i){try{let a=`${$g}/${e}`;try{if(await t.stat(a),!r)return{stdout:``,stderr:`upskill: skill "${e}" already exists (use --force to overwrite)\n`,exitCode:1};await t.rm(a,{recursive:!0})}catch{}let o=`${Zg}/download?slug=${encodeURIComponent(e)}`,s=await n(o,{});if(s.status===404)return{stdout:``,stderr:`upskill: skill "${e}" not found on ClawHub\n`,exitCode:1};if(s.status!==200)return{stdout:``,stderr:`upskill: failed to download skill (HTTP ${s.status})\n`,exitCode:1};let c=s.headers[`content-type`]||``,l=Sa(o);l||=Xg(s.body);let u;try{u=M(l)}catch(e){let t=e instanceof Error?e.message:String(e),n=Array.from(l.slice(0,20)).map(e=>e.toString(16).padStart(2,`0`)).join(` `);return{stdout:``,stderr:`upskill: failed to unzip: ${t}\nContent-Type: ${c}\nBody: ${l.length} bytes\nHex: ${n}\n`,exitCode:1}}await t.mkdir(a,{recursive:!0});let d=0;for(let[e,n]of Object.entries(u)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`)||r===`_meta.json`)continue;let i=`${a}/${r}`,o=i.substring(0,i.lastIndexOf(`/`));o!==a&&await t.mkdir(o,{recursive:!0}),await t.writeFile(i,n),d++}let f=P_(u,i);return await H_(),{stdout:`Installed skill "${e}" from ClawHub (${d} files)\n${f}`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from ClawHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function P_(e,t){let n;for(let[t,r]of Object.entries(e))if((t.split(`/`).pop()||``).toLowerCase()===`skill.md`){n=new TextDecoder().decode(r);break}if(!n)return``;let r=n.match(/^---\s*\n([\s\S]*?)\n---/);if(!r)return``;let i=r[1],a=F_(i);if(a.length===0)return``;if(!t||t.length===0)return` Requires: ${a.join(`, `)}\n`;let o=new Set(t),s=a.filter(e=>!o.has(e));return s.length===0?` Requires: ${a.join(`, `)} (all available)\n`:` Requires: ${a.join(`, `)}\n Missing: ${s.join(`, `)} -- this skill may not work in the SLICC shell\n`}function F_(e){let t=e.match(/metadata:\s*\n\s*(\{[\s\S]*\})/);if(t)try{let e=JSON.parse(t[1]);for(let t of[`openclaw`,`clawdis`,`clawdbot`]){let n=e[t];if(n?.requires&&typeof n.requires==`object`){let e=n.requires;if(Array.isArray(e.bins))return e.bins.filter(e=>typeof e==`string`)}}}catch{}let n=e.match(/"bins"\s*:\s*\[([^\]]*)\]/);return n?n[1].split(`,`).map(e=>e.trim().replace(/^["']|["']$/g,``)).filter(Boolean):[]}async function I_(e,t){let n=await t(`${Qg}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,{headers:{Accept:`application/json`}});if(n.status!==200)return{error:`Tessl search failed (HTTP ${n.status})`};let r=Yg(n.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!r)return{error:`skill "${e}" not found on Tessl registry`};let i=k_(r.attributes.sourceUrl);if(!i)return{error:`skill "${e}" has no GitHub source URL`};let a=r.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:i.owner,repo:i.repo,skillPath:a,skillName:e}}async function L_(e,t,n,r=`main`){let i=`https://codeload.github.com/${e}/${t}/zip/refs/heads/${r}`,a=await n(i,{headers:{"User-Agent":`slicc-upskill`}});if(a.status===404)return r===`main`?L_(e,t,n,`master`):{status:`not_found`};if(a.status!==200)return{status:`error`,message:`codeload returned HTTP ${a.status}`};let o=Sa(i);o||=Xg(a.body);try{return{status:`ok`,files:M(o)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function R_(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.indexOf(`/`);if(e<0)continue;let i=n.slice(e+1);i&&(t[i]=r)}return t}async function z_(e,t,n,r,i,a){if(i){let n=await L_(e,t,i,a);if(n.status===`ok`){let e=R_(n.files),t=[],i=r?r.replace(/^\/|\/$/g,``)+`/`:``;for(let n of Object.keys(e))if(n.startsWith(i)&&(n.split(`/`).pop()||``)===`SKILL.md`){let e=n.replace(/\/SKILL\.md$/,``),r=e.split(`/`).pop()||e;t.push({name:r,path:e})}return{skills:t}}if(n.status===`not_found`)return{skills:[],error:`${a?`branch "${a}" in ${e}/${t}`:`repository ${e}/${t}`} not found`}}let o=[];async function s(r){let i=`https://api.github.com/repos/${e}/${t}/contents/${r}`,c=a?`${i}?ref=${encodeURIComponent(a)}`:i,l=await n.request(c);if(l.status!==200)throw Error(__(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=Yg(l.body);for(let e of u)if(e.type===`file`&&e.name===`SKILL.md`){let t=e.path.replace(`/SKILL.md`,``),n=t.split(`/`).pop()||t;o.push({name:n,path:t})}else e.type===`dir`&&await s(e.path)}try{return await s(r||``),{skills:o}}catch(e){return{skills:[],error:e instanceof Error?e.message:String(e)}}}async function B_(e,t,n,r,i,a,o=!1,s,c){try{let l=`${$g}/${r}`;try{if(await i.stat(l),!o)return{stdout:``,stderr:`upskill: skill "${r}" already exists (use --force to overwrite)\n`,exitCode:1};await i.rm(l,{recursive:!0})}catch{}if(s){let a=await L_(e,t,s,c);if(a.status===`not_found`)return{stdout:``,stderr:`upskill: ${c?`branch "${c}" in ${e}/${t}`:`repository ${e}/${t}`} not found\n`,exitCode:1};if(a.status===`ok`){let o=R_(a.files),s=n.replace(/^\/|\/$/g,``)+`/`;await i.mkdir(l,{recursive:!0});let c=0;for(let[e,t]of Object.entries(o)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let r=`${l}/${n}`,a=r.substring(0,r.lastIndexOf(`/`));a!==l&&await i.mkdir(a,{recursive:!0}),await i.writeFile(r,t),c++}if(c>0)return await K_(),await W_(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}}let u=`https://api.github.com/repos/${e}/${t}/contents/${n}`,d=c?`${u}?ref=${encodeURIComponent(c)}`:u,f=await a.request(d);if(f.status!==200)return{stdout:``,stderr:`upskill: ${__(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=Yg(f.body);await i.mkdir(l,{recursive:!0});async function m(n,r){for(let o of n)if(o.type===`file`&&o.download_url){let n=await a.request(o.download_url,`*/*`);if(n.status!==200)throw Error(__(n,`${e}/${t}/${o.path}`,a.hasToken));let s=Sa(o.download_url);await i.writeFile(`${r}/${o.name}`,s??n.body)}else if(o.type===`dir`){let n=`https://api.github.com/repos/${e}/${t}/contents/${o.path}`,s=c?`${n}?ref=${encodeURIComponent(c)}`:n,l=await a.request(s);if(l.status!==200)throw Error(__(l,`${e}/${t}/${o.path}`,a.hasToken));let u=Yg(l.body);await i.mkdir(`${r}/${o.name}`,{recursive:!0}),await m(u,`${r}/${o.name}`)}}try{await m(p,l)}catch(e){try{await i.rm(l,{recursive:!0})}catch{}throw e}return await H_(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from GitHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function V_(e){let t=e.match(/^https?:\/\/clawhub\.ai\/[^\/]+\/([^\/]+)/);if(t)return t[1];if(e.startsWith(`clawhub:`)){let t=e.slice(8);return t.includes(`/`)?t.split(`/`)[1]:t}return null}async function H_(){await K_(),await W_()}async function U_(e,t,n,r,i=!1){let a=`${$g}/${t}`;try{if(await r.stat(a),!i)return{ok:!1,error:`skill "${t}" already exists (use --force to overwrite)`};await r.rm(a,{recursive:!0})}catch{}let o=e.replace(/^\/|\/$/g,``),s=o?o+`/`:``;await r.mkdir(a,{recursive:!0});let c=0;try{for(let[e,t]of Object.entries(n)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let i=`${a}/${n}`,o=i.replace(/\/+/g,`/`);if(o.includes(`/../`)||o.includes(`/..`)||!o.startsWith(a+`/`))continue;let l=i.substring(0,i.lastIndexOf(`/`));l!==a&&await r.mkdir(l,{recursive:!0}),await r.writeFile(i,t),c++}}catch(e){throw await r.rm(a,{recursive:!0}).catch(()=>{}),e}return c===0?(await r.rm(a,{recursive:!0}).catch(()=>{}),{ok:!1,error:`no files found for skill "${t}" in ZIP`}):{ok:!0}}async function W_(){try{let e=(typeof window<`u`?window:globalThis).__slicc_reloadSkills;if(typeof e==`function`){await e();return}typeof chrome<`u`&&chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}})}catch{}}function G_(e){let t=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./\-]+))?$/);return t?{owner:t[1],repo:t[2],branch:t[3]}:null}async function K_(){try{if(typeof window>`u`)return;let e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function q_(e,t,n){let r=null;try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);r=JSON.parse(t);break}catch{}}catch{}if(!r)return{stdout:``,stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
1796
- `,exitCode:1};let i,a;try{let[n,r]=await Promise.all([(async()=>{let e=await t(r_,{headers:{Accept:`application/json`}});if(e.status!==200)throw Error(`HTTP ${e.status}`);return a_(Yg(e.body).data)})(),l_(e)]);i=n,a=r}catch(e){return{stdout:``,stderr:`upskill: failed to fetch skill catalog from ${r_}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=s_(i,r).filter(e=>!a.has(e.entry.name));if(o.length===0)return{stdout:`No new skill recommendations — all matching skills are already installed.
1795
+ `),{stdout:h,stderr:``,exitCode:0}}async function N_(e,t,n,r=!1,i){try{let a=`${$g}/${e}`;try{if(await t.stat(a),!r)return{stdout:``,stderr:`upskill: skill "${e}" already exists (use --force to overwrite)\n`,exitCode:1};await t.rm(a,{recursive:!0})}catch{}let o=`${Zg}/download?slug=${encodeURIComponent(e)}`,s=await n(o,{});if(s.status===404)return{stdout:``,stderr:`upskill: skill "${e}" not found on ClawHub\n`,exitCode:1};if(s.status!==200)return{stdout:``,stderr:`upskill: failed to download skill (HTTP ${s.status})\n`,exitCode:1};let c=s.headers[`content-type`]||``,l=Sa(o);l||=Oa(s.body);let u;try{u=M(l)}catch(e){let t=e instanceof Error?e.message:String(e),n=Array.from(l.slice(0,20)).map(e=>e.toString(16).padStart(2,`0`)).join(` `);return{stdout:``,stderr:`upskill: failed to unzip: ${t}\nContent-Type: ${c}\nBody: ${l.length} bytes\nHex: ${n}\n`,exitCode:1}}await t.mkdir(a,{recursive:!0});let d=0;for(let[e,n]of Object.entries(u)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`)||r===`_meta.json`)continue;let i=`${a}/${r}`,o=i.substring(0,i.lastIndexOf(`/`));o!==a&&await t.mkdir(o,{recursive:!0}),await t.writeFile(i,n),d++}let f=P_(u,i);return await H_(),{stdout:`Installed skill "${e}" from ClawHub (${d} files)\n${f}`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from ClawHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function P_(e,t){let n;for(let[t,r]of Object.entries(e))if((t.split(`/`).pop()||``).toLowerCase()===`skill.md`){n=new TextDecoder().decode(r);break}if(!n)return``;let r=n.match(/^---\s*\n([\s\S]*?)\n---/);if(!r)return``;let i=r[1],a=F_(i);if(a.length===0)return``;if(!t||t.length===0)return` Requires: ${a.join(`, `)}\n`;let o=new Set(t),s=a.filter(e=>!o.has(e));return s.length===0?` Requires: ${a.join(`, `)} (all available)\n`:` Requires: ${a.join(`, `)}\n Missing: ${s.join(`, `)} -- this skill may not work in the SLICC shell\n`}function F_(e){let t=e.match(/metadata:\s*\n\s*(\{[\s\S]*\})/);if(t)try{let e=JSON.parse(t[1]);for(let t of[`openclaw`,`clawdis`,`clawdbot`]){let n=e[t];if(n?.requires&&typeof n.requires==`object`){let e=n.requires;if(Array.isArray(e.bins))return e.bins.filter(e=>typeof e==`string`)}}}catch{}let n=e.match(/"bins"\s*:\s*\[([^\]]*)\]/);return n?n[1].split(`,`).map(e=>e.trim().replace(/^["']|["']$/g,``)).filter(Boolean):[]}async function I_(e,t){let n=await t(`${Qg}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,{headers:{Accept:`application/json`}});if(n.status!==200)return{error:`Tessl search failed (HTTP ${n.status})`};let r=Da(n.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!r)return{error:`skill "${e}" not found on Tessl registry`};let i=k_(r.attributes.sourceUrl);if(!i)return{error:`skill "${e}" has no GitHub source URL`};let a=r.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:i.owner,repo:i.repo,skillPath:a,skillName:e}}async function L_(e,t,n,r=`main`){let i=`https://codeload.github.com/${e}/${t}/zip/refs/heads/${r}`,a=await n(i,{headers:{"User-Agent":`slicc-upskill`}});if(a.status===404)return r===`main`?L_(e,t,n,`master`):{status:`not_found`};if(a.status!==200)return{status:`error`,message:`codeload returned HTTP ${a.status}`};let o=Sa(i);o||=Oa(a.body);try{return{status:`ok`,files:M(o)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function R_(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.indexOf(`/`);if(e<0)continue;let i=n.slice(e+1);i&&(t[i]=r)}return t}async function z_(e,t,n,r,i,a){if(i){let n=await L_(e,t,i,a);if(n.status===`ok`){let e=R_(n.files),t=[],i=r?r.replace(/^\/|\/$/g,``)+`/`:``;for(let n of Object.keys(e))if(n.startsWith(i)&&(n.split(`/`).pop()||``)===`SKILL.md`){let e=n.replace(/\/SKILL\.md$/,``),r=e.split(`/`).pop()||e;t.push({name:r,path:e})}return{skills:t}}if(n.status===`not_found`)return{skills:[],error:`${a?`branch "${a}" in ${e}/${t}`:`repository ${e}/${t}`} not found`}}let o=[];async function s(r){let i=`https://api.github.com/repos/${e}/${t}/contents/${r}`,c=a?`${i}?ref=${encodeURIComponent(a)}`:i,l=await n.request(c);if(l.status!==200)throw Error(__(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=Da(l.body);for(let e of u)if(e.type===`file`&&e.name===`SKILL.md`){let t=e.path.replace(`/SKILL.md`,``),n=t.split(`/`).pop()||t;o.push({name:n,path:t})}else e.type===`dir`&&await s(e.path)}try{return await s(r||``),{skills:o}}catch(e){return{skills:[],error:e instanceof Error?e.message:String(e)}}}async function B_(e,t,n,r,i,a,o=!1,s,c){try{let l=`${$g}/${r}`;try{if(await i.stat(l),!o)return{stdout:``,stderr:`upskill: skill "${r}" already exists (use --force to overwrite)\n`,exitCode:1};await i.rm(l,{recursive:!0})}catch{}if(s){let a=await L_(e,t,s,c);if(a.status===`not_found`)return{stdout:``,stderr:`upskill: ${c?`branch "${c}" in ${e}/${t}`:`repository ${e}/${t}`} not found\n`,exitCode:1};if(a.status===`ok`){let o=R_(a.files),s=n.replace(/^\/|\/$/g,``)+`/`;await i.mkdir(l,{recursive:!0});let c=0;for(let[e,t]of Object.entries(o)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let r=`${l}/${n}`,a=r.substring(0,r.lastIndexOf(`/`));a!==l&&await i.mkdir(a,{recursive:!0}),await i.writeFile(r,t),c++}if(c>0)return await K_(),await W_(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}}let u=`https://api.github.com/repos/${e}/${t}/contents/${n}`,d=c?`${u}?ref=${encodeURIComponent(c)}`:u,f=await a.request(d);if(f.status!==200)return{stdout:``,stderr:`upskill: ${__(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=Da(f.body);await i.mkdir(l,{recursive:!0});async function m(n,r){for(let o of n)if(o.type===`file`&&o.download_url){let n=await a.request(o.download_url,`*/*`);if(n.status!==200)throw Error(__(n,`${e}/${t}/${o.path}`,a.hasToken));let s=Sa(o.download_url);await i.writeFile(`${r}/${o.name}`,s??n.body)}else if(o.type===`dir`){let n=`https://api.github.com/repos/${e}/${t}/contents/${o.path}`,s=c?`${n}?ref=${encodeURIComponent(c)}`:n,l=await a.request(s);if(l.status!==200)throw Error(__(l,`${e}/${t}/${o.path}`,a.hasToken));let u=Da(l.body);await i.mkdir(`${r}/${o.name}`,{recursive:!0}),await m(u,`${r}/${o.name}`)}}try{await m(p,l)}catch(e){try{await i.rm(l,{recursive:!0})}catch{}throw e}return await H_(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from GitHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function V_(e){let t=e.match(/^https?:\/\/clawhub\.ai\/[^\/]+\/([^\/]+)/);if(t)return t[1];if(e.startsWith(`clawhub:`)){let t=e.slice(8);return t.includes(`/`)?t.split(`/`)[1]:t}return null}async function H_(){await K_(),await W_()}async function U_(e,t,n,r,i=!1){let a=`${$g}/${t}`;try{if(await r.stat(a),!i)return{ok:!1,error:`skill "${t}" already exists (use --force to overwrite)`};await r.rm(a,{recursive:!0})}catch{}let o=e.replace(/^\/|\/$/g,``),s=o?o+`/`:``;await r.mkdir(a,{recursive:!0});let c=0;try{for(let[e,t]of Object.entries(n)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let i=`${a}/${n}`,o=i.replace(/\/+/g,`/`);if(o.includes(`/../`)||o.includes(`/..`)||!o.startsWith(a+`/`))continue;let l=i.substring(0,i.lastIndexOf(`/`));l!==a&&await r.mkdir(l,{recursive:!0}),await r.writeFile(i,t),c++}}catch(e){throw await r.rm(a,{recursive:!0}).catch(()=>{}),e}return c===0?(await r.rm(a,{recursive:!0}).catch(()=>{}),{ok:!1,error:`no files found for skill "${t}" in ZIP`}):{ok:!0}}async function W_(){try{let e=(typeof window<`u`?window:globalThis).__slicc_reloadSkills;if(typeof e==`function`){await e();return}typeof chrome<`u`&&chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}})}catch{}}function G_(e){let t=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./\-]+))?$/);return t?{owner:t[1],repo:t[2],branch:t[3]}:null}async function K_(){try{if(typeof window>`u`)return;let e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function q_(e,t,n){let r=null;try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);r=JSON.parse(t);break}catch{}}catch{}if(!r)return{stdout:``,stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
1796
+ `,exitCode:1};let i,a;try{let[n,r]=await Promise.all([(async()=>{let e=await t(r_,{headers:{Accept:`application/json`}});if(e.status!==200)throw Error(`HTTP ${e.status}`);return a_(Da(e.body).data)})(),l_(e)]);i=n,a=r}catch(e){return{stdout:``,stderr:`upskill: failed to fetch skill catalog from ${r_}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=s_(i,r).filter(e=>!a.has(e.entry.name));if(o.length===0)return{stdout:`No new skill recommendations — all matching skills are already installed.
1797
1797
  `,stderr:``,exitCode:0};if(n){let n=new Map;for(let e of o){let t=e.entry.source.repo,r=n.get(t);r?r.push(e):n.set(t,[e])}let r=o.length,i=0,a=Date.now(),s=``,c=``,l=0,u=await Promise.allSettled(Array.from(n.entries()).map(async([n,o])=>{let[c,l]=n.split(`/`),u=await L_(c,l,t);if(u.status===`not_found`||u.status===`error`){let e=u.status===`not_found`?`upskill: repository ${n} not found\n`:`upskill: failed to fetch ${n}: ${u.message}\n`,t=[];for(let e of o){i++,((Date.now()-a)/1e3).toFixed(1);let o=i<r?` (~${Math.round((r-i)*(Date.now()-a)/i/1e3)}s remaining)`:``;s+=`[${i}/${r}] Failed "${e.entry.name}" from ${n}: repo fetch failed${o}\n`,t.push({ok:!1,name:e.entry.name,error:`repo fetch failed for ${n}`})}return{errors:e,results:t}}let d=R_(u.files),f=[],p=new Map;for(let e of Object.keys(d))if(e.endsWith(`/SKILL.md`)){let t=e.replace(/\/SKILL\.md$/,``),n=t.split(`/`).pop()||t;p.set(n,t)}for(let t of o){let o=t.entry.source,c,l;if(o.skill){let e=p.get(o.skill);if(!e){let e=`skill "${o.skill}" not found in ${n}`;f.push({ok:!1,name:t.entry.name,error:e}),i++,((Date.now()-a)/1e3).toFixed(1);let c=i<r?` (~${Math.round((r-i)*(Date.now()-a)/i/1e3)}s remaining)`:``;s+=`[${i}/${r}] Failed "${t.entry.name}" from ${n}: ${e}${c}\n`;continue}c=e,l=o.skill}else c=o.path?o.path.replace(/^\/|\/$/g,``):``,l=t.entry.name;let u=Date.now(),m=await U_(c,l,d,e,!1);i++;let h=((Date.now()-u)/1e3).toFixed(1),g=(Date.now()-a)/i,_=Math.round((r-i)*g/1e3),v=i<r?` (~${_}s remaining)`:``;m.ok?(f.push({ok:!0,name:l}),s+=`[${i}/${r}] Installed "${l}" from ${n} (${h}s)${v}\n`):(f.push({ok:!1,name:l,error:m.error}),s+=`[${i}/${r}] Failed "${l}" from ${n}: ${m.error}${v}\n`)}return{errors:``,results:f}}));for(let e of u){if(e.status===`rejected`){c+=`upskill: unexpected error: ${e.reason}\n`;continue}e.value.errors&&(c+=e.value.errors);for(let t of e.value.results)t.ok?l++:t.error&&(c+=`upskill: ${t.error}\n`)}let d=((Date.now()-a)/1e3).toFixed(1);return l>0&&(s+=`\nInstalled ${l} recommended skill(s) in ${d}s\n`,await H_()),{stdout:s,stderr:c,exitCode:+!!c}}let s=`Recommended skills for you:
1798
1798
 
1799
1799
  `,c=0;for(let e of o){c++;let t=c_(e.entry.source);s+=` ${c}. ${e.entry.displayName.padEnd(35)} score: ${Math.round(e.score)}\n`,s+=` ${e.entry.description}\n`,s+=` Match: ${e.matchReasons.join(`, `)}\n`,s+=` Install: ${t}\n\n`}return s+=`To install all recommended: upskill recommendations --install
@@ -1842,7 +1842,7 @@ Usage: mount <target-path>
1842
1842
  </div>
1843
1843
  `,onAction:async e=>{if(e===`approve`)try{return{approved:!0,handle:await window.showDirectoryPicker({mode:`readwrite`})}}catch(e){return e instanceof Error&&e.name===`AbortError`?{cancelled:!0}:{error:e instanceof Error?e.message:String(e)}}return{denied:!0}}});if(!e)return{stdout:``,stderr:`mount: tool UI not available`,exitCode:1};let t=e;if(t.denied)return{stdout:``,stderr:`mount: denied by user`,exitCode:1};if(t.cancelled)return{stdout:``,stderr:`mount: cancelled`,exitCode:1};if(t.error)return{stdout:``,stderr:`mount: ${t.error}`,exitCode:1};if(!t.handle)return{stdout:``,stderr:`mount: no directory selected`,exitCode:1};o=t.handle}else try{o=await window.showDirectoryPicker({mode:`readwrite`})}catch(e){return e instanceof Error&&e.name===`AbortError`?{stdout:``,stderr:`mount: cancelled`,exitCode:1}:{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}try{return await this.options.fs.mount(r,o),{stdout:`Mounted '${o.name}' → ${r} (live bridge — reads and writes go to the real filesystem)\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}}help(){return{stdout:[`Usage: mount <target-path>`,` mount unmount <path>`,` mount list`,``,`Transparently bridge a real filesystem directory into the virtual filesystem.`,`Opens a directory picker; all reads and writes under <target-path> go directly`,`to the real directory — no copying occurs. Changes are immediately visible on`,`both sides. Mount points must be empty so existing VFS files are not hidden.`,``,`Arguments:`,` <target-path> Mount point in the virtual filesystem (required).`,``,`Sub-commands:`,` unmount <path> Remove a mount point`,` list Show active mount points`,``,`Examples:`,` mount /mnt/myapp # Mount selected dir at /mnt/myapp`,` mount list # Show active mounts`,` mount unmount /mnt/myapp`].join(`
1844
1844
  `)+`
1845
- `,stderr:``,exitCode:0}}},Q_=new Set([`http`,`https`,`net`,`tls`,`dgram`,`dns`,`cluster`,`worker_threads`,`child_process`,`crypto`,`os`,`stream`,`zlib`,`vm`,`v8`,`perf_hooks`,`readline`,`repl`,`tty`,`inspector`]);function $_(e){let t=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,n=[],r;for(;(r=t.exec(e))!==null;)n.push(r[1]);return[...new Set(n)]}async function ev(e,t,n){return await n.fs.exists(e)?tv(await n.fs.readFile(e),[`node`,e,...t],n):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function tv(e,t,n){let r=[],i=[],a=e=>{r.push(typeof e==`string`?e:String(e))},o=e=>{i.push(typeof e==`string`?e:String(e))},s={log:(...e)=>a(`${e.map(Cm).join(` `)}\n`),info:(...e)=>a(`${e.map(Cm).join(` `)}\n`),warn:(...e)=>o(`${e.map(Cm).join(` `)}\n`),error:(...e)=>o(`${e.map(Cm).join(` `)}\n`)},c={argv:t,env:Object.fromEntries(n.env.entries()),cwd:()=>n.cwd,exit:e=>{throw new dm(Number.isFinite(e)?Number(e):0)},stdout:{write:a},stderr:{write:o}},l={readFile:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFile(t)},readFileBinary:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFileBuffer(t)},writeFile:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e);await n.fs.writeFile(r,t)},writeFileBinary:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e),i=new Uint8Array(t.byteLength);i.set(t),await n.fs.writeFile(r,i)},readDir:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readdir(t)},exists:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.exists(t)},stat:async e=>{let t=n.fs.resolvePath(n.cwd,e),r=await n.fs.stat(t);return{isDirectory:r.isDirectory,isFile:r.isFile,size:r.size}},mkdir:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.mkdir(t,{recursive:!0})},rm:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.rm(t,{recursive:!0})},fetchToFile:async(e,t)=>{if(typeof fetch>`u`)throw Error(`fetch is not available in this runtime`);let r=await fetch(e);if(!r.ok)throw Error(`fetch ${r.status} ${r.statusText}`);let i=new Uint8Array(await r.arrayBuffer()),a=n.fs.resolvePath(n.cwd,t);return await n.fs.writeFile(a,i),i.byteLength}},u=async e=>{if(!n.exec)throw Error(`exec is not available in this runtime`);let t=await n.exec(e,{cwd:n.cwd});return{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode}},d=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!d){let t=$_(e),n=new Set([`fs`,`process`,`buffer`]),r=t.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!n.has(e)&&!Q_.has(e)),i=um.__requireCache??=Object.create(null),a=r.filter(e=>!(e in i));if(a.length>0){let e=await Promise.allSettled(a.map(async e=>{let t=await v(()=>import(`https://esm.sh/`+e),[]);return{id:e,value:t.default===void 0?t:t.default}}));for(let t of e)t.status===`fulfilled`&&(i[t.value.id]=t.value.value)}}let f=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return l;if(t===`process`)return c;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=um.__requireCache;if(t&&`path`in t)return t.path;if(t&&e in t)return t[e];throw Error(`require('${e}'): path module not pre-loaded. Add require('path') as a static import.`)}if(Q_.has(t))throw Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${{http:` Use fetch() instead.`,https:` Use fetch() instead.`,child_process:` Use exec() which is available as a shell bridge.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`}[t]||``}`);let n=um.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal so it can be pre-fetched, or use \`await import('https://esm.sh/${e}')\` directly.`)},p={exports:{},filename:t[1]||`<script>`};try{if(d){let r=`
1845
+ `,stderr:``,exitCode:0}}},Q_=new Set([`http`,`https`,`net`,`tls`,`dgram`,`dns`,`cluster`,`worker_threads`,`child_process`,`crypto`,`os`,`stream`,`zlib`,`vm`,`v8`,`perf_hooks`,`readline`,`repl`,`tty`,`inspector`]);function $_(e){let t=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,n=[],r;for(;(r=t.exec(e))!==null;)n.push(r[1]);return[...new Set(n)]}async function ev(e,t,n){return await n.fs.exists(e)?tv(await n.fs.readFile(e),[`node`,e,...t],n):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function tv(e,t,n){let r=[],i=[],a=e=>{r.push(typeof e==`string`?e:String(e))},o=e=>{i.push(typeof e==`string`?e:String(e))},s={log:(...e)=>a(`${e.map(Dm).join(` `)}\n`),info:(...e)=>a(`${e.map(Dm).join(` `)}\n`),warn:(...e)=>o(`${e.map(Dm).join(` `)}\n`),error:(...e)=>o(`${e.map(Dm).join(` `)}\n`)},c={argv:t,env:Object.fromEntries(n.env.entries()),cwd:()=>n.cwd,exit:e=>{throw new hm(Number.isFinite(e)?Number(e):0)},stdout:{write:a},stderr:{write:o}},l={readFile:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFile(t)},readFileBinary:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFileBuffer(t)},writeFile:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e);await n.fs.writeFile(r,t)},writeFileBinary:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e),i=new Uint8Array(t.byteLength);i.set(t),await n.fs.writeFile(r,i)},readDir:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readdir(t)},exists:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.exists(t)},stat:async e=>{let t=n.fs.resolvePath(n.cwd,e),r=await n.fs.stat(t);return{isDirectory:r.isDirectory,isFile:r.isFile,size:r.size}},mkdir:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.mkdir(t,{recursive:!0})},rm:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.rm(t,{recursive:!0})},fetchToFile:async(e,t)=>{if(typeof fetch>`u`)throw Error(`fetch is not available in this runtime`);let r=await fetch(e);if(!r.ok)throw Error(`fetch ${r.status} ${r.statusText}`);let i=new Uint8Array(await r.arrayBuffer()),a=n.fs.resolvePath(n.cwd,t);return await n.fs.writeFile(a,i),i.byteLength}},u=async e=>{if(!n.exec)throw Error(`exec is not available in this runtime`);let t=await n.exec(e,{cwd:n.cwd});return{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode}},d=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!d){let t=$_(e),n=new Set([`fs`,`process`,`buffer`]),r=t.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!n.has(e)&&!Q_.has(e)),i=mm.__requireCache??=Object.create(null),a=r.filter(e=>!(e in i));if(a.length>0){let e=await Promise.allSettled(a.map(async e=>{let t=await v(()=>import(`https://esm.sh/`+e),[]);return{id:e,value:t.default===void 0?t:t.default}}));for(let t of e)t.status===`fulfilled`&&(i[t.value.id]=t.value.value)}}let f=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return l;if(t===`process`)return c;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=mm.__requireCache;if(t&&`path`in t)return t.path;if(t&&e in t)return t[e];throw Error(`require('${e}'): path module not pre-loaded. Add require('path') as a static import.`)}if(Q_.has(t))throw Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${{http:` Use fetch() instead.`,https:` Use fetch() instead.`,child_process:` Use exec() which is available as a shell bridge.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`}[t]||``}`);let n=mm.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal so it can be pre-fetched, or use \`await import('https://esm.sh/${e}')\` directly.`)},p={exports:{},filename:t[1]||`<script>`};try{if(d){let r=`
1846
1846
  const __stdout = [];
1847
1847
  const __stderr = [];
1848
1848
  const __origConsole = { log: console.log, error: console.error, warn: console.warn, info: console.info };
@@ -1938,8 +1938,8 @@ Usage: mount <target-path>
1938
1938
  console.info = __origConsole.info;
1939
1939
  return { stdout: __stdout.join(''), stderr: __stderr.join('') };
1940
1940
  `,i=document.querySelector(`iframe[data-js-tool]`);i||(i=document.createElement(`iframe`),i.style.display=`none`,i.dataset.jsTool=`true`,i.src=chrome.runtime.getURL(`sandbox.html`),document.body.appendChild(i),await new Promise(e=>{i.addEventListener(`load`,()=>e(),{once:!0})}));let a=`jsh-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=e=>{let t=e.data;!t||t.type!==`vfs`||(async()=>{try{let e,r=t.args?.[0]?n.fs.resolvePath(n.cwd,t.args[0]):t.args?.[0];switch(t.op){case`readFile`:e=await n.fs.readFile(r);break;case`readFileBinary`:e=await n.fs.readFileBuffer(r);break;case`writeFile`:await n.fs.writeFile(r,t.args[1]),e=!0;break;case`writeFileBinary`:await n.fs.writeFile(r,t.binaryData??new Uint8Array),e=!0;break;case`readDir`:e=await n.fs.readdir(r);break;case`exists`:e=await n.fs.exists(r);break;case`stat`:{let t=await n.fs.stat(r);e={isDirectory:t.isDirectory,isFile:t.isFile,size:t.size};break}case`mkdir`:await n.fs.mkdir(r,{recursive:!0}),e=!0;break;case`rm`:await n.fs.rm(r,{recursive:!0}),e=!0;break}i.contentWindow.postMessage({type:`vfs_response`,id:t.id,result:e},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`vfs_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,o);let s=e=>{let t=e.data;!t||t.type!==`shell_exec`||(async()=>{try{let e=await u(t.command);i.contentWindow.postMessage({type:`shell_exec_response`,id:t.id,result:e},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`shell_exec_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,s);let l=e=>{let t=e.data;!t||t.type!==`fetch_proxy`||(async()=>{try{let e={method:t.init?.method??`GET`,cache:`no-store`};t.init?.headers&&(e.headers=t.init.headers),t.init?.body&&![`GET`,`HEAD`].includes(e.method)&&(e.body=t.init.body);let n=await fetch(t.url,e),r=await n.arrayBuffer(),a={};n.headers.forEach((e,t)=>{a[t]=e}),i.contentWindow.postMessage({type:`fetch_proxy_response`,id:t.id,status:n.status,statusText:n.statusText,headers:a,body:new Uint8Array(r)},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`fetch_proxy_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,l);let d=await new Promise((e,t)=>{let n,o=t=>{if(t.data?.type===`exec_result`&&t.data.id===a)if(window.removeEventListener(`message`,o),clearTimeout(n),t.data.error)e({stdout:``,stderr:t.data.error+`
1941
- `});else try{let n=JSON.parse(t.data.result);e({stdout:n.stdout||``,stderr:n.stderr||``})}catch{e({stdout:t.data.result||``,stderr:``})}};n=setTimeout(()=>{window.removeEventListener(`message`,o),t(Error(`jsh eval timed out (30s)`))},3e4),window.addEventListener(`message`,o),i.contentWindow.postMessage({type:`exec`,id:a,code:r},`*`)});return window.removeEventListener(`message`,o),window.removeEventListener(`message`,s),window.removeEventListener(`message`,l),{stdout:d.stdout,stderr:d.stderr,exitCode:+!!d.stderr}}let a=Object.getPrototypeOf(async function(){}).constructor;return await new a(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${e}`)(l,c,s,f,p,p.exports,um,u),{stdout:r.join(``),stderr:i.join(``),exitCode:0}}catch(e){if(e instanceof dm)return{stdout:r.join(``),stderr:i.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:r.join(``),stderr:`${i.join(``)}${t}\n`,exitCode:1}}}function nv(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var rv=[`/workspace`,`/shared`];async function iv(e){let t=[],n=new Set;for(let r of rv)await e.exists(r)&&await av(e,r,t,n);return t}async function av(e,t,n,r){for await(let i of e.walk(t)){if(!i.endsWith(`.bsh`)||r.has(i))continue;r.add(i);let t=ov(i);if(!t)continue;let a=await e.readFile(i,{encoding:`utf-8`}),o=sv(typeof a==`string`?a:new TextDecoder().decode(a));n.push({path:i,hostnamePattern:t,matchPatterns:o})}}function ov(e){let t=e.split(`/`).pop()??``;if(!t.endsWith(`.bsh`))return null;let n=t.slice(0,-4);return n?n.startsWith(`-.`)?`*`+n.slice(1):n:null}function sv(e){let t=e.split(`
1942
- `).slice(0,10),n=[];for(let e of t){let t=e.match(/^\s*\/\/\s*@match\s+(.+)$/);t&&n.push(t[1].trim())}return n}function cv(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e===t.slice(2)||e.endsWith(n)&&e.length>n.length}return e===t}function lv(e,t){try{let n=new URL(e),r=t.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/);if(!r)return!1;let[,i,a,o]=r;return i!==`*`&&n.protocol.slice(0,-1)!==i||!cv(n.hostname,a)?!1:o?uv(n.pathname+n.search,o):!0}catch{return!1}}function uv(e,t){let n=`^`+t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`)+`$`;return new RegExp(n).test(e)}function dv(e,t){try{let n=new URL(t);return e.filter(e=>cv(n.hostname,e.hostnamePattern)?e.matchPatterns.length>0?e.matchPatterns.some(e=>lv(t,e)):!0:!1)}catch{return[]}}var fv=[`/workspace`,`/shared`];function pv(e){return new Map(e)}function mv(e){return e.map(e=>({...e,matchPatterns:[...e.matchPatterns]}))}function hv(e){if(e&&typeof e.listMounts==`function`)return e;if(e&&typeof e.getUnderlyingFS==`function`){let t=e.getUnderlyingFS?.();if(t&&typeof t.listMounts==`function`)return t}return null}function gv(e){return(hv(e)?.listMounts?.().length??0)>0}function _v(e){return e?(hv(e)?.listMounts?.()??[]).some(e=>fv.some(t=>e===t||e.startsWith(t+`/`))):!1}var vv=class{jshFs;bshFs;watcher;watcherUnsubs=[];jshCache=null;jshInflight=null;bshCache=null;bshInflight=null;jshGeneration=0;bshGeneration=0;constructor(e){if(this.jshFs=e.jshFs,this.bshFs=e.bshFs,this.watcher=e.watcher??null,this.watcher&&(this.watcherUnsubs.push(this.watcher.watch(`/`,()=>!0,()=>this.invalidateJsh())),this.bshFs))for(let e of fv)this.watcherUnsubs.push(this.watcher.watch(e,()=>!0,()=>this.invalidateBsh()))}dispose(){for(let e of this.watcherUnsubs)e();this.watcherUnsubs.length=0,this.invalidateAll()}invalidateAll(){this.invalidateJsh(),this.invalidateBsh()}invalidateJsh(){this.jshGeneration++,this.jshCache=null,this.jshInflight=null}invalidateBsh(){this.bshGeneration++,this.bshCache=null,this.bshInflight=null}async getJshCommands(){return pv(await this.loadJshCommands())}async getJshCommandNames(){return[...(await this.getJshCommands()).keys()]}async getBshEntries(){return this.bshFs?mv(await this.loadBshEntries()):[]}async findMatchingBshScripts(e){return this.bshFs?mv(dv(await this.loadBshEntries(),e)):[]}shouldCacheJsh(){return!!this.watcher&&!gv(this.jshFs)}shouldCacheBsh(){return!!this.watcher&&!!this.bshFs&&!_v(this.bshFs)}async loadJshCommands(){let e=this.shouldCacheJsh();if(e&&this.jshCache)return this.jshCache;if(!this.jshInflight){let t=this.jshGeneration,n=Xh(this.jshFs).then(n=>{let r=pv(n);return e&&this.jshGeneration===t&&(this.jshCache=r),r}).finally(()=>{this.jshInflight===n&&(this.jshInflight=null)});this.jshInflight=n}return this.jshInflight}async loadBshEntries(){if(!this.bshFs)return[];let e=this.shouldCacheBsh();if(e&&this.bshCache)return this.bshCache;if(!this.bshInflight){let t=this.bshGeneration,n=iv(this.bshFs).then(n=>{let r=mv(n);return e&&this.bshGeneration===t&&(this.bshCache=r),r}).finally(()=>{this.bshInflight===n&&(this.bshInflight=null)});this.bshInflight=n}return this.bshInflight}},yv=null,bv=!1;function xv(){return typeof chrome<`u`&&chrome?.runtime?.id?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function Sv(){if(!bv&&!(typeof localStorage<`u`&&localStorage.getItem(`telemetry-disabled`)===`true`))try{typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),yv=(await v(()=>import(`./src-CgSXdUB7.js`),[])).sampleRUM,bv=!0,yv&&yv(`navigate`,{source:typeof document<`u`?document.referrer:``,target:xv()})}catch{}}function Cv(e,t){yv?.(`formsubmit`,{source:e,target:t})}function wv(e){yv?.(`fill`,{source:e})}function Tv(e){yv?.(`viewblock`,{source:e})}function Ev(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function Dv(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?Dv(e.getUnderlyingFS?.()):null}function Ov(e){if(!e)return!0;let t=e.toLowerCase();return t.startsWith(`text/`)||t.includes(`json`)||t.includes(`xml`)||t.includes(`javascript`)||t.includes(`ecmascript`)||t.includes(`html`)||t.includes(`css`)||t.includes(`svg`)}async function kv(e,t){let n=e.headers.get(`content-type`)??``,r=await e.arrayBuffer(),i=new Uint8Array(r);if(!Ov(n)){let e=32768,n=``;for(let t=0;t<i.length;t+=e)n+=String.fromCharCode(...i.subarray(t,t+e));ba(n,i),t&&xa(t,i)}return i}function Av(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}}function jv(e,t){if(e){if((t?.[`Content-Type`]??t?.[`content-type`]??``).includes(`multipart/form-data`)){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}return e}}function Mv(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();e===`cookie`?t[`X-Proxy-Cookie`]=r:e===`origin`?t[`X-Proxy-Origin`]=r:e===`referer`?t[`X-Proxy-Referer`]=r:e.startsWith(`proxy-`)?t[`X-Proxy-${n}`]=r:t[n]=r}return t}function Nv(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`x-proxy-set-cookie`?t[`set-cookie`]=r:t[n]=r;return t}function Pv(){return typeof chrome<`u`&&chrome?.runtime?.id?async(e,t)=>{let n=Av(t?.headers),r=await fetch(e,{method:t?.method??`GET`,headers:n,body:jv(t?.body,n)}),i=await kv(r,e),a={};return r.headers.forEach((e,t)=>{a[t]=e}),{status:r.status,statusText:r.statusText,headers:a,body:i,url:e}}:async(e,t)=>{let n=t?.method??`GET`,r={...Mv(Av(t?.headers)),"X-Target-URL":e},i={method:n,headers:r,cache:`no-store`};t?.body&&![`GET`,`HEAD`].includes(n)&&(i.body=jv(t.body,r));let a=await fetch(`/api/fetch-proxy`,i);if(a.status===502||a.status===400){let e=await a.text(),t=`Proxy error ${a.status}`;try{t=JSON.parse(e).error??t}catch{}throw Error(t)}let o=await kv(a,e),s={};a.headers.forEach((e,t)=>{s[t]=e});let c=Nv(s);return{status:a.status,statusText:a.statusText,headers:c,body:o,url:e}}}var Fv=class{bash;vfsAdapter;gitCommands;mountCommands;terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;lastEnv;cwd;builtinCommandNames;scriptCatalog;ownsScriptCatalog;constructor(e){this.options=e,this.vfsAdapter=new wa(e.fs);let t=e.cwd??`/`,n={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env};this.gitCommands=new Ef({fs:e.fs,authorName:n.GIT_AUTHOR_NAME??`User`,authorEmail:n.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new Z_({fs:e.fs});let r=e.jshDiscoveryFs??e.fs,i=e.bshDiscoveryFs??e.fs,a=Dv(r)??Dv(i);this.scriptCatalog=e.scriptCatalog??new vv({jshFs:r,bshFs:i,watcher:a}),this.ownsScriptCatalog=!e.scriptCatalog;let o=this.createGitCustomCommand(),s=Kg({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),fs:e.fs,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI}),c=this.createMountCustomCommand(),l=Pv(),u=[o,c,Y_(e.fs),J_(e.fs,l),...s];this.bash=new qe({fs:this.vfsAdapter,cwd:t,env:n,fetch:l,customCommands:u});let d=u.map(e=>e.name);this.builtinCommandNames=new Set([...We(),...Ue(),...d]),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...n},this.cwd=t}createGitCustomCommand(){let e=this.gitCommands;return z(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return z(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||t.set(n,r);return t}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?nv(i):[],s=this.options.jshDiscoveryFs??this.options.fs,c;try{let e=await s.readFile(a,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${a}'\n`,exitCode:127,env:this.lastEnv}}let l=[`node`,a,...o],u=await tv(c,l,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})});return{stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode,env:this.lastEnv}}async runCommand(e,t){wv(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t??this.execAbort?.signal},r=await this.bash.exec(e,n);if(r.env&&(this.lastEnv={...r.env}),r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return t}return r}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await v(async()=>{let{Terminal:e}=await import(`./xterm-DHgoOdoP.js`);return{Terminal:e}},[]),{FitAddon:r}=await v(async()=>{let{FitAddon:e}=await import(`./addon-fit-CJBYijzN.js`);return{FitAddon:e}},[]);await v(()=>Promise.resolve({}),__vite__mapDeps([21]));let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
1941
+ `});else try{let n=JSON.parse(t.data.result);e({stdout:n.stdout||``,stderr:n.stderr||``})}catch{e({stdout:t.data.result||``,stderr:``})}};n=setTimeout(()=>{window.removeEventListener(`message`,o),t(Error(`jsh eval timed out (30s)`))},3e4),window.addEventListener(`message`,o),i.contentWindow.postMessage({type:`exec`,id:a,code:r},`*`)});return window.removeEventListener(`message`,o),window.removeEventListener(`message`,s),window.removeEventListener(`message`,l),{stdout:d.stdout,stderr:d.stderr,exitCode:+!!d.stderr}}let a=Object.getPrototypeOf(async function(){}).constructor;return await new a(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${e}`)(l,c,s,f,p,p.exports,mm,u),{stdout:r.join(``),stderr:i.join(``),exitCode:0}}catch(e){if(e instanceof hm)return{stdout:r.join(``),stderr:i.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:r.join(``),stderr:`${i.join(``)}${t}\n`,exitCode:1}}}function nv(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var rv=[`/workspace`,`/shared`];async function iv(e){let t=[],n=new Set;for(let r of rv)await e.exists(r)&&await av(e,r,t,n);return t}async function av(e,t,n,r){for await(let i of e.walk(t)){if(!i.endsWith(`.bsh`)||r.has(i))continue;r.add(i);let t=ov(i);if(!t)continue;let a=await e.readFile(i,{encoding:`utf-8`}),o=sv(typeof a==`string`?a:new TextDecoder().decode(a));n.push({path:i,hostnamePattern:t,matchPatterns:o})}}function ov(e){let t=e.split(`/`).pop()??``;if(!t.endsWith(`.bsh`))return null;let n=t.slice(0,-4);return n?n.startsWith(`-.`)?`*`+n.slice(1):n:null}function sv(e){let t=e.split(`
1942
+ `).slice(0,10),n=[];for(let e of t){let t=e.match(/^\s*\/\/\s*@match\s+(.+)$/);t&&n.push(t[1].trim())}return n}function cv(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e===t.slice(2)||e.endsWith(n)&&e.length>n.length}return e===t}function lv(e,t){try{let n=new URL(e),r=t.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/);if(!r)return!1;let[,i,a,o]=r;return i!==`*`&&n.protocol.slice(0,-1)!==i||!cv(n.hostname,a)?!1:o?uv(n.pathname+n.search,o):!0}catch{return!1}}function uv(e,t){let n=`^`+t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`)+`$`;return new RegExp(n).test(e)}function dv(e,t){try{let n=new URL(t);return e.filter(e=>cv(n.hostname,e.hostnamePattern)?e.matchPatterns.length>0?e.matchPatterns.some(e=>lv(t,e)):!0:!1)}catch{return[]}}var fv=[`/workspace`,`/shared`];function pv(e){return new Map(e)}function mv(e){return e.map(e=>({...e,matchPatterns:[...e.matchPatterns]}))}function hv(e){if(e&&typeof e.listMounts==`function`)return e;if(e&&typeof e.getUnderlyingFS==`function`){let t=e.getUnderlyingFS?.();if(t&&typeof t.listMounts==`function`)return t}return null}function gv(e){return(hv(e)?.listMounts?.().length??0)>0}function _v(e){return e?(hv(e)?.listMounts?.()??[]).some(e=>fv.some(t=>e===t||e.startsWith(t+`/`))):!1}var vv=class{jshFs;bshFs;watcher;watcherUnsubs=[];jshCache=null;jshInflight=null;bshCache=null;bshInflight=null;jshGeneration=0;bshGeneration=0;constructor(e){if(this.jshFs=e.jshFs,this.bshFs=e.bshFs,this.watcher=e.watcher??null,this.watcher&&(this.watcherUnsubs.push(this.watcher.watch(`/`,()=>!0,()=>this.invalidateJsh())),this.bshFs))for(let e of fv)this.watcherUnsubs.push(this.watcher.watch(e,()=>!0,()=>this.invalidateBsh()))}dispose(){for(let e of this.watcherUnsubs)e();this.watcherUnsubs.length=0,this.invalidateAll()}invalidateAll(){this.invalidateJsh(),this.invalidateBsh()}invalidateJsh(){this.jshGeneration++,this.jshCache=null,this.jshInflight=null}invalidateBsh(){this.bshGeneration++,this.bshCache=null,this.bshInflight=null}async getJshCommands(){return pv(await this.loadJshCommands())}async getJshCommandNames(){return[...(await this.getJshCommands()).keys()]}async getBshEntries(){return this.bshFs?mv(await this.loadBshEntries()):[]}async findMatchingBshScripts(e){return this.bshFs?mv(dv(await this.loadBshEntries(),e)):[]}shouldCacheJsh(){return!!this.watcher&&!gv(this.jshFs)}shouldCacheBsh(){return!!this.watcher&&!!this.bshFs&&!_v(this.bshFs)}async loadJshCommands(){let e=this.shouldCacheJsh();if(e&&this.jshCache)return this.jshCache;if(!this.jshInflight){let t=this.jshGeneration,n=eg(this.jshFs).then(n=>{let r=pv(n);return e&&this.jshGeneration===t&&(this.jshCache=r),r}).finally(()=>{this.jshInflight===n&&(this.jshInflight=null)});this.jshInflight=n}return this.jshInflight}async loadBshEntries(){if(!this.bshFs)return[];let e=this.shouldCacheBsh();if(e&&this.bshCache)return this.bshCache;if(!this.bshInflight){let t=this.bshGeneration,n=iv(this.bshFs).then(n=>{let r=mv(n);return e&&this.bshGeneration===t&&(this.bshCache=r),r}).finally(()=>{this.bshInflight===n&&(this.bshInflight=null)});this.bshInflight=n}return this.bshInflight}},yv=null,bv=!1;function xv(){return typeof chrome<`u`&&chrome?.runtime?.id?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function Sv(){if(!bv&&!(typeof localStorage<`u`&&localStorage.getItem(`telemetry-disabled`)===`true`))try{typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),yv=(await v(()=>import(`./src-CgSXdUB7.js`),[])).sampleRUM,bv=!0,yv&&yv(`navigate`,{source:typeof document<`u`?document.referrer:``,target:xv()})}catch{}}function Cv(e,t){yv?.(`formsubmit`,{source:e,target:t})}function wv(e){yv?.(`fill`,{source:e})}function Tv(e){yv?.(`viewblock`,{source:e})}function Ev(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function Dv(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?Dv(e.getUnderlyingFS?.()):null}function Ov(e){if(!e)return!0;let t=e.toLowerCase();return t.startsWith(`text/`)||t.includes(`json`)||t.includes(`xml`)||t.includes(`javascript`)||t.includes(`ecmascript`)||t.includes(`html`)||t.includes(`css`)||t.includes(`svg`)}async function kv(e,t){let n=e.headers.get(`content-type`)??``,r=await e.arrayBuffer(),i=new Uint8Array(r);if(!Ov(n)){let e=``;for(let t=0;t<i.length;t+=32768)e+=String.fromCharCode(...i.subarray(t,t+32768));ba(e,i),t&&xa(t,i)}return i}function Av(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}}function jv(e,t){if(e){if((t?.[`Content-Type`]??t?.[`content-type`]??``).includes(`multipart/form-data`)){let t=Oa(e);return new Blob([t])}return e}}function Mv(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();e===`cookie`?t[`X-Proxy-Cookie`]=r:e===`origin`?t[`X-Proxy-Origin`]=r:e===`referer`?t[`X-Proxy-Referer`]=r:e.startsWith(`proxy-`)?t[`X-Proxy-${n}`]=r:t[n]=r}return t}function Nv(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`x-proxy-set-cookie`?t[`set-cookie`]=r:t[n]=r;return t}function Pv(){return typeof chrome<`u`&&chrome?.runtime?.id?async(e,t)=>{let n=Av(t?.headers),r=await fetch(e,{method:t?.method??`GET`,headers:n,body:jv(t?.body,n)}),i=await kv(r,e),a={};return r.headers.forEach((e,t)=>{a[t]=e}),{status:r.status,statusText:r.statusText,headers:a,body:i,url:e}}:async(e,t)=>{let n=t?.method??`GET`,r={...Mv(Av(t?.headers)),"X-Target-URL":e},i={method:n,headers:r,cache:`no-store`};t?.body&&![`GET`,`HEAD`].includes(n)&&(i.body=jv(t.body,r));let a=await fetch(`/api/fetch-proxy`,i);if(a.status===502||a.status===400){let e=await a.text(),t=`Proxy error ${a.status}`;try{t=JSON.parse(e).error??t}catch{}throw Error(t)}let o=await kv(a,e),s={};a.headers.forEach((e,t)=>{s[t]=e});let c=Nv(s);return{status:a.status,statusText:a.statusText,headers:c,body:o,url:e}}}var Fv=class{bash;vfsAdapter;gitCommands;mountCommands;terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;lastEnv;cwd;builtinCommandNames;scriptCatalog;ownsScriptCatalog;constructor(e){this.options=e,this.vfsAdapter=new wa(e.fs);let t=e.cwd??`/`,n={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env};this.gitCommands=new Af({fs:e.fs,authorName:n.GIT_AUTHOR_NAME??`User`,authorEmail:n.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new Z_({fs:e.fs});let r=e.jshDiscoveryFs??e.fs,i=e.bshDiscoveryFs??e.fs,a=Dv(r)??Dv(i);this.scriptCatalog=e.scriptCatalog??new vv({jshFs:r,bshFs:i,watcher:a}),this.ownsScriptCatalog=!e.scriptCatalog;let o=this.createGitCustomCommand(),s=Xg({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),fs:e.fs,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI}),c=this.createMountCustomCommand(),l=Pv(),u=[o,c,Y_(e.fs),J_(e.fs,l),...s];this.bash=new qe({fs:this.vfsAdapter,cwd:t,env:n,fetch:l,customCommands:u});let d=u.map(e=>e.name);this.builtinCommandNames=new Set([...We(),...Ue(),...d]),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...n},this.cwd=t}createGitCustomCommand(){let e=this.gitCommands;return z(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return z(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||t.set(n,r);return t}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?nv(i):[],s=this.options.jshDiscoveryFs??this.options.fs,c;try{let e=await s.readFile(a,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${a}'\n`,exitCode:127,env:this.lastEnv}}let l=[`node`,a,...o],u=await tv(c,l,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})});return{stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode,env:this.lastEnv}}async runCommand(e,t){wv(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t??this.execAbort?.signal},r=await this.bash.exec(e,n);if(r.env&&(this.lastEnv={...r.env}),r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return t}return r}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await v(async()=>{let{Terminal:e}=await import(`./xterm-DHgoOdoP.js`);return{Terminal:e}},[]),{FitAddon:r}=await v(async()=>{let{FitAddon:e}=await import(`./addon-fit-CJBYijzN.js`);return{FitAddon:e}},[]);await v(()=>Promise.resolve({}),__vite__mapDeps([21]));let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
1943
1943
  `),this.showPrompt(),this.setupInputHandler()}async executeCommand(e,t){let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}async executeScriptFile(e,t=[]){return ev(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})})}refit(){this.fitAddon?.fit()}setPreviewStateListener(e){this.previewStateListener=e,this.previewStateListener?.(this.hasPreview)}async executeCommandInTerminal(e){let t=e.trim();if(!t)return{stdout:``,stderr:``,exitCode:0};if(!this.terminal)return this.executeCommand(t);if(this.isExecuting||this.currentLine.length>0||this.continuationBuffer.length>0)return{stdout:``,stderr:`terminal is busy; finish current input first
1944
1944
  `,exitCode:1};this.history[this.history.length-1]!==t&&this.history.push(t),this.historyIndex=-1,this.terminal.write(t),this.terminal.writeln(``),this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(t),n=this.execAbort.signal.aborted;return this.execAbort=null,n?{stdout:``,stderr:``,exitCode:130}:(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0),{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode})}catch(e){if(this.execAbort?.signal.aborted)return this.execAbort=null,{stdout:``,stderr:``,exitCode:130};this.execAbort=null;let t=`Error: ${e instanceof Error?e.message:String(e)}\n`;return this.writeToTerminal(t,!0),{stdout:``,stderr:t,exitCode:1}}finally{this.isExecuting=!1,this.showPrompt()}}clearTerminal(){this.terminal?.clear(),this.clearMediaPreview()}dispose(){this.themeObserver?.disconnect(),this.themeObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.clearMediaPreview(),this.terminal?.dispose(),this.terminal=null,this.fitAddon=null,this.terminalHost=null,this.previewHost=null,this.ownsScriptCatalog&&this.scriptCatalog.dispose()}showPrompt(){if(!this.terminal)return;let e=this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd;this.terminal.write(`\x1b[34m${e}\x1b[0m \x1b[90m$\x1b[0m `)}setupInputHandler(){this.terminal&&this.terminal.onData(e=>{if(this.isExecuting){(e===``||e.length===1&&e.charCodeAt(0)===3)&&(this.execAbort?.abort(),this.terminal?.writeln(`^C`));return}if(e.startsWith(`\x1B[`)||e.startsWith(`\x1BO`)){switch(e){case`\x1B[A`:this.handleHistoryUp();return;case`\x1B[B`:this.handleHistoryDown();return;case`\x1B[C`:this.handleArrowRight();return;case`\x1B[D`:this.handleArrowLeft();return;case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:this.handleHome();return;case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:this.handleEnd();return;case`\x1B[3~`:this.handleDelete();return}return}for(let t of e)switch(t){case`\r`:this.handleEnter();break;case``:this.handleBackspace();break;case``:this.handleCtrlC();break;case` `:this.handleTab();break;default:t>=` `&&this.insertChar(t)}})}getPromptWidth(){return(this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd).length+3}getCursorVisualLine(){let e=0;for(let[t,n]of this.currentLine.split(`
1945
1945
  `).entries()){if(e+n.length>=this.cursorPos)return t;e+=n.length+1}return 0}positionTerminalCursor(){let e=this.currentLine.split(`
@@ -12644,7 +12644,7 @@ The following skills are available. To use a skill, first read its full instruct
12644
12644
  ${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowedTools.join(`, `)}\n`:``;return`- **${e.metadata.name}**: ${e.metadata.description}\n${t} Path: ${e.path}`}).join(`
12645
12645
  `)}
12646
12646
  ---`}async function Ey(e,t=`/workspace/skills`){let n=yy();for(let[r,i]of Object.entries(n)){let n=r.slice(18),a=n.startsWith(`/workspace/skills`),o=n.startsWith(`/workspace/scripts`);if(!a&&!o)continue;let s=n;a&&t!==`/workspace/skills`&&(s=n.replace(`/workspace/skills`,t)),o&&t!==`/workspace/skills`&&(s=t.replace(`/workspace/skills`,``)+n);try{await e.stat(s)}catch{let t=s.substring(0,s.lastIndexOf(`/`));try{await e.mkdir(t,{recursive:!0})}catch{}await e.writeFile(s,i),hy.info(`Created default file`,{path:s})}}}async function Dy(e){let t=yy();for(let[n,r]of Object.entries(t)){let t=n.slice(18);if(t.startsWith(`/shared/`))try{await e.stat(t)}catch{let n=t.substring(0,t.lastIndexOf(`/`));try{await e.mkdir(n,{recursive:!0})}catch{}await e.writeFile(t,r),hy.info(`Created default shared file`,{path:t})}}}var Oy=n(`scoop-management-tools`);function ky(e){let{scoop:t,onSendMessage:n,onFeedScoop:r,getScoops:i,getScoopTabState:a,onScoopScoop:o,onDropScoop:s,onSetGlobalMemory:c,getGlobalMemory:l}=e,u=[];return u.push({name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:async e=>{let{text:r,sender:i}=e;return n(r,i),Oy.info(`Message sent`,{scoopFolder:t.folder,textLength:r.length}),{content:`Message sent.`}}}),t.isCone&&r&&u.push({name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:async e=>{let{scoop_name:t,prompt:n}=e,a=i().find(e=>e.folder===t||e.name===t);if(!a)return{content:`Scoop "${t}" not found. Available: ${i().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0};if(a.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await r(a.jid,n),Oy.info(`Fed scoop`,{target:a.folder,promptLength:n.length}),{content:`Task sent to ${a.folder}. You will be notified when it completes.`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),t.isCone&&(u.push({name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:async()=>{let e=i();return e.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${e.map(e=>{let t=a?.(e.jid),n=t?.status??`unknown`,r=t?.lastActivity?new Date(t.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,i=r?` — ${n} (since ${r})`:` — ${n}`;return e.isCone?`- ${e.assistantLabel} (${e.folder}) [CONE]${i}`:`- ${e.name} (${e.folder})${i}`}).join(`
12647
- `)}`}}}),o&&u.push({name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model and/or a prompt. If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`}},required:[`name`]},execute:async e=>{let{name:t,model:n,prompt:i}=e,a=t.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`;try{let e=await o({name:t,folder:a,trigger:`@${a}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:a,addedAt:new Date().toISOString(),config:n?{modelId:n}:void 0});return Oy.info(`Scoop created`,{name:t,folder:a}),i&&r?(r(e.jid,i).catch(e=>{let n=e instanceof Error?e.message:String(e);Oy.error(`Auto-feed failed`,{name:t,error:n})}),{content:`Scoop "${t}" created as "${a}" and task sent. It will start working as soon as initialization completes.`}):{content:`Scoop "${t}" created as "${a}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),s&&u.push({name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:async e=>{let{scoop_name:t}=e,n=i().find(e=>e.folder===t||e.name===t);if(!n)return{content:`Scoop "${t}" not found. Available: ${i().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0};if(n.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await s(n.jid),Oy.info(`Scoop dropped`,{name:n.name,folder:n.folder}),{content:`Scoop "${n.name}" (${n.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),c&&l&&u.push({name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:async e=>{let{content:t}=e;try{return await c(t),Oy.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}})),u}var Ay=n(`secret-env`);async function jy(){if(typeof chrome<`u`&&chrome?.runtime?.id)return{};try{let e=await fetch(`/api/secrets/masked`);if(!e.ok)return Ay.warn(`Failed to fetch masked secrets`,{status:e.status}),{};let t=await e.json();if(!Array.isArray(t)||t.length===0)return{};let n={};for(let e of t)e.name&&e.maskedValue&&(n[e.name]=e.maskedValue);return Object.keys(n).length>0&&Ay.info(`Loaded masked secrets into shell env`,{count:Object.keys(n).length}),n}catch(e){return Ay.debug(`Could not fetch masked secrets (server may be unavailable)`,{error:e instanceof Error?e.message:String(e)}),{}}}var My=n(`scoop-context`);function Ny(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}var Py=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;didStreamDeltas=!1;unsubscribe=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;skillsFs=null;skillsDir=`/workspace/skills`;constructor(e,t,n,r,i){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.sessionId=e.jid}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);My.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let e=this.scoop.isCone?`/`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await Ey(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await jy();this.shell=new Fv({fs:this.fs,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0}),My.info(`WasmShell initialized`,{folder:this.scoop.folder});let i=await Sy(n,this.skillsDir),a=ky({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory}),o=y([...Lv(this.fs),Gv(this.shell),...a]),s=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,c=``;try{let e=await this.fs.readFile(s,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let l=await this.callbacks.getGlobalMemory();if(l)try{this.scoop.isCone&&await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,l)}catch{}if(!T()){let e=ie();throw Error(`No API key configured for provider "${e}"`)}let u=this.scoop.config?.modelId?S(this.scoop.config.modelId):re(),d=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${d} using model: ${u.id} (provider: ${u.provider})`);let f=this.buildSystemPrompt(l,c,i),p=[];if(this.sessionStore)try{let e=await this.sessionStore.load(this.sessionId);e&&(p=e.messages,this.sessionCreatedAt=e.createdAt,My.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:p.length}))}catch(e){My.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}let m=O({model:u,getApiKey:()=>T()??void 0});this.agent=new b({initialState:{model:u,tools:o,systemPrompt:f,messages:p},getApiKey:()=>T()??void 0,transformContext:m}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),My.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:o.length})}catch(e){let t=e instanceof Error?e.message:String(e);My.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async prompt(e){if(!this.agent){this.callbacks.onError(`Agent not initialized`);return}let t=this.agent.state?.isStreaming??!1;if(this.isProcessing||t){My.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:t}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()});return}this.isProcessing=!0,this.didStreamDeltas=!1,this.setStatus(`processing`);try{await this.agent.prompt(e)}catch(e){let t=e instanceof Error?e.message:String(e);My.error(`Agent error`,{folder:this.scoop.folder,error:t}),this.callbacks.onError(t)}finally{this.isProcessing=!1,this.setStatus(`ready`)}}stop(){this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=re();this.agent.state.model=e,My.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id})}async reloadSkills(){if(!this.agent)return;let e=await Sy(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,My.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}dispose(){this.unsubscribe?.(),this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.status=e,this.callbacks.onStatusChange(e)}handleAgentEvent(e){switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:{let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId);break}case`tool_execution_end`:{let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);this.callbacks.onToolEnd?.(e.toolName,n.join(`
12647
+ `)}`}}}),o&&u.push({name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model and/or a prompt. If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`}},required:[`name`]},execute:async e=>{let{name:t,model:n,prompt:i}=e,a=t.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`;try{let e=await o({name:t,folder:a,trigger:`@${a}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:a,addedAt:new Date().toISOString(),config:n?{modelId:n}:void 0});return Oy.info(`Scoop created`,{name:t,folder:a}),i&&r?(r(e.jid,i).catch(e=>{let n=e instanceof Error?e.message:String(e);Oy.error(`Auto-feed failed`,{name:t,error:n})}),{content:`Scoop "${t}" created as "${a}" and task sent. It will start working as soon as initialization completes.`}):{content:`Scoop "${t}" created as "${a}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),s&&u.push({name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:async e=>{let{scoop_name:t}=e,n=i().find(e=>e.folder===t||e.name===t);if(!n)return{content:`Scoop "${t}" not found. Available: ${i().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0};if(n.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await s(n.jid),Oy.info(`Scoop dropped`,{name:n.name,folder:n.folder}),{content:`Scoop "${n.name}" (${n.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),c&&l&&u.push({name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:async e=>{let{content:t}=e;try{return await c(t),Oy.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}})),u}var Ay=n(`secret-env`);async function jy(){if(typeof chrome<`u`&&chrome?.runtime?.id)return{};try{let e=await fetch(`/api/secrets/masked`);if(!e.ok)return Ay.warn(`Failed to fetch masked secrets`,{status:e.status}),{};let t=await e.json();if(!Array.isArray(t)||t.length===0)return{};let n={};for(let e of t)e.name&&e.maskedValue&&(n[e.name]=e.maskedValue);return Object.keys(n).length>0&&Ay.info(`Loaded masked secrets into shell env`,{count:Object.keys(n).length}),n}catch(e){return Ay.debug(`Could not fetch masked secrets (server may be unavailable)`,{error:e instanceof Error?e.message:String(e)}),{}}}var My=n(`scoop-context`);function Ny(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}var Py=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;unsubscribe=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;skillsFs=null;skillsDir=`/workspace/skills`;constructor(e,t,n,r,i){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.sessionId=e.jid}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);My.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let e=this.scoop.isCone?`/`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await Ey(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await jy();this.shell=new Fv({fs:this.fs,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0}),My.info(`WasmShell initialized`,{folder:this.scoop.folder});let i=await Sy(n,this.skillsDir),a=ky({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory}),o=y([...Lv(this.fs),Gv(this.shell),...a]),s=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,c=``;try{let e=await this.fs.readFile(s,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let l=await this.callbacks.getGlobalMemory();if(l)try{this.scoop.isCone&&await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,l)}catch{}if(!T()){let e=ie();throw Error(`No API key configured for provider "${e}"`)}let u=this.scoop.config?.modelId?S(this.scoop.config.modelId):re(),d=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${d} using model: ${u.id} (provider: ${u.provider})`);let f=this.buildSystemPrompt(l,c,i),p=[];if(this.sessionStore)try{let e=await this.sessionStore.load(this.sessionId);e&&(p=e.messages,this.sessionCreatedAt=e.createdAt,My.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:p.length}))}catch(e){My.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}let m=O({model:u,getApiKey:()=>T()??void 0});if(this.disposed)return;this.agent=new b({initialState:{model:u,tools:o,systemPrompt:f,messages:p},getApiKey:()=>T()??void 0,transformContext:m}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),My.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:o.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);My.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async prompt(e){if(!this.agent){this.callbacks.onError(`Agent not initialized`);return}let t=this.agent.state?.isStreaming??!1;if(this.isProcessing||t){My.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:t}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()});return}this.isProcessing=!0,this.didStreamDeltas=!1,this.setStatus(`processing`);try{await this.agent.prompt(e)}catch(e){if(!this.disposed){let t=e instanceof Error?e.message:String(e);My.error(`Agent error`,{folder:this.scoop.folder,error:t}),this.callbacks.onError(t)}}finally{this.isProcessing=!1,this.setStatus(`ready`)}}stop(){this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=re();this.agent.state.model=e,My.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id})}async reloadSkills(){if(!this.agent)return;let e=await Sy(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,My.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}dispose(){this.disposed=!0,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleAgentEvent(e){if(!this.disposed)switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:{let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId);break}case`tool_execution_end`:{let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);this.callbacks.onToolEnd?.(e.toolName,n.join(`
12648
12648
  `),e.isError);break}case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:{let t=e.messages;if(t.length>0){let e=t[t.length-1];if(e.role===`assistant`&&e.errorMessage){let n=e.errorMessage;if(!this.isRecovering&&Ny(n)){this.recoverFromImageError(t);break}if(!this.isRecovering&&x(e)){this.recoverFromOverflow(t);break}this.isRecovering=!1,this.callbacks.onError(n)}else this.isRecovering=!1}let n=this.agent?.state?.messages??e.messages;this.sessionStore&&n.length>0&&this.sessionStore.save({id:this.sessionId,messages:n,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{My.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})});break}}}recoverFromOverflow(e){if(this.agent){My.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`overflow`,this.callbacks.onResponse(`Context window exceeded — recovering by trimming oversized messages...`,!1);try{let t=e.slice(0,-1),n=0;for(let e=t.length-1;e>=0&&n<5;e--){let r=t[e];if(!Array.isArray(r.content))continue;let i=0;for(let e of r.content)e.type===`text`&&e.text&&(i+=e.text.length),e.type===`image`&&e.data&&(i+=e.data.length);if(i>4e4){let a={type:`text`,text:`[Content removed: ${r.role===`toolResult`?`tool result`:r.role} was too large for context window (${Math.round(i/1e3)}K chars). The operation completed but output could not be retained.]`};if(r.role===`assistant`){let n=r.content.filter(e=>e.type===`toolCall`);t[e]={...r,content:[a,...n]}}else t[e]={...r,content:[a]};n++,My.info(`Replaced oversized message`,{index:e,role:r.role,size:i,preservedToolCalls:r.role===`assistant`?r.content.filter(e=>e.type===`toolCall`).length:0})}}this.agent.state.messages=t;let r=n>0?`[System: Context overflow recovered. ${n} oversized message(s) were replaced with placeholders to fit within the context window. The conversation continues — you may need to re-read files or re-run commands if their output was removed.]`:`[System: Context overflow recovered. Older messages were trimmed. The conversation continues — compaction will summarize history on the next turn.]`;this.agent.prompt(r).catch(e=>{My.error(`Recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){My.error(`Recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}recoverFromImageError(e){if(this.agent){My.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`image`,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{My.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){My.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.scoop.isCone?[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
12649
12649
 
12650
12650
  ${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
@@ -12725,11 +12725,11 @@ ${e}
12725
12725
  ${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
12726
12726
  ${t}
12727
12727
  ---`);let a=Ty(n);return a&&(i+=a),i}},Fy=n(`scheduler`),Iy=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=window.setInterval(()=>this.checkTasks(),6e4),this.checkTasks(),Fy.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,Fy.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await He(i),Fy.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await Me(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await He(r),Fy.info(`Task updated`,{id:e,updates:Object.keys(t)}),r}async pauseTask(e){return await this.updateTask(e,{status:`paused`})!==null}async resumeTask(e){return await Me(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await Me(e)?(await Ce(e),Fy.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await je()).filter(t=>t.groupFolder===e)}async getAllTasks(){return je()}async checkTasks(){let e=await je(),t=new Date;for(let n of e)n.status===`active`&&n.nextRun&&(new Date(n.nextRun)>t||await this.runTask(n))}async runTask(e){let t=this.callbacks.getScoop(e.groupFolder);if(!t){Fy.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}Fy.info(`Running task`,{id:e.id,groupFolder:e.groupFolder});try{let n=new Date().toISOString(),r=this.calculateNextRun(e.scheduleType,e.scheduleValue),i=e.scheduleType===`once`?`completed`:e.status;await He({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),Fy.info(`Task completed`,{id:e.id})}catch(t){Fy.error(`Task execution failed`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}calculateNextRun(e,t){let n=new Date;switch(e){case`cron`:return this.getNextCronTime(t,n)?.toISOString()??null;case`interval`:{let e=parseInt(t,10);return isNaN(e)||e<=0?null:new Date(n.getTime()+e).toISOString()}case`once`:return new Date(t)>n?t:null;default:return null}}getNextCronTime(e,t){let n=e.trim().split(/\s+/);if(n.length!==5)return null;let[r,i,a,o,s]=n,c=new Date(t);c.setSeconds(0),c.setMilliseconds(0),c.setMinutes(c.getMinutes()+1);for(let e=0;e<527040;e++){if(this.cronMatches(c,r,i,a,o,s))return c;c.setMinutes(c.getMinutes()+1)}return null}cronMatches(e,t,n,r,i,a){return this.cronFieldMatches(e.getMinutes(),t)&&this.cronFieldMatches(e.getHours(),n)&&this.cronFieldMatches(e.getDate(),r)&&this.cronFieldMatches(e.getMonth()+1,i)&&this.cronFieldMatches(e.getDay(),a)}cronFieldMatches(e,t){if(t===`*`)return!0;if(t.includes(`,`))return t.split(`,`).some(t=>this.cronFieldMatches(e,t.trim()));if(t.includes(`-`)){let[n,r]=t.split(`-`).map(e=>parseInt(e,10));return e>=n&&e<=r}if(t.includes(`/`)){let[n,r]=t.split(`/`),i=parseInt(r,10);if(n===`*`)return e%i===0;let a=parseInt(n,10);return e>=a&&(e-a)%i===0}return parseInt(t,10)===e}},Ly=n(`lick-manager`),Ry=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;async init(){await ke();let e=await ze();for(let t of e)this.webhooks.set(t.id,t);Ly.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Le();for(let e of t)this.crontasks.set(e.id,e);Ly.info(`Loaded crontasks`,{count:this.crontasks.size}),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),Ly.info(`Cron scheduler started`)}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}emitEvent(e){Ly.info(`External lick event`,{type:e.type,target:e.targetScoop}),this.eventHandler?.(e)}async createWebhook(e,t,n){let r=this.generateId(),i={id:r,name:e,createdAt:new Date().toISOString(),filter:n,scoop:t};return n&&this.compileFilter(n,!0),this.webhooks.set(r,i),await we(i),Ly.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await Pe(e),Ly.info(`Webhook deleted`,{id:e}),!0):!1}listWebhooks(){return Array.from(this.webhooks.values())}getWebhook(e){return this.webhooks.get(e)}handleWebhookEvent(e,t,n){let r=this.webhooks.get(e);if(!r){Ly.warn(`Webhook not found`,{webhookId:e});return}let i={type:`webhook`,webhookId:e,webhookName:r.name,targetScoop:r.scoop,timestamp:new Date().toISOString(),headers:t,body:n};if(r.filter)try{let t=this.compileFilter(r.filter,!0)(i);if(t===!1){Ly.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name});return}typeof t==`object`&&t&&(i=t)}catch(t){Ly.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}Ly.info(`Webhook event received`,{webhookId:e,name:r.name,targetScoop:r.scoop}),this.eventHandler?.(i)}async createCronTask(e,t,n,r){let i=this.getNextCronTime(t,new Date);if(!i)throw Error(`Invalid cron expression`);r&&this.compileFilter(r,!1);let a=this.generateId(),o={id:a,name:e,cron:t,scoop:n,filter:r,nextRun:i.toISOString(),lastRun:null,status:`active`,createdAt:new Date().toISOString()};return this.crontasks.set(a,o),await Oe(o),Ly.info(`Cron task created`,{id:a,name:e,cron:t,scoop:n}),o}async deleteCronTask(e){return this.crontasks.has(e)?(this.crontasks.delete(e),await Ne(e),Ly.info(`Cron task deleted`,{id:e}),!0):!1}listCronTasks(){return Array.from(this.crontasks.values())}getCronTask(e){return this.crontasks.get(e)}getLicksForScoop(e,t){let n=n=>n===e||n===t||`${n}-scoop`===t;return{webhooks:Array.from(this.webhooks.values()).filter(e=>n(e.scoop)),cronTasks:Array.from(this.crontasks.values()).filter(e=>n(e.scoop))}}async runCronScheduler(){let e=new Date;for(let t of this.crontasks.values()){if(t.status!==`active`||!t.nextRun||new Date(t.nextRun)>e)continue;let n={time:e.toISOString()};if(t.filter)try{let r=this.compileFilter(t.filter,!1)(null);if(r===!1){Ly.debug(`Cron task skipped by filter`,{id:t.id,name:t.name}),t.nextRun=this.getNextCronTime(t.cron,e)?.toISOString()??null,t.lastRun=e.toISOString(),await Oe(t);continue}typeof r==`object`&&r&&(n=r)}catch(e){Ly.error(`Cron filter error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}let r={type:`cron`,cronId:t.id,cronName:t.name,targetScoop:t.scoop,timestamp:e.toISOString(),body:n};Ly.info(`Cron task running`,{id:t.id,name:t.name}),this.eventHandler?.(r),t.nextRun=this.getNextCronTime(t.cron,e)?.toISOString()??null,t.lastRun=e.toISOString(),await Oe(t)}}generateId(){let e=``;for(let t=0;t<12;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return e}compileFilter(e,t){try{return t?Function(`event`,`return (${e})(event);`):Function(`return (${e})();`)}catch(e){throw Error(`Invalid filter function: ${e instanceof Error?e.message:String(e)}`)}}getNextCronTime(e,t){let n=e.trim().split(/\s+/);if(n.length!==5)return null;let[r,i,a,o,s]=n,c=new Date(t);c.setSeconds(0),c.setMilliseconds(0),c.setMinutes(c.getMinutes()+1);let l=(e,t)=>{if(t===`*`)return!0;if(t.includes(`,`))return t.split(`,`).some(t=>l(e,t.trim()));if(t.includes(`-`)){let[n,r]=t.split(`-`).map(e=>parseInt(e,10));return e>=n&&e<=r}if(t.includes(`/`)){let[n,r]=t.split(`/`),i=parseInt(r,10);if(n===`*`)return e%i===0;let a=parseInt(n,10);return e>=a&&(e-a)%i===0}return parseInt(t,10)===e};for(let e=0;e<527040;e++){if(l(c.getMinutes(),r)&&l(c.getHours(),i)&&l(c.getDate(),a)&&l(c.getMonth()+1,o)&&l(c.getDay(),s))return c;c.setMinutes(c.getMinutes()+1)}return null}};function zy(e,t,n){if(t.length===0&&n.length===0)return null;let r=[];t.length>0&&r.push(`${t.length} active webhook${t.length>1?`s`:``}`),n.length>0&&r.push(`${n.length} active cron task${n.length>1?`s`:``}`);let i=[...t.map(e=>` webhook delete ${e.id}`),...n.map(e=>` crontask delete ${e.id}`)].join(`
12728
- `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var By=null;function Vy(){return By||=new Ry,By}var Q=n(`orchestrator`),Hy=120*1e3,Uy=class{scoops=new Map;tabs=new Map;contexts=new Map;messageQueues=new Map;lastAgentTimestamp=new Map;container;callbacks;config;pollInterval=null;scheduler=null;globalMemoryCache=``;sharedFs=null;scoopResponseBuffer=new Map;lickManager=null;sessionStore=null;fsWatcher=null;idleTimers=new Map;constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n}async init(){await ke(),this.sharedFs=await I.create({dbName:`slicc-fs`}),this.sessionStore=new D,this.fsWatcher=new se,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure();let e=await Te();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.scoops.set(t.jid,t),this.messageQueues.set(t.jid,[]);let e=await Fe(`lastAgentTs_${t.jid}`);e&&this.lastAgentTimestamp.set(t.jid,e)}await this.ensureGlobalMemory(),this.scheduler=new Iy({onTaskRun:async(e,t)=>{Q.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),Q.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())await this.createScoopTab(e.jid);Ke(()=>this.getSessionCosts()),this.startMessageLoop()}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}async ensureGlobalMemory(){if(this.sharedFs){await Dy(this.sharedFs);try{let e=await this.sharedFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof e==`string`?e:new TextDecoder().decode(e)}catch{Q.warn(`Global memory file not found after creating defaults`)}}}async getGlobalMemory(){if(this.globalMemoryCache)return this.globalMemoryCache;if(this.sharedFs)try{let e=await this.sharedFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}return this.globalMemoryCache}async setGlobalMemory(e){this.sharedFs&&(await this.sharedFs.writeFile(`/shared/CLAUDE.md`,e),this.globalMemoryCache=e,Q.info(`Global memory updated`))}getSharedFS(){return this.sharedFs}setLickManager(e){this.lickManager=e,globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}async registerScoop(e){await Be(e),this.scoops.set(e.jid,e),this.messageQueues.set(e.jid,[]),Q.info(`Scoop registered`,{jid:e.jid,name:e.name}),this.createScoopTab(e.jid).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Scoop init failed`,{jid:e.jid,error:n})})}async unregisterScoop(e){let t=this.scoops.get(e);if(t&&this.lickManager){let{webhooks:e,cronTasks:n}=this.lickManager.getLicksForScoop(t.name,t.folder),r=zy(t.folder,e,n);if(r)throw r}this.clearIdleTimer(e),await this.destroyScoopTab(e),this.sessionStore?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await Ae(e),this.scoops.delete(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),Q.info(`Scoop unregistered`,{jid:e})}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){for(let[e,t]of this.contexts.entries())this.clearIdleTimer(e),t.stop(),this.contexts.delete(e);this.sharedFs=await I.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await Ey(this.sharedFs).catch(e=>{Q.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),Q.info(`Filesystem reset and defaults re-seeded`)}async clearAllMessages(){await Re(),this.sessionStore&&await this.sessionStore.clearAll().catch(e=>{Q.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.contexts.values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.scoops.keys())this.messageQueues.set(e,[]);Q.info(`All messages cleared`)}async handleMessage(e){Q.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)});let t=this.scoops.get(e.chatJid);Cv(t?.isCone?`cone`:t?.name??`unknown`,localStorage.getItem(`selected-model`)??`unknown`),await Se(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.scoops.get(e);if(!r)throw Error(`Scoop not found: ${e}`);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await Se(i),this.callbacks.onIncomingMessage?.(e,i),Q.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Delegation failed`,{scoopJid:e,error:n}),this.callbacks.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.scoops.get(e.chatJid);if(!t){Q.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){Q.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.tabs.get(e.chatJid);if(Q.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){Q.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.createScoopTab(e.chatJid),i=this.tabs.get(e.chatJid)}catch{Q.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async createScoopTab(e){let t=this.scoops.get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{Q.debug(`Context already exists`,{jid:e});return}if(!this.sharedFs)throw Error(`Shared filesystem not initialized`);let n=`scoop-${t.folder}-${Date.now()}`,r=t.isCone?this.sharedFs:new le(this.sharedFs,[`/scoops/${t.folder}/`,`/shared/`],[`/workspace/`]),i=new Py(t,{onResponse:(n,r)=>{if(this.callbacks.onResponse(e,n,r),!t.isCone)if(r){let t=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,t+n)}else this.scoopResponseBuffer.set(e,n)},onResponseDone:()=>{let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),this.callbacks.onResponseDone(e)},onError:t=>{let n=this.tabs.get(e);n&&(n.status=`error`,n.error=t,this.tabs.set(e,n)),this.callbacks.onError(e,t),this.callbacks.onStatusChange(e,`error`)},onStatusChange:n=>{let r=this.tabs.get(e);if(r&&(r.status=n,r.lastActivity=new Date().toISOString(),this.tabs.set(e,r)),this.callbacks.onStatusChange(e,n),n===`ready`&&!t.isCone){let n=this.scoopResponseBuffer.get(e);if(this.scoopResponseBuffer.delete(e),n){let r=Array.from(this.scoops.values()).find(e=>e.isCone);if(r){let i=n.length>2e3?n.slice(0,2e3)+`
12728
+ `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var By=null;function Vy(){return By||=new Ry,By}var Q=n(`orchestrator`),Hy=120*1e3,Uy=class{scoops=new Map;tabs=new Map;contexts=new Map;messageQueues=new Map;lastAgentTimestamp=new Map;container;callbacks;config;pollInterval=null;scheduler=null;globalMemoryCache=``;sharedFs=null;scoopResponseBuffer=new Map;lickManager=null;sessionStore=null;fsWatcher=null;idleTimers=new Map;constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n}async init(){await ke(),this.sharedFs=await I.create({dbName:`slicc-fs`}),this.sessionStore=new D,this.fsWatcher=new se,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure();let e=await Te();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.scoops.set(t.jid,t),this.messageQueues.set(t.jid,[]);let e=await Fe(`lastAgentTs_${t.jid}`);e&&this.lastAgentTimestamp.set(t.jid,e)}await this.ensureGlobalMemory(),this.scheduler=new Iy({onTaskRun:async(e,t)=>{Q.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),Q.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())await this.createScoopTab(e.jid);Ke(()=>this.getSessionCosts()),this.startMessageLoop()}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}async ensureGlobalMemory(){if(this.sharedFs){await Dy(this.sharedFs);try{let e=await this.sharedFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof e==`string`?e:new TextDecoder().decode(e)}catch{Q.warn(`Global memory file not found after creating defaults`)}}}async getGlobalMemory(){if(this.globalMemoryCache)return this.globalMemoryCache;if(this.sharedFs)try{let e=await this.sharedFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}return this.globalMemoryCache}async setGlobalMemory(e){this.sharedFs&&(await this.sharedFs.writeFile(`/shared/CLAUDE.md`,e),this.globalMemoryCache=e,Q.info(`Global memory updated`))}getSharedFS(){return this.sharedFs}setLickManager(e){this.lickManager=e,globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}async registerScoop(e){await Be(e),this.scoops.set(e.jid,e),this.messageQueues.set(e.jid,[]),Q.info(`Scoop registered`,{jid:e.jid,name:e.name}),this.createScoopTab(e.jid).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Scoop init failed`,{jid:e.jid,error:n})})}async unregisterScoop(e){let t=this.scoops.get(e);if(t&&this.lickManager){let{webhooks:e,cronTasks:n}=this.lickManager.getLicksForScoop(t.name,t.folder),r=zy(t.folder,e,n);if(r)throw r}this.clearIdleTimer(e),await this.destroyScoopTab(e),this.sessionStore?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await Ae(e),this.scoops.delete(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.scoopResponseBuffer.delete(e),Q.info(`Scoop unregistered`,{jid:e})}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){for(let[e,t]of this.contexts.entries())this.clearIdleTimer(e),t.stop(),this.contexts.delete(e);this.sharedFs=await I.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await Ey(this.sharedFs).catch(e=>{Q.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),Q.info(`Filesystem reset and defaults re-seeded`)}async clearAllMessages(){await Re(),this.sessionStore&&await this.sessionStore.clearAll().catch(e=>{Q.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.contexts.values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.scoops.keys())this.messageQueues.set(e,[]);Q.info(`All messages cleared`)}async handleMessage(e){Q.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)});let t=this.scoops.get(e.chatJid);Cv(t?.isCone?`cone`:t?.name??`unknown`,localStorage.getItem(`selected-model`)??`unknown`),await Se(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.scoops.get(e);if(!r)throw Error(`Scoop not found: ${e}`);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await Se(i),this.callbacks.onIncomingMessage?.(e,i),Q.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Delegation failed`,{scoopJid:e,error:n}),this.callbacks.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.scoops.get(e.chatJid);if(!t){Q.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){Q.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.tabs.get(e.chatJid);if(Q.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){Q.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.createScoopTab(e.chatJid),i=this.tabs.get(e.chatJid)}catch{Q.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async createScoopTab(e){let t=this.scoops.get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{Q.debug(`Context already exists`,{jid:e});return}if(!this.sharedFs)throw Error(`Shared filesystem not initialized`);let n=`scoop-${t.folder}-${Date.now()}`,r=t.isCone?this.sharedFs:new le(this.sharedFs,[`/scoops/${t.folder}/`,`/shared/`],[`/workspace/`]),i=new Py(t,{onResponse:(n,r)=>{if(this.scoops.has(e)&&(this.callbacks.onResponse(e,n,r),!t.isCone))if(r){let t=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,t+n)}else this.scoopResponseBuffer.set(e,n)},onResponseDone:()=>{if(!this.scoops.has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),this.callbacks.onResponseDone(e)},onError:t=>{if(!this.scoops.has(e))return;let n=this.tabs.get(e);n&&(n.status=`error`,n.error=t,this.tabs.set(e,n)),this.callbacks.onError(e,t),this.callbacks.onStatusChange(e,`error`)},onStatusChange:n=>{if(!this.scoops.has(e))return;let r=this.tabs.get(e);if(r&&(r.status=n,r.lastActivity=new Date().toISOString(),this.tabs.set(e,r)),this.callbacks.onStatusChange(e,n),n===`ready`&&!t.isCone){let n=this.scoopResponseBuffer.get(e);if(this.scoopResponseBuffer.delete(e),n){let r=Array.from(this.scoops.values()).find(e=>e.isCone);if(r){let i=n.length>2e3?n.slice(0,2e3)+`
12729
12729
  ... (truncated)`:n,a={id:`scoop-done-${e}-${Date.now()}`,chatJid:r.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} completed]:\n${i}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-notify`};Q.info(`Routing scoop completion to cone`,{scoop:t.folder,responseLength:n.length}),this.handleMessage(a).catch(e=>{let n=e instanceof Error?e.message:String(e);Q.error(`Failed to route scoop completion to cone`,{scoop:t.folder,error:n}),this.callbacks.onError(r.jid,`Scoop ${t.folder} completed but notification failed: ${n}`)})}}}},onToolStart:(t,n)=>{this.callbacks.onToolStart?.(e,t,n)},onToolEnd:(t,n,r)=>{this.callbacks.onToolEnd?.(e,t,n,r)},onToolUI:(t,n,r)=>{this.callbacks.onToolUI?.(e,t,n,r)},onToolUIDone:t=>{this.callbacks.onToolUIDone?.(e,t)},onSendMessage:(t,n)=>{this.callbacks.onSendMessage(e,`${n?`[${n}] `:``}${t}`)},getScoops:()=>this.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>this.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await this.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await this.unregisterScoop(e)}:void 0,getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:t.isCone?e=>this.setGlobalMemory(e):void 0,getBrowserAPI:()=>this.callbacks.getBrowserAPI()},r,this.sessionStore??void 0,this.sharedFs??void 0);this.contexts.set(e,i),this.tabs.set(e,{jid:e,contextId:n,status:`initializing`,lastActivity:new Date().toISOString()}),await i.init();let a=this.tabs.get(e);a&&a.status===`initializing`&&(a.status=`ready`,this.tabs.set(e,a),this.callbacks.onStatusChange(e,`ready`));let o=this.scoops.get(e);o&&!o.isCone&&this.startIdleTimer(e),Q.info(`Scoop context created`,{jid:e,contextId:n})}async destroyScoopTab(e){this.clearIdleTimer(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}isProcessing(e){return this.tabs.get(e)?.status===`processing`}getScoopContext(e){return this.contexts.get(e)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await Ie(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await Ie(t)}async getMessagesForScoop(e){return Ee(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r){let i=this.contexts.get(e);i||=(await this.createScoopTab(e),this.contexts.get(e));let a=this.tabs.get(e);if(a?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}i=this.contexts.get(e),a=this.tabs.get(e)}if(!i){Q.error(`Context not found after creation`,{jid:e});return}this.clearIdleTimer(e),this.scoopResponseBuffer.delete(e),a&&(a.status=`processing`,a.lastActivity=new Date().toISOString(),this.tabs.set(e,a),this.callbacks.onStatusChange(e,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length}),await i.prompt(t)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){Q.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.tabs.get(e);if(n?.status!==`ready`){Q.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.scoops.get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await De(e,a,i);if(Q.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){Q.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${e.content}`).join(`
12730
- `);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await Ve(`lastAgentTs_${e}`,c.timestamp),await this.sendPrompt(e,s,c.senderId,c.senderName)}startMessageLoop(){this.pollInterval||=window.setInterval(()=>{for(let e of this.scoops.keys())this.tabs.get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Message queue processing failed`,{jid:e,error:n}),this.callbacks.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}updateModel(){for(let e of this.contexts.values())e.updateModel();Q.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}stopScoop(e){let t=this.contexts.get(e);t&&t.stop()}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=n.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)continue;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1);let o=``,s=0;for(let[e,t]of a)t>s&&(o=e,s=t);e.push({name:t.assistantLabel,type:t.isCone?`cone`:`scoop`,model:o,usage:i,turns:r.length})}return e}startIdleTimer(e){if(this.clearIdleTimer(e),this.tabs.get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.idleTimers.delete(e);let t=this.scoops.get(e);if(!t||t.isCone||this.tabs.get(e)?.status!==`ready`)return;let n=Array.from(this.scoops.values()).find(e=>e.isCone);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};Q.info(`Scoop idle timeout`,{jid:e,scoop:t.folder}),this.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Failed to send idle notification`,{jid:e,error:n})})},Hy);this.idleTimers.set(e,t)}clearIdleTimer(e){let t=this.idleTimers.get(e);t&&(clearTimeout(t),this.idleTimers.delete(e))}async shutdown(){this.stopMessageLoop();for(let e of this.idleTimers.keys())this.clearIdleTimer(e);this.scheduler?.stop(),this.scheduler=null;for(let e of this.contexts.keys())await this.destroyScoopTab(e);Q.info(`Orchestrator shutdown`)}};n(`heartbeat`);var Wy=n(`tray-follower`);function Gy(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function Ky(e){let t=Gy(e.joinUrl),n=await $y(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return Wy.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),qy(n)}function qy(e){let t={trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,action:e.result.action,code:e.result.code,iceServers:e.iceServers};return e.result.action===`wait`?{...t,retryAfterMs:e.result.retryAfterMs}:e.result.action===`signal`?{...t,bootstrap:e.result.bootstrap}:e.result.action===`fail`?{...t,error:e.result.error}:t}async function Jy(e){return Qy(await eb(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function Yy(e){return Qy(await eb(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function Xy(e){return Qy(await eb(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function Zy(e){return Qy(await eb(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Qy(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function $y(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!tb(n)){let n=t?t.slice(0,200):`(empty)`;throw Wy.warn(`Tray follower attach returned an invalid response`,{status:e.status,body:n}),Error(`Tray follower attach returned an invalid response (${e.status}): ${n}`)}return n}async function eb(e,t){let n=Gy(e.joinUrl),r=await(e.fetchImpl??fetch)(n,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),i=await r.json().catch(()=>null);if(!nb(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function tb(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.trayId!=`string`||typeof t.controllerId!=`string`||t.role!==`follower`||typeof t.participantCount!=`number`)return!1;let n=t.result;if(!n||typeof n!=`object`)return!1;let r=n;return r.action===`wait`?(r.code===`LEADER_NOT_ELECTED`||r.code===`LEADER_NOT_CONNECTED`)&&typeof r.retryAfterMs==`number`:r.action===`signal`?r.code===`LEADER_CONNECTED`&&rb(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function nb(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.trayId==`string`&&typeof t.controllerId==`string`&&t.role===`follower`&&typeof t.participantCount==`number`&&rb(t.bootstrap)&&Array.isArray(t.events)}function rb(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.controllerId==`string`&&typeof t.bootstrapId==`string`&&typeof t.attempt==`number`&&typeof t.state==`string`&&typeof t.expiresAt==`string`&&typeof t.cursor==`number`&&typeof t.maxRetries==`number`&&typeof t.retriesRemaining==`number`}var ib=n(`tray-webrtc`),ab=`tray-control`,ob=250,sb=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>ub(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??ab}setIceServers(e){this.iceServers=e}async handleControlMessage(e){e.type===`follower.join_requested`?(e.iceServers&&!this.iceServers&&(this.iceServers=e.iceServers),await this.handleJoinRequested(e)):e.type===`bootstrap.answer`?await this.peers.get(e.bootstrapId)?.peer.setRemoteDescription(e.answer):e.type===`bootstrap.ice_candidate`&&await this.peers.get(e.bootstrapId)?.peer.addIceCandidate(e.candidate)}getPeers(){return Array.from(this.peers.values()).map(({state:e})=>({...e}))}getChannel(e){return this.peers.get(e)?.channel??null}stop(){for(let e of this.peers.values())e.peer.close();this.peers.clear()}async handleJoinRequested(e){this.closeControllerPeers(e.controllerId);let t=this.peerConnectionFactory(),n={controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,state:`connecting`,connectedAt:null,runtime:e.runtime},r=t.createDataChannel(this.dataChannelLabel);this.peers.set(e.bootstrapId,{state:n,peer:t,channel:r}),t.addEventListener(`icecandidate`,({candidate:t})=>{let n=fb(t);n&&this.options.sendControlMessage({type:`bootstrap.ice_candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:n})}),t.addEventListener(`connectionstatechange`,()=>{let n=this.peers.get(e.bootstrapId);n&&(n.state.state===`connected`?(t.connectionState===`disconnected`||t.connectionState===`failed`)&&(ib.warn(`Leader peer connection state changed post-connect`,{bootstrapId:e.bootstrapId,state:t.connectionState}),this.options.onPeerDisconnected?.(e.bootstrapId,`Peer connection ${t.connectionState}`)):t.connectionState===`failed`&&this.failPeer(e,`Leader peer connection failed before the data channel opened`))}),r.addEventListener(`open`,()=>{let t=this.peers.get(e.bootstrapId);!t||t.state.state===`connected`||(t.state.state=`connected`,t.state.connectedAt=new Date().toISOString(),this.options.onPeerConnected?.({...t.state},t.channel))}),r.addEventListener(`close`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(ib.warn(`Leader data channel closed post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel closed`)):this.failPeer(e,`Leader data channel closed before opening`))}),r.addEventListener(`error`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(ib.warn(`Leader data channel error post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel error`)):this.failPeer(e,`Leader data channel failed before opening`))});try{let n=await t.createOffer();await t.setLocalDescription(n),this.options.sendControlMessage({type:`bootstrap.offer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,offer:db(t.localDescription??n,`offer`)})}catch(t){this.failPeer(e,t instanceof Error?t.message:String(t))}}closeControllerPeers(e){for(let[t,n]of this.peers.entries())n.state.controllerId===e&&(n.peer.close(),this.peers.delete(t))}failPeer(e,t){let n=this.peers.get(e.bootstrapId);if(n){n.peer.close(),this.peers.delete(e.bootstrapId);try{this.options.sendControlMessage({type:`bootstrap.failed`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,code:`WEBRTC_BOOTSTRAP_FAILED`,message:t,retryable:!0,retryAfterMs:1e3})}catch(e){ib.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},cb=class{fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;constructor(e){this.options=e,this.fetchImpl=e.fetchImpl??fetch,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>ub(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??ob}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();f({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),ib.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){pb(this.stopped),n++;let t;try{t=await Ky({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw f({...m(),attachAttempts:n,lastError:t}),e}if(f({...m(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;ib.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&ib.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),ib.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return f({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),ib.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),ib.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,f({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(pb(this.stopped),this.activePeer.open&&this.activePeer.channel)return{trayId:e,controllerId:t,bootstrapId:r.bootstrapId,channel:this.activePeer.channel};if(this.activePeer.openError)throw Error(this.activePeer.openError);let n=await Jy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,cursor:i,fetchImpl:this.fetchImpl});r=n.bootstrap,i=r.cursor;try{for(let e of n.events)if(e.type===`bootstrap.offer`){await this.activePeer.peer.setRemoteDescription(e.offer);let n=await this.activePeer.peer.createAnswer();await this.activePeer.peer.setLocalDescription(n),await Yy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:db(this.activePeer.peer.localDescription??n,`answer`),fetchImpl:this.fetchImpl})}else if(e.type===`bootstrap.ice_candidate`)await this.activePeer.peer.addIceCandidate(e.candidate);else if(e.type===`bootstrap.failed`)throw Error(e.failure.message)}catch(e){if(r.failure?.retryable&&r.retriesRemaining>0){r=(await Zy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,runtime:this.options.runtime,fetchImpl:this.fetchImpl})).bootstrap,i=0,this.activePeer.peer.close(),this.activePeer=this.createFollowerPeer(t,r.bootstrapId);continue}throw e}this.activePeer.open||await this.sleep(this.pollIntervalMs)}}createFollowerPeer(e,t){let n=this.peerConnectionFactory(),r={peer:n,channel:null,open:!1,openError:null};return n.addEventListener(`connectionstatechange`,()=>{r.open&&(n.connectionState===`disconnected`||n.connectionState===`failed`)&&(ib.warn(`Follower peer connection state changed post-connect`,{bootstrapId:t,state:n.connectionState}),this.options.onDisconnected?.(`Peer connection ${n.connectionState}`))}),n.addEventListener(`datachannel`,({channel:e})=>{r.channel=e,e.addEventListener(`open`,()=>{r.open=!0}),e.addEventListener(`close`,()=>{r.open?(ib.warn(`Follower data channel closed post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel closed`)):r.openError=`Follower data channel closed before opening`}),e.addEventListener(`error`,()=>{r.open?(ib.warn(`Follower data channel error post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel error`)):r.openError=`Follower data channel failed before opening`})}),n.addEventListener(`icecandidate`,({candidate:n})=>{let r=fb(n);r&&Xy({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{ib.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function lb(e,t){let n=t.baseDelayMs??1e3,r=t.backoffMultiplier??2,i=t.maxDelayMs??3e4,a=t.maxAttempts??10,o=t.sleep??e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=!1,c=!1,l=null,u={cancel(){s=!0,c=!1,l?.stop(),l=null},get reconnecting(){return c}},d=()=>{let t=new cb({...e,sleep:o,onDisconnected:e=>{s||(ib.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),p(e))}});return l=t,{manager:t,connectionPromise:t.start()}},p=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let p=0,h=n,g=u??`Unknown disconnect`;for(;!s&&p<a&&(p++,t.onReconnecting?.(p),f({...m(),state:`reconnecting`,error:null,reconnectAttempts:p}),ib.info(`Reconnect attempt`,{attempt:p,delay:h}),await o(h),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,f({...m(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),ib.info(`Reconnect successful`,{attempt:p,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),ib.warn(`Reconnect attempt failed`,{attempt:p,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,f({...m(),state:`error`,error:`Reconnect failed after ${p} attempts: ${g}`,reconnectAttempts:p}),ib.warn(`Reconnect gave up`,{attempts:p,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=d();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||ib.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function ub(e){if(typeof RTCPeerConnection>`u`)throw Error(`RTCPeerConnection is not available in this runtime`);let t=e?.length?{iceServers:e}:void 0;return new RTCPeerConnection(t)}function db(e,t){if(!e||e.type!==t||typeof e.sdp!=`string`)throw Error(`Expected a local ${t} description before signaling`);return{type:e.type,sdp:e.sdp}}function fb(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.candidate==`string`?{candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:null,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:null,usernameFragment:typeof t.usernameFragment==`string`?t.usernameFragment:null}:null}function pb(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var mb=64*1024;async function hb(e,t){try{switch(t.op){case`readFile`:return await gb(e,t.path,t.encoding);case`writeFile`:return[await _b(e,t.path,t.content,t.encoding)];case`stat`:return[await vb(e,t.path)];case`readDir`:return[await yb(e,t.path)];case`mkdir`:return[await bb(e,t.path,t.recursive)];case`rm`:return[await xb(e,t.path,t.recursive)];case`exists`:return[await Sb(e,t.path)];case`walk`:return[await Cb(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[Tb(e)]}}async function gb(e,t,n){return(n??`utf-8`)===`utf-8`?wb(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):wb(Eb(await e.readFile(t,{encoding:`binary`})),`base64`)}async function _b(e,t,n,r){if(r===`base64`){let r=Db(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function vb(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function yb(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function bb(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function xb(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function Sb(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function Cb(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function wb(e,t){if(e.length<=mb)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/mb),r=[];for(let i=0;i<n;i++){let a=i*mb,o=e.slice(a,a+mb);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function Tb(e){return e instanceof Error&&`code`in e?{ok:!1,error:e.message,code:e.code}:{ok:!1,error:e instanceof Error?e.message:String(e)}}function Eb(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Db(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}var Ob=class{runtimes=new Map;dirty=!1;setTargets(e,t){this.runtimes.set(e,t),this.dirty=!0}removeRuntime(e){this.runtimes.delete(e)&&(this.dirty=!0)}getEntries(){this.dirty=!1;let e=[];for(let[t,n]of this.runtimes)for(let r of n)e.push({targetId:`${t}:${r.targetId}`,localTargetId:r.targetId,runtimeId:t,title:r.title,url:r.url,isLocal:!1});return e}hasChanged(){return this.dirty}getRuntimeIds(){return[...this.runtimes.keys()]}},kb=n(`data-channel-keepalive`),Ab=class{sendPing;onDead;intervalMs;maxMissed;timer=null;missedPongs=0;awaitingPong=!1;stopped=!1;constructor(e){this.sendPing=e.sendPing,this.onDead=e.onDead,this.intervalMs=e.intervalMs??1e4,this.maxMissed=e.maxMissed??3}start(){this.timer||this.stopped||(this.timer=setInterval(()=>this.tick(),this.intervalMs))}stop(){this.stopped=!0,this.timer&&=(clearInterval(this.timer),null)}receivePong(){this.awaitingPong=!1,this.missedPongs=0}receivePing(){this.missedPongs=0,this.awaitingPong=!1}get missed(){return this.missedPongs}tick(){if(!this.stopped){if(this.awaitingPong&&(this.missedPongs++,kb.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){kb.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},jb=n(`tray-leader-sync`);function Mb(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var Nb=class{followers=new Map;registry=new Ob;runtimeToBootstrap=new Map;pendingCDPRoutes=new Map;cdpChunkBuffers=new Map;remoteTransports=new Map;pendingTabOpenRoutes=new Map;tabOpenResolvers=new Map;pendingFsRoutes=new Map;fsResolvers=new Map;constructor(e){this.options=e}addFollower(e,t,n){this.removeFollower(e);let r=he(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new Ab({sendPing:()=>r.send({type:`ping`}),onDead:()=>{jb.warn(`Follower keepalive dead, removing follower`,{bootstrapId:e}),this.removeFollower(e),this.options.onFollowerDead?.(e)}});a.start(),this.followers.set(e,{bootstrapId:e,sync:r,unsubscribe:i,keepalive:a,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:Date.now(),floatType:Mb(n?.runtime)}),jb.info(`Follower added to sync`,{bootstrapId:e,followerCount:this.followers.size}),this.sendSnapshotToFollower(e);let o=this.getConnectedEntries();o.length>0&&r.send({type:`targets.registry`,targets:o})}removeFollower(e){let t=this.followers.get(e);if(t){t.keepalive.stop(),t.unsubscribe(),t.sync.close(),this.followers.delete(e);for(let[t,n]of this.runtimeToBootstrap)if(n===e){this.cleanupRemoteTransports(t),this.registry.removeRuntime(t),this.runtimeToBootstrap.delete(t);break}this.registry.hasChanged()&&this.broadcastTargetRegistry(),jb.info(`Follower removed from sync`,{bootstrapId:e,followerCount:this.followers.size})}}broadcastEvent(e){if(this.followers.size===0)return;let t={type:`agent_event`,event:e,scoopJid:this.options.getScoopJid()};for(let e of this.followers.values())e.sync.send(t)}broadcastUserMessage(e,t){if(this.followers.size===0)return;let n={type:`user_message_echo`,text:e,messageId:t,scoopJid:this.options.getScoopJid()};for(let e of this.followers.values())e.sync.send(n)}broadcastStatus(e){if(this.followers.size===0)return;let t={type:`status`,scoopStatus:e};for(let e of this.followers.values())e.sync.send(t)}sendSnapshotToFollower(e){let t=this.followers.get(e);if(!t)return;let n=this.options.getMessages(),r=this.options.getScoopJid();pe(t.sync,n,r),jb.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:jb.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:jb.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:jb.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:jb.info(`Follower targets advertised`,{bootstrapId:e,runtimeId:t.runtimeId,targetCount:t.targets.length});for(let e of[...this.remoteTransports.keys()]){let n=e.substring(0,e.indexOf(`:`));n!==`leader`&&!this.runtimeToBootstrap.has(n)&&n!==t.runtimeId&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),jb.debug(`Cleaned up orphaned remote transport on advertise`,{key:e}))}this.runtimeToBootstrap.set(t.runtimeId,e),this.registry.setTargets(t.runtimeId,t.targets),this.broadcastTargetRegistry();break;case`cdp.request`:{let{requestId:n,targetRuntimeId:r,localTargetId:i,method:a,params:o,sessionId:s}=t;r===`leader`?this.executeLocalCDP(n,i,a,o,s,e):this.forwardCDPRequest(n,r,i,a,o,s,e);break}case`cdp.response`:this.handleCDPResponse(t);break;case`cdp.event`:this.handleCDPEvent(e,t.method,t.params,t.sessionId);break;case`tab.open`:{let{requestId:n,targetRuntimeId:r,url:i}=t;r===`leader`?this.executeLocalTabOpen(n,i,e):this.forwardTabOpen(n,r,i,e);break}case`tab.opened`:this.handleTabOpenResponse(t.requestId,t.targetId);break;case`tab.open.error`:this.handleTabOpenError(t.requestId,t.error);break;case`fs.request`:{let{requestId:n,targetRuntimeId:r,request:i}=t;r===`leader`?this.executeLocalFs(n,i,e):this.forwardFsRequest(n,r,i,e);break}case`fs.response`:this.handleFsResponse(t.requestId,t.response);break;case`ping`:{let t=this.followers.get(e);t&&(t.keepalive.receivePing(),t.lastActivity=Date.now(),t.sync.send({type:`pong`}));break}case`pong`:{let t=this.followers.get(e);t&&(t.keepalive.receivePong(),t.lastActivity=Date.now());break}}}setLocalTargets(e){this.registry.setTargets(`leader`,e),this.registry.hasChanged()&&this.broadcastTargetRegistry()}broadcastTargetRegistry(){if(this.followers.size===0)return;let e={type:`targets.registry`,targets:this.getConnectedEntries()};for(let t of this.followers.values())t.sync.send(e)}getTargets(){return this.getConnectedEntries()}getConnectedEntries(){return this.registry.getEntries().filter(e=>{if(e.runtimeId===`leader`)return!0;let t=this.runtimeToBootstrap.get(e.runtimeId);return t?this.followers.has(t):!1})}createRemoteTransport(e,t){let n=new _e({sendCDPRequest:(n,r,i,a)=>{let o=this.runtimeToBootstrap.get(e),s=o?this.followers.get(o):void 0;if(!s){this.remoteTransports.get(`${e}:${t}`)?.handleResponse(n,void 0,`Target runtime "${e}" not connected`);return}this.pendingCDPRoutes.set(n,{requesterBootstrapId:`__leader__`,requestId:n}),s.sync.send({type:`cdp.request`,requestId:n,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}cleanupRemoteTransports(e){let t=`${e}:`;for(let e of[...this.remoteTransports.keys()])e.startsWith(t)&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),jb.debug(`Cleaned up stale remote transport`,{key:e}))}getConnectedFollowers(){return[...this.runtimeToBootstrap.entries()].map(([e,t])=>{let n=this.followers.get(t);return{runtimeId:e,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:n?.lastActivity,floatType:n?.floatType}})}getBestFollowerForTeleport(){let e=[];for(let[t,n]of this.runtimeToBootstrap){let r=this.followers.get(n);r&&e.push({runtimeId:t,bootstrapId:n,floatType:r.floatType,lastActivity:r.lastActivity})}if(e.length===0)return null;let t=e.filter(e=>e.floatType===`standalone`),n=t.length>0?t:e;return n.sort((e,t)=>t.lastActivity-e.lastActivity),n[0]}get hasFollowers(){return this.followers.size>0}stop(){for(let e of[...this.followers.keys()])this.removeFollower(e)}async executeLocalCDP(e,t,n,r,i,a){let o=this.followers.get(a);if(!o)return;let s=this.options.browserTransport;if(!s){o.sync.send({type:`cdp.response`,requestId:e,error:`Leader has no browser transport`});return}try{let t=await s.send(n,r,i);be(o.sync,e,t)}catch(t){o.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardCDPRequest(e,t,n,r,i,a,o){let s=this.runtimeToBootstrap.get(t),c=s?this.followers.get(s):void 0,l=this.followers.get(o);if(!c){l&&l.sync.send({type:`cdp.response`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingCDPRoutes.set(e,{requesterBootstrapId:o,requestId:e}),c.sync.send({type:`cdp.request`,requestId:e,localTargetId:n,method:r,params:i,sessionId:a})}handleCDPResponse(e){let{requestId:t,result:n,error:r,chunkData:i,chunkIndex:a,totalChunks:o}=e,s=this.pendingCDPRoutes.get(t);if(!s)return;let c=fe(this.cdpChunkBuffers,e);if(!c)return;if(this.pendingCDPRoutes.delete(t),s.requesterBootstrapId===`__leader__`){for(let e of this.remoteTransports.values())e.handleResponse(t,c.result,c.error);return}let l=this.followers.get(s.requesterBootstrapId);l&&be(l.sync,t,c.result,c.error)}handleCDPEvent(e,t,n,r){let i;for(let[t,n]of this.runtimeToBootstrap)if(n===e){i=t;break}if(!i)return;let a=`${i}:`;for(let[e,r]of this.remoteTransports)e.startsWith(a)&&r.handleEvent(t,n)}openRemoteTab(e,t){let n=this.runtimeToBootstrap.get(e),r=n?this.followers.get(n):void 0;if(!r)return Promise.reject(Error(`Target runtime "${e}" not connected`));let i=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,n)=>{this.tabOpenResolvers.set(i,{resolve:e,reject:n}),this.pendingTabOpenRoutes.set(i,{requesterBootstrapId:`__leader__`,requestId:i}),r.sync.send({type:`tab.open`,requestId:i,url:t})})}async executeLocalTabOpen(e,t,n){let r=this.followers.get(n);if(!r)return;let i=this.options.browserTransport;if(!i){r.sync.send({type:`tab.open.error`,requestId:e,error:`Leader has no browser transport`});return}try{let n=(await i.send(`Target.createTarget`,{url:t,background:!0})).targetId;r.sync.send({type:`tab.opened`,requestId:e,targetId:`leader:${n}`})}catch(t){r.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardTabOpen(e,t,n,r){let i=this.runtimeToBootstrap.get(t),a=i?this.followers.get(i):void 0,o=this.followers.get(r);if(!a){o&&o.sync.send({type:`tab.open.error`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingTabOpenRoutes.set(e,{requesterBootstrapId:r,requestId:e}),a.sync.send({type:`tab.open`,requestId:e,url:n})}handleTabOpenResponse(e,t){let n=this.pendingTabOpenRoutes.get(e);if(!n)return;if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.resolve(t));return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`tab.opened`,requestId:e,targetId:t})}handleTabOpenError(e,t){let n=this.pendingTabOpenRoutes.get(e);if(!n)return;if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.reject(Error(t)));return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`tab.open.error`,requestId:e,error:t})}async executeLocalFs(e,t,n){let r=this.followers.get(n);if(!r)return;let i=this.options.vfs;if(!i){r.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Leader has no VFS`}});return}let a=await hb(i,t);for(let t of a)r.sync.send({type:`fs.response`,requestId:e,response:t})}forwardFsRequest(e,t,n,r){let i=this.runtimeToBootstrap.get(t),a=i?this.followers.get(i):void 0,o=this.followers.get(r);if(!a){o&&o.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Target runtime "${t}" not connected`}});return}this.pendingFsRoutes.set(e,{requesterBootstrapId:r,requestId:e,chunks:[],totalChunks:1}),a.sync.send({type:`fs.request`,requestId:e,request:n})}handleFsResponse(e,t){let n=this.pendingFsRoutes.get(e);if(!n){let n=this.fsResolvers.get(e);if(n){n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}return}if(n.requesterBootstrapId===`__leader__`){let n=this.fsResolvers.get(e);if(n){n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),this.pendingFsRoutes.delete(e),n.resolve(n.responses))}return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`fs.response`,requestId:e,response:t}),n.chunks.push(t),n.totalChunks=t.ok&&t.totalChunks||1,n.chunks.length>=n.totalChunks&&this.pendingFsRoutes.delete(e)}sendFsRequest(e,t){if(e===`leader`){let e=this.options.vfs;return e?hb(e,t):Promise.resolve([{ok:!1,error:`Leader has no VFS`}])}let n=this.runtimeToBootstrap.get(e),r=n?this.followers.get(n):void 0;if(!r)return Promise.resolve([{ok:!1,error:`Target runtime "${e}" not connected`}]);let i=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,n)=>{this.fsResolvers.set(i,{resolve:e,reject:n,responses:[]}),this.pendingFsRoutes.set(i,{requesterBootstrapId:`__leader__`,requestId:i,chunks:[],totalChunks:1}),r.sync.send({type:`fs.request`,requestId:i,request:t})})}},Pb=n(`tray-follower-sync`),Fb=class{sync;eventListeners=new Set;unsubscribe;keepalive;latestSnapshot=null;sentMessageIds=new Set;targetEntries=[];remoteTransports=new Map;cdpChunkBuffers=new Map;snapshotChunkBuffer=null;remoteCDPSessions=new Set;cdpEventCleanups=[];tabOpenResolvers=new Map;fsResolvers=new Map;constructor(e,t={}){this.options=t,this.sync=ye(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new Ab({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{Pb.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{Pb.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{Pb.warn(`Data channel error`),this.handleDisconnect(`Data channel error`)})}sendMessage(e,t){let n=t??`follower-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.sentMessageIds.add(n),this.sync.send({type:`user_message`,text:e,messageId:n}),Pb.info(`Sent user message to leader`,{messageId:n})}onEvent(e){return this.eventListeners.add(e),()=>this.eventListeners.delete(e)}stop(){this.sync.send({type:`abort`}),Pb.info(`Sent abort to leader`)}requestSnapshot(){this.sync.send({type:`request_snapshot`})}getLatestSnapshot(){return this.latestSnapshot}close(){this.keepalive.stop(),this.unsubscribe(),this.sync.close(),this.eventListeners.clear(),this.cleanupCDPEventForwarding(),Pb.info(`Follower sync closed`)}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,f({...m(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(e))}handleLeaderMessage(e){switch(e.type){case`snapshot`:Pb.info(`Snapshot received from leader`,{messageCount:e.messages.length,scoopJid:e.scoopJid}),this.snapshotChunkBuffer=null,this.latestSnapshot={messages:e.messages,scoopJid:e.scoopJid},this.options.onSnapshot?.(e.messages,e.scoopJid);break;case`snapshot_chunk`:{let t=ve(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(Pb.info(`Chunked snapshot reassembled from leader`,{messageCount:t.result.messages.length,scoopJid:t.result.scoopJid}),this.latestSnapshot=t.result,this.options.onSnapshot?.(t.result.messages,t.result.scoopJid));break}case`agent_event`:this.emitEvent(e.event);break;case`user_message_echo`:if(this.sentMessageIds.has(e.messageId)){this.sentMessageIds.delete(e.messageId),Pb.debug(`Skipping own message echo`,{messageId:e.messageId});break}Pb.info(`User message echo received`,{messageId:e.messageId,scoopJid:e.scoopJid}),this.options.onUserMessage?.(e.text,e.messageId,e.scoopJid);break;case`status`:this.options.onStatus?.(e.scoopStatus);break;case`error`:Pb.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:Pb.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),l(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){Pb.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new _e({sendCDPRequest:(n,r,i,a)=>{this.sync.send({type:`cdp.request`,requestId:n,targetRuntimeId:e,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}openRemoteTab(e,t){let n=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.tabOpenResolvers.set(n,{resolve:r,reject:i}),this.sync.send({type:`tab.open`,requestId:n,targetRuntimeId:e,url:t})})}async executeLocalTabOpen(e,t){let n=this.options.browserTransport;if(!n){this.sync.send({type:`tab.open.error`,requestId:e,error:`Follower has no browser transport`});return}try{let r=(await n.send(`Target.createTarget`,{url:t,background:!0})).targetId;this.sync.send({type:`tab.opened`,requestId:e,targetId:r}),this.options.onTargetsChanged?.()}catch(t){this.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}async executeLocalCDP(e,t,n,r,i){let a=this.options.browserTransport;if(!a){this.sync.send({type:`cdp.response`,requestId:e,error:`Follower has no browser transport`});return}try{let t=await a.send(n,r,i);if(n===`Target.attachToTarget`&&t.sessionId){let e=t.sessionId;this.remoteCDPSessions.add(e),this.setupCDPEventForwarding(a,e),Pb.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),Pb.debug(`Removed remote CDP session on detach`,{sessionId:i})),be(this.sync,e,t)}catch(t){this.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}setupCDPEventForwarding(e,t){for(let n of[`Page.frameNavigated`,`Page.loadEventFired`,`Page.domContentEventFired`,`Network.responseReceived`,`Network.loadingFinished`,`Network.requestWillBeSent`]){let r=e=>{if(e.sessionId!==t||!this.remoteCDPSessions.has(t))return;let{sessionId:r,...i}=e;this.sync.send({type:`cdp.event`,method:n,params:i,sessionId:t})};e.on(n,r),this.cdpEventCleanups.push(()=>e.off(n,r))}}cleanupCDPEventForwarding(){for(let e of this.cdpEventCleanups)e();this.cdpEventCleanups.length=0,this.remoteCDPSessions.clear()}routeCDPResponse(e){let t=fe(this.cdpChunkBuffers,e);if(t)for(let n of this.remoteTransports.values())n.handleResponse(e.requestId,t.result,t.error)}async executeLocalFs(e,t){let n=this.options.vfs;if(!n){this.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Follower has no VFS`}});return}let r=await hb(n,t);for(let t of r)this.sync.send({type:`fs.response`,requestId:e,response:t})}routeFsResponse(e,t){let n=this.fsResolvers.get(e);if(!n)return;n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}sendFsRequest(e,t){let n=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.fsResolvers.set(n,{resolve:r,reject:i,responses:[]}),this.sync.send({type:`fs.request`,requestId:n,targetRuntimeId:e,request:t})})}};function Ib(e,t){if(t)return`extension`;try{return zb(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function Lb(e,t){return e===`electron-overlay`||e===`standalone`&&t}function Rb(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&qi(t)?t:Gi}catch{return Gi}}function zb(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Bb(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Vb(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Hb(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function Ub(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var Wb=[`/shared/sprinkles`];async function Gb(e){let t=new Map;for(let n of Wb)await e.exists(n)&&await Kb(e,n,t);return await Kb(e,`/`,t),t}async function Kb(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=qb(r);if(!n.has(t)){let i;try{i=await e.readFile(r,{encoding:`utf-8`})??``}catch{i=``}n.set(t,{name:t,path:r,title:Jb(i,t),autoOpen:Yb(i)})}}}function qb(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function Jb(e,t){let n=e.match(/data-sprinkle-title=["']([^"']+)["']/);if(n)return n[1];let r=e.match(/<title>([^<]+)<\/title>/i);return r?r[1].trim():t}function Yb(e){return/data-sprinkle-autoopen\b/.test(e)}var Xb=class{listeners=new Map;lickHandler;fs;closeHandler;stopConeHandler;constructor(e,t,n,r){this.fs=e,this.lickHandler=t,this.closeHandler=n,this.stopConeHandler=r}createAPI(e){let t={name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data,i={type:`sprinkle`,sprinkleName:e,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:n,data:r}};this.lickHandler(i)},on:(t,n)=>{let r=`${e}:${t}`,i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n)},off:(t,n)=>{let r=`${e}:${t}`;this.listeners.get(r)?.delete(n)},readFile:async e=>await this.fs.readFile(e,{encoding:`utf-8`}),writeFile:async(e,t)=>{await this.fs.writeFile(e,t)},readDir:async e=>(await this.fs.readDir(e)).map(e=>({name:e.name,type:e.type})),exists:async e=>this.fs.exists(e),stat:async e=>{let t=await this.fs.stat(e);return{type:t.type,size:t.size}},mkdir:async e=>{await this.fs.mkdir(e,{recursive:!0})},rm:async e=>{await this.fs.rm(e)},screenshot:async e=>{let n=t._container;if(!n)return``;let r=e?n.querySelector(e):n;if(!r)throw Error(`Element not found: `+(e||`container`));let i=r.getBoundingClientRect(),a=Math.ceil(i.width),o=Math.ceil(i.height);if(a===0||o===0)throw Error(`Element has zero dimensions`);let s=document.createElement(`canvas`),c=window.devicePixelRatio||1;s.width=a*c,s.height=o*c;let l=s.getContext(`2d`);l.scale(c,c);let u=r.cloneNode(!0),d=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${o}"><foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(u)}</foreignObject></svg>`;return new Promise((e,t)=>{let n=new Image;n.onload=()=>{l.drawImage(n,0,0),e(s.toDataURL(`image/png`))},n.onerror=()=>t(Error(`Screenshot rendering failed`)),n.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(d)})},setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch{}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch{return null}},open:e=>{let t=/^https?:|^chrome-extension:/.test(e)?e:bm(e);window.open(t,`_blank`)},close:()=>this.closeHandler(e),stopCone:()=>this.stopConeHandler()};return t}pushUpdate(e,t){let n=`${e}:update`,r=this.listeners.get(n);if(r)for(let e of r)try{e(t)}catch{}}removeSprinkle(e){for(let t of this.listeners.keys())t.startsWith(`${e}:`)&&this.listeners.delete(t)}},Zb=n(`sprinkle-manager`),Qb=`slicc-open-sprinkles`,$b=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Xb(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(Qb);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{Zb.warn(`Failed to auto-open sprinkle`,{name:e.name})}return}let t=JSON.parse(e);for(let e of t)try{await this.open(e)}catch{Zb.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(Qb,JSON.stringify([...this.openSprinkles.keys()]))}catch{}}async openNewAutoOpenSprinkles(){await this.refresh();for(let e of this.availableSprinkles.values())if(e.autoOpen&&!this.openSprinkles.has(e.name))try{await this.open(e.name),Zb.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{Zb.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await Gb(this.fs),Zb.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){Zb.info(`Sprinkle already open`,{name:e});return}let n=this.availableSprinkles.get(e);if(n||=(await this.refresh(),this.availableSprinkles.get(e)),!n)throw Error(`Sprinkle not found: ${e}`);let r=await this.fs.readFile(n.path,{encoding:`utf-8`}),i=document.createElement(`div`);i.className=`sprinkle-panel`,i.style.cssText=`width: 100%; height: 100%; display: flex; flex-direction: column; overflow: hidden;`,i.dataset.sprinkle=e,this.openSprinkles.set(e,{renderer:null,container:i}),this.callbacks.addSprinkle(e,n.title,i,t);let a=new ai(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),Tv(e),Zb.info(`Sprinkle opened`,{name:e,title:n.title})}close(e){let t=this.openSprinkles.get(e);t&&(t.renderer?.dispose(),t.container.remove(),this.bridge.removeSprinkle(e),this.openSprinkles.delete(e),this.callbacks.removeSprinkle(e),this.persistOpenSprinkles(),Zb.info(`Sprinkle closed`,{name:e}))}available(){return Array.from(this.availableSprinkles.values())}opened(){return Array.from(this.openSprinkles.keys())}setupWatcher(e){this.watcherUnsub=e.watch(`/workspace`,e=>e.endsWith(`.shtml`),()=>void this.refresh())}dispose(){this.watcherUnsub?.()}sendToSprinkle(e,t){let n=this.openSprinkles.get(e);if(!n){Zb.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function ex(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function tx(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${ex(e.sourceUrl)}.`),t.push(`## Instruction`),t.push(n.instruction),n.urls&&n.urls.length>0){t.push(`## URLs`);for(let e of n.urls)t.push(`- ${e}`)}if(n.context&&(t.push(`## Context`),t.push(n.context)),n.acceptanceCriteria&&n.acceptanceCriteria.length>0){t.push(`## Acceptance Criteria`);for(let e of n.acceptanceCriteria)t.push(`- ${e}`)}return n.notes&&(t.push(`## Notes`),t.push(n.notes)),t.join(`
12730
+ `);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await Ve(`lastAgentTs_${e}`,c.timestamp),await this.sendPrompt(e,s,c.senderId,c.senderName)}startMessageLoop(){this.pollInterval||=window.setInterval(()=>{for(let e of this.scoops.keys())this.tabs.get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Message queue processing failed`,{jid:e,error:n}),this.callbacks.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}updateModel(){for(let e of this.contexts.values())e.updateModel();Q.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}stopScoop(e){let t=this.contexts.get(e);t&&t.stop()}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=n.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)continue;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1);let o=``,s=0;for(let[e,t]of a)t>s&&(o=e,s=t);e.push({name:t.assistantLabel,type:t.isCone?`cone`:`scoop`,model:o,usage:i,turns:r.length})}return e}startIdleTimer(e){if(this.clearIdleTimer(e),this.tabs.get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.idleTimers.delete(e);let t=this.scoops.get(e);if(!t||t.isCone||this.tabs.get(e)?.status!==`ready`)return;let n=Array.from(this.scoops.values()).find(e=>e.isCone);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};Q.info(`Scoop idle timeout`,{jid:e,scoop:t.folder}),this.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Failed to send idle notification`,{jid:e,error:n})})},Hy);this.idleTimers.set(e,t)}clearIdleTimer(e){let t=this.idleTimers.get(e);t&&(clearTimeout(t),this.idleTimers.delete(e))}async shutdown(){this.stopMessageLoop();for(let e of this.idleTimers.keys())this.clearIdleTimer(e);this.scheduler?.stop(),this.scheduler=null;for(let e of this.contexts.keys())await this.destroyScoopTab(e);Q.info(`Orchestrator shutdown`)}};n(`heartbeat`);var Wy=n(`tray-follower`);function Gy(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function Ky(e){let t=Gy(e.joinUrl),n=await $y(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return Wy.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),qy(n)}function qy(e){let t={trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,action:e.result.action,code:e.result.code,iceServers:e.iceServers};return e.result.action===`wait`?{...t,retryAfterMs:e.result.retryAfterMs}:e.result.action===`signal`?{...t,bootstrap:e.result.bootstrap}:e.result.action===`fail`?{...t,error:e.result.error}:t}async function Jy(e){return Qy(await eb(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function Yy(e){return Qy(await eb(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function Xy(e){return Qy(await eb(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function Zy(e){return Qy(await eb(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Qy(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function $y(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!tb(n)){let n=t?t.slice(0,200):`(empty)`;throw Wy.warn(`Tray follower attach returned an invalid response`,{status:e.status,body:n}),Error(`Tray follower attach returned an invalid response (${e.status}): ${n}`)}return n}async function eb(e,t){let n=Gy(e.joinUrl),r=await(e.fetchImpl??fetch)(n,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),i=await r.json().catch(()=>null);if(!nb(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function tb(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.trayId!=`string`||typeof t.controllerId!=`string`||t.role!==`follower`||typeof t.participantCount!=`number`)return!1;let n=t.result;if(!n||typeof n!=`object`)return!1;let r=n;return r.action===`wait`?(r.code===`LEADER_NOT_ELECTED`||r.code===`LEADER_NOT_CONNECTED`)&&typeof r.retryAfterMs==`number`:r.action===`signal`?r.code===`LEADER_CONNECTED`&&rb(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function nb(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.trayId==`string`&&typeof t.controllerId==`string`&&t.role===`follower`&&typeof t.participantCount==`number`&&rb(t.bootstrap)&&Array.isArray(t.events)}function rb(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.controllerId==`string`&&typeof t.bootstrapId==`string`&&typeof t.attempt==`number`&&typeof t.state==`string`&&typeof t.expiresAt==`string`&&typeof t.cursor==`number`&&typeof t.maxRetries==`number`&&typeof t.retriesRemaining==`number`}var ib=n(`tray-webrtc`),ab=`tray-control`,ob=250,sb=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>ub(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??ab}setIceServers(e){this.iceServers=e}async handleControlMessage(e){e.type===`follower.join_requested`?(e.iceServers&&!this.iceServers&&(this.iceServers=e.iceServers),await this.handleJoinRequested(e)):e.type===`bootstrap.answer`?await this.peers.get(e.bootstrapId)?.peer.setRemoteDescription(e.answer):e.type===`bootstrap.ice_candidate`&&await this.peers.get(e.bootstrapId)?.peer.addIceCandidate(e.candidate)}getPeers(){return Array.from(this.peers.values()).map(({state:e})=>({...e}))}getChannel(e){return this.peers.get(e)?.channel??null}stop(){for(let e of this.peers.values())e.peer.close();this.peers.clear()}async handleJoinRequested(e){this.closeControllerPeers(e.controllerId);let t=this.peerConnectionFactory(),n={controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,state:`connecting`,connectedAt:null,runtime:e.runtime},r=t.createDataChannel(this.dataChannelLabel);this.peers.set(e.bootstrapId,{state:n,peer:t,channel:r}),t.addEventListener(`icecandidate`,({candidate:t})=>{let n=fb(t);n&&this.options.sendControlMessage({type:`bootstrap.ice_candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:n})}),t.addEventListener(`connectionstatechange`,()=>{let n=this.peers.get(e.bootstrapId);n&&(n.state.state===`connected`?(t.connectionState===`disconnected`||t.connectionState===`failed`)&&(ib.warn(`Leader peer connection state changed post-connect`,{bootstrapId:e.bootstrapId,state:t.connectionState}),this.options.onPeerDisconnected?.(e.bootstrapId,`Peer connection ${t.connectionState}`)):t.connectionState===`failed`&&this.failPeer(e,`Leader peer connection failed before the data channel opened`))}),r.addEventListener(`open`,()=>{let t=this.peers.get(e.bootstrapId);!t||t.state.state===`connected`||(t.state.state=`connected`,t.state.connectedAt=new Date().toISOString(),this.options.onPeerConnected?.({...t.state},t.channel))}),r.addEventListener(`close`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(ib.warn(`Leader data channel closed post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel closed`)):this.failPeer(e,`Leader data channel closed before opening`))}),r.addEventListener(`error`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(ib.warn(`Leader data channel error post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel error`)):this.failPeer(e,`Leader data channel failed before opening`))});try{let n=await t.createOffer();await t.setLocalDescription(n),this.options.sendControlMessage({type:`bootstrap.offer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,offer:db(t.localDescription??n,`offer`)})}catch(t){this.failPeer(e,t instanceof Error?t.message:String(t))}}closeControllerPeers(e){for(let[t,n]of this.peers.entries())n.state.controllerId===e&&(n.peer.close(),this.peers.delete(t))}failPeer(e,t){let n=this.peers.get(e.bootstrapId);if(n){n.peer.close(),this.peers.delete(e.bootstrapId);try{this.options.sendControlMessage({type:`bootstrap.failed`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,code:`WEBRTC_BOOTSTRAP_FAILED`,message:t,retryable:!0,retryAfterMs:1e3})}catch(e){ib.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},cb=class{fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;constructor(e){this.options=e,this.fetchImpl=e.fetchImpl??fetch,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>ub(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??ob}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();f({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),ib.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){pb(this.stopped),n++;let t;try{t=await Ky({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw f({...m(),attachAttempts:n,lastError:t}),e}if(f({...m(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;ib.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&ib.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),ib.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return f({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),ib.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),ib.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,f({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(pb(this.stopped),this.activePeer.open&&this.activePeer.channel)return{trayId:e,controllerId:t,bootstrapId:r.bootstrapId,channel:this.activePeer.channel};if(this.activePeer.openError)throw Error(this.activePeer.openError);let n=await Jy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,cursor:i,fetchImpl:this.fetchImpl});r=n.bootstrap,i=r.cursor;try{for(let e of n.events)if(e.type===`bootstrap.offer`){await this.activePeer.peer.setRemoteDescription(e.offer);let n=await this.activePeer.peer.createAnswer();await this.activePeer.peer.setLocalDescription(n),await Yy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:db(this.activePeer.peer.localDescription??n,`answer`),fetchImpl:this.fetchImpl})}else if(e.type===`bootstrap.ice_candidate`)await this.activePeer.peer.addIceCandidate(e.candidate);else if(e.type===`bootstrap.failed`)throw Error(e.failure.message)}catch(e){if(r.failure?.retryable&&r.retriesRemaining>0){r=(await Zy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,runtime:this.options.runtime,fetchImpl:this.fetchImpl})).bootstrap,i=0,this.activePeer.peer.close(),this.activePeer=this.createFollowerPeer(t,r.bootstrapId);continue}throw e}this.activePeer.open||await this.sleep(this.pollIntervalMs)}}createFollowerPeer(e,t){let n=this.peerConnectionFactory(),r={peer:n,channel:null,open:!1,openError:null};return n.addEventListener(`connectionstatechange`,()=>{r.open&&(n.connectionState===`disconnected`||n.connectionState===`failed`)&&(ib.warn(`Follower peer connection state changed post-connect`,{bootstrapId:t,state:n.connectionState}),this.options.onDisconnected?.(`Peer connection ${n.connectionState}`))}),n.addEventListener(`datachannel`,({channel:e})=>{r.channel=e,e.addEventListener(`open`,()=>{r.open=!0}),e.addEventListener(`close`,()=>{r.open?(ib.warn(`Follower data channel closed post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel closed`)):r.openError=`Follower data channel closed before opening`}),e.addEventListener(`error`,()=>{r.open?(ib.warn(`Follower data channel error post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel error`)):r.openError=`Follower data channel failed before opening`})}),n.addEventListener(`icecandidate`,({candidate:n})=>{let r=fb(n);r&&Xy({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{ib.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function lb(e,t){let n=t.baseDelayMs??1e3,r=t.backoffMultiplier??2,i=t.maxDelayMs??3e4,a=t.maxAttempts??10,o=t.sleep??e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=!1,c=!1,l=null,u={cancel(){s=!0,c=!1,l?.stop(),l=null},get reconnecting(){return c}},d=()=>{let t=new cb({...e,sleep:o,onDisconnected:e=>{s||(ib.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),p(e))}});return l=t,{manager:t,connectionPromise:t.start()}},p=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let p=0,h=n,g=u??`Unknown disconnect`;for(;!s&&p<a&&(p++,t.onReconnecting?.(p),f({...m(),state:`reconnecting`,error:null,reconnectAttempts:p}),ib.info(`Reconnect attempt`,{attempt:p,delay:h}),await o(h),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,f({...m(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),ib.info(`Reconnect successful`,{attempt:p,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),ib.warn(`Reconnect attempt failed`,{attempt:p,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,f({...m(),state:`error`,error:`Reconnect failed after ${p} attempts: ${g}`,reconnectAttempts:p}),ib.warn(`Reconnect gave up`,{attempts:p,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=d();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||ib.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function ub(e){if(typeof RTCPeerConnection>`u`)throw Error(`RTCPeerConnection is not available in this runtime`);let t=e?.length?{iceServers:e}:void 0;return new RTCPeerConnection(t)}function db(e,t){if(!e||e.type!==t||typeof e.sdp!=`string`)throw Error(`Expected a local ${t} description before signaling`);return{type:e.type,sdp:e.sdp}}function fb(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.candidate==`string`?{candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:null,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:null,usernameFragment:typeof t.usernameFragment==`string`?t.usernameFragment:null}:null}function pb(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var mb=64*1024;async function hb(e,t){try{switch(t.op){case`readFile`:return await gb(e,t.path,t.encoding);case`writeFile`:return[await _b(e,t.path,t.content,t.encoding)];case`stat`:return[await vb(e,t.path)];case`readDir`:return[await yb(e,t.path)];case`mkdir`:return[await bb(e,t.path,t.recursive)];case`rm`:return[await xb(e,t.path,t.recursive)];case`exists`:return[await Sb(e,t.path)];case`walk`:return[await Cb(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[Tb(e)]}}async function gb(e,t,n){return(n??`utf-8`)===`utf-8`?wb(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):wb(Eb(await e.readFile(t,{encoding:`binary`})),`base64`)}async function _b(e,t,n,r){if(r===`base64`){let r=Db(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function vb(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function yb(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function bb(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function xb(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function Sb(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function Cb(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function wb(e,t){if(e.length<=mb)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/mb),r=[];for(let i=0;i<n;i++){let a=i*mb,o=e.slice(a,a+mb);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function Tb(e){return e instanceof Error&&`code`in e?{ok:!1,error:e.message,code:e.code}:{ok:!1,error:e instanceof Error?e.message:String(e)}}function Eb(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Db(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}var Ob=class{runtimes=new Map;dirty=!1;setTargets(e,t){this.runtimes.set(e,t),this.dirty=!0}removeRuntime(e){this.runtimes.delete(e)&&(this.dirty=!0)}getEntries(){this.dirty=!1;let e=[];for(let[t,n]of this.runtimes)for(let r of n)e.push({targetId:`${t}:${r.targetId}`,localTargetId:r.targetId,runtimeId:t,title:r.title,url:r.url,isLocal:!1});return e}hasChanged(){return this.dirty}getRuntimeIds(){return[...this.runtimes.keys()]}},kb=n(`data-channel-keepalive`),Ab=class{sendPing;onDead;intervalMs;maxMissed;timer=null;missedPongs=0;awaitingPong=!1;stopped=!1;constructor(e){this.sendPing=e.sendPing,this.onDead=e.onDead,this.intervalMs=e.intervalMs??1e4,this.maxMissed=e.maxMissed??3}start(){this.timer||this.stopped||(this.timer=setInterval(()=>this.tick(),this.intervalMs))}stop(){this.stopped=!0,this.timer&&=(clearInterval(this.timer),null)}receivePong(){this.awaitingPong=!1,this.missedPongs=0}receivePing(){this.missedPongs=0,this.awaitingPong=!1}get missed(){return this.missedPongs}tick(){if(!this.stopped){if(this.awaitingPong&&(this.missedPongs++,kb.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){kb.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},jb=n(`tray-leader-sync`);function Mb(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var Nb=class{followers=new Map;registry=new Ob;runtimeToBootstrap=new Map;pendingCDPRoutes=new Map;cdpChunkBuffers=new Map;remoteTransports=new Map;pendingTabOpenRoutes=new Map;tabOpenResolvers=new Map;pendingFsRoutes=new Map;fsResolvers=new Map;constructor(e){this.options=e}addFollower(e,t,n){this.removeFollower(e);let r=he(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new Ab({sendPing:()=>r.send({type:`ping`}),onDead:()=>{jb.warn(`Follower keepalive dead, removing follower`,{bootstrapId:e}),this.removeFollower(e),this.options.onFollowerDead?.(e)}});a.start(),this.followers.set(e,{bootstrapId:e,sync:r,unsubscribe:i,keepalive:a,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:Date.now(),floatType:Mb(n?.runtime)}),jb.info(`Follower added to sync`,{bootstrapId:e,followerCount:this.followers.size}),this.sendSnapshotToFollower(e);let o=this.getConnectedEntries();o.length>0&&r.send({type:`targets.registry`,targets:o})}removeFollower(e){let t=this.followers.get(e);if(t){t.keepalive.stop(),t.unsubscribe(),t.sync.close(),this.followers.delete(e);for(let[t,n]of this.runtimeToBootstrap)if(n===e){this.cleanupRemoteTransports(t),this.registry.removeRuntime(t),this.runtimeToBootstrap.delete(t);break}this.registry.hasChanged()&&this.broadcastTargetRegistry(),jb.info(`Follower removed from sync`,{bootstrapId:e,followerCount:this.followers.size})}}broadcastEvent(e){if(this.followers.size===0)return;let t={type:`agent_event`,event:e,scoopJid:this.options.getScoopJid()};for(let e of this.followers.values())e.sync.send(t)}broadcastUserMessage(e,t){if(this.followers.size===0)return;let n={type:`user_message_echo`,text:e,messageId:t,scoopJid:this.options.getScoopJid()};for(let e of this.followers.values())e.sync.send(n)}broadcastStatus(e){if(this.followers.size===0)return;let t={type:`status`,scoopStatus:e};for(let e of this.followers.values())e.sync.send(t)}sendSnapshotToFollower(e){let t=this.followers.get(e);if(!t)return;let n=this.options.getMessages(),r=this.options.getScoopJid();pe(t.sync,n,r),jb.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:jb.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:jb.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:jb.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:jb.info(`Follower targets advertised`,{bootstrapId:e,runtimeId:t.runtimeId,targetCount:t.targets.length});for(let e of[...this.remoteTransports.keys()]){let n=e.substring(0,e.indexOf(`:`));n!==`leader`&&!this.runtimeToBootstrap.has(n)&&n!==t.runtimeId&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),jb.debug(`Cleaned up orphaned remote transport on advertise`,{key:e}))}this.runtimeToBootstrap.set(t.runtimeId,e),this.registry.setTargets(t.runtimeId,t.targets),this.broadcastTargetRegistry();break;case`cdp.request`:{let{requestId:n,targetRuntimeId:r,localTargetId:i,method:a,params:o,sessionId:s}=t;r===`leader`?this.executeLocalCDP(n,i,a,o,s,e):this.forwardCDPRequest(n,r,i,a,o,s,e);break}case`cdp.response`:this.handleCDPResponse(t);break;case`cdp.event`:this.handleCDPEvent(e,t.method,t.params,t.sessionId);break;case`tab.open`:{let{requestId:n,targetRuntimeId:r,url:i}=t;r===`leader`?this.executeLocalTabOpen(n,i,e):this.forwardTabOpen(n,r,i,e);break}case`tab.opened`:this.handleTabOpenResponse(t.requestId,t.targetId);break;case`tab.open.error`:this.handleTabOpenError(t.requestId,t.error);break;case`fs.request`:{let{requestId:n,targetRuntimeId:r,request:i}=t;r===`leader`?this.executeLocalFs(n,i,e):this.forwardFsRequest(n,r,i,e);break}case`fs.response`:this.handleFsResponse(t.requestId,t.response);break;case`ping`:{let t=this.followers.get(e);t&&(t.keepalive.receivePing(),t.lastActivity=Date.now(),t.sync.send({type:`pong`}));break}case`pong`:{let t=this.followers.get(e);t&&(t.keepalive.receivePong(),t.lastActivity=Date.now());break}}}setLocalTargets(e){this.registry.setTargets(`leader`,e),this.registry.hasChanged()&&this.broadcastTargetRegistry()}broadcastTargetRegistry(){if(this.followers.size===0)return;let e={type:`targets.registry`,targets:this.getConnectedEntries()};for(let t of this.followers.values())t.sync.send(e)}getTargets(){return this.getConnectedEntries()}getConnectedEntries(){return this.registry.getEntries().filter(e=>{if(e.runtimeId===`leader`)return!0;let t=this.runtimeToBootstrap.get(e.runtimeId);return t?this.followers.has(t):!1})}createRemoteTransport(e,t){let n=new _e({sendCDPRequest:(n,r,i,a)=>{let o=this.runtimeToBootstrap.get(e),s=o?this.followers.get(o):void 0;if(!s){this.remoteTransports.get(`${e}:${t}`)?.handleResponse(n,void 0,`Target runtime "${e}" not connected`);return}this.pendingCDPRoutes.set(n,{requesterBootstrapId:`__leader__`,requestId:n}),s.sync.send({type:`cdp.request`,requestId:n,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}cleanupRemoteTransports(e){let t=`${e}:`;for(let e of[...this.remoteTransports.keys()])e.startsWith(t)&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),jb.debug(`Cleaned up stale remote transport`,{key:e}))}getConnectedFollowers(){return[...this.runtimeToBootstrap.entries()].map(([e,t])=>{let n=this.followers.get(t);return{runtimeId:e,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:n?.lastActivity,floatType:n?.floatType}})}getBestFollowerForTeleport(){let e=[];for(let[t,n]of this.runtimeToBootstrap){let r=this.followers.get(n);r&&e.push({runtimeId:t,bootstrapId:n,floatType:r.floatType,lastActivity:r.lastActivity})}if(e.length===0)return null;let t=e.filter(e=>e.floatType===`standalone`),n=t.length>0?t:e;return n.sort((e,t)=>t.lastActivity-e.lastActivity),n[0]}get hasFollowers(){return this.followers.size>0}stop(){for(let e of[...this.followers.keys()])this.removeFollower(e)}async executeLocalCDP(e,t,n,r,i,a){let o=this.followers.get(a);if(!o)return;let s=this.options.browserTransport;if(!s){o.sync.send({type:`cdp.response`,requestId:e,error:`Leader has no browser transport`});return}try{let t=await s.send(n,r,i);be(o.sync,e,t)}catch(t){o.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardCDPRequest(e,t,n,r,i,a,o){let s=this.runtimeToBootstrap.get(t),c=s?this.followers.get(s):void 0,l=this.followers.get(o);if(!c){l&&l.sync.send({type:`cdp.response`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingCDPRoutes.set(e,{requesterBootstrapId:o,requestId:e}),c.sync.send({type:`cdp.request`,requestId:e,localTargetId:n,method:r,params:i,sessionId:a})}handleCDPResponse(e){let{requestId:t,result:n,error:r,chunkData:i,chunkIndex:a,totalChunks:o}=e,s=this.pendingCDPRoutes.get(t);if(!s)return;let c=fe(this.cdpChunkBuffers,e);if(!c)return;if(this.pendingCDPRoutes.delete(t),s.requesterBootstrapId===`__leader__`){for(let e of this.remoteTransports.values())e.handleResponse(t,c.result,c.error);return}let l=this.followers.get(s.requesterBootstrapId);l&&be(l.sync,t,c.result,c.error)}handleCDPEvent(e,t,n,r){let i;for(let[t,n]of this.runtimeToBootstrap)if(n===e){i=t;break}if(!i)return;let a=`${i}:`;for(let[e,r]of this.remoteTransports)e.startsWith(a)&&r.handleEvent(t,n)}openRemoteTab(e,t){let n=this.runtimeToBootstrap.get(e),r=n?this.followers.get(n):void 0;if(!r)return Promise.reject(Error(`Target runtime "${e}" not connected`));let i=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,n)=>{this.tabOpenResolvers.set(i,{resolve:e,reject:n}),this.pendingTabOpenRoutes.set(i,{requesterBootstrapId:`__leader__`,requestId:i}),r.sync.send({type:`tab.open`,requestId:i,url:t})})}async executeLocalTabOpen(e,t,n){let r=this.followers.get(n);if(!r)return;let i=this.options.browserTransport;if(!i){r.sync.send({type:`tab.open.error`,requestId:e,error:`Leader has no browser transport`});return}try{let n=(await i.send(`Target.createTarget`,{url:t,background:!0})).targetId;r.sync.send({type:`tab.opened`,requestId:e,targetId:`leader:${n}`})}catch(t){r.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardTabOpen(e,t,n,r){let i=this.runtimeToBootstrap.get(t),a=i?this.followers.get(i):void 0,o=this.followers.get(r);if(!a){o&&o.sync.send({type:`tab.open.error`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingTabOpenRoutes.set(e,{requesterBootstrapId:r,requestId:e}),a.sync.send({type:`tab.open`,requestId:e,url:n})}handleTabOpenResponse(e,t){let n=this.pendingTabOpenRoutes.get(e);if(!n)return;if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.resolve(t));return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`tab.opened`,requestId:e,targetId:t})}handleTabOpenError(e,t){let n=this.pendingTabOpenRoutes.get(e);if(!n)return;if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.reject(Error(t)));return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`tab.open.error`,requestId:e,error:t})}async executeLocalFs(e,t,n){let r=this.followers.get(n);if(!r)return;let i=this.options.vfs;if(!i){r.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Leader has no VFS`}});return}let a=await hb(i,t);for(let t of a)r.sync.send({type:`fs.response`,requestId:e,response:t})}forwardFsRequest(e,t,n,r){let i=this.runtimeToBootstrap.get(t),a=i?this.followers.get(i):void 0,o=this.followers.get(r);if(!a){o&&o.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Target runtime "${t}" not connected`}});return}this.pendingFsRoutes.set(e,{requesterBootstrapId:r,requestId:e,chunks:[],totalChunks:1}),a.sync.send({type:`fs.request`,requestId:e,request:n})}handleFsResponse(e,t){let n=this.pendingFsRoutes.get(e);if(!n){let n=this.fsResolvers.get(e);if(n){n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}return}if(n.requesterBootstrapId===`__leader__`){let n=this.fsResolvers.get(e);if(n){n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),this.pendingFsRoutes.delete(e),n.resolve(n.responses))}return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`fs.response`,requestId:e,response:t}),n.chunks.push(t),n.totalChunks=t.ok&&t.totalChunks||1,n.chunks.length>=n.totalChunks&&this.pendingFsRoutes.delete(e)}sendFsRequest(e,t){if(e===`leader`){let e=this.options.vfs;return e?hb(e,t):Promise.resolve([{ok:!1,error:`Leader has no VFS`}])}let n=this.runtimeToBootstrap.get(e),r=n?this.followers.get(n):void 0;if(!r)return Promise.resolve([{ok:!1,error:`Target runtime "${e}" not connected`}]);let i=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,n)=>{this.fsResolvers.set(i,{resolve:e,reject:n,responses:[]}),this.pendingFsRoutes.set(i,{requesterBootstrapId:`__leader__`,requestId:i,chunks:[],totalChunks:1}),r.sync.send({type:`fs.request`,requestId:i,request:t})})}},Pb=n(`tray-follower-sync`),Fb=class{sync;eventListeners=new Set;unsubscribe;keepalive;latestSnapshot=null;sentMessageIds=new Set;targetEntries=[];remoteTransports=new Map;cdpChunkBuffers=new Map;snapshotChunkBuffer=null;remoteCDPSessions=new Set;cdpEventCleanups=[];tabOpenResolvers=new Map;fsResolvers=new Map;constructor(e,t={}){this.options=t,this.sync=ye(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new Ab({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{Pb.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{Pb.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{Pb.warn(`Data channel error`),this.handleDisconnect(`Data channel error`)})}sendMessage(e,t){let n=t??`follower-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.sentMessageIds.add(n),this.sync.send({type:`user_message`,text:e,messageId:n}),Pb.info(`Sent user message to leader`,{messageId:n})}onEvent(e){return this.eventListeners.add(e),()=>this.eventListeners.delete(e)}stop(){this.sync.send({type:`abort`}),Pb.info(`Sent abort to leader`)}requestSnapshot(){this.sync.send({type:`request_snapshot`})}getLatestSnapshot(){return this.latestSnapshot}close(){this.keepalive.stop(),this.unsubscribe(),this.sync.close(),this.eventListeners.clear(),this.cleanupCDPEventForwarding(),Pb.info(`Follower sync closed`)}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,f({...m(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(e))}handleLeaderMessage(e){switch(e.type){case`snapshot`:Pb.info(`Snapshot received from leader`,{messageCount:e.messages.length,scoopJid:e.scoopJid}),this.snapshotChunkBuffer=null,this.latestSnapshot={messages:e.messages,scoopJid:e.scoopJid},this.options.onSnapshot?.(e.messages,e.scoopJid);break;case`snapshot_chunk`:{let t=ve(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(Pb.info(`Chunked snapshot reassembled from leader`,{messageCount:t.result.messages.length,scoopJid:t.result.scoopJid}),this.latestSnapshot=t.result,this.options.onSnapshot?.(t.result.messages,t.result.scoopJid));break}case`agent_event`:this.emitEvent(e.event);break;case`user_message_echo`:if(this.sentMessageIds.has(e.messageId)){this.sentMessageIds.delete(e.messageId),Pb.debug(`Skipping own message echo`,{messageId:e.messageId});break}Pb.info(`User message echo received`,{messageId:e.messageId,scoopJid:e.scoopJid}),this.options.onUserMessage?.(e.text,e.messageId,e.scoopJid);break;case`status`:this.options.onStatus?.(e.scoopStatus);break;case`error`:Pb.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:Pb.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),l(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){Pb.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new _e({sendCDPRequest:(n,r,i,a)=>{this.sync.send({type:`cdp.request`,requestId:n,targetRuntimeId:e,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}openRemoteTab(e,t){let n=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.tabOpenResolvers.set(n,{resolve:r,reject:i}),this.sync.send({type:`tab.open`,requestId:n,targetRuntimeId:e,url:t})})}async executeLocalTabOpen(e,t){let n=this.options.browserTransport;if(!n){this.sync.send({type:`tab.open.error`,requestId:e,error:`Follower has no browser transport`});return}try{let r=(await n.send(`Target.createTarget`,{url:t,background:!0})).targetId;this.sync.send({type:`tab.opened`,requestId:e,targetId:r}),this.options.onTargetsChanged?.()}catch(t){this.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}async executeLocalCDP(e,t,n,r,i){let a=this.options.browserTransport;if(!a){this.sync.send({type:`cdp.response`,requestId:e,error:`Follower has no browser transport`});return}try{let t=await a.send(n,r,i);if(n===`Target.attachToTarget`&&t.sessionId){let e=t.sessionId;this.remoteCDPSessions.add(e),this.setupCDPEventForwarding(a,e),Pb.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),Pb.debug(`Removed remote CDP session on detach`,{sessionId:i})),be(this.sync,e,t)}catch(t){this.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}setupCDPEventForwarding(e,t){for(let n of[`Page.frameNavigated`,`Page.loadEventFired`,`Page.domContentEventFired`,`Network.responseReceived`,`Network.loadingFinished`,`Network.requestWillBeSent`]){let r=e=>{if(e.sessionId!==t||!this.remoteCDPSessions.has(t))return;let{sessionId:r,...i}=e;this.sync.send({type:`cdp.event`,method:n,params:i,sessionId:t})};e.on(n,r),this.cdpEventCleanups.push(()=>e.off(n,r))}}cleanupCDPEventForwarding(){for(let e of this.cdpEventCleanups)e();this.cdpEventCleanups.length=0,this.remoteCDPSessions.clear()}routeCDPResponse(e){let t=fe(this.cdpChunkBuffers,e);if(t)for(let n of this.remoteTransports.values())n.handleResponse(e.requestId,t.result,t.error)}async executeLocalFs(e,t){let n=this.options.vfs;if(!n){this.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Follower has no VFS`}});return}let r=await hb(n,t);for(let t of r)this.sync.send({type:`fs.response`,requestId:e,response:t})}routeFsResponse(e,t){let n=this.fsResolvers.get(e);if(!n)return;n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}sendFsRequest(e,t){let n=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.fsResolvers.set(n,{resolve:r,reject:i,responses:[]}),this.sync.send({type:`fs.request`,requestId:n,targetRuntimeId:e,request:t})})}};function Ib(e,t){if(t)return`extension`;try{return zb(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function Lb(e,t){return e===`electron-overlay`||e===`standalone`&&t}function Rb(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&qi(t)?t:Gi}catch{return Gi}}function zb(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Bb(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Vb(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Hb(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function Ub(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var Wb=[`/shared/sprinkles`];async function Gb(e){let t=new Map;for(let n of Wb)await e.exists(n)&&await Kb(e,n,t);return await Kb(e,`/`,t),t}async function Kb(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=qb(r);if(!n.has(t)){let i;try{i=await e.readFile(r,{encoding:`utf-8`})??``}catch{i=``}n.set(t,{name:t,path:r,title:Jb(i,t),autoOpen:Yb(i)})}}}function qb(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function Jb(e,t){let n=e.match(/data-sprinkle-title=["']([^"']+)["']/);if(n)return n[1];let r=e.match(/<title>([^<]+)<\/title>/i);return r?r[1].trim():t}function Yb(e){return/data-sprinkle-autoopen\b/.test(e)}var Xb=class{listeners=new Map;lickHandler;fs;closeHandler;stopConeHandler;constructor(e,t,n,r){this.fs=e,this.lickHandler=t,this.closeHandler=n,this.stopConeHandler=r}createAPI(e){let t={name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data,i={type:`sprinkle`,sprinkleName:e,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:n,data:r}};this.lickHandler(i)},on:(t,n)=>{let r=`${e}:${t}`,i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n)},off:(t,n)=>{let r=`${e}:${t}`;this.listeners.get(r)?.delete(n)},readFile:async e=>await this.fs.readFile(e,{encoding:`utf-8`}),writeFile:async(e,t)=>{await this.fs.writeFile(e,t)},readDir:async e=>(await this.fs.readDir(e)).map(e=>({name:e.name,type:e.type})),exists:async e=>this.fs.exists(e),stat:async e=>{let t=await this.fs.stat(e);return{type:t.type,size:t.size}},mkdir:async e=>{await this.fs.mkdir(e,{recursive:!0})},rm:async e=>{await this.fs.rm(e)},screenshot:async e=>{let n=t._container;if(!n)return``;let r=e?n.querySelector(e):n;if(!r)throw Error(`Element not found: `+(e||`container`));let i=r.getBoundingClientRect(),a=Math.ceil(i.width),o=Math.ceil(i.height);if(a===0||o===0)throw Error(`Element has zero dimensions`);let s=document.createElement(`canvas`),c=window.devicePixelRatio||1;s.width=a*c,s.height=o*c;let l=s.getContext(`2d`);l.scale(c,c);let u=r.cloneNode(!0),d=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${o}"><foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(u)}</foreignObject></svg>`;return new Promise((e,t)=>{let n=new Image;n.onload=()=>{l.drawImage(n,0,0),e(s.toDataURL(`image/png`))},n.onerror=()=>t(Error(`Screenshot rendering failed`)),n.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(d)})},setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch{}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch{return null}},open:e=>{let t=/^https?:|^chrome-extension:/.test(e)?e:wm(e);window.open(t,`_blank`)},close:()=>this.closeHandler(e),stopCone:()=>this.stopConeHandler()};return t}pushUpdate(e,t){let n=`${e}:update`,r=this.listeners.get(n);if(r)for(let e of r)try{e(t)}catch{}}removeSprinkle(e){for(let t of this.listeners.keys())t.startsWith(`${e}:`)&&this.listeners.delete(t)}},Zb=n(`sprinkle-manager`),Qb=`slicc-open-sprinkles`,$b=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Xb(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(Qb);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{Zb.warn(`Failed to auto-open sprinkle`,{name:e.name})}return}let t=JSON.parse(e);for(let e of t)try{await this.open(e)}catch{Zb.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(Qb,JSON.stringify([...this.openSprinkles.keys()]))}catch{}}async openNewAutoOpenSprinkles(){await this.refresh();for(let e of this.availableSprinkles.values())if(e.autoOpen&&!this.openSprinkles.has(e.name))try{await this.open(e.name),Zb.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{Zb.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await Gb(this.fs),Zb.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){Zb.info(`Sprinkle already open`,{name:e});return}let n=this.availableSprinkles.get(e);if(n||=(await this.refresh(),this.availableSprinkles.get(e)),!n)throw Error(`Sprinkle not found: ${e}`);let r=await this.fs.readFile(n.path,{encoding:`utf-8`}),i=document.createElement(`div`);i.className=`sprinkle-panel`,i.style.cssText=`width: 100%; height: 100%; display: flex; flex-direction: column; overflow: hidden;`,i.dataset.sprinkle=e,this.openSprinkles.set(e,{renderer:null,container:i}),this.callbacks.addSprinkle(e,n.title,i,t);let a=new ai(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),Tv(e),Zb.info(`Sprinkle opened`,{name:e,title:n.title})}close(e){let t=this.openSprinkles.get(e);t&&(t.renderer?.dispose(),t.container.remove(),this.bridge.removeSprinkle(e),this.openSprinkles.delete(e),this.callbacks.removeSprinkle(e),this.persistOpenSprinkles(),Zb.info(`Sprinkle closed`,{name:e}))}available(){return Array.from(this.availableSprinkles.values())}opened(){return Array.from(this.openSprinkles.keys())}setupWatcher(e){this.watcherUnsub=e.watch(`/workspace`,e=>e.endsWith(`.shtml`),()=>void this.refresh())}dispose(){this.watcherUnsub?.()}sendToSprinkle(e,t){let n=this.openSprinkles.get(e);if(!n){Zb.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function ex(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function tx(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${ex(e.sourceUrl)}.`),t.push(`## Instruction`),t.push(n.instruction),n.urls&&n.urls.length>0){t.push(`## URLs`);for(let e of n.urls)t.push(`- ${e}`)}if(n.context&&(t.push(`## Context`),t.push(n.context)),n.acceptanceCriteria&&n.acceptanceCriteria.length>0){t.push(`## Acceptance Criteria`);for(let e of n.acceptanceCriteria)t.push(`- ${e}`)}return n.notes&&(t.push(`## Notes`),t.push(n.notes)),t.join(`
12731
12731
 
12732
- `)}function nx(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var rx=class{onPendingHandoffsChange;pendingByHandoffId=new Map;constructor(e){this.onPendingHandoffsChange=e.onPendingHandoffsChange}injectHandoff(e,t=`local`){let n=`injected-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.pendingByHandoffId.set(n,{handoffId:n,sourceUrl:t,payload:e,receivedAt:new Date().toISOString()}),this.emitChange(),n}clearHandoff(e){let t=this.pendingByHandoffId.get(e)??null;return this.pendingByHandoffId.delete(e),t&&this.emitChange(),{handoff:t,targetIds:[]}}emitChange(){this.onPendingHandoffsChange?.([...this.pendingByHandoffId.values()].sort(nx))}},$=n(`main`),ix=`slicc-pending-mount`,ax=`pendingMount`;async function ox(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(ix,1);n.onupgradeneeded=()=>n.result.createObjectStore(`handles`),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),n=t.transaction(`handles`,`readwrite`);n.objectStore(`handles`).put(e,ax),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function sx(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(ix,1);n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}catch{return}let n=t.transaction(`handles`,`readwrite`),r=await new Promise(e=>{let t=n.objectStore(`handles`).get(ax);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(ax),await new Promise(e=>n.oncomplete=()=>e());let t=`/mnt/${r.name}`;await e.mount(t,r),$.info(`Mounted folder from welcome onboarding`,{name:r.name,path:t})}t.close()}function cx(){let e=document.createElement(`div`);e.className=`skill-drop-overlay`;let t=document.createElement(`div`);t.className=`skill-drop-overlay__card`;let n=document.createElement(`div`);n.className=`skill-drop-overlay__title`,t.appendChild(n);let r=document.createElement(`div`);return r.className=`skill-drop-overlay__desc`,t.appendChild(r),e.appendChild(t),document.body.appendChild(e),{show(t,i){n.textContent=t,r.textContent=i,e.classList.add(`skill-drop-overlay--visible`)},hide(){e.classList.remove(`skill-drop-overlay--visible`)}}}function lx(){let e=document.createElement(`div`);return e.className=`skill-drop-toast-container`,document.body.appendChild(e),(t,n)=>{let r=document.createElement(`div`);r.className=`skill-drop-toast skill-drop-toast--${n}`,r.textContent=t,e.appendChild(r),requestAnimationFrame(()=>r.classList.add(`skill-drop-toast--visible`)),window.setTimeout(()=>{r.classList.remove(`skill-drop-toast--visible`),window.setTimeout(()=>r.remove(),180)},4200)}}function ux(e,t,n){let r=cx(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ha(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ha(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragleave`,()=>{i!==0&&(i=Math.max(0,i-1),i===0&&!a&&r.hide())}),window.addEventListener(`dragend`,o),window.addEventListener(`blur`,o),window.addEventListener(`drop`,async s=>{let c=ga(s.dataTransfer);if(!c){o();return}if(s.preventDefault(),i=0,a){r.hide(),t(`Another .skill installation is already in progress.`,`error`);return}a=!0,r.show(`Installing skill…`,c.name);try{let r=await ue(e,c);await n(),t(`Installed "${r.skillName}" to ${r.destinationPath} (${r.fileCount} files). Run "skill install ${r.skillName}" to apply it.`,`success`)}catch(e){t(`Failed to install dropped skill: ${e instanceof Error?e.message:String(e)}`,`error`)}finally{a=!1,r.hide()}})}async function dx(e){let{OffscreenClient:t}=await v(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BIdj4gf1.js`);return{OffscreenClient:e}},__vite__mapDeps([22,15])),{VirtualFS:n}=await v(async()=>{let{VirtualFS:e}=await import(`./fs-Br5jEe6j.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([20,1,15])),r=new Qi(e,!0);window.__slicc_debug_tabs=e=>r.setDebugTabs(e),await r.panels.chat.initSession(`session-cone`);let i=null,a=await n.create({dbName:`slicc-fs`});r.panels.fileBrowser.setFs(a),$.info(`File browser wired to shared VFS (local IndexedDB)`);let o=new BroadcastChannel(`preview-vfs`);o.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await a.readFile(n,{encoding:e});o.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),o.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},ux(a,lx(),async()=>{await r.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-DIbWaFel.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await v(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-B4yzwpE0.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([23,1,4,15])),{fetchSecretEnvVars:i}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-f5hqXzA8.js`);return{fetchSecretEnvVars:e}},[]),o=new t;await o.connect();let s=new n(o),c=await i(),l=new e({fs:a,browserAPI:s,env:Object.keys(c).length>0?c:void 0});await r.panels.terminal.mountShell(l),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await v(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-DhUP8Ozj.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([24,1]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let c,l=new Set,u=e=>{r.setPendingHandoffCount(e.length),r.panels.chat.setPendingHandoffs(e)},d=async e=>{i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid),r.setScoopSwitcherSelected?.(e.jid),r.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await r.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&r.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{r.panels.scoops.updateScoopStatus(e,t),r.updateScoopSwitcherStatus?.(e,t),i?.jid===e&&(r.setAgentProcessing(t===`processing`),t===`processing`?r.panels.chat.setProcessing(!0):t===`ready`&&r.panels.chat.setProcessing(!1))},onScoopCreated:e=>{r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),i||(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||r.panels.chat.deleteSessionById(`session-${t}`);if(l=e,r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),!i){let e=c.getScoops().find(e=>e.isCone);e&&(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(i?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;r.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:u,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,c.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=i??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(i=e,c.selectedScoopJid=e.jid,await d(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(a);let f=c.createAgentHandle();r.panels.chat.setAgent(f),r.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=c.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await d(t),r.setActiveTab(`chat`),f.sendMessage(tx(e),`handoff-${e.handoffId}`),c.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{c.dismissPendingHandoff(e.handoffId)}}),c.requestPendingHandoffs(),r.panels.scoops.setOrchestrator(c),r.panels.memory.setOrchestrator(c),r.setScoopSwitcherOrchestrator?.(c),r.onScoopSelect=d,r.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},r.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await r.panels.chat.deleteSessionById(e)}c.clearAllMessages()},r.onClearFilesystem=async()=>{c.clearFilesystem()},r.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let p=new $b(a,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&a.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&p.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&sx(a).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await ox(t),p.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),p.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body)}},{addSprinkle:(e,t,n,i)=>r.addSprinkle(e,t,n,i),removeSprinkle:e=>r.removeSprinkle(e)},()=>{let e=c.getScoops().find(e=>e.isCone);e&&c.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=p,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),c.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await p.refresh(),e=p.available();break;case`opened`:e=p.opened();break;case`refresh`:await p.refresh(),e=p.available().length;break;case`open`:await p.open(r),e=!0;break;case`close`:p.close(r),e=!0;break;case`send`:p.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await p.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await p.refresh(),r.onSprinkleClose=e=>p.close(e),r.getAvailableSprinkles=()=>{let e=new Set(p.opened());return p.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},r.onOpenSprinkle=(e,t)=>p.open(e,t),r.updateAddButtons(),await p.restoreOpenSprinkles(),!await a.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await a.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await a.exists(`/shared/.welcomed`)&&!s(window.localStorage)&&p.available().some(e=>e.name===`welcome`))try{await p.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),c.requestState(),$.info(`Extension UI connected to offscreen agent engine`),Sv().catch(()=>{})}async function fx(){ia(),fa();let e=document.getElementById(`app`);if(!e)throw Error(`#app element not found`);`serviceWorker`in navigator&&navigator.serviceWorker.register(`/preview-sw.js`,{scope:`/preview/`}).then(()=>$.info(`Preview SW registered`)).catch(e=>$.error(`Preview SW registration failed — preview feature will not work`,e)),k();let t=T(),n=s(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await C({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await C({preferTrayJoin:!0}):await C(),t=T()}let i=!t&&s(window.localStorage),a=typeof chrome<`u`&&!!chrome?.runtime?.id,c=Ib(window.location.href,a);if(c===`extension`)return dx(e);let l=new Qi(e,c===`electron-overlay`);if(c===`electron-overlay`){let e=Rb(window.location.href);l.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
12732
+ `)}function nx(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var rx=class{onPendingHandoffsChange;pendingByHandoffId=new Map;constructor(e){this.onPendingHandoffsChange=e.onPendingHandoffsChange}injectHandoff(e,t=`local`){let n=`injected-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.pendingByHandoffId.set(n,{handoffId:n,sourceUrl:t,payload:e,receivedAt:new Date().toISOString()}),this.emitChange(),n}clearHandoff(e){let t=this.pendingByHandoffId.get(e)??null;return this.pendingByHandoffId.delete(e),t&&this.emitChange(),{handoff:t,targetIds:[]}}emitChange(){this.onPendingHandoffsChange?.([...this.pendingByHandoffId.values()].sort(nx))}},$=n(`main`),ix=`slicc-pending-mount`,ax=`pendingMount`;async function ox(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(ix,1);n.onupgradeneeded=()=>n.result.createObjectStore(`handles`),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),n=t.transaction(`handles`,`readwrite`);n.objectStore(`handles`).put(e,ax),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function sx(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(ix,1);n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}catch{return}let n=t.transaction(`handles`,`readwrite`),r=await new Promise(e=>{let t=n.objectStore(`handles`).get(ax);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(ax),await new Promise(e=>n.oncomplete=()=>e());let t=`/mnt/${r.name}`;await e.mount(t,r),$.info(`Mounted folder from welcome onboarding`,{name:r.name,path:t})}t.close()}function cx(){let e=document.createElement(`div`);e.className=`skill-drop-overlay`;let t=document.createElement(`div`);t.className=`skill-drop-overlay__card`;let n=document.createElement(`div`);n.className=`skill-drop-overlay__title`,t.appendChild(n);let r=document.createElement(`div`);return r.className=`skill-drop-overlay__desc`,t.appendChild(r),e.appendChild(t),document.body.appendChild(e),{show(t,i){n.textContent=t,r.textContent=i,e.classList.add(`skill-drop-overlay--visible`)},hide(){e.classList.remove(`skill-drop-overlay--visible`)}}}function lx(){let e=document.createElement(`div`);return e.className=`skill-drop-toast-container`,document.body.appendChild(e),(t,n)=>{let r=document.createElement(`div`);r.className=`skill-drop-toast skill-drop-toast--${n}`,r.textContent=t,e.appendChild(r),requestAnimationFrame(()=>r.classList.add(`skill-drop-toast--visible`)),window.setTimeout(()=>{r.classList.remove(`skill-drop-toast--visible`),window.setTimeout(()=>r.remove(),180)},4200)}}function ux(e,t,n){let r=cx(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ha(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ha(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragleave`,()=>{i!==0&&(i=Math.max(0,i-1),i===0&&!a&&r.hide())}),window.addEventListener(`dragend`,o),window.addEventListener(`blur`,o),window.addEventListener(`drop`,async s=>{let c=ga(s.dataTransfer);if(!c){o();return}if(s.preventDefault(),i=0,a){r.hide(),t(`Another .skill installation is already in progress.`,`error`);return}a=!0,r.show(`Installing skill…`,c.name);try{let r=await ue(e,c);await n(),t(`Installed "${r.skillName}" to ${r.destinationPath} (${r.fileCount} files). Run "skill install ${r.skillName}" to apply it.`,`success`)}catch(e){t(`Failed to install dropped skill: ${e instanceof Error?e.message:String(e)}`,`error`)}finally{a=!1,r.hide()}})}async function dx(e){let{OffscreenClient:t}=await v(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BIdj4gf1.js`);return{OffscreenClient:e}},__vite__mapDeps([22,15])),{VirtualFS:n}=await v(async()=>{let{VirtualFS:e}=await import(`./fs-Br5jEe6j.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([20,1,15])),r=new Qi(e,!0);window.__slicc_debug_tabs=e=>r.setDebugTabs(e),await r.panels.chat.initSession(`session-cone`);let i=null,a=await n.create({dbName:`slicc-fs`});r.panels.fileBrowser.setFs(a),$.info(`File browser wired to shared VFS (local IndexedDB)`);let o=new BroadcastChannel(`preview-vfs`);o.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await a.readFile(n,{encoding:e});o.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),o.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},ux(a,lx(),async()=>{await r.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-B45M6r84.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await v(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-B4yzwpE0.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([23,1,4,15])),{fetchSecretEnvVars:i}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-OKzGv9D2.js`);return{fetchSecretEnvVars:e}},[]),o=new t;await o.connect();let s=new n(o),c=await i(),l=new e({fs:a,browserAPI:s,env:Object.keys(c).length>0?c:void 0});await r.panels.terminal.mountShell(l),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await v(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-DhUP8Ozj.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([24,1]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let c,l=new Set,u=e=>{r.setPendingHandoffCount(e.length),r.panels.chat.setPendingHandoffs(e)},d=async e=>{i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid),r.setScoopSwitcherSelected?.(e.jid),r.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await r.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&r.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{r.panels.scoops.updateScoopStatus(e,t),r.updateScoopSwitcherStatus?.(e,t),i?.jid===e&&(r.setAgentProcessing(t===`processing`),t===`processing`?r.panels.chat.setProcessing(!0):t===`ready`&&r.panels.chat.setProcessing(!1))},onScoopCreated:e=>{r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),i||(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||r.panels.chat.deleteSessionById(`session-${t}`);if(l=e,r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),!i){let e=c.getScoops().find(e=>e.isCone);e&&(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(i?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;r.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:u,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,c.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=i??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(i=e,c.selectedScoopJid=e.jid,await d(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(a);let f=c.createAgentHandle();r.panels.chat.setAgent(f),r.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=c.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await d(t),r.setActiveTab(`chat`),f.sendMessage(tx(e),`handoff-${e.handoffId}`),c.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{c.dismissPendingHandoff(e.handoffId)}}),c.requestPendingHandoffs(),r.panels.scoops.setOrchestrator(c),r.panels.memory.setOrchestrator(c),r.setScoopSwitcherOrchestrator?.(c),r.onScoopSelect=d,r.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},r.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await r.panels.chat.deleteSessionById(e)}c.clearAllMessages()},r.onClearFilesystem=async()=>{c.clearFilesystem()},r.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let p=new $b(a,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&a.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&p.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&sx(a).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await ox(t),p.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),p.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body)}},{addSprinkle:(e,t,n,i)=>r.addSprinkle(e,t,n,i),removeSprinkle:e=>r.removeSprinkle(e)},()=>{let e=c.getScoops().find(e=>e.isCone);e&&c.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=p,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),c.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await p.refresh(),e=p.available();break;case`opened`:e=p.opened();break;case`refresh`:await p.refresh(),e=p.available().length;break;case`open`:await p.open(r),e=!0;break;case`close`:p.close(r),e=!0;break;case`send`:p.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await p.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await p.refresh(),r.onSprinkleClose=e=>p.close(e),r.getAvailableSprinkles=()=>{let e=new Set(p.opened());return p.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},r.onOpenSprinkle=(e,t)=>p.open(e,t),r.updateAddButtons(),await p.restoreOpenSprinkles(),!await a.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await a.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await a.exists(`/shared/.welcomed`)&&!s(window.localStorage)&&p.available().some(e=>e.name===`welcome`))try{await p.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),c.requestState(),$.info(`Extension UI connected to offscreen agent engine`),Sv().catch(()=>{})}async function fx(){ia(),fa();let e=document.getElementById(`app`);if(!e)throw Error(`#app element not found`);`serviceWorker`in navigator&&navigator.serviceWorker.register(`/preview-sw.js`,{scope:`/preview/`}).then(()=>$.info(`Preview SW registered`)).catch(e=>$.error(`Preview SW registration failed — preview feature will not work`,e)),k();let t=T(),n=s(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await C({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await C({preferTrayJoin:!0}):await C(),t=T()}let i=!t&&s(window.localStorage),a=typeof chrome<`u`&&!!chrome?.runtime?.id,c=Ib(window.location.href,a);if(c===`extension`)return dx(e);let l=new Qi(e,c===`electron-overlay`);if(c===`electron-overlay`){let e=Rb(window.location.href);l.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
12733
12733
  #app > .tab-bar { display: none !important; }
12734
12734
  #app > .tab-content {
12735
12735
  height: calc(100vh - var(--s2-header-height));
@@ -12737,4 +12737,4 @@ ${t}
12737
12737
  #app > .tab-content > .tab-content__panel {
12738
12738
  height: 100%;
12739
12739
  }
12740
- `,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&Ub(e.data)&&l.setActiveTab(Rb(`http://localhost/?tab=${e.data.tab??``}`))}),window.addEventListener(`keydown`,e=>{e.code===`Semicolon`&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey&&!e.repeat&&(e.preventDefault(),e.stopPropagation(),window.parent.postMessage({type:`slicc-electron-overlay:toggle`},`*`))},!0)}let d=lx();await l.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let f=new xe,p=e=>{l.setPendingHandoffCount(e.length),l.panels.chat.setPendingHandoffs(e)},m=new Set,g=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:m.size});for(let t of m)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},_=null,y=new Map,b=new Map;function x(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=b.get(e);return t||(t=[],b.set(e,t)),t}function w(e,t){let n=S(e),r=y.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${x()}`,y.set(e,r);let i=E.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),_?.jid===e&&g({type:`message_start`,messageId:r}),o}let E=new Uy(l.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),_?.jid===e&&(g({type:`content_delta`,messageId:r.id,text:t}),n||g({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=y.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),_?.jid===e&&g({type:`content_done`,messageId:n}),y.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${x()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};E.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),_?.jid===e&&(g({type:`message_start`,messageId:n}),g({type:`content_delta`,messageId:n,text:t}),g({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(l.panels.scoops.updateScoopStatus(e,t),l.updateScoopSwitcherStatus?.(e,t),_?.jid===e){if(l.setAgentProcessing(t===`processing`),t===`processing`)l.panels.chat.setProcessing(!0);else if(t===`ready`){l.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),g({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),_?.jid===e&&g({type:`error`,error:t})},getBrowserAPI:()=>f,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=w(e);r.toolCalls||=[],r.toolCalls.push({id:x(),name:t,input:n}),_?.jid===e&&g({type:`tool_use_start`,messageId:r.id,toolName:t,toolInput:n})},onToolEnd:(e,t,n,r)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let i=S(e),a=y.get(e);if(a){let e=i.find(e=>e.id===a);if(e?.toolCalls){let i=[...e.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);i&&(i.result=n,i.isError=r)}}_?.jid===e&&a&&g({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?g({type:`tool_ui`,messageId:i,toolName:t,requestId:n,html:r}):$.warn(`Cannot emit tool_ui - no message ID for scoop`,{scoopJid:e,requestId:n})},onToolUIDone:(e,t)=>{let n=y.get(e);n&&g({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};S(e).push(n),_?.jid===e&&(g({type:`message_start`,messageId:t.id}),g({type:`content_delta`,messageId:t.id,text:n.content}),g({type:`content_done`,messageId:t.id}))}});await E.init(),l.panels.scoops.setOrchestrator(E),l.panels.memory.setOrchestrator(E),l.setScoopSwitcherOrchestrator?.(E);let D=E.getSharedFS();if(D){l.panels.fileBrowser.setFs(D),$.info(`File browser wired to shared VFS`);let e=new BroadcastChannel(`preview-vfs`);e.onmessage=t=>{if(t.data?.type!==`preview-vfs-read`)return;let{id:n,path:r,asText:i}=t.data;(async()=>{try{let t=i?`utf-8`:`binary`,a=await D.readFile(r,{encoding:t});e.postMessage({type:`preview-vfs-response`,id:n,content:a})}catch(t){let i=t instanceof Error?t.message:String(t);i.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:r,error:i}),e.postMessage({type:`preview-vfs-response`,id:n,error:i})}})()},ux(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await l.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-DIbWaFel.js`);return{WasmShell:e}},[]),{fetchSecretEnvVars:t}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-f5hqXzA8.js`);return{fetchSecretEnvVars:e}},[]),n=await t(),r=new e({fs:D,browserAPI:f,env:Object.keys(n).length>0?n:void 0});await l.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await v(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-BaiyTJC8.js`);return{BshWatchdog:e}},__vite__mapDeps([25,15])),t=new e({browserAPI:f,scriptCatalog:r.getScriptCatalog(),fs:D});t.start(),window.addEventListener(`beforeunload`,()=>t.stop(),{once:!0}),$.info(`BSH navigation watchdog started`)}catch(e){$.warn(`Failed to start BSH watchdog`,e)}}catch(e){$.warn(`Failed to mount shell to terminal`,e)}}let O=E.getScoops(),ee=O.some(e=>e.isCone);if(i)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)_=await l.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=O.find(t=>t.folder===e);t?(_=t,$.info(`Restored scoop from URL`,{folder:e})):_=O.find(e=>e.isCone)??O[0]}else _=O.find(e=>e.isCone)??O[0]}_&&l.panels.memory.setSelectedScoop(_.jid);let A=null,j=null,te={sendMessage(e,t){if(!_){g({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:_.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(_.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),E.handleMessage(n),E.createScoopTab(_.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){_&&(E.stopScoop(_.jid),E.clearQueuedMessages(_.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};l.panels.chat.setAgent(te),l.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=E.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await P(t),l.setActiveTab(`chat`),te.sendMessage(tx(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>f.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>f.closePage(e)))}}),l.panels.chat.setDeleteQueuedMessageCallback(e=>{if(_){E.deleteQueuedMessage(_.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(_.jid);if(t){let n=t.findIndex(t=>t.id===e);n!==-1&&t.splice(n,1)}}}),$.info(`Cone agent handle wired to chat UI`);let{getLickManager:ne}=await v(async()=>{let{getLickManager:e}=await import(`./lick-manager-D-0-f8cq.js`);return{getLickManager:e}},[]),re=ne();await re.init(),E.setLickManager(re);let ie=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`session-reload`:e.cronName,o=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:i?`session-reload`:e.cronId,s=e.type;if($.debug(`Lick event`,{type:e.type,name:a,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&D?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&M?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&D&&sx(D).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(n&&e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){(async()=>{try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await ox(t),M?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),M?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let c=E.getScoops(),u;if(u=n||!e.targetScoop?c.find(e=>e.isCone):c.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`),u){let c=`${s}-${o}-${Date.now()}`,d=`[${t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:`Cron Event`}: ${a}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``,f={id:c,chatJid:u.jid,senderId:s,senderName:`${s}:${a}`,content:d,timestamp:e.timestamp,fromAssistant:!1,channel:s};S(u.jid).push({id:c,role:`user`,content:d,timestamp:Date.now(),source:`lick`,channel:s}),_?.jid===u.jid&&l.panels.chat.addLickMessage(c,d,s),$.info(`Routing lick to scoop`,{type:s,name:a,scoopJid:u.jid}),E.handleMessage(f)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};re.setEventHandler(ie),D&&oe().then(async e=>{if(e.length===0)return;let t=[];for(let{path:n,handle:r}of e)try{if(!(`queryPermission`in r)){t.push({path:n,dirName:r.name});continue}await r.queryPermission({mode:`readwrite`})===`granted`?(await D.mount(n,r),$.info(`Restored mount from previous session`,{path:n,name:r.name})):t.push({path:n,dirName:r.name})}catch{t.push({path:n,dirName:r.name})}t.length>0&&ie({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:t}})}).catch(e=>$.warn(`Failed to restore persisted mounts`,e)),l.panels.chat.onInlineSprinkleLick=(e,t)=>{ie({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(D){if(M=new $b(D,ie,{addSprinkle:(e,t,n,r)=>l.addSprinkle(e,t,n,r),removeSprinkle:e=>l.removeSprinkle(e)},()=>{let e=E.getScoops().find(e=>e.isCone);e&&(E.stopScoop(e.jid),E.clearQueuedMessages(e.jid).catch(e=>{$.error(`Failed to clear queued messages on sprinkle stopCone`,{error:e instanceof Error?e.message:String(e)})}))}),window.__slicc_sprinkleManager=M,window.__slicc_reloadSkills=()=>E.reloadAllSkills(),await M.refresh(),l.onSprinkleClose=e=>M.close(e),l.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},l.onOpenSprinkle=(e,t)=>M.open(e,t),l.updateAddButtons(),!await D.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await D.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await D.exists(`/shared/.welcomed`)&&!i&&M.available().some(e=>e.name===`welcome`))try{await M.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await M.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let N=()=>{let e=Bb(window.location.href),t=new WebSocket(e);t.onopen=()=>{$.info(`Lick WebSocket connected`)},t.onmessage=async e=>{try{let n=JSON.parse(e.data);if(n.requestId){let e;try{switch(n.type){case`list_webhooks`:e={type:`response`,requestId:n.requestId,data:re.listWebhooks()};break;case`create_webhook`:{let t=await re.createWebhook(n.name||`default`,n.scoop,n.filter),r=Fp().session,i=r?.webhookUrl?Hb(r.webhookUrl,t.id):Vb(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await re.deleteWebhook(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Webhook not found`}};break;case`list_crontasks`:e={type:`response`,requestId:n.requestId,data:re.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await re.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await re.deleteCronTask(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Cron task not found`}};break;case`tray_status`:{let t=Fp();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}n.type===`webhook_event`&&re.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`handoff_event`&&j&&j.injectHandoff(n.payload,n.sourceUrl)}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(N,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};N(),l.onModelChange=e=>{localStorage.setItem(`selected-model`,e),E.updateModel()},l.onClearChat=async()=>{await E.clearAllMessages(),b.clear()},l.onClearFilesystem=async()=>{await E.resetFilesystem()};let P=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),_=e,E.createScoopTab(e.jid),l.panels.memory.setSelectedScoop(e.jid),l.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=b.get(e.jid),r=e.isCone?void 0:e.name;if(n&&n.length>0)await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.loadMessages(n);else if(await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.getMessages().length===0){let t=await E.getMessagesForScoop(e.jid);for(let n of t){let t=n.channel===`webhook`||n.channel===`cron`,r=n.channel===`delegation`;if(t){let t={id:n.id,role:`user`,content:n.content,timestamp:new Date(n.timestamp).getTime(),source:`lick`,channel:n.channel};S(e.jid).push(t),l.panels.chat.addUserMessage(n.content)}else if(r){let t={id:n.id,role:`user`,content:`**[Instructions from sliccy]**\n\n${n.content}`,timestamp:new Date(n.timestamp).getTime(),source:`delegation`,channel:`delegation`};S(e.jid).push(t),l.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(g({type:`message_start`,messageId:n.id}),g({type:`content_delta`,messageId:n.id,text:n.content}),g({type:`content_done`,messageId:n.id})):l.panels.chat.addUserMessage(n.content)}}e.isCone&&E.isProcessing(e.jid)&&l.panels.chat.setProcessing(!0)};if(l.onScoopSelect=P,_&&(E.createScoopTab(_.jid),await P(_)),j=new rx({onPendingHandoffsChange:p}),c===`standalone`||c===`electron-overlay`){let e=await r(),t=Lb(c,e!==null)?o:null,n=await h({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),i=null,a=null,s=null;Ph(()=>A?(e,t)=>A.sendFsRequest(e,t):i?(e,t)=>i.sendFsRequest(e,t):null),kf(()=>A?()=>A.getBestFollowerForTeleport():null),Af(()=>A?()=>A.getConnectedFollowers():null);let d=e=>{s&&=(clearInterval(s),null),i?.close();let t=`follower-${e.bootstrapId}`,n=new Fb(e.channel,{browserTransport:f.getTransport(),browserAPI:f,onSnapshot:e=>{l.panels.chat.loadMessages(e)},onUserMessage:e=>{l.panels.chat.addUserMessage(e)},onStatus:e=>{l.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void r()});i=n,f.setTrayTargetProvider(n),l.panels.chat.setAgent(n),n.requestSnapshot();let r=async()=>{try{let e=await f.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(r,5e3),r(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},p=e=>{a?.cancel(),s&&=(clearInterval(s),null),i?.close(),i=null,a=lb({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:Up()},{onConnected:e=>d(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{p(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),i?.close(),a?.cancel()},{once:!0}),n?.joinUrl)p(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new Nb({browserTransport:f.getTransport(),browserAPI:f,getMessages:()=>l.panels.chat.getMessages(),getScoopJid:()=>_?.jid??`cone`,onFollowerMessage:(e,t)=>{l.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,Gp(()=>t.getConnectedFollowers()),f.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await f.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new sb({sendControlMessage:t=>e.sendControlMessage(t),onPeerConnected:(e,n)=>{$.info(`Tray follower data channel opened`,{controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,runtime:e.runtime}),t.addFollower(e.bootstrapId,n,{runtime:e.runtime,connectedAt:e.connectedAt??void 0})}})};a(),m.add(e=>{t.broadcastEvent(e)}),e=new zp({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:Up(),onControlMessage:e=>{if(e.type===`webhook.event`){re.handleWebhookEvent(e.webhookId,e.headers,e.body);return}r.handleControlMessage(e).catch(e=>{$.warn(`Tray leader bootstrap handling failed`,{error:e instanceof Error?e.message:String(e)})})}}),Jp(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=u(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),Fp()}),e.start().then(e=>{let t=u(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:E.getScoops().length}),Sv().catch(()=>{})}fx().catch(e=>{$.error(`Fatal error`,e);let t=document.getElementById(`app`);if(t){let n=document.createElement(`div`);n.style.cssText=`padding: 2rem; text-align: center;`;let r=document.createElement(`h1`);r.style.color=`var(--s2-negative, #e34850)`,r.textContent=`Failed to start`;let i=document.createElement(`p`);i.style.color=`var(--s2-content-tertiary, #717171)`,i.textContent=e.message,n.appendChild(r),n.appendChild(i);let a=document.createElement(`button`);for(a.textContent=`Reset all data & reload`,a.style.cssText=`margin-top: 1rem; padding: 0.5rem 1.5rem; background: var(--s2-negative, #e34850); color: #fff; border: none; border-radius: 6px; cursor: pointer; font-size: 14px;`,a.addEventListener(`click`,async()=>{a.disabled=!0,a.textContent=`Resetting…`;let e=await indexedDB.databases();await Promise.all(e.map(e=>e.name?new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()}):Promise.resolve())),location.reload()}),n.appendChild(a);t.firstChild;)t.removeChild(t.firstChild);t.appendChild(n)}});export{Fv as a,si as c,jy as i,ii as l,zy as n,wa as o,Vy as r,ai as s,Ry as t};
12740
+ `,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&Ub(e.data)&&l.setActiveTab(Rb(`http://localhost/?tab=${e.data.tab??``}`))}),window.addEventListener(`keydown`,e=>{e.code===`Semicolon`&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey&&!e.repeat&&(e.preventDefault(),e.stopPropagation(),window.parent.postMessage({type:`slicc-electron-overlay:toggle`},`*`))},!0)}let d=lx();await l.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let f=new xe,p=e=>{l.setPendingHandoffCount(e.length),l.panels.chat.setPendingHandoffs(e)},m=new Set,g=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:m.size});for(let t of m)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},_=null,y=new Map,b=new Map;function x(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=b.get(e);return t||(t=[],b.set(e,t)),t}function w(e,t){let n=S(e),r=y.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${x()}`,y.set(e,r);let i=E.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),_?.jid===e&&g({type:`message_start`,messageId:r}),o}let E=new Uy(l.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),_?.jid===e&&(g({type:`content_delta`,messageId:r.id,text:t}),n||g({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=y.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),_?.jid===e&&g({type:`content_done`,messageId:n}),y.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${x()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};E.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),_?.jid===e&&(g({type:`message_start`,messageId:n}),g({type:`content_delta`,messageId:n,text:t}),g({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(l.panels.scoops.updateScoopStatus(e,t),l.updateScoopSwitcherStatus?.(e,t),_?.jid===e){if(l.setAgentProcessing(t===`processing`),t===`processing`)l.panels.chat.setProcessing(!0);else if(t===`ready`){l.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),g({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),_?.jid===e&&g({type:`error`,error:t})},getBrowserAPI:()=>f,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=w(e);r.toolCalls||=[],r.toolCalls.push({id:x(),name:t,input:n}),_?.jid===e&&g({type:`tool_use_start`,messageId:r.id,toolName:t,toolInput:n})},onToolEnd:(e,t,n,r)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let i=S(e),a=y.get(e);if(a){let e=i.find(e=>e.id===a);if(e?.toolCalls){let i=[...e.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);i&&(i.result=n,i.isError=r)}}_?.jid===e&&a&&g({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?g({type:`tool_ui`,messageId:i,toolName:t,requestId:n,html:r}):$.warn(`Cannot emit tool_ui - no message ID for scoop`,{scoopJid:e,requestId:n})},onToolUIDone:(e,t)=>{let n=y.get(e);n&&g({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};S(e).push(n),_?.jid===e&&(g({type:`message_start`,messageId:t.id}),g({type:`content_delta`,messageId:t.id,text:n.content}),g({type:`content_done`,messageId:t.id}))}});await E.init(),l.panels.scoops.setOrchestrator(E),l.panels.memory.setOrchestrator(E),l.setScoopSwitcherOrchestrator?.(E);let D=E.getSharedFS();if(D){l.panels.fileBrowser.setFs(D),$.info(`File browser wired to shared VFS`);let e=new BroadcastChannel(`preview-vfs`);e.onmessage=t=>{if(t.data?.type!==`preview-vfs-read`)return;let{id:n,path:r,asText:i}=t.data;(async()=>{try{let t=i?`utf-8`:`binary`,a=await D.readFile(r,{encoding:t});e.postMessage({type:`preview-vfs-response`,id:n,content:a})}catch(t){let i=t instanceof Error?t.message:String(t);i.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:r,error:i}),e.postMessage({type:`preview-vfs-response`,id:n,error:i})}})()},ux(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await l.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-B45M6r84.js`);return{WasmShell:e}},[]),{fetchSecretEnvVars:t}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-OKzGv9D2.js`);return{fetchSecretEnvVars:e}},[]),n=await t(),r=new e({fs:D,browserAPI:f,env:Object.keys(n).length>0?n:void 0});await l.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await v(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-BaiyTJC8.js`);return{BshWatchdog:e}},__vite__mapDeps([25,15])),t=new e({browserAPI:f,scriptCatalog:r.getScriptCatalog(),fs:D});t.start(),window.addEventListener(`beforeunload`,()=>t.stop(),{once:!0}),$.info(`BSH navigation watchdog started`)}catch(e){$.warn(`Failed to start BSH watchdog`,e)}}catch(e){$.warn(`Failed to mount shell to terminal`,e)}}let O=E.getScoops(),ee=O.some(e=>e.isCone);if(i)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)_=await l.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=O.find(t=>t.folder===e);t?(_=t,$.info(`Restored scoop from URL`,{folder:e})):_=O.find(e=>e.isCone)??O[0]}else _=O.find(e=>e.isCone)??O[0]}_&&l.panels.memory.setSelectedScoop(_.jid);let A=null,j=null,te={sendMessage(e,t){if(!_){g({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:_.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(_.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),E.handleMessage(n),E.createScoopTab(_.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){_&&(E.stopScoop(_.jid),E.clearQueuedMessages(_.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};l.panels.chat.setAgent(te),l.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=E.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await P(t),l.setActiveTab(`chat`),te.sendMessage(tx(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>f.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>f.closePage(e)))}}),l.panels.chat.setDeleteQueuedMessageCallback(e=>{if(_){E.deleteQueuedMessage(_.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(_.jid);if(t){let n=t.findIndex(t=>t.id===e);n!==-1&&t.splice(n,1)}}}),$.info(`Cone agent handle wired to chat UI`);let{getLickManager:ne}=await v(async()=>{let{getLickManager:e}=await import(`./lick-manager-D6_9f0OR.js`);return{getLickManager:e}},[]),re=ne();await re.init(),E.setLickManager(re);let ie=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`session-reload`:e.cronName,o=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:i?`session-reload`:e.cronId,s=e.type;if($.debug(`Lick event`,{type:e.type,name:a,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&D?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&M?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&D&&sx(D).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(n&&e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){(async()=>{try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await ox(t),M?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),M?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let c=E.getScoops(),u;if(u=n||!e.targetScoop?c.find(e=>e.isCone):c.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`),u){let c=`${s}-${o}-${Date.now()}`,d=`[${t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:`Cron Event`}: ${a}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``,f={id:c,chatJid:u.jid,senderId:s,senderName:`${s}:${a}`,content:d,timestamp:e.timestamp,fromAssistant:!1,channel:s};S(u.jid).push({id:c,role:`user`,content:d,timestamp:Date.now(),source:`lick`,channel:s}),_?.jid===u.jid&&l.panels.chat.addLickMessage(c,d,s),$.info(`Routing lick to scoop`,{type:s,name:a,scoopJid:u.jid}),E.handleMessage(f)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};re.setEventHandler(ie),D&&oe().then(async e=>{if(e.length===0)return;let t=[];for(let{path:n,handle:r}of e)try{if(!(`queryPermission`in r)){t.push({path:n,dirName:r.name});continue}await r.queryPermission({mode:`readwrite`})===`granted`?(await D.mount(n,r),$.info(`Restored mount from previous session`,{path:n,name:r.name})):t.push({path:n,dirName:r.name})}catch{t.push({path:n,dirName:r.name})}t.length>0&&ie({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:t}})}).catch(e=>$.warn(`Failed to restore persisted mounts`,e)),l.panels.chat.onInlineSprinkleLick=(e,t)=>{ie({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(D){if(M=new $b(D,ie,{addSprinkle:(e,t,n,r)=>l.addSprinkle(e,t,n,r),removeSprinkle:e=>l.removeSprinkle(e)},()=>{let e=E.getScoops().find(e=>e.isCone);e&&(E.stopScoop(e.jid),E.clearQueuedMessages(e.jid).catch(e=>{$.error(`Failed to clear queued messages on sprinkle stopCone`,{error:e instanceof Error?e.message:String(e)})}))}),window.__slicc_sprinkleManager=M,window.__slicc_reloadSkills=()=>E.reloadAllSkills(),await M.refresh(),l.onSprinkleClose=e=>M.close(e),l.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},l.onOpenSprinkle=(e,t)=>M.open(e,t),l.updateAddButtons(),!await D.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await D.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await D.exists(`/shared/.welcomed`)&&!i&&M.available().some(e=>e.name===`welcome`))try{await M.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await M.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let N=()=>{let e=Bb(window.location.href),t=new WebSocket(e);t.onopen=()=>{$.info(`Lick WebSocket connected`)},t.onmessage=async e=>{try{let n=JSON.parse(e.data);if(n.requestId){let e;try{switch(n.type){case`list_webhooks`:e={type:`response`,requestId:n.requestId,data:re.listWebhooks()};break;case`create_webhook`:{let t=await re.createWebhook(n.name||`default`,n.scoop,n.filter),r=zp().session,i=r?.webhookUrl?Hb(r.webhookUrl,t.id):Vb(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await re.deleteWebhook(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Webhook not found`}};break;case`list_crontasks`:e={type:`response`,requestId:n.requestId,data:re.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await re.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await re.deleteCronTask(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Cron task not found`}};break;case`tray_status`:{let t=zp();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}n.type===`webhook_event`&&re.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`handoff_event`&&j&&j.injectHandoff(n.payload,n.sourceUrl)}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(N,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};N(),l.onModelChange=e=>{localStorage.setItem(`selected-model`,e),E.updateModel()},l.onClearChat=async()=>{await E.clearAllMessages(),b.clear()},l.onClearFilesystem=async()=>{await E.resetFilesystem()};let P=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),_=e,E.createScoopTab(e.jid),l.panels.memory.setSelectedScoop(e.jid),l.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=b.get(e.jid),r=e.isCone?void 0:e.name;if(n&&n.length>0)await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.loadMessages(n);else if(await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.getMessages().length===0){let t=await E.getMessagesForScoop(e.jid);for(let n of t){let t=n.channel===`webhook`||n.channel===`cron`,r=n.channel===`delegation`;if(t){let t={id:n.id,role:`user`,content:n.content,timestamp:new Date(n.timestamp).getTime(),source:`lick`,channel:n.channel};S(e.jid).push(t),l.panels.chat.addUserMessage(n.content)}else if(r){let t={id:n.id,role:`user`,content:`**[Instructions from sliccy]**\n\n${n.content}`,timestamp:new Date(n.timestamp).getTime(),source:`delegation`,channel:`delegation`};S(e.jid).push(t),l.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(g({type:`message_start`,messageId:n.id}),g({type:`content_delta`,messageId:n.id,text:n.content}),g({type:`content_done`,messageId:n.id})):l.panels.chat.addUserMessage(n.content)}}e.isCone&&E.isProcessing(e.jid)&&l.panels.chat.setProcessing(!0)};if(l.onScoopSelect=P,_&&(E.createScoopTab(_.jid),await P(_)),j=new rx({onPendingHandoffsChange:p}),c===`standalone`||c===`electron-overlay`){let e=await r(),t=Lb(c,e!==null)?o:null,n=await h({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),i=null,a=null,s=null;Rh(()=>A?(e,t)=>A.sendFsRequest(e,t):i?(e,t)=>i.sendFsRequest(e,t):null),Nf(()=>A?()=>A.getBestFollowerForTeleport():null),Pf(()=>A?()=>A.getConnectedFollowers():null);let d=e=>{s&&=(clearInterval(s),null),i?.close();let t=`follower-${e.bootstrapId}`,n=new Fb(e.channel,{browserTransport:f.getTransport(),browserAPI:f,onSnapshot:e=>{l.panels.chat.loadMessages(e)},onUserMessage:e=>{l.panels.chat.addUserMessage(e)},onStatus:e=>{l.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void r()});i=n,f.setTrayTargetProvider(n),l.panels.chat.setAgent(n),n.requestSnapshot();let r=async()=>{try{let e=await f.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(r,5e3),r(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},p=e=>{a?.cancel(),s&&=(clearInterval(s),null),i?.close(),i=null,a=lb({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:qp()},{onConnected:e=>d(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{p(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),i?.close(),a?.cancel()},{once:!0}),n?.joinUrl)p(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new Nb({browserTransport:f.getTransport(),browserAPI:f,getMessages:()=>l.panels.chat.getMessages(),getScoopJid:()=>_?.jid??`cone`,onFollowerMessage:(e,t)=>{l.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,Yp(()=>t.getConnectedFollowers()),f.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await f.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new sb({sendControlMessage:t=>e.sendControlMessage(t),onPeerConnected:(e,n)=>{$.info(`Tray follower data channel opened`,{controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,runtime:e.runtime}),t.addFollower(e.bootstrapId,n,{runtime:e.runtime,connectedAt:e.connectedAt??void 0})}})};a(),m.add(e=>{t.broadcastEvent(e)}),e=new Up({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:qp(),onControlMessage:e=>{if(e.type===`webhook.event`){re.handleWebhookEvent(e.webhookId,e.headers,e.body);return}r.handleControlMessage(e).catch(e=>{$.warn(`Tray leader bootstrap handling failed`,{error:e instanceof Error?e.message:String(e)})})}}),Qp(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=u(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),zp()}),e.start().then(e=>{let t=u(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:E.getScoops().length}),Sv().catch(()=>{})}fx().catch(e=>{$.error(`Fatal error`,e);let t=document.getElementById(`app`);if(t){let n=document.createElement(`div`);n.style.cssText=`padding: 2rem; text-align: center;`;let r=document.createElement(`h1`);r.style.color=`var(--s2-negative, #e34850)`,r.textContent=`Failed to start`;let i=document.createElement(`p`);i.style.color=`var(--s2-content-tertiary, #717171)`,i.textContent=e.message,n.appendChild(r),n.appendChild(i);let a=document.createElement(`button`);for(a.textContent=`Reset all data & reload`,a.style.cssText=`margin-top: 1rem; padding: 0.5rem 1.5rem; background: var(--s2-negative, #e34850); color: #fff; border: none; border-radius: 6px; cursor: pointer; font-size: 14px;`,a.addEventListener(`click`,async()=>{a.disabled=!0,a.textContent=`Resetting…`;let e=await indexedDB.databases();await Promise.all(e.map(e=>e.name?new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()}):Promise.resolve())),location.reload()}),n.appendChild(a);t.firstChild;)t.removeChild(t.firstChild);t.appendChild(n)}});export{Fv as a,si as c,jy as i,ii as l,zy as n,wa as o,Vy as r,ai as s,Ry as t};