sliccy 6.12.1 → 6.13.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.
- package/README.md +1 -1
- package/dist/node-server/_shared/tray-sync-protocol.d.ts +49 -3
- package/dist/node-server/_shared/tray-sync-protocol.d.ts.map +1 -1
- package/dist/node-server/_shared/tray-sync-protocol.js +5 -3
- package/dist/node-server/_shared/tray-sync-protocol.js.map +1 -1
- package/dist/ui/assets/{account-store-BBCJS2kk.js → account-store-BGZXP38Z.js} +1 -1
- package/dist/ui/assets/{account-store-7_igW1xZ.js → account-store-BlDFX_iR.js} +1 -1
- package/dist/ui/assets/{adobe-C2SYO25k.js → adobe-D401sVgj.js} +1 -1
- package/dist/ui/assets/{adobe-pMNuaaiJ.js → adobe-d5p2O9eh.js} +1 -1
- package/dist/ui/assets/{apps-CHFwCF-m.js → apps-Da6VEmJt.js} +1 -1
- package/dist/ui/assets/{azure-openai-ClPx-RU2.js → azure-openai-CXz46PZH.js} +1 -1
- package/dist/ui/assets/{azure-openai-N4-g_Slk.js → azure-openai-DuMpTpPG.js} +1 -1
- package/dist/ui/assets/{cdp-BbdoN1_1.js → cdp-uBLa5oK-.js} +1 -1
- package/dist/ui/assets/{cerebras-CTfiuRqo.js → cerebras-DSGp8gFq.js} +1 -1
- package/dist/ui/assets/{cerebras-DSB2SrnE.js → cerebras-lKqtmjhc.js} +1 -1
- package/dist/ui/assets/{connect-surface-DqGhBG2Y.js → connect-surface-D1jL-YsN.js} +1 -1
- package/dist/ui/assets/{extension-bridge-transport-Dq1Od_T7.js → extension-bridge-transport-CikuxrQ4.js} +1 -1
- package/dist/ui/assets/{fs-CGlT61Qi.js → fs-C6SkDVVM.js} +2 -2
- package/dist/ui/assets/{fs-CFBRwa_C.js → fs-DC6FadkH.js} +1 -1
- package/dist/ui/assets/{github-CyLcYhhN.js → github-CG9r0qFL.js} +1 -1
- package/dist/ui/assets/{github-B1TiC10L.js → github-DYoqx8hA.js} +2 -2
- package/dist/ui/assets/{github-copilot-C201I3N7.js → github-copilot-BD_K1mxY.js} +1 -1
- package/dist/ui/assets/{github-copilot-DU_Sqb6T.js → github-copilot-CAIPk1jo.js} +1 -1
- package/dist/ui/assets/{kernel-worker-B-c8gsZG.js → kernel-worker-BIMcHhLv.js} +19 -19
- package/dist/ui/assets/{local-llm-CZThdumb.js → local-llm-BfIp8rMI.js} +1 -1
- package/dist/ui/assets/{local-llm-DDmuETmY.js → local-llm-c6JxoVB5.js} +1 -1
- package/dist/ui/assets/{main-DG6Gk2aY.js → main-CQysbD_2.js} +3 -3
- package/dist/ui/assets/{main-cherry-ZFxBF0gE.js → main-cherry-C8VTPpbn.js} +1 -1
- package/dist/ui/assets/{mount-OtwjnuEI.js → mount-BXzdt95O.js} +1 -1
- package/dist/ui/assets/{mount-Dgvntkm-.js → mount-CowQPInX.js} +2 -2
- package/dist/ui/assets/{mount-recovery-BV6fn6QF.js → mount-recovery-COqMGgnC.js} +1 -1
- package/dist/ui/assets/{new-session-DIo20pYC.js → new-session-By_N2CTg.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-DD-ttSfT.js → oauth-bootstrap-BG-7io1X.js} +2 -2
- package/dist/ui/assets/{openai-codex-CLt1s3EO.js → openai-codex-Cf6n_wlc.js} +1 -1
- package/dist/ui/assets/{openai-codex-D3UCr3Ii.js → openai-codex-NEW83bMc.js} +1 -1
- package/dist/ui/assets/{openrouter-CLK5bdnS.js → openrouter-BvyUPf3T.js} +1 -1
- package/dist/ui/assets/{openrouter-DC_wtPBf.js → openrouter-dLDk6_nN.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-atRrey7Y.js → openrouter-oauth-DEXKF6GY.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BHeaGkAP.js → openrouter-oauth-DpHEbuGk.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-F_L0xtfO.js → panel-rpc-handlers-DFE4HJwt.js} +2 -2
- package/dist/ui/assets/{provider-D2cqHgJm.js → provider-BQTjKtNx.js} +2 -2
- package/dist/ui/assets/{provider-B6ul9w8T.js → provider-CEf9N9jt.js} +1 -1
- package/dist/ui/assets/{provider-settings-D-CGYQ30.js → provider-settings-B0MZyvjr.js} +1 -1
- package/dist/ui/assets/{provider-settings-C4emfAvi.js → provider-settings-DemFH9QU.js} +1 -1
- package/dist/ui/assets/{provider-store-access-FRtGj6mY.js → provider-store-access-Cg2f_272.js} +2 -2
- package/dist/ui/assets/provider-store-access-DeurQAHW.js +1 -0
- package/dist/ui/assets/{providers-CMnY0-eX.js → providers-C3ZN8FcH.js} +1 -1
- package/dist/ui/assets/{providers-atT59AZ9.js → providers-n204cBup.js} +2 -2
- package/dist/ui/assets/{quick-llm-C7nKCGel.js → quick-llm-CSpaM2fB.js} +1 -1
- package/dist/ui/assets/{redirect-uri-B9FLj_m4.js → redirect-uri-CA1V4zRv.js} +1 -1
- package/dist/ui/assets/{remote-cdp-transport-CaLf00Hc.js → remote-cdp-transport-BS_0BClw.js} +1 -1
- package/dist/ui/assets/{session-freezer-D65YxFGN.js → session-freezer-gsaPM-ia.js} +2 -2
- package/dist/ui/assets/{setup-feature-flags-remote-CuTkC4nM.js → setup-feature-flags-remote-Bb6Okb1l.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-CfuA0mWA.js → setup-standalone-prelude-ZuRHPj-z.js} +2 -2
- package/dist/ui/assets/{setup-sudo-CJJ-SJXz.js → setup-sudo-9jdX7JmN.js} +2 -2
- package/dist/ui/assets/{skills-DqvJwg2w.js → skills-CgTYDcS2.js} +1 -1
- package/dist/ui/assets/{store-Bo6AQxIe.js → store-Dvfacvs3.js} +1 -1
- package/dist/ui/assets/{sudo-DpMM2PNU.js → sudo-BIgVLkiv.js} +1 -1
- package/dist/ui/assets/{tray-sync-protocol-CQ9Z94EX.js → tray-sync-protocol-D9BQVq93.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-Zdl2rqUw.js → upgrade-detection-CNscsCCc.js} +1 -1
- package/dist/ui/assets/{wc-extension-C2PMMZEs.js → wc-extension-CLEF_jFz.js} +2 -2
- package/dist/ui/assets/wc-follower-kYpbk9Iu.js +17 -0
- package/dist/ui/assets/wc-follower-model-surface-DJRncbD2.js +1 -0
- package/dist/ui/assets/wc-live-C5clQ2Q_.js +8 -0
- package/dist/ui/assets/{wc-nav-CAFPETHt.js → wc-nav-Csm4nak0.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-GzhjT5Cb.js → wc-onboarding-DE7oom7t.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-CK41-wSK.js → wc-placeholder-BghZEkH1.js} +2 -2
- package/dist/ui/assets/{wc-settings-B4j3koZ-.js → wc-settings-DVWN7ACt.js} +2 -2
- package/dist/ui/assets/{wc-shell-D1X-FzQH.js → wc-shell-DSDsmJBH.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-PmCzL6rC.js → wc-sprinkles-DVrFDzpY.js} +2 -2
- package/dist/ui/assets/wc-tray-DxeJn7Yj.js +2 -0
- package/dist/ui/assets/wc-tray-scoops-CZSktpcG.js +5 -0
- package/dist/ui/assets/{xai-grok-hEqM8CaH.js → xai-grok-CfwGHRp8.js} +1 -1
- package/dist/ui/assets/{xai-grok-LwQHCD05.js → xai-grok-DpYI-OOQ.js} +1 -1
- package/dist/ui/index.html +6 -6
- package/dist/ui/llm-proxy-sw.js +1 -1
- package/dist/ui/packages/webapp/index.html +6 -6
- package/package.json +1 -1
- package/dist/ui/assets/leader-session-events-DlAsC04B.js +0 -1
- package/dist/ui/assets/provider-store-access-Cyam6iay.js +0 -1
- package/dist/ui/assets/wc-follower-CVJSFw63.js +0 -17
- package/dist/ui/assets/wc-live-ozMdZAna.js +0 -8
- package/dist/ui/assets/wc-tray-DhplU2Nn.js +0 -2
- package/dist/ui/assets/wc-tray-scoops-BPhWy9cl.js +0 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,n as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}from"./logger-LESFN7Hj.js";import{n as i,r as a,t as o}from"./panel-rpc-CjFVE0nK.js";import{a as s,t as c}from"./providers-
|
|
1
|
+
import{i as e,n as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}from"./logger-LESFN7Hj.js";import{n as i,r as a,t as o}from"./panel-rpc-CjFVE0nK.js";import{a as s,t as c}from"./providers-C3ZN8FcH.js";import{n as l,t as u}from"./base64-Ba7QB87Z.js";import{a as d,i as f,n as p,r as m,s as h,t as g}from"./src-BcePBv4G.js";import{$ as _,$t as v,An as y,At as b,Bt as x,Cn as S,Ct as C,D as w,Dn as T,Dt as E,E as D,En as ee,Et as te,F as ne,Ft as O,Gt as k,Ht as re,I as ie,It as ae,J as oe,Jt as se,Kt as ce,Lt as le,Mt as ue,Nt as de,On as A,Ot as j,Pt as fe,Q as pe,Qt as me,R as he,Rt as ge,Sn as _e,St as ve,Tn as ye,Tt as be,Ut as M,Vt as N,Wt as xe,X as Se,Xt as P,Y as Ce,Yt as F,Z as we,Zt as I,_n as L,_t as Te,an as R,at as Ee,bn as De,bt as z,cn as Oe,ct as ke,dn as Ae,dt as je,en as Me,et as Ne,fn as Pe,ft as Fe,gn as Ie,gt as Le,hn as Re,ht as ze,in as B,it as Be,jn as Ve,jt as He,kn as Ue,kt as We,ln as V,lt as Ge,m as Ke,mn as qe,mt as Je,nn as Ye,nt as Xe,on as Ze,ot as Qe,pn as $e,pt as et,q as tt,qt as nt,rn as H,rt,sn as it,st as at,tn as ot,tt as st,un as ct,ut as lt,vn as ut,vt as dt,w as ft,wn as pt,wt as eee,xn as mt,xt as ht,yn as gt,yt as _t,zt as vt}from"./account-store-BGZXP38Z.js";import{a as yt,c as bt,d as xt,f as St,i as Ct,l as wt,n as Tt,p as Et,r as Dt,s as Ot,t as kt,u as At}from"./proxied-fetch-GabK83LB.js";import{t as jt}from"./runtime-env-byAg9ij-.js";import{n as Mt,r as Nt,t as Pt}from"./fetch-body-DDu_AU5I.js";import{a as Ft,i as It,n as Lt,r as Rt}from"./transcript-limits-HrXqL2T0.js";import{n as zt,o as Bt,s as Vt}from"./tool-ui-t6ocn6AG.js";import{a as Ht,i as Ut,n as Wt,o as Gt,r as Kt,t as qt}from"./backend-local-D4WZgy4J.js";import{t as Jt}from"./types-idfTVsM8.js";import{n as Yt,t as Xt}from"./mime-types-D7IV6i7k.js";import{a as Zt,i as Qt,n as $t,r as en}from"./mount-BXzdt95O.js";import{o as tn}from"./mount-table-store-CTrzlrNn.js";import{t as nn}from"./remote-cache-D59F5FOx.js";import{r as rn,t as tee}from"./mount-recovery-COqMGgnC.js";import{C as nee,D as ree,E as an,S as on,_ as sn,a as cn,b as ln,d as un,g as dn,h as fn,m as pn,n as mn,o as hn,r as gn,s as _n,t as vn,u as yn,w as bn,y as xn}from"./db-BTiVtoD4.js";import{a as Sn,i as Cn,n as wn,r as Tn}from"./tray-runtime-config-kGqQt9_W.js";import{a as En,i as Dn,n as On,o as kn,r as An}from"./runtime-mode-jkSDrVfl.js";import{a as jn,c as Mn,d as Nn,i as Pn,l as Fn,n as In,o as Ln,s as Rn,t as zn,u as Bn}from"./lick-manager-Ce_d4NxJ.js";import{i as Vn,n as Hn,r as Un,t as Wn}from"./path-utils-DU6QhF_k.js";import{u as Gn}from"./transform-messages-D27pVLZ-.js";import{l as Kn,m as qn}from"./bedrock-camp-CHi38ceE.js";import{t as Jn}from"./__vite-browser-external-SwrSgYTf.js";import{a as Yn,n as Xn,r as Zn}from"./fs-DC6FadkH.js";import{a as U,c as Qn,i as $n,l as er,n as tr,o as nr,r as rr,s as ir}from"./cost-command-_BMgmnMI.js";import{a as ar,c as or,d as sr,f as iee,i as aee,l as cr,m as lr,n as oee,o as ur,p as dr,r as fr,s as pr,u as mr}from"./skills-CgTYDcS2.js";import{n as hr,t as gr}from"./llm-session-id-ZObKEXzb.js";import{n as _r,r as vr}from"./frozen-archive-format-CqpMlNNW.js";import{a as yr,c as br,d as xr,f as Sr,i as Cr,l as wr,n as Tr,o as Er,r as Dr,s as Or,t as kr,u as Ar}from"./installer-kDSMsl2T.js";import{n as jr,t as Mr}from"./safe-buffer-C0pSmFaz.js";import{t as Nr}from"./global-db-DvmmimLY.js";import{a as Pr,i as Fr,r as Ir,t as Lr}from"./git-config-Lj0BT7Oc.js";import{t as Rr}from"./process-manager-B5dz0PkO.js";import{C as zr,O as Br,S as Vr,_ as Hr,a as Ur,b as Wr,c as Gr,f as Kr,g as qr,h as Jr,i as Yr,k as Xr,l as Zr,m as Qr,n as $r,o as ei,p as ti,r as ni,s as ri,t as ii,u as ai,v as oi,x as si,y as ci}from"./shared-pjIf7b3g.js";import{n as li,t as ui}from"./esbuild-wasm-Bnp5hszJ.js";import{n as di,t as fi}from"./wasm-compiler-Ct7QZURL.js";import{a as pi,i as mi,r as hi,t as gi}from"./script-catalog-BYXhqRAc.js";import{n as _i,t as vi}from"./magick-wasm-CTgpng4k.js";import{t as yi}from"./local-llm-c6JxoVB5.js";import{t as bi}from"./client-CAAAFAry.js";import{t as xi}from"./redirect-uri-CA1V4zRv.js";const Si=r(`cdp`);var Ci=class{ws=null;nextId=1;_superseded=!1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,Si.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Si.error(`Connection failed`,{url:t}),this.cleanup(),i(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),Si.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};return t&&(a.params=t),n&&(a.sessionId=n),Si.debug(`Send`,{method:e,id:i,sessionId:n}),new Promise((t,n)=>{let o=setTimeout(()=>{this.pending.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`))},r);this.pending.set(i,{resolve:e=>{clearTimeout(o),t(e)},reject:e=>{clearTimeout(o),n(e)}}),this.ws.send(JSON.stringify(a))})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Si.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Si.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),n.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):n.resolve(e.result??{}));return}if(`method`in t){let e=t;Si.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){let t=e===4001;t?(this._superseded=!0,Si.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Si.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;for(let[,e]of this.pending)e.reject(Error(n));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};const wi=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -881,7 +881,7 @@ import{i as e,n as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}f
|
|
|
881
881
|
`).trim();return e?e.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`):null}return t.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`)}const da=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function fa(e){if(typeof e!=`string`)return{kind:`absent`};let t=ua(e);return t===null?{kind:`noise`}:{kind:`kept`,value:t,mutated:t!==e}}function pa(e){let t=fa(e.source),n=fa(e.target),r=t.kind!==`kept`,i=n.kind!==`kept`;if((t.kind!==`absent`||n.kind!==`absent`)&&r&&i)return!0;let a=!1;return t.kind===`kept`?t.mutated&&(e.source=t.value,a=!0):t.kind===`noise`&&(e.source=``,a=!0),n.kind===`kept`?n.mutated&&(e.target=n.value,a=!0):n.kind===`noise`&&(e.target=``,a=!0),a?JSON.stringify(e):null}function ma(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[da])return;let t=e.bind(navigator),n=((e,n)=>{try{let r=typeof n==`string`?n:n instanceof ArrayBuffer?new TextDecoder().decode(n):null;if(r&&r.length>0&&r.charCodeAt(0)===123){let n=JSON.parse(r);if(n?.checkpoint===`error`){let r=pa(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[da]=!0,navigator.sendBeacon=n}var ha=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new Map;unsubscribe=null;opts;label;constructor(e){this.opts=e,this.label=e.label??`CDP transport`}get state(){return this._state}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);this.unsubscribe=this.opts.subscribeIncoming(e=>this.handleIncoming(e)),this._state=`connected`}disconnect(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.pendingCommands)clearTimeout(e.timer),e.reject(Error(`${this.label} disconnected`));this.pendingCommands.clear(),this.listeners.clear(),this._state=`disconnected`}async send(e,t,n,r=3e4){if(this._state!==`connected`)throw Error(`${this.label} is not connected`);let i=this.nextCommandId++,a=this.opts.buildCommandEnvelope(i,e,t,n);return new Promise((t,n)=>{let o=!1,s=setTimeout(()=>{o||(o=!0,this.pendingCommands.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`)))},r);this.pendingCommands.set(i,{resolve:e=>{o||(o=!0,t(e))},reject:e=>{o||(o=!0,n(e))},timer:s}),this.opts.sendEnvelope(a).catch(e=>{o||(o=!0,this.pendingCommands.delete(i),clearTimeout(s),n(Error(`Failed to send CDP command: ${e instanceof Error?e.message:String(e)}`)))})})}on(e,t){let n=this.listeners.get(e),r=!n;n||(n=new Set,this.listeners.set(e,n)),n.add(t),r&&this.opts.onSubscribeEvent?.(e)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&(this.listeners.delete(e),this.opts.onUnsubscribeEvent?.(e)))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleIncoming(e){let t=this.opts.parseResponse(e);if(t){this.handleResponse(t);return}let n=this.opts.parseEvent(e);n&&this.handleEvent(n)}handleResponse(e){let t=this.pendingCommands.get(e.id);if(!t){this.opts.onUnknownResponseId?.(e.id);return}this.pendingCommands.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result??{})}handleEvent(e){let t=this.listeners.get(e.method);if(t)for(let n of t)try{n(e.params??{})}catch(t){this.opts.onListenerError?.(e.method,t)}}};function ga(e){let t=!1,n=()=>{t||(t=!0,typeof e.start==`function`&&e.start())};return{onMessage:t=>{let r=e=>{t(e.data)};return e.addEventListener(`message`,r),n(),()=>{e.removeEventListener(`message`,r)}},send:(t,n)=>{n&&n.length>0?e.postMessage(t,n):e.postMessage(t)}}}function _a(e){let t=ga(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var va=class extends ha{constructor(e){let t=ga(e);super({label:`WorkerCdpProxy`,buildCommandEnvelope:(e,t,n,r)=>({type:`cdp-cmd`,id:e,method:t,params:n,sessionId:r}),sendEnvelope:e=>(t.send(e),Promise.resolve()),subscribeIncoming:e=>t.onMessage(e),parseResponse:e=>{let t=e;if(t?.type!==`cdp-response`)return null;if(typeof t.id!=`number`||!Number.isFinite(t.id))return console.warn(`[WorkerCdpProxy] dropping cdp-response with invalid id`,t),null;let n=e;return{id:n.id,result:n.result,error:n.error}},parseEvent:e=>{let t=e;if(t?.type!==`cdp-event`)return null;if(typeof t.method!=`string`)return console.warn(`[WorkerCdpProxy] dropping cdp-event with invalid method`,t),null;let n=e;return{method:n.method,params:n.params}},onSubscribeEvent:e=>{t.send({type:`cdp-subscribe`,event:e})},onUnsubscribeEvent:e=>{t.send({type:`cdp-unsubscribe`,event:e})}})}};const ya=`sessions`;function ba(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(ya)||e.createObjectStore(ya,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var xa=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await ba();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(ya,`readwrite`);i.objectStore(ya).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(ya,`readonly`).objectStore(ya).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(ya,`readonly`).objectStore(ya).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(ya,`readwrite`);i.objectStore(ya).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};const Sa=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`sudo-request`,`preview`,`discovery`]);function Ca(e){return e!=null&&Sa.has(e)}const wa={webhook:`Webhook Event`,sprinkle:`Sprinkle Event`,fswatch:`File Watch Event`,"session-reload":`Session Reload`,navigate:`Navigate Event`,upgrade:`Upgrade Event`,cherry:`Cherry Event`,workflow:`Workflow Event`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`,preview:`Preview`,discovery:`Discovery Event`};function Ta(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`session-reload`:return`mount-recovery`;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`cherry`:return e.cherryName;case`workflow`:return e.workflowName;case`sudo-request`:return e.sudoScoopName;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Ea(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=tee(n.mounts??[]);return e===null?null:{label:t,content:`${e}${r?`\n\nLick ID: ${r}\nThis card is actionable: call \`lick_confirm\` with this lick id to re-run the listed \`mount …\` command(s) so the user can re-authorize, or \`lick_dismiss\` to leave them unmounted. The card flips to ✓ on confirm / muted ✗ on dismiss.`:``}`}}let i=Na(e,t);if(!r)return i;let a=`\n\nLick ID: ${r}\nThis card is informational — there is NO confirm action. Call \`lick_dismiss\` with this lick id to acknowledge and clear it. The card flips to muted ✗ on dismiss.`;return{label:i.label,content:`${i.content}${a}`}}function Da(e,t){let n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`,i=e.body?.releasedAt??null,a=i?`\nReleased: ${i}`:``,o=e.lickId;return{label:t,content:`[${t}: ${n}→${r}]\n\nSLICC was upgraded from \`${n}\` to \`${r}\`.${a}${o?`\n\nLick ID: ${o}\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`). The card is a binary action: call \`lick_confirm\` with this lick id to **Update workspace files** (it runs the three-way merge of bundled vfs-root content into the user's VFS), or \`lick_dismiss\` to clear it. The card flips to ✓ on confirm / muted ✗ on dismiss. Reviewing the changelog is a separate step you can run first — it is NOT a card action.`:`
|
|
882
882
|
|
|
883
883
|
Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function Oa(e,t){let n=e.cherryOrigin??`unknown origin`,r=e.cherryRuntimeId??`unknown`;return{label:t,content:`[${t}: ${e.cherryName??`unnamed`}] from ${n} (runtime ${r})\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function ka(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function Aa(e,t){let n=e.workflowName??`workflow`,r=e.resultPath??`(no result file)`,i=e.preview??``;return{label:t,content:`[${t}: ${n}] ${e.body?.status??`complete`} — ${i}\nFull result: ${r} (read it only if you need the whole thing).`}}function ja(e,t){let n=e.sudoScoopName??`a scoop`,r=e.lickId??`(unknown)`,i=e.sudoKind??`unknown`,a=e.sudoDetail??``,o=[`[${t}: ${n}]`,`Lick ID: ${r}`,`Kind: ${i}`,`Detail: ${a}`];return e.sudoSuggestedPattern&&o.push(`Suggested pattern: ${e.sudoSuggestedPattern}`),o.push(``,`Use the lick_confirm tool with lick_id="${r}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${r}" to deny.`),{label:t,content:o.join(`
|
|
884
|
-
`)}}function Ma(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.\nThis is informational — there is no card action. You MAY fetch it (e.g. \`curl ${r}\`) and act on it if it's relevant to the current task; otherwise ignore it.`}}function Na(e,t){let n=Ta(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Pa(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Na(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Fa(e,t){let n=Na(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill\` with any branch/path scope from the body); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Ia(e){let t=wa[e.type];return e.type===`session-reload`?Ea(e,t):e.type===`upgrade`?Da(e,t):e.type===`cherry`?Oa(e,t):e.type===`preview`?ka(e,t):e.type===`workflow`?Aa(e,t):e.type===`sudo-request`?ja(e,t):e.type===`navigate`?Fa(e,t):e.type===`webhook`?Pa(e,t):e.type===`discovery`?Ma(e,t):Na(e,t)}const La=new Map;function Ra(e){let t=La.get(e.id);t&&(La.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}let za={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Ba(){return{...za}}function Va(){let e=Ba();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.followerTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Ha=new Set;function Ua(e){return Ha.add(e),()=>{Ha.delete(e)}}const Wa=`__slicc_binary__`;function Ga(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Wa]===`b64`&&typeof t.data==`string`}function Ka(e){if(e instanceof Uint8Array)return{[Wa]:`b64`,data:l(e)};if(Array.isArray(e))return e.map(Ka);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Ka(r);return t}return e}function qa(e){if(Ga(e))return u(e.data);if(Array.isArray(e))return e.map(qa);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=qa(r);return t}return e}const see=r(`panel-transport`);function cee(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function lee(){return{onMessage:e=>{let t=(t,n,r)=>(cee(t)&&e(qa(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Ka(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||see.error(`Offscreen → panel transport send failed`,{error:t})})}}}const Ja=r(`kernel-bridge`);function uee(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var Ya=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;activeScoopJid=null;agentEventListeners=new Set;fanOutMessageId=new Map;constructor(e){this._transport=e??null}get transport(){return this._transport||=lee(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new xa;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Xa()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopStatuses.set(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r)=>{Ft.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{Ft.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=Lt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Xa(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=Rt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:It(n),isError:r})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),this.scoopStatuses.delete(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){let t=e.config&&(e.config.modelId!==void 0||e.config.thinkingLevel!==void 0)?{...e.config.modelId===void 0?{}:{modelId:e.config.modelId},...e.config.thinkingLevel===void 0?{}:{thinkingLevel:e.config.thinkingLevel}}:void 0;return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.scoopStatuses.get(e.jid)??`ready`,...t?{config:t}:{}}}buildStateSnapshot(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[],t=e.find(e=>e.isCone);return{type:`state-snapshot`,scoops:e,activeScoopJid:this.getActiveScoopJid()??t?.jid??null,trayRuntimeStatus:this.buildTrayRuntimeStatus()}}emitTrayRuntimeStatus(){let e=this.buildTrayRuntimeStatus(),t={type:`tray-runtime-status`,leader:e.leader,follower:e.follower};this.emit(t)}buildTrayRuntimeStatus(){let e=En(),t=Ba();return{leader:{state:e.state,session:e.session,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}onAgentEvent(e){return this.agentEventListeners.add(e),()=>{this.agentEventListeners.delete(e)}}fanOutAgentEvent(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.fanOutMessageId.get(t);return e||(e=`scoop-${t}-${Xa()}`,this.fanOutMessageId.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.fanOutMessageId.delete(t);break}case`turn_end`:this.fanOutMessageId.delete(t);break}for(let e of r)for(let n of this.agentEventListeners)try{n(t,e)}catch(e){Ja.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=uee(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=Ia({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming,model:e.model,usage:e.usage}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.fanOutMessageId.delete(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{Ja.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error});break}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopStatuses.set(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-CuDaZRuR.js`);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1}))}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];t.length>0&&(this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){Ja.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a})}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Za(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-CuDaZRuR.js`),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Za(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){Ja.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${Xa()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){Ra(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:{let t=e;try{await this.orchestrator.setScoopThinkingLevel(t.scoopJid,t.level,t.effortOverride)}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}break}case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear());break}}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.scoopStatuses.delete(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.fanOutMessageId.delete(t)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.emitEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Vt.markMounted(t);return}try{await Vt.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Vt.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.fanOutAgentEvent(e)}};function Xa(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Za(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
884
|
+
`)}}function Ma(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.\nThis is informational — there is no card action. You MAY fetch it (e.g. \`curl ${r}\`) and act on it if it's relevant to the current task; otherwise ignore it.`}}function Na(e,t){let n=Ta(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Pa(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Na(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Fa(e,t){let n=Na(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill\` with any branch/path scope from the body); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Ia(e){let t=wa[e.type];return e.type===`session-reload`?Ea(e,t):e.type===`upgrade`?Da(e,t):e.type===`cherry`?Oa(e,t):e.type===`preview`?ka(e,t):e.type===`workflow`?Aa(e,t):e.type===`sudo-request`?ja(e,t):e.type===`navigate`?Fa(e,t):e.type===`webhook`?Pa(e,t):e.type===`discovery`?Ma(e,t):Na(e,t)}const La=new Map;function Ra(e){let t=La.get(e.id);t&&(La.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}let za={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Ba(){return{...za}}function Va(){let e=Ba();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.followerTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Ha=new Set;function Ua(e){return Ha.add(e),()=>{Ha.delete(e)}}const Wa=`__slicc_binary__`;function Ga(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Wa]===`b64`&&typeof t.data==`string`}function Ka(e){if(e instanceof Uint8Array)return{[Wa]:`b64`,data:l(e)};if(Array.isArray(e))return e.map(Ka);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Ka(r);return t}return e}function qa(e){if(Ga(e))return u(e.data);if(Array.isArray(e))return e.map(qa);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=qa(r);return t}return e}const see=r(`panel-transport`);function cee(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function lee(){return{onMessage:e=>{let t=(t,n,r)=>(cee(t)&&e(qa(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Ka(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||see.error(`Offscreen → panel transport send failed`,{error:t})})}}}const Ja=r(`kernel-bridge`);function uee(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var Ya=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;activeScoopJid=null;agentEventListeners=new Set;fanOutMessageId=new Map;constructor(e){this._transport=e??null}get transport(){return this._transport||=lee(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new xa;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${Xa()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopStatuses.set(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r)=>{Ft.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{Ft.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=Lt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:Xa(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=Rt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:It(n),isError:r})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),this.scoopStatuses.delete(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){let t=e.config&&(e.config.modelId!==void 0||e.config.thinkingLevel!==void 0)?{...e.config.modelId===void 0?{}:{modelId:e.config.modelId},...e.config.thinkingLevel===void 0?{}:{thinkingLevel:e.config.thinkingLevel}}:void 0;return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.scoopStatuses.get(e.jid)??`ready`,...t?{config:t}:{}}}buildStateSnapshot(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[],t=e.find(e=>e.isCone);return{type:`state-snapshot`,scoops:e,activeScoopJid:this.getActiveScoopJid()??t?.jid??null,trayRuntimeStatus:this.buildTrayRuntimeStatus()}}emitTrayRuntimeStatus(){let e=this.buildTrayRuntimeStatus(),t={type:`tray-runtime-status`,leader:e.leader,follower:e.follower};this.emit(t)}buildTrayRuntimeStatus(){let e=En(),t=Ba();return{leader:{state:e.state,session:e.session,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}onAgentEvent(e){return this.agentEventListeners.add(e),()=>{this.agentEventListeners.delete(e)}}fanOutAgentEvent(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.fanOutMessageId.get(t);return e||(e=`scoop-${t}-${Xa()}`,this.fanOutMessageId.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.fanOutMessageId.delete(t);break}case`turn_end`:this.fanOutMessageId.delete(t);break}for(let e of r)for(let n of this.agentEventListeners)try{n(t,e)}catch(e){Ja.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=uee(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=Ia({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming,model:e.model,usage:e.usage}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.fanOutMessageId.delete(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{Ja.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error});break}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopStatuses.set(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-CuDaZRuR.js`);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1}))}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];t.length>0&&(this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){Ja.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a})}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Za(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-CuDaZRuR.js`),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:Za(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){Ja.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${Xa()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){Ra(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear());break}}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.scoopStatuses.delete(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.fanOutMessageId.delete(t)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=globalThis.__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.emitEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Vt.markMounted(t);return}try{await Vt.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Vt.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.fanOutAgentEvent(e)}};function Xa(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Za(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
885
885
|
`)}const dee=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function fee(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(dee.map(e=>pee(i,e,t,r)))).filter(e=>e!==null)}async function pee(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal});return e.status!==200||!mee(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function mee(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}const Qa=r(`navigation-watcher`);function hee(e,t){return Rn(e,t)}var gee=class{transport;onEvent;sessions=new Map;started=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;probedOrigins=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;t&&this.sessions.delete(t)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId)for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url))};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameNavigated=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n)return;let r=e.frame;r?.id&&(r.parentId||(n.rootFrameId=r.id,typeof r.url==`string`&&(n.url=r.url)))};onResponseReceived=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n||e.type!==`Document`)return;let r=e.frameId;if(!r||r!==n.rootFrameId)return;let i=e.response;if(!i)return;let a=typeof i.url==`string`&&i.url.length>0?i.url:n.url;if(!a)return;let{match:o,links:s}=hee(i.headers,a);if(o){let e={url:a,verb:o.verb,target:o.target,links:s,targetId:n.targetId};o.instruction!=null&&(e.instruction=o.instruction),o.branch!=null&&(e.branch=o.branch),o.path!=null&&(e.path=o.path),n.title!=null&&(e.title=n.title),this.onEvent(e)}this.maybeRunDiscovery(a,s,n.targetId)};constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs}maybeRunDiscovery(e,t,n){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let r;try{r=new URL(e).origin}catch{return}let i=Bn(t);i&&this.onDiscovery({origin:r,kind:i.kind,url:i.url,targetId:n}),this.probeFetch&&!this.probedOrigins.has(r)&&(this.probedOrigins.add(r),this.runWellKnownProbe(r,n))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await fee(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){Qa.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){this.transport.on(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.on(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.on(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.on(`Target.targetCreated`,this.onTargetCreated),this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.transport.on(`Network.responseReceived`,this.onResponseReceived);try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!0})}catch(e){Qa.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived);return}this.started=!0;try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;if(!(e||typeof n!=`string`))try{await this.transport.send(`Target.attachToTarget`,{targetId:n,flatten:!0})}catch(e){Qa.debug(`Failed to attach to preexisting target`,{targetId:n,error:e instanceof Error?e.message:String(e)})}}}catch(e){Qa.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}}async stop(){if(this.started){this.started=!1,this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived),this.sessions.clear();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){Qa.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;if(!(t?.type!==`page`||typeof t.targetId!=`string`)&&!t.attached)try{await this.transport.send(`Target.attachToTarget`,{targetId:t.targetId,flatten:!0})}catch(e){Qa.debug(`Failed to attach to discovered target`,{targetId:t.targetId,error:e instanceof Error?e.message:String(e)})}}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!(!t||!n||n.type!==`page`||typeof n.targetId!=`string`)){this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,title:n.title,url:n.url});try{await this.transport.send(`Page.enable`,{},t),await this.transport.send(`Network.enable`,{},t);let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){Qa.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}}};const _ee=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function vee(e){return _ee.test(e)}function $a(e,t){return`(${e} && ${t})`}function eo(e,t){return`(${e} || ${t})`}function to(e){return`!(${e})`}function no(e){return`Array.isArray(${e})`}function ro(e){return`typeof ${e} === "bigint"`}function io(e){return`typeof ${e} === "boolean"`}function ao(e){return`Number.isInteger(${e})`}function oo(e){return`${e} === null`}function so(e){return`Number.isFinite(${e})`}function co(e){return $a(lo(e),to(no(e)))}function lo(e){return`typeof ${e} === "object" && ${e} !== null`}function uo(e){return`typeof ${e} === "string"`}function fo(e){return`typeof ${e} === "symbol"`}function po(e){return`${e} === undefined`}function mo(e){return`typeof ${e} === "function"`}function ho(e){return`Guard.IsConstructor(${e})`}function go(e,t){return`${e} === ${t}`}function _o(e,t){return`${e} > ${t}`}function vo(e,t){return`${e} < ${t}`}function yo(e,t){return`${e} <= ${t}`}function bo(e,t){return`${e} >= ${t}`}function xo(e,t){return`Guard.IsMinLength(${e}, ${t})`}function So(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Co(e,t,n,r){return V(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => ${r})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${n[0]}, ${n[1]}) => ${r})`}function wo(e){return`Object.entries(${e})`}function To(e){return`Object.getOwnPropertyNames(${e})`}function Eo(e,t){return V(t,`"__proto__"`)||V(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function Do(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function Oo(e){return`[${e.join(`, `)}]`}function ko(e,t){return`((${e.join(`, `)}) => ${t})`}function Ao(e,t){return`${e}(${t.join(`, `)})`}function jo(e,t){return`new ${e}(${t.join(`, `)})`}function W(e,t){return`${e}${vee(t)?`.${t}`:`[${G(t)}]`}`}function G(e){return S(e)?JSON.stringify(e):`${e}`}function Mo(e,t,n){return`(${e} ? ${t} : ${n})`}function No(e){return`{ ${e.join(`; `)}; }`}function Po(e,t){return`const ${e} = ${t}`}function Fo(e,t){return`if(${e}) { ${t} }`}function Io(e){return`return ${e}`}function Lo(e){return V(e.length,0)?`true`:e.reduce((e,t)=>$a(e,t))}function Ro(e){return V(e.length,0)?`false`:e.reduce((e,t)=>eo(e,t))}function zo(e){return`++${e}`}function Bo(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Vo=Ue;function Ho(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let Uo;function Wo(){try{return Ko(`null`)(),!0}catch{return!1}}function Go(){return ye(Uo)&&(Uo=Wo()),Uo&&I().useAcceleration}function Ko(...e){return new globalThis.Function(...e)}function qo(e){switch(e.keyword){case`additionalProperties`:return`must not have additional properties`;case`anyOf`:return`must match a schema in anyOf`;case`boolean`:return`schema is false`;case`const`:return`must be equal to constant`;case`contains`:return`must contain at least 1 valid item`;case`dependencies`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`dependentRequired`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`enum`:return`must be equal to one of the allowed values`;case`exclusiveMaximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`exclusiveMinimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`format`:return`must match format "${e.params.format}"`;case`if`:return`must match "${e.params.failingKeyword}" schema`;case`maxItems`:return`must not have more than ${e.params.limit} items`;case`maxLength`:return`must not have more than ${e.params.limit} characters`;case`maxProperties`:return`must not have more than ${e.params.limit} properties`;case`maximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`minItems`:return`must not have fewer than ${e.params.limit} items`;case`minLength`:return`must not have fewer than ${e.params.limit} characters`;case`minProperties`:return`must not have fewer than ${e.params.limit} properties`;case`minimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`multipleOf`:return`must be multiple of ${e.params.multipleOf}`;case`not`:return`must not be valid`;case`oneOf`:return`must match exactly one schema in oneOf`;case`pattern`:return`must match pattern "${e.params.pattern}"`;case`propertyNames`:return`property names ${e.params.propertyNames.join(`, `)} are invalid`;case`required`:return`must have required properties ${e.params.requiredProperties.join(`, `)}`;case`type`:return typeof e.params.type==`string`?`must be ${e.params.type}`:`must be either ${e.params.type.join(` or `)}`;case`unevaluatedItems`:return`must not have unevaluated items`;case`unevaluatedProperties`:return`must not have unevaluated properties`;case`uniqueItems`:return`must not have duplicate items`;case`~refine`:return e.params.message;default:return`an unknown validation error occurred`}}let Jo=qo;function Yo(){return Jo}const Xo=[/prompt is too long/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i],Zo=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Qo(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!Zo.some(t=>t.test(e.errorMessage))&&Xo.some(t=>t.test(e.errorMessage))||t&&e.stopReason===`stop`&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason===`length`&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}function $o(e){return H(e,`~refine`)&&B(e[`~refine`])&&ot(e[`~refine`],0,e=>mt(e)&&H(e,`check`)&&H(e,`error`)&&ct(e.check)&&ct(e.error))}function es(e){return mt(e)&&!B(e)}function ts(e){return Ze(e)}function ns(e){return es(e)||ts(e)}function rs(e){return H(e,`additionalItems`)&&ns(e.additionalItems)}function is(e){return H(e,`additionalProperties`)&&ns(e.additionalProperties)}function as(e){return H(e,`allOf`)&&B(e.allOf)&&e.allOf.every(e=>ns(e))}function os(e){return H(e,`$anchor`)&&S(e.$anchor)}function ss(e){return H(e,`anyOf`)&&B(e.anyOf)&&e.anyOf.every(e=>ns(e))}function cs(e){return H(e,`const`)}function ls(e){return H(e,`contains`)&&ns(e.contains)}function us(e){return H(e,`default`)}function ds(e){return H(e,`dependencies`)&&mt(e.dependencies)&&Object.values(e.dependencies).every(e=>ns(e)||B(e)&&e.every(e=>S(e)))}function fs(e){return H(e,`dependentRequired`)&&mt(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>B(e)&&e.every(e=>S(e)))}function ps(e){return H(e,`dependentSchemas`)&&mt(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>ns(e))}function ms(e){return H(e,`$dynamicAnchor`)&&S(e.$dynamicAnchor)}function hs(e){return H(e,`$dynamicRef`)&&S(e.$dynamicRef)}function gs(e){return H(e,`else`)&&ns(e.else)}function _s(e){return H(e,`enum`)&&B(e.enum)}function vs(e){return H(e,`exclusiveMaximum`)&&(De(e.exclusiveMaximum)||R(e.exclusiveMaximum))}function ys(e){return H(e,`exclusiveMinimum`)&&(De(e.exclusiveMinimum)||R(e.exclusiveMinimum))}function bs(e){return H(e,`format`)&&S(e.format)}function xs(e){return H(e,`$id`)&&S(e.$id)}function Ss(e){return H(e,`if`)&&ns(e.if)}function Cs(e){return H(e,`items`)&&(ns(e.items)||B(e.items)&&e.items.every(e=>ns(e)))}function ws(e){return Cs(e)&&B(e.items)}function Ts(e){return H(e,`maximum`)&&(De(e.maximum)||R(e.maximum))}function Es(e){return H(e,`maxContains`)&&De(e.maxContains)}function Ds(e){return H(e,`maxItems`)&&De(e.maxItems)}function Os(e){return H(e,`maxLength`)&&De(e.maxLength)}function ks(e){return H(e,`maxProperties`)&&De(e.maxProperties)}function As(e){return H(e,`minimum`)&&(De(e.minimum)||R(e.minimum))}function js(e){return H(e,`minContains`)&&De(e.minContains)}function Ms(e){return H(e,`minItems`)&&De(e.minItems)}function Ns(e){return H(e,`minLength`)&&De(e.minLength)}function Ps(e){return H(e,`minProperties`)&&De(e.minProperties)}function Fs(e){return H(e,`multipleOf`)&&(De(e.multipleOf)||R(e.multipleOf))}function Is(e){return H(e,`not`)&&ns(e.not)}function Ls(e){return H(e,`oneOf`)&&B(e.oneOf)&&e.oneOf.every(e=>ns(e))}function Rs(e){return H(e,`pattern`)&&(S(e.pattern)||e.pattern instanceof RegExp)}function zs(e){return H(e,`patternProperties`)&&mt(e.patternProperties)&&Object.values(e.patternProperties).every(e=>ns(e))}function Bs(e){return H(e,`prefixItems`)&&B(e.prefixItems)&&e.prefixItems.every(e=>ns(e))}function Vs(e){return H(e,`properties`)&&mt(e.properties)&&Object.values(e.properties).every(e=>ns(e))}function Hs(e){return H(e,`propertyNames`)&&(mt(e.propertyNames)||ns(e.propertyNames))}function Us(e){return H(e,`$recursiveAnchor`)&&Ze(e.$recursiveAnchor)}function Ws(e){return Us(e)&&V(e.$recursiveAnchor,!0)}function Gs(e){return H(e,`$recursiveRef`)&&S(e.$recursiveRef)}function Ks(e){return H(e,`$ref`)&&S(e.$ref)}function qs(e){return H(e,`required`)&&B(e.required)&&e.required.every(e=>S(e))}function Js(e){return H(e,`then`)&&ns(e.then)}function Ys(e){return H(e,`type`)&&(S(e.type)||B(e.type)&&e.type.every(e=>S(e)))}function Xs(e){return H(e,`uniqueItems`)&&Ze(e.uniqueItems)}function Zs(e){return H(e,`unevaluatedItems`)&&ns(e.unevaluatedItems)}function Qs(e){return H(e,`unevaluatedProperties`)&&ns(e.unevaluatedProperties)}function $s(e){return Zs(e)||Qs(e)||A(e).some(t=>tc(e[t]))}function ec(e){return e.some(e=>tc(e))}function tc(e){return B(e)?ec(e):mt(e)?$s(e):!1}function nc(e,t){return tc(t)||A(e).some(t=>tc(e[t]))}var rc=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Ao(W(`context`,`Push`),[])}Pop(){return Ao(W(`context`,`Pop`),[])}AddIndex(e){return Ao(W(`context`,`AddIndex`),[e])}AddKey(e){return Ao(W(`context`,`AddKey`),[e])}Merge(e){return Ao(W(`context`,`Merge`),[e])}},ic=class{constructor(){let e=new Set,t=new Set;this.stack=[{indices:e,keys:t}]}Push(){let e=new Set,t=new Set;return this.stack.push({indices:e,keys:t}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let t of e)t.GetIndices().forEach(e=>this.GetIndices().add(e)),t.GetKeys().forEach(e=>this.GetKeys().add(e));return!0}},ac=class extends ic{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},oc=class extends ac{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const sc={identifier:`External`,variables:[]};function cc(e){let t=`External[${sc.variables.length}]`;return sc.variables.push(e),t}function lc(){sc.variables=[]}function uc(){return{...sc}}function dc(e,t,n,r){return Co(cc(n[`~refine`].map(e=>e)),G(0),[`refinement`,`_`],Ao(W(`refinement`,`check`),[r]))}function fc(e,t,n,r){return ot(n[`~refine`],0,(e,t)=>e.check(r))}function pc(e,t,n,r,i,a){return Ye(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let mc=0;function hc(){return`var_${mc++}`}function gc(e){return Cs(e)&&B(e.items)}function _c(e,t,n,r){if(!gc(n))return G(!0);let[i,a]=[hc(),hc()],o=jd(e,t,n.additionalItems,i),s=vo(a,G(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?eo(s,$a(o,c)):eo(s,o);return Ao(W(r,`every`),[ko([i,a],l)])}function vc(e,t,n,r){return!gc(n)||r.every((r,i)=>Re(i,n.items.length)||Nd(e,t,n.additionalItems,r)&&t.AddIndex(i))}function yc(e,t,n,r,i,a){return!gc(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return Re(o,i.items.length)||Fd(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function bc(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function xc(e){let t=[];return zs(e)&&t.push(...A(e.patternProperties)),Vs(e)&&t.push(...A(e.properties).map(bc)),V(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function Sc(e,t,n){return qs(t)&&Vs(t)&&!zs(t)&&V(t.additionalProperties,!1)&&V(A(t.properties).length,t.required.length)}function Cc(e,t,n){return go(W(Ao(W(`Object`,`getOwnPropertyNames`),[n]),`length`),G(t.required.length))}function wc(e,t,n,r){let[i,a]=[hc(),hc()],o=cc(new RegExp(xc(n))),s=jd(e,t,n.additionalProperties,`${r}[${i}]`),c=Ao(W(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?eo(c,$a(s,l)):eo(c,s);return Co(To(r),G(0),[i,a],u)}function Tc(e,t,n,r){return Sc(t,n,r)?Cc(t,n,r):wc(e,t,n,r)}function Ec(e,t,n,r){let i=new RegExp(xc(n));return ot(A(r),0,(a,o)=>i.test(a)||Nd(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function Dc(e,t,n,r,i,a){let o=new RegExp(xc(i)),s=[];return Ye(A(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new oc,p=o.test(c)||Fd(e,f,u,d,i.additionalProperties,a[c])&&t.AddKey(c);return p||s.push(c),p})||t.AddError({keyword:`additionalProperties`,schemaPath:n,instancePath:r,params:{additionalProperties:s}})}function Oc(e,t,n,r,i){let a=Po(`results`,`[]`),o=n.map((e,t)=>Po(`context_${t}`,jo(`CheckContext`,[]))),s=n.map((n,i)=>Po(`condition_${i}`,Ao(ko([`context`],Md(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>Fo(`condition_${t}`,Ao(W(`results`,`push`),[`context_${t}`]))),l=Io($a(i,t.Merge(`results`)));return Ao(ko([],No([a,...o,...s,...c,l])),[])}function kc(e,t,n,r){return Oc(e,t,n.allOf,r,go(W(`results`,`length`),G(n.allOf.length)))}function Ac(e,t,n,r){return Lo(n.allOf.map(n=>Md(e,t,n,r)))}function jc(e,t,n,r){return t.UseUnevaluated()?kc(e,t,n,r):Ac(e,t,n,r)}function Mc(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new ic;return Pd(e,i,n,r)?[...t,i]:t},[]);return V(i.length,n.allOf.length)&&t.Merge(i)}function Nc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new oc,u=Id(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=V(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function Pc(e,t,n,r){return Oc(e,t,n.anyOf,r,_o(W(`results`,`length`),G(0)))}function Fc(e,t,n,r){return Ro(n.anyOf.map(n=>Md(e,t,n,r)))}function Ic(e,t,n,r){return t.UseUnevaluated()?Pc(e,t,n,r):Fc(e,t,n,r)}function Lc(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new ic;return Pd(e,i,n,r)?[...t,i]:t},[]);return Pe(i.length,0)&&t.Merge(i)}function Rc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new oc,l=Id(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=Pe(s.length,0)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c||t.AddError({keyword:`anyOf`,schemaPath:n,instancePath:r,params:{}})}function zc(e,t,n,r){return G(!!n)}function Bc(e,t,n,r){return n}function Vc(e,t,n,r,i,a){return Bc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function Hc(e,t,n,r){return T(n.const)?go(r,G(n.const)):Do(r,cc(n.const))}function Uc(e,t,n,r){return T(n.const)?V(r,n.const):Oe(r,n.const)}function Wc(e,t,n,r,i,a){return Uc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function Gc(e){return!(js(e)&&V(e.minContains,0))}function Kc(e,t,n,r){if(!Gc(n))return G(!0);let i=hc();return $a(to(go(W(r,`length`),G(0))),Ao(W(r,`some`),[ko([i],Md(e,t,n.contains,i))]))}function qc(e,t,n,r){return!Gc(n)||!V(r.length,0)&&r.some(r=>Pd(e,t,n.contains,r))}function Jc(e,t,n,r,i,a){return qc(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Yc(e,t,n,r){return eo(go(W(To(r),`length`),G(0)),Lo(v(n.dependencies).map(([n,i])=>{let a=to(Eo(r,G(n))),o=Md(e,t,i,r);return eo(a,B(i)?(e=>Lo(e.map(e=>Eo(r,G(e)))))(i):o)})))}function Xc(e,t,n,r){let i=V(A(r).length,0),a=ot(v(n.dependencies),0,([n,i])=>!H(r,n)||(B(i)?i.every(e=>H(r,e)):Pd(e,t,i,r)));return i||a}function Zc(e,t,n,r,i,a){let o=V(A(a).length,0),s=Ye(v(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!H(a,i)||(B(o)?o.every(e=>H(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):Id(e,t,s,r,o,a))});return o||s}function Qc(e,t,n,r){return eo(go(W(To(r),`length`),G(0)),Lo(v(n.dependentRequired).map(([e,t])=>eo(to(Eo(r,G(e))),Lo(t.map(e=>Eo(r,G(e))))))))}function $c(e,t,n,r){let i=V(A(r).length,0),a=ot(v(n.dependentRequired),0,([e,t])=>!H(r,e)||t.every(e=>H(r,e)));return i||a}function el(e,t,n,r,i,a){let o=V(A(a).length,0),s=Ye(v(i.dependentRequired),0,([e,i])=>!H(a,e)||Ye(i,0,o=>H(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function tl(e,t,n,r){return eo(go(W(To(r),`length`),G(0)),Lo(v(n.dependentSchemas).map(([n,i])=>eo(to(Eo(r,G(n))),Md(e,t,i,r)))))}function nl(e,t,n,r){let i=V(A(r).length,0),a=ot(v(n.dependentSchemas),0,([n,i])=>!H(r,n)||Pd(e,t,i,r));return i||a}function rl(e,t,n,r,i,a){let o=V(A(a).length,0),s=Ye(v(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!H(a,i)||Id(e,t,s,r,o,a)});return o||s}function il(e,t,n,r){return Kd(e,t,e.DynamicRef(n)??!1,r)}function al(e,t,n,r){let i=e.DynamicRef(n)??!1;return ns(i)&&Pd(e,t,i,r)}function ol(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return ns(o)&&Id(e,t,`#`,r,o,a)}function sl(e,t,n,r){return Ro(n.enum.map(e=>T(e)?go(r,G(e)):Do(r,cc(e))))}function cl(e,t,n,r){return n.enum.some(e=>T(e)?V(r,e):Oe(r,e))}function ll(e,t,n,r,i,a){return cl(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function ul(e,t,n,r){return vo(r,G(n.exclusiveMaximum))}function dl(e,t,n,r){return Re(r,n.exclusiveMaximum)}function fl(e,t,n,r,i,a){return dl(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function pl(e,t,n,r){return _o(r,G(n.exclusiveMinimum))}function ml(e,t,n,r){return Pe(r,n.exclusiveMinimum)}function hl(e,t,n,r,i,a){return ml(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const gl=[0,31,28,31,30,31,30,31,31,30,31,30,31],_l=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function vl(e){return e%4==0&&(e%100!=0||e%400==0)}function yl(e){let t=_l.exec(e);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r===2&&vl(n)?29:gl[r])}const bl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function xl(e,t=!0){let n=bl.exec(e);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4]===`-`?-1:1,s=+(n[5]||0),c=+(n[6]||0);if(s>23||c>59||t&&!n[4]&&e.toLowerCase().indexOf(`z`)===-1)return!1;if(r<=23&&i<=59&&a<60)return!0;let l=i-c*o,u=r-s*o-+(l<0);return(u===23||u===-1)&&(l===59||l===-1)&&a<61}function Sl(e,t=!0){let n=e.split(/T/i);return n.length===2&&yl(n[0])&&xl(n[1],t)}const Cl=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function wl(e){return Cl.test(e)}const Tl=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function El(e){return Tl.test(e)}function Dl(e,t,n){e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let r=0;for(;e>455;)e=Math.floor(e/35),r+=36;return r+Math.floor(36*e/(e+38))}function Ol(e){let t=[],n=128,r=0,i=72,a=e.lastIndexOf(`-`);if(a>0)for(let n=0;n<a;n++){let r=e.charCodeAt(n);if(r>=128)throw Error(`Invalid punycode: non-basic before delimiter`);t.push(r)}let o=a<0?0:a+1;for(;o<e.length;){let a=r,s=1,c=36;for(;;){if(o>=e.length)throw Error(`Invalid punycode: unexpected end of input`);let t=e.charCodeAt(o++),n;if(t>=97&&t<=122)n=t-97;else if(t>=48&&t<=57)n=t-48+26;else if(t>=65&&t<=90)de();else throw Error(`Invalid punycode: bad digit character`);r+=n*s;let a=c<=i?1:c>=i+26?26:c-i;if(n<a)break;s*=36-a,c+=36}let l=t.length+1;i=Dl(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function kl(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function Al(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function jl(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function Ml(e){return kl(e)||Al(e)||jl(e)}const Nl=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),Pl=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function Fl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function Il(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function Ll(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function Rl(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function zl(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function Bl(e){return e>=1632&&e<=1641}function Vl(e){return e>=1776&&e<=1785}function Hl(e){return Pl.has(e)}function Ul(e){if(e.length===0)return de();let t=[...e].map(e=>e.codePointAt(0)),n=t.length;if(t[0]===45||t[n-1]===45||n>=4&&t[2]===45&&t[3]===45||Ml(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(Nl.has(n))return!1;(Ll(n)||Rl(n)||zl(n))&&(r=!0),Bl(n)&&(i=!0),Vl(n)&&(a=!0);let o=t[e-1],s=t[e+1];switch(n){case 183:if(o!==108||s!==108)return!1;break;case 885:if(s===void 0||!Fl(s))return!1;break;case 1523:case 1524:if(o===void 0||!Il(o))return!1;break;case 8204:if(o===void 0||o<128&&!Hl(o))return!1;break;case 8205:if(o===void 0||!Hl(o))return!1;break;case 12539:break}}return!(e.includes(`・`)&&!r||i&&a)}function Wl(e){if(e.charCodeAt(0)===45||e.charCodeAt(e.length-1)===45||e.length>=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!(n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45))return!1}return!0}function Gl(e){return e.toLowerCase().startsWith(`xn--`)}function Kl(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=Ol(t);return n?Ul(n):!1}catch{return!1}}function ql(e){return e.length===0||e.length>63?!1:Gl(e)?Kl(e):Ul(e)}function Jl(e){return e.length===0||e.length>63?!1:Gl(e)?Kl(e):Wl(e)}function Yl(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!Jl(t))return!1;return!0}const Xl=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function Zl(e){return Xl.test(e)}function Ql(e){if(e.length===0||e.includes(` `))return!1;let t=e.normalize(`NFC`).replace(/[\u002E\u3002\uFF0E\uFF61]/g,`.`);if(t.length>253)return!1;for(let e of t.split(`.`))if(!ql(e))return!1;return!0}function $l(e,t,n){let r=0,i=0,a=0,o=0;for(let s=t;s<n;s++){let t=e.charCodeAt(s);if(t===46){if(a===0||i>255||o===48&&a>1)return!1;r++,i=0,a=0,o=0}else if(t>=48&&t<=57)a===0&&(o=t),i=i*10+(t-48),a++;else return!1}return r===3&&a>0&&i<=255&&!(o===48&&a>1)}function eu(e){return $l(e,0,e.length)}function tu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function nu(e){let t=e.length;if(t===0)return!1;let n=0,r=!1,i=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;r=!0,i=2}for(;i<t;){let a=0,o=i;for(;i<t&&tu(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!$l(e,o,t))return!1;n+=2,i=t;break}if(a>4)return!1;if(n++,i===t)break;if(s!==58)return!1;if(i++,e.charCodeAt(i)===58){if(r||e.charCodeAt(i+1)===58)return!1;if(r=!0,i++,i===t)break}}return r?n<=7:n===8}function ru(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function iu(e){if(e.includes(` `)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e===``)return!0;let t=e.indexOf(`:`);return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?ru(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:ru(e)}function au(e){try{return new URL(e),!0}catch{return!1}}const ou=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function su(e){return ou.test(e)}const cu=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function lu(e){return cu.test(e)}function uu(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const du=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function fu(e){return du.test(e)}const pu=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function mu(e){return pu.test(e)}const hu=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function gu(e){return hu.test(e)}function _u(e){return e>=97&&e<=122||e>=65&&e<=90}function vu(e){return _u(e)||e>=48&&e<=57}function yu(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function bu(e){return vu(e)||e===43||e===45||e===46}function xu(e){return vu(e)||e===45||e===46||e===95||e===126}function Su(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function Cu(e){return xu(e)||Su(e)||e===58||e===64}function wu(e){let t=e.length;if(t===0||!_u(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!bu(t))return!1;n++}if(e.charCodeAt(n)!==58)return!1;if(n++,e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47){n+=2;let r=n,i=-1;for(let r=n;r<t;r++){let t=e.charCodeAt(r);if(t===64){i=r;break}if(t===47||t===63||t===35)break}if(i!==-1){for(let t=r;t<i;t++){let n=e.charCodeAt(t);if(n===91||n===93)return!1;if(n===37){if(t+2>=i||!yu(e.charCodeAt(t+1))||!yu(e.charCodeAt(t+2)))return!1;t+=2}else if(!xu(n)&&!Su(n)&&n!==58)return!1}n=i+1}if(e.charCodeAt(n)===91){for(n++;n<t&&e.charCodeAt(n)!==93;)n++;if(e.charCodeAt(n)!==93)return!1;n++}else for(;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35||t===58)break;if(t<128&&!xu(t)&&!Su(t))return!1;n++}if(e.charCodeAt(n)===58)for(n++;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35)break;if(t<48||t>57)return!1;n++}}for(;n<t;){let r=e.charCodeAt(n);if(r===37){if(n+2>=t||!yu(e.charCodeAt(n+1))||!yu(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(Cu(r)||r===47||r===63||r===35))return!1;n++}return!0}const Tu=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function Eu(e){return Tu.test(e)}const Du=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Ou(e){return Du.test(e)}const ku=new Map;function Au(){ku.clear()}function ju(){return[...ku.entries()]}function Mu(e,t){ku.set(e,t)}function Nu(e){return ku.has(e)}function Pu(e){return ku.get(e)}function Fu(e,t){return ku.get(e)?.(t)??!0}function Iu(){Au(),ku.set(`date-time`,Sl),ku.set(`date`,yl),ku.set(`duration`,wl),ku.set(`email`,El),ku.set(`hostname`,Yl),ku.set(`idn-email`,Zl),ku.set(`idn-hostname`,Ql),ku.set(`ipv4`,eu),ku.set(`ipv6`,nu),ku.set(`iri-reference`,iu),ku.set(`iri`,au),ku.set(`json-pointer-uri-fragment`,su),ku.set(`json-pointer`,lu),ku.set(`regex`,uu),ku.set(`relative-json-pointer`,fu),ku.set(`time`,xl),ku.set(`uri-reference`,mu),ku.set(`uri-template`,gu),ku.set(`uri`,wu),ku.set(`url`,Eu),ku.set(`uuid`,Ou)}Iu();var yee=t({Clear:()=>Au,Entries:()=>ju,Get:()=>Pu,Has:()=>Nu,IsDate:()=>yl,IsDateTime:()=>Sl,IsDuration:()=>wl,IsEmail:()=>El,IsHostname:()=>Yl,IsIPv4:()=>eu,IsIPv6:()=>nu,IsIdnEmail:()=>Zl,IsIdnHostname:()=>Ql,IsIri:()=>au,IsIriReference:()=>iu,IsJsonPointer:()=>lu,IsJsonPointerUriFragment:()=>su,IsRegex:()=>uu,IsRelativeJsonPointer:()=>fu,IsTime:()=>xl,IsUri:()=>wu,IsUriReference:()=>mu,IsUriTemplate:()=>gu,IsUrl:()=>Eu,IsUuid:()=>Ou,Reset:()=>Iu,Set:()=>Mu,Test:()=>Fu});function bee(e,t,n,r){return Ao(W(`Format`,`Test`),[G(n.format),r])}function Lu(e,t,n,r){return Fu(n.format,r)}function xee(e,t,n,r,i,a){return Lu(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function See(e,t,n,r){let i=!Js(n)||n.then,a=!gs(n)||n.else;return Mo(Md(e,t,n.if,r),Md(e,t,i,r),Md(e,t,a,r))}function Cee(e,t,n,r){let i=!Js(n)||n.then,a=!gs(n)||n.else;return Pd(e,t,n.if,r)?Pd(e,t,i,r):Pd(e,t,a,r)}function wee(e,t,n,r,i,a){let o=!Js(i)||i.then,s=!gs(i)||i.else,c=new oc,l=Id(e,c,`${n}/if`,r,i.if,a)?Id(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):Id(e,t,`${n}/else`,r,s,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`else`}});return l&&t.Merge([c]),l}function Tee(e,t,n,r){return Lo(n.items.map((n,i)=>{let a=yo(W(r,`length`),G(i)),o=jd(e,t,n,`${r}[${i}]`),s=t.AddIndex(G(i));return eo(a,t.UseUnevaluated()?$a(o,s):o)}))}function Eee(e,t,n,r){return ot(n.items,0,(n,i)=>qe(r.length,i)||Nd(e,t,n,r[i])&&t.AddIndex(i))}function Dee(e,t,n,r,i,a){return Ye(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return qe(a.length,o)||Fd(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Oee(e,t,n,r){let i=Bs(n)?n.prefixItems.length:0,a=jd(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?$a(a,o):a;return Co(r,G(i),[`element`,`index`],s)}function kee(e,t,n,r){return ot(r,Bs(n)?n.prefixItems.length:0,(r,i)=>Nd(e,t,n.items,r)&&t.AddIndex(i))}function Aee(e,t,n,r,i,a){return Ye(a,Bs(i)?i.prefixItems.length:0,(a,o)=>Fd(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function jee(e,t,n,r){return ws(n)?Tee(e,t,n,r):Oee(e,t,n,r)}function Mee(e,t,n,r){return ws(n)?Eee(e,t,n,r):kee(e,t,n,r)}function Nee(e,t,n,r,i,a){return ws(i)?Dee(e,t,n,r,i,a):Aee(e,t,n,r,i,a)}function Ru(e){return ls(e)}function Pee(e,t,n,r){if(!Ru(n))return G(!0);let[i,a]=[hc(),hc()];return yo(Ao(W(r,`reduce`),[ko([i,a],Mo(Md(e,t,n.contains,a),zo(i),i)),G(0)]),G(n.maxContains))}function zu(e,t,n,r){return!Ru(n)||qe(r.reduce((r,i)=>Pd(e,t,n.contains,i)?++r:r,0),n.maxContains)}function Fee(e,t,n,r,i,a){let o=js(i)?i.minContains:1;return zu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function Iee(e,t,n,r){return yo(r,G(n.maximum))}function Bu(e,t,n,r){return qe(r,n.maximum)}function Lee(e,t,n,r,i,a){return Bu(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function Ree(e,t,n,r){return yo(W(r,`length`),G(n.maxItems))}function Vu(e,t,n,r){return qe(r.length,n.maxItems)}function zee(e,t,n,r,i,a){return Vu(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function Bee(e,t,n,r){return So(r,G(n.maxLength))}function Hu(e,t,n,r){return Ie(r,n.maxLength)}function Vee(e,t,n,r,i,a){return Hu(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function Hee(e,t,n,r){return yo(W(To(r),`length`),G(n.maxProperties))}function Uu(e,t,n,r){return qe(A(r).length,n.maxProperties)}function Uee(e,t,n,r,i,a){return Uu(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function Wu(e){return ls(e)}function Wee(e,t,n,r){if(!Wu(n))return G(!0);let[i,a]=[hc(),hc()];return bo(Ao(W(r,`reduce`),[ko([i,a],Mo(Md(e,t,n.contains,a),zo(i),i)),G(0)]),G(n.minContains))}function Gu(e,t,n,r){return!Wu(n)||Ae(r.reduce((r,i)=>Pd(e,t,n.contains,i)?++r:r,0),n.minContains)}function Gee(e,t,n,r,i,a){return Gu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function Kee(e,t,n,r){return bo(r,G(n.minimum))}function Ku(e,t,n,r){return Ae(r,n.minimum)}function qee(e,t,n,r,i,a){return Ku(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function Jee(e,t,n,r){return bo(W(r,`length`),G(n.minItems))}function qu(e,t,n,r){return Ae(r.length,n.minItems)}function Yee(e,t,n,r,i,a){return qu(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function Xee(e,t,n,r){return xo(r,G(n.minLength))}function Ju(e,t,n,r){return L(r,n.minLength)}function Zee(e,t,n,r,i,a){return Ju(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function Qee(e,t,n,r){return bo(W(To(r),`length`),G(n.minProperties))}function Yu(e,t,n,r){return Ae(A(r).length,n.minProperties)}function $ee(e,t,n,r,i,a){return Yu(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function ete(e,t,n,r){return Bo(r,G(n.multipleOf))}function Xu(e,t,n,r){return ut(r,n.multipleOf)}function tte(e,t,n,r,i,a){return Xu(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function nte(e,t,n,r){return Oc(e,t,[n.not],r,to(go(W(`results`,`length`),G(1))))}function rte(e,t,n,r){return to(Md(e,t,n.not,r))}function ite(e,t,n,r){return t.UseUnevaluated()?nte(e,t,n,r):rte(e,t,n,r)}function Zu(e,t,n,r){let i=new ic;return!Pd(e,i,n.not,r)&&t.Merge([i])}function ate(e,t,n,r,i,a){return Zu(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function ote(e,t,n,r){return Oc(e,t,n.oneOf,r,go(W(`results`,`length`),G(1)))}function ste(e,t,n,r){return go(Ao(W(Oo(n.oneOf.map(n=>Md(e,t,n,r))),`reduce`),[ko([`count`,`result`],Mo(go(`result`,G(!0)),zo(`count`),`count`)),G(0)]),G(1))}function cte(e,t,n,r){return t.UseUnevaluated()?ote(e,t,n,r):ste(e,t,n,r)}function lte(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new ic;return Pd(e,i,n,r)?[...t,i]:t},[]);return V(i.length,1)&&t.Merge(i)}function ute(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new oc,u=Id(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=V(c.length,1)&&t.Merge(c);return!l&&V(s.length,0)&&o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),l||t.AddError({keyword:`oneOf`,schemaPath:n,instancePath:r,params:{passingSchemas:s}})}function dte(e,t,n,r){return Ao(W(cc(S(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function Qu(e,t,n,r){return(S(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function fte(e,t,n,r,i,a){return Qu(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function pte(e,t,n,r){return Lo(v(n.patternProperties).map(([n,i])=>{let[a,o]=[hc(),hc()],s=to(Ao(W(cc(new RegExp(n,`u`)),`test`),[a])),c=jd(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?eo(s,$a(c,l)):eo(s,c);return Co(wo(r),G(0),[`[${a}, ${o}]`,`_`],u)}))}function mte(e,t,n,r){return ot(v(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return ot(v(r),0,([n,r])=>!a.test(n)||Nd(e,t,i,r)&&t.AddKey(n))})}function hte(e,t,n,r,i,a){return Ye(v(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return Ye(v(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||Fd(e,t,s,a,o,i)&&t.AddKey(n)})})}function gte(e,t,n,r){return Lo(n.prefixItems.map((n,i)=>{let a=yo(W(r,`length`),G(i)),o=jd(e,t,n,`${r}[${i}]`),s=t.AddIndex(G(i));return eo(a,t.UseUnevaluated()?$a(o,s):o)}))}function _te(e,t,n,r){return V(r.length,0)||ot(n.prefixItems,0,(n,i)=>qe(r.length,i)||Nd(e,t,n,r[i])&&t.AddIndex(i))}function vte(e,t,n,r,i,a){return V(a.length,0)||Ye(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return qe(a.length,o)||Fd(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function $u(e,t){return e.includes(t)||I().exactOptionalPropertyTypes}function yte(e,t){return po(W(e,t))}function ed(e,t){return ye(e[t])}function bte(e,t,n,r){let i=qs(n)?n.required:[];return Lo(v(n.properties).map(([n,a])=>{let o=to(Eo(r,G(n))),s=jd(e,t,a,W(r,n)),c=t.AddKey(G(n)),l=t.UseUnevaluated()?$a(s,c):s,u=i.includes(n)?l:eo(o,l);return $u(i,n)?u:eo(yte(r,n),u)}))}function xte(e,t,n,r){let i=qs(n)?n.required:[];return ot(v(n.properties),0,([n,a])=>{let o=!H(r,n)||Nd(e,t,a,r[n])&&t.AddKey(n);return $u(i,n)?o:ed(r,n)||o})}function Ste(e,t,n,r,i,a){let o=qs(i)?i.required:[];return Ye(v(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!H(a,i)||Fd(e,t,c,l,s,a[i])&&t.AddKey(i);return $u(o,i)?u():ed(a,i)||u()})}function Cte(e,t,n,r){let[i,a]=[hc(),hc()];return Co(To(r),G(0),[i,a],Md(e,t,n.propertyNames,i))}function wte(e,t,n,r){return ot(A(r),0,(r,i)=>Pd(e,t,n.propertyNames,r))}function Tte(e,t,n,r,i,a){let o=[];return Ye(A(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=Id(e,new oc,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Ete(e,t,n,r){return Kd(e,t,e.RecursiveRef(n)??!1,r)}function Dte(e,t,n,r){let i=e.RecursiveRef(n)??!1;return ns(i)&&Pd(e,t,i,r)}function Ote(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return ns(o)&&Id(e,t,`#`,r,o,a)}function kte(e,t,n,r){let i=ko([`context`,`value`],Kd(e,t,n,`value`));return Ao(ko([`context`,`value`],No([Po(`nextContext`,jo(`CheckContext`,[])),Po(`result`,Ao(i,[`nextContext`,`value`])),Fo(`result`,t.Merge(`[nextContext]`)),Io(`result`)])),[`context`,r])}function Ate(e,t,n,r){return Kd(e,t,n,r)}function jte(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?kte(e,t,i,r):Ate(e,t,i,r)}function Mte(e,t,n,r){let i=e.Ref(n)??!1,a=new ic,o=ns(i)&&Pd(e,a,i,r);return o&&t.Merge([a]),o}function td(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new oc,c=ns(o)&&Id(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function nd(e,t,n,r){return Lo(n.required.map(e=>Eo(r,G(e))))}function rd(e,t,n,r){return ot(n.required,0,e=>H(r,e))}function id(e,t,n,r,i,a){let o=[];return Ye(i.required,0,e=>{let t=H(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function ad(e,t,n,r){return V(n,`object`)?co(r):V(n,`array`)?no(r):V(n,`boolean`)?io(r):V(n,`integer`)?ao(r):V(n,`number`)?so(r):V(n,`null`)?oo(r):V(n,`string`)?uo(r):V(n,`bigint`)?ro(r):V(n,`constructor`)?ho(r):V(n,`function`)?mo(r):V(n,`symbol`)?fo(r):V(n,`undefined`)||V(n,`void`)?po(r):G(!0)}function od(e,t,n,r,i){return V(n,`object`)?_e(i):V(n,`array`)?B(i):V(n,`boolean`)?Ze(i):V(n,`integer`)?$e(i):V(n,`number`)?De(i):V(n,`null`)?gt(i):V(n,`string`)?S(i):V(n,`bigint`)?R(i):V(n,`constructor`)?it(i):V(n,`function`)?ct(i):V(n,`symbol`)?pt(i):V(n,`undefined`)?ye(i):!V(n,`void`)||ye(i)}function sd(e,t,n,r){return Ro(n.map(n=>ad(e,t,n,r)))}function cd(e,t,n,r,i){return n.some(n=>od(e,t,n,r,i))}function ld(e,t,n,r){return B(n.type)?sd(e,t,n.type,r):ad(e,t,n.type,r)}function ud(e,t,n,r){return B(n.type)?cd(e,t,n.type,n,r):od(e,t,n.type,n,r)}function dd(e,t,n,r,i,a){return(B(i.type)?cd(e,t,i.type,i,a):od(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function fd(e,t,n,r){let[i,a]=[hc(),hc()],o=Ao(W(`context`,`GetIndices`),[]),s=Ao(W(`indices`,`has`),[i]),c=Md(e,t,n.unevaluatedItems,a),l=Ao(W(`context`,`AddIndex`),[i]),u=Co(r,G(0),[a,i],$a(eo(s,c),l));return Ao(ko([`context`],No([Po(`indices`,o),Io(u)])),[`context`])}function pd(e,t,n,r){let i=t.GetIndices();return ot(r,0,(r,a)=>(i.has(a)||Pd(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function md(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return Ye(a,0,(a,c)=>{let l=new oc,u=(o.has(c)||Id(e,l,n,r,i.unevaluatedItems,a))&&t.AddIndex(c);return u||s.push(c),u})||t.AddError({keyword:`unevaluatedItems`,schemaPath:n,instancePath:r,params:{unevaluatedItems:s}})}function hd(e,t,n,r){let[i,a]=[hc(),hc()],o=Ao(W(`context`,`GetKeys`),[]),s=Ao(W(`keys`,`has`),[i]),c=Ao(W(`context`,`AddKey`),[i]),l=Md(e,t,n.unevaluatedProperties,a),u=Co(wo(r),G(0),[`[${i}, ${a}]`,`_`],eo(s,$a(l,c)));return Ao(ko([`context`],No([Po(`keys`,o),Io(u)])),[`context`])}function gd(e,t,n,r){let i=t.GetKeys();return ot(v(r),0,([r,a])=>i.has(r)||Pd(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function _d(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return Ye(v(a),0,([a,c])=>{let l=new oc,u=o.has(a)||Id(e,l,n,r,i.unevaluatedProperties,c)&&t.AddKey(a);return u||s.push(a),u})||t.AddError({keyword:`unevaluatedProperties`,schemaPath:n,instancePath:r,params:{unevaluatedProperties:s}})}function vd(e){return!V(e.uniqueItems,!1)}function yd(e,t,n,r){return vd(n)?go(W(jo(`Set`,[Ao(W(r,`map`),[W(`Hashing`,`Hash`)])]),`size`),W(r,`length`)):G(!0)}function bd(e,t,n,r){if(!vd(n))return!0;let i=new Set(r.map(He)).size,a=r.length;return V(i,a)}function xd(e,t,n,r,i,a){if(!vd(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=He(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return V(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function Sd(e,t){return Ys(e)&&(B(e.type)&&Pe(e.type.length,0)&&ot(e.type,0,e=>V(e,t))||V(e.type,t))}function Cd(e){return Sd(e,`object`)}function wd(e){return es(e)&&(is(e)||ds(e)||fs(e)||ps(e)||Vs(e)||zs(e)||Hs(e)||Ps(e)||ks(e)||qs(e)||Qs(e))}function Td(e){return Sd(e,`array`)}function Ed(e){return es(e)&&(rs(e)||Cs(e)||ls(e)||Es(e)||Ds(e)||js(e)||Ms(e)||Bs(e)||Zs(e)||Xs(e))}function Dd(e){return Sd(e,`string`)}function Od(e){return es(e)&&(Ns(e)||Os(e)||bs(e)||Rs(e))}function kd(e){return Sd(e,`number`)||Sd(e,`bigint`)}function Ad(e){return es(e)&&(As(e)||Ts(e)||vs(e)||ys(e)||Fs(e))}function jd(e,t,n,r){return t.UseUnevaluated()?$a($a(t.Push(),Md(e,t,n,r)),t.Pop()):Md(e,t,n,r)}function Md(e,t,n,r){e.Push(n);let i=[];if(ts(n))return zc(e,t,n,r);if(Ys(n)&&i.push(ld(e,t,n,r)),wd(n)){let a=[];qs(n)&&a.push(nd(e,t,n,r)),is(n)&&a.push(Tc(e,t,n,r)),ds(n)&&a.push(Yc(e,t,n,r)),fs(n)&&a.push(Qc(e,t,n,r)),ps(n)&&a.push(tl(e,t,n,r)),zs(n)&&a.push(pte(e,t,n,r)),Vs(n)&&a.push(bte(e,t,n,r)),Hs(n)&&a.push(Cte(e,t,n,r)),Ps(n)&&a.push(Qee(e,t,n,r)),ks(n)&&a.push(Hee(e,t,n,r));let o=Lo(a),s=eo(to(co(r)),o);i.push(Cd(n)?o:s)}if(Ed(n)){let a=[];rs(n)&&a.push(_c(e,t,n,r)),ls(n)&&a.push(Kc(e,t,n,r)),Cs(n)&&a.push(jee(e,t,n,r)),Es(n)&&a.push(Pee(e,t,n,r)),Ds(n)&&a.push(Ree(e,t,n,r)),js(n)&&a.push(Wee(e,t,n,r)),Ms(n)&&a.push(Jee(e,t,n,r)),Bs(n)&&a.push(gte(e,t,n,r)),Xs(n)&&a.push(yd(e,t,n,r));let o=Lo(a),s=eo(to(no(r)),o);i.push(Td(n)?o:s)}if(Od(n)){let a=[];Os(n)&&a.push(Bee(e,t,n,r)),Ns(n)&&a.push(Xee(e,t,n,r)),bs(n)&&a.push(bee(e,t,n,r)),Rs(n)&&a.push(dte(e,t,n,r));let o=Lo(a),s=eo(to(uo(r)),o);i.push(Dd(n)?o:s)}if(Ad(n)){let a=[];vs(n)&&a.push(ul(e,t,n,r)),ys(n)&&a.push(pl(e,t,n,r)),Ts(n)&&a.push(Iee(e,t,n,r)),As(n)&&a.push(Kee(e,t,n,r)),Fs(n)&&a.push(ete(e,t,n,r));let o=Lo(a),s=eo(to(eo(so(r),ro(r))),o);i.push(kd(n)?o:s)}Ks(n)&&i.push(jte(e,t,n,r)),Gs(n)&&i.push(Ete(e,t,n,r)),hs(n)&&i.push(il(e,t,n,r)),cs(n)&&i.push(Hc(e,t,n,r)),_s(n)&&i.push(sl(e,t,n,r)),Ss(n)&&i.push(See(e,t,n,r)),Is(n)&&i.push(ite(e,t,n,r)),as(n)&&i.push(jc(e,t,n,r)),ss(n)&&i.push(Ic(e,t,n,r)),Ls(n)&&i.push(cte(e,t,n,r)),Zs(n)&&i.push(eo(to(no(r)),fd(e,t,n,r))),Qs(n)&&i.push(eo(to(lo(r)),hd(e,t,n,r))),$o(n)&&i.push(dc(e,t,n,r));let a=Lo(i);return e.Pop(n),a}function Nd(e,t,n,r){return t.Push()&&Pd(e,t,n,r)&&t.Pop()}function Pd(e,t,n,r){e.Push(n);let i=ts(n)?Bc(e,t,n,r):(!Ys(n)||ud(e,t,n,r))&&(!(mt(r)&&!B(r))||(!qs(n)||rd(e,t,n,r))&&(!is(n)||Ec(e,t,n,r))&&(!ds(n)||Xc(e,t,n,r))&&(!fs(n)||$c(e,t,n,r))&&(!ps(n)||nl(e,t,n,r))&&(!zs(n)||mte(e,t,n,r))&&(!Vs(n)||xte(e,t,n,r))&&(!Hs(n)||wte(e,t,n,r))&&(!Ps(n)||Yu(e,t,n,r))&&(!ks(n)||Uu(e,t,n,r)))&&(!B(r)||(!rs(n)||vc(e,t,n,r))&&(!ls(n)||qc(e,t,n,r))&&(!Cs(n)||Mee(e,t,n,r))&&(!Es(n)||zu(e,t,n,r))&&(!Ds(n)||Vu(e,t,n,r))&&(!js(n)||Gu(e,t,n,r))&&(!Ms(n)||qu(e,t,n,r))&&(!Bs(n)||_te(e,t,n,r))&&(!Xs(n)||bd(e,t,n,r)))&&(!S(r)||(!Os(n)||Hu(e,t,n,r))&&(!Ns(n)||Ju(e,t,n,r))&&(!bs(n)||Lu(e,t,n,r))&&(!Rs(n)||Qu(e,t,n,r)))&&(!(De(r)||R(r))||(!vs(n)||dl(e,t,n,r))&&(!ys(n)||ml(e,t,n,r))&&(!Ts(n)||Bu(e,t,n,r))&&(!As(n)||Ku(e,t,n,r))&&(!Fs(n)||Xu(e,t,n,r)))&&(!Ks(n)||Mte(e,t,n,r))&&(!Gs(n)||Dte(e,t,n,r))&&(!hs(n)||al(e,t,n,r))&&(!cs(n)||Uc(e,t,n,r))&&(!_s(n)||cl(e,t,n,r))&&(!Ss(n)||Cee(e,t,n,r))&&(!Is(n)||Zu(e,t,n,r))&&(!as(n)||Mc(e,t,n,r))&&(!ss(n)||Lc(e,t,n,r))&&(!Ls(n)||lte(e,t,n,r))&&(!Zs(n)||!B(r)||pd(e,t,n,r))&&(!Qs(n)||!mt(r)||gd(e,t,n,r))&&(!$o(n)||fc(e,t,n,r));return e.Pop(n),i}function Fd(e,t,n,r,i,a){return t.Push()&&Id(e,t,n,r,i,a)&&t.Pop()}function Id(e,t,n,r,i,a){e.Push(i);let o=ts(i)?Vc(e,t,n,r,i,a):!!((!Ys(i)||dd(e,t,n,r,i,a))&+(!(mt(a)&&!B(a))||!!((!qs(i)||id(e,t,n,r,i,a))&+(!is(i)||Dc(e,t,n,r,i,a))&(!ds(i)||Zc(e,t,n,r,i,a))&(!fs(i)||el(e,t,n,r,i,a))&(!ps(i)||rl(e,t,n,r,i,a))&(!zs(i)||hte(e,t,n,r,i,a))&(!Vs(i)||Ste(e,t,n,r,i,a))&(!Hs(i)||Tte(e,t,n,r,i,a))&(!Ps(i)||$ee(e,t,n,r,i,a))&(!ks(i)||Uee(e,t,n,r,i,a))))&(!B(a)||!!((!rs(i)||yc(e,t,n,r,i,a))&+(!ls(i)||Jc(e,t,n,r,i,a))&(!Cs(i)||Nee(e,t,n,r,i,a))&(!Es(i)||Fee(e,t,n,r,i,a))&(!Ds(i)||zee(e,t,n,r,i,a))&(!js(i)||Gee(e,t,n,r,i,a))&(!Ms(i)||Yee(e,t,n,r,i,a))&(!Bs(i)||vte(e,t,n,r,i,a))&(!Xs(i)||xd(e,t,n,r,i,a))))&(!S(a)||!!((!Os(i)||Vee(e,t,n,r,i,a))&+(!Ns(i)||Zee(e,t,n,r,i,a))&(!bs(i)||xee(e,t,n,r,i,a))&(!Rs(i)||fte(e,t,n,r,i,a))))&(!(De(a)||R(a))||!!((!vs(i)||fl(e,t,n,r,i,a))&+(!ys(i)||hl(e,t,n,r,i,a))&(!Ts(i)||Lee(e,t,n,r,i,a))&(!As(i)||qee(e,t,n,r,i,a))&(!Fs(i)||tte(e,t,n,r,i,a))))&(!Ks(i)||td(e,t,n,r,i,a))&(!Gs(i)||Ote(e,t,n,r,i,a))&(!hs(i)||ol(e,t,n,r,i,a))&(!cs(i)||Wc(e,t,n,r,i,a))&(!_s(i)||ll(e,t,n,r,i,a))&(!Ss(i)||wee(e,t,n,r,i,a))&(!Is(i)||ate(e,t,n,r,i,a))&(!as(i)||Nc(e,t,n,r,i,a))&(!ss(i)||Rc(e,t,n,r,i,a))&(!Ls(i)||ute(e,t,n,r,i,a))&(!Zs(i)||!B(a)||md(e,t,n,r,i,a))&(!Qs(i)||!mt(a)||_d(e,t,n,r,i,a)))&&(!$o(i)||pc(e,t,n,r,i,a));return e.Pop(i),o}const Ld=[0],Rd=new Map,zd=new Map;function Bd(){return He(Ld[0]++)}function Vd(e,t){Rd.has(e)||Rd.set(e,new Map);let n=Rd.get(e);if(n.has(t))return n.get(t);let r=Bd();return n.set(t,r),r}function Hd(e,t,n,r){return e.UseUnevaluated()?Ao(`check_${n}`,[`context`,r]):Ao(`check_${n}`,[r])}function Ud(e,t,n,r){let i=Md(e,t,n,`value`);return t.UseUnevaluated()?Po(`check_${r}`,ko([`context`,`value`],i)):Po(`check_${r}`,ko([`value`],i))}function Wd(){Ld[0]=0,Rd.clear(),zd.clear()}function Gd(){return[...zd.values()]}function Kd(e,t,n,r){let i=Vd(n,e.BaseURL().href),a=Hd(t,n,i,r);return zd.has(i)?a:(zd.set(i,``),zd.set(i,Ud(e,t,n,i)),a)}function qd(e,t){return mt(t)&&!ee(e)?t[e]:void 0}function Jd(e,t){return e.reduce((e,t)=>qd(t,e),t)}function Yd(e){if(V(e.length,0))return[];let t=e.split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`));return t.length>0&&t[0]===``?t.slice(1):t}function Xd(e,t){return Jd(Yd(t),e)}function Zd(e,t,n){if(e.$id===n.hash)return e;let r=new URL(e.$id,t.href),i=new URL(n.href,t.href);if(V(r.pathname,i.pathname))return n.hash.startsWith(`#`)?ef(e,t,n):e}function Qd(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return V(r.href,i.href)?e:void 0}function $d(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return V(r.href,i.href)?e:void 0}function ef(e,t,n){if(n.href.endsWith(`#`))return e;if(!n.hash.startsWith(`#`))return;let r=decodeURIComponent(n.hash.slice(1));if(r.startsWith(`/`))return Xd(e,r)}function tf(e,t,n){if(xs(e)){let r=Zd(e,t,n);if(!ye(r))return r}if(os(e)){let r=Qd(e,t,n);if(!ye(r))return r}if(ms(e)){let r=$d(e,t,n);if(!ye(r))return r}return ef(e,t,n)}function nf(e,t,n){return e.reduce((e,r)=>{let i=af(r,t,n);return ye(i)?e:i},void 0)}function rf(e,t,n){return A(e).reduce((r,i)=>{let a=af(e[i],t,n);return ye(a)?r:a},void 0)}function af(e,t,n){let r=es(e)&&xs(e)?new URL(e.$id,t.href):t;if(es(e)){let t=tf(e,r,n);if(!ye(t))return t}if(B(e))return nf(e,r,n);if(mt(e))return rf(e,r,n)}function of(e,t){let n=new URL(`http://unknown/`),r=xs(e)?new URL(e.$id,n.href):n;return af(e,r,new URL(t,r.href))}function sf(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?of(t,n.$dynamicRef):of(e,n.$dynamicRef);if(!ye(i))return!es(i)||!ms(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var cf=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},lf,uf,df,ff,pf,mf=class{constructor(e,t){lf.add(this),this.context=e,this.schema=t,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((e,t)=>new URL(t.$id,e),new URL(`http://unknown`))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(e){es(e)&&(xs(e)&&(this.ids.push(e),cf(this,lf,`m`,uf).call(this,e)),os(e)&&this.anchors.push(e),Ws(e)&&this.recursiveAnchors.push(e),ms(e)&&this.dynamicAnchors.push(e))}Pop(e){es(e)&&(xs(e)&&(this.ids.pop(),cf(this,lf,`m`,df).call(this,e)),os(e)&&this.anchors.pop(),Ws(e)&&this.recursiveAnchors.pop(),ms(e)&&this.dynamicAnchors.pop())}Ref(e){return cf(this,lf,`m`,ff).call(this,e)??cf(this,lf,`m`,pf).call(this,e)}RecursiveRef(e){return Ws(this.Base())?of(this.recursiveAnchors[0],e.$recursiveRef):of(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return sf(t,this.Base(),e,this.dynamicAnchors)}};lf=new WeakSet,uf=function e(t,n=!0){if(!es(t))return;let r=t;if(!(!n&&xs(r))){!n&&ms(r)&&this.dynamicAnchors.push(r);for(let t of A(r))cf(this,lf,`m`,e).call(this,r[t],!1)}},df=function e(t,n=!0){if(!es(t))return;let r=t;if(!(!n&&xs(r))){!n&&ms(r)&&this.dynamicAnchors.pop();for(let t of A(r))cf(this,lf,`m`,e).call(this,r[t],!1)}},ff=function(e){return H(this.context,e.$ref)?this.context[e.$ref]:void 0},pf=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?of(this.Base(),e.$ref):of(t,e.$ref)};function hf(e){return`${e.Functions().join(`;
|
|
886
886
|
`)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function gf(e,t){return Ko(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(ic,Ue,yee,ue,e.External().variables)}function _f(e){let t=new mf(e.Context(),e.Schema()),n=new ic;return r=>Pd(t,n,e.Schema(),r)}function vf(e,t){return Go()?gf(e,t):_f(e)}var yf=class{constructor(e,t,n){this.isAccelerated=e,this.code=t,this.check=n}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}},bf=class{constructor(e,t,n,r,i,a){this.context=e,this.schema=t,this.external=n,this.functions=r,this.entry=i,this.useUnevaluated=a}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=hf(this),t=vf(this,e);return new yf(Go(),e,t)}};function xf(...e){let[t,n]=Ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});lc(),Wd();let r=new mf(t,n),i=new rc(nc(t,n)),a=Kd(r,i,n,`value`),o=Gd();return new bf(t,n,uc(),o,a,i.UseUnevaluated())}function Sf(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=I(),a=Yo(),o=[];return[Id(new mf(t,n),new ac(e=>{if(!Ae(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function Cf(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Pd(new mf(t,n),new ic,n,r)}function wf(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Cf(t,n,r)}function Tf(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=Sf(t,n,r);return a}var Ef=class extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"cause",{value:{source:e,errors:n,value:t},writable:!1,configurable:!1,enumerable:!1})}};function Df(e,t,n){return B(n)?n.map(n=>Rf(e,t.items,n)):n}function Of(e,t,n){return Rf({...e,...t.$defs},xe(t.$ref),n)}function kf(e,t){let n=H(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=Ne(st(e,t));return vt(r)?Xe(r,n):r}function Af(e,t,n){return Rf(e,kf(e,t),n)}function jf(e){return H(e,`additionalProperties`)?e.additionalProperties:void 0}function Mf(e,t,n){if(!mt(n)||B(n))return n;let r=jf(t);for(let i of A(n)){if(H(t.properties,i)){n[i]=Rf(e,t.properties[i],n[i]);continue}if(Ze(r)&&V(r,!0)||P(r)&&wf(e,r,n[i])){n[i]=Rf(e,r,n[i]);continue}delete n[i]}return n}function Nf(e,t,n){if(!mt(n))return n;let r=jf(t),[i,a]=[new RegExp(Ge(t)),lt(t)];for(let t of A(n)){if(i.test(t)){n[t]=Rf(e,a,n[t]);continue}if(Ze(r)&&V(r,!0)||P(r)&&wf(e,r,n[t])){n[t]=Rf(e,r,n[t]);continue}delete n[t]}return n}function Pf(e,t,n){return H(e,t.$ref)?Rf(e,e[t.$ref],n):n}function Ff(e,t,n){if(!B(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;i<r;i++)n[i]=Rf(e,t.items[i],n[i]);return Pe(n.length,r)?n.slice(0,r):n}function If(e){return me(e)}function Lf(e,t,n){for(let r of t.anyOf){let t=Rf(e,r,If(n));if(wf(e,r,t))return t}return n}function Rf(e,t,n){return se(t)?Df(e,t,n):le(t)?Of(e,t,n):O(t)?Af(e,t,n):vt(t)?Mf(e,t,n):Qe(t)?Nf(e,t,n):M(t)?Pf(e,t,n):je(t)?Ff(e,t,n):Je(t)?Lf(e,t,n):n}function zf(e,t){for(let n of Vo.Keys(e))Vo.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function Bf(e){let t={};for(let n of Vo.Keys(e))t[n]=Uf(e[n]);return t}function Vf(e){return Hf(_(e))}function Hf(e){return e.map(e=>Uf(e))}function Uf(e){return zf(e,se(e)?F(Uf(e.items),nt(e)):O(e)?fe(Hf(e.allOf)):Je(e)?ze(Vf(e.anyOf)):vt(e)?x(Bf(e.properties)):Qe(e)?at(ke(e),Uf(lt(e))):je(e)?Fe(Hf(e.items)):e)}function Wf(e){return Uf(e)}function Gf(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Rf(t,I().unionPrioritySort?Wf(n):n,r)}function Kf(e){return mt(e)&&H(e,`value`)}function K(e){return{value:e}}function qf(e){return B(e)?K(e):K([e])}function Jf(e){return V(e,!0)?K(BigInt(1)):K(BigInt(0))}const Yf=/^-?(0|[1-9]\d*)n$/,Xf=/^-?(0|[1-9]\d*)\.\d+$/,Zf=/^-?(0|[1-9]\d*)$/;function Qf(e){return Yf.test(e)}function $f(e){return Xf.test(e)}function ep(e){return Zf.test(e)}function tp(e){let t=e.toLowerCase();return Qf(e)?K(BigInt(e.slice(0,e.length-1))):$f(e)?K(BigInt(e.split(`.`)[0])):ep(e)?K(BigInt(e)):V(t,`false`)?K(BigInt(0)):V(t,`true`)?K(BigInt(1)):void 0}function np(e){return R(e)?K(e):Ze(e)?Jf(e):De(e)?K(BigInt(Math.trunc(e))):gt(e)?K(BigInt(0)):S(e)?tp(e):ye(e)?K(BigInt(0)):void 0}function rp(e){return V(e,BigInt(0))?K(!1):V(e,BigInt(1))?K(!0):void 0}function ip(e){return V(e,0)?K(!1):V(e,1)?K(!0):void 0}function ap(e){return V(e.toLowerCase(),`false`)?K(!1):V(e.toLowerCase(),`true`)?K(!0):V(e,`0`)?K(!1):V(e,`1`)?K(!0):void 0}function op(e){return R(e)?rp(e):Ze(e)?K(e):De(e)?ip(e):gt(e)?K(!1):S(e)?ap(e):ye(e)?K(!1):void 0}function sp(e){return V(e,BigInt(0))?K(null):void 0}function cp(e){return V(e,!1)?K(null):void 0}function lp(e){return V(e,0)?K(null):void 0}function up(e){let t=e.toLowerCase();return V(t,`undefined`)||V(t,`null`)||V(e,``)||V(e,`0`)?K(null):void 0}function dp(e){return R(e)?sp(e):Ze(e)?cp(e):De(e)?lp(e):gt(e)?K(null):S(e)?up(e):ye(e)?K(null):void 0}const fp=BigInt(2**53-1),pp=BigInt(-(2**53-1));function mp(e){return e<=fp&&e>=pp?K(Number(e)):void 0}function hp(e){return K(+!!e)}function gp(e){let t=+e;if(De(t))return K(t);let n=e.toLowerCase();if(V(n,`false`))return K(0);if(V(n,`true`))return K(1);let r=np(e);if(Kf(r))return r.value<=fp&&r.value>=pp?K(Number(r.value)):void 0}function _p(e){return R(e)?mp(e):Ze(e)?hp(e):De(e)?K(e):gt(e)?K(0):S(e)?gp(e):ye(e)?K(0):void 0}function vp(e){return R(e)||Ze(e)||De(e)?K(e.toString()):gt(e)?K(`null`):S(e)?K(e):ye(e)?K(``):void 0}function yp(e){return V(e,BigInt(0))?K(void 0):void 0}function bp(e){return V(e,!1)?K(void 0):void 0}function xp(e){return V(e,0)?K(void 0):void 0}function Sp(e){let t=e.toLowerCase();return V(t,`undefined`)||V(t,`null`)||V(e,``)||V(e,`0`)?K(void 0):void 0}function Cp(e){return R(e)?yp(e):Ze(e)?bp(e):De(e)?xp(e):gt(e)?K(void 0):S(e)?Sp(e):ye(e)?K(e):void 0}function wp(e,t,n){return qf(n).value.map(n=>Zp(e,t.items,n))}function Tp(e,t,n){let r=np(n);return Kf(r)?r.value:n}function Ep(e,t,n){let r=op(n);return Kf(r)?r.value:n}function Dp(e,t,n){return Zp({...e,...t.$defs},xe(t.$ref),n)}function Op(e,t,n){return Zp(e,Ne(t),n)}function kp(e,t,n){let r=_p(n);return Kf(r)?Math.trunc(r.value):n}function Ap(e,t,n){return Zp(e,Ne(st(e,t)),n)}function jp(e,t,n){let r=np(n);return Kf(r)&&V(t.const,r.value)?r.value:n}function Mp(e,t,n){let r=op(n);return Kf(r)&&V(t.const,r.value)?r.value:n}function Np(e,t,n){let r=_p(n);return Kf(r)&&V(t.const,r.value)?r.value:n}function Pp(e,t,n){let r=vp(n);return Kf(r)&&V(t.const,r.value)?r.value:n}function Fp(e,t,n){return V(t.const,n)?n:ve(t)?jp(e,t,n):C(t)?Mp(e,t,n):eee(t)?Np(e,t,n):be(t)?Pp(e,t,n):de()}function Ip(e,t,n){let r=dp(n);return Kf(r)?r.value:n}function Lp(e,t,n){let r=_p(n);return Kf(r)?r.value:n}function Rp(e,t,n,r){let i=A(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=Zp(e,n,r[t]));return r}function zp(e,t,n){return N(e)&&ye(n[t])}function Bp(e,t,n){let r=Me(t.properties),i=A(n);for(let[t,a]of r)for(let r of i)!t.test(r)||zp(a,r,n)||(n[r]=Zp(e,a,n[r]));return H(t,`additionalProperties`)&&mt(t.additionalProperties)?Rp(e,r,t.additionalProperties,n):n}function Vp(e,t,n){return _e(n)?Bp(e,t,n):n}function Hp(e,t,n){let r=Me(t.patternProperties),i=A(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=Zp(e,a,n[r]));return H(t,`additionalProperties`)&&mt(t.additionalProperties)?Rp(e,r,t.additionalProperties,n):n}function Up(e,t,n){return _e(n)?Hp(e,t,n):n}function Wp(e,t,n){return H(e,t.$ref)?Zp(e,e[t.$ref],n):n}function Gp(e,t,n){let r=vp(n);return Kf(r)?r.value:n}function Kp(e,t,n){return Zp(e,Ne(t),n)}function qp(e,t,n){if(!B(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=Zp(e,t.items[r],n[r]);return n}function Jp(e,t,n){let r=Cp(n);return Kf(r)?r.value:n}function Yp(e,t,n){if(t.anyOf.some(t=>wf(e,t,n)))return n;let r=t.anyOf.map(t=>Zp(e,t,If(n))).find(n=>wf(e,t,n));return ye(r)?n:r}function Xp(e,t,n){return Kf(Cp(n))?void 0:n}function Zp(e,t,n){return se(t)?wp(e,t,n):We(t)?Tp(e,t,n):j(t)?Ep(e,t,n):le(t)?Dp(e,t,n):ae(t)?Op(e,t,n):E(t)?kp(e,t,n):O(t)?Ap(e,t,n):ht(t)?Fp(e,t,n):z(t)?Ip(e,t,n):_t(t)?Lp(e,t,n):vt(t)?Vp(e,t,n):Qe(t)?Up(e,t,n):M(t)?Wp(e,t,n):Le(t)?Gp(e,t,n):rt(t)?Kp(e,t,n):je(t)?qp(e,t,n):Ee(t)?Jp(e,t,n):Je(t)?Yp(e,t,n):Be(t)?Xp(e,t,n):n}function Qp(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Zp(t,n,r)}function $p(e,t,n){if(!B(n))return n;for(let r=0;r<n.length;r++)n[r]=cm(e,t.items,n[r]);return n}function em(e,t,n){return cm({...e,...t.$defs},xe(t.$ref),n)}function tm(e,t){return ye(t)?ct(e.default)?e.default():If(e.default):t}function nm(e,t,n){return cm(e,Ne(st(e,t)),n)}function rm(e,t,n){if(!mt(n))return n;let r=A(t.properties);for(let i of r){let r=cm(e,t.properties[i],n[i]);ye(r)&&(N(t.properties[i])||!H(t.properties[i],`default`))||(n[i]=r)}if(!is(t)||Ze(t.additionalProperties))return n;for(let i of A(n))r.includes(i)||(n[i]=cm(e,t.additionalProperties,n[i]));return n}function im(e,t,n){if(!mt(n))return n;let[r,i]=[new RegExp(Ge(t)),lt(t)];for(let t of A(n))r.test(t)&&us(i)&&(n[t]=cm(e,i,n[t]));if(!is(t))return n;for(let i of A(n))r.test(i)||(n[i]=cm(e,t.additionalProperties,n[i]));return n}function am(e,t,n){return H(e,t.$ref)?cm(e,e[t.$ref],n):n}function om(e,t,n){if(!B(n))return n;let[r,i]=[t.items,Math.max(t.items.length,n.length)];for(let t=0;t<i;t++)t<r.length&&(n[t]=cm(e,r[t],n[t]));return n}function sm(e,t,n){for(let r of t.anyOf){let t=cm(e,r,If(n));if(wf(e,r,t))return t}return n}function cm(e,t,n){let r=us(t)?tm(t,n):n;return se(t)?$p(e,t,r):le(t)?em(e,t,r):O(t)?nm(e,t,r):vt(t)?rm(e,t,r):Qe(t)?im(e,t,r):M(t)?am(e,t,r):je(t)?om(e,t,r):Je(t)?sm(e,t,r):r}function lm(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return cm(t,n,r)}function um(e){return(...t)=>{let[n,r,i]=Ho(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function dm(e,t,n){return t[`~codec`].decode(n)}function fm(e,t,n){return t[`~codec`].encode(n)}function pm(e,t,n,r){return b(n)?V(e,`Decode`)?dm(t,n,r):fm(t,n,r):r}function mm(e,t,n,r){if(!B(r))return r;for(let i=0;i<r.length;i++)r[i]=Lm(e,t,n.items,r[i]);return pm(e,t,n,r)}function hm(e,t,n,r){let i=pm(e,t,n,r);if(!B(i))return i;for(let r=0;r<i.length;r++)i[r]=Lm(e,t,n.items,i[r]);return i}function gm(e,t,n,r){return V(e,`Decode`)?mm(e,t,n,r):hm(e,t,n,r)}function _m(e,t,n,r){return r=Lm(e,{...t,...n.$defs},xe(n.$ref),r),pm(e,t,n,r)}function vm(e){return e.reduce((e,t)=>({...e,...t}),{})}function ym(e,t){for(let n of t)if(!Oe(e,n))return n;return e}function bm(e,t,n,r){if(V(n.allOf.length,0))return pm(e,t,n,r);let i=n.allOf.map(n=>Lm(e,t,n,Gf(n,If(r))));return pm(e,t,n,i.every(e=>mt(e))?vm(i):ym(r,i))}function xm(e,t,n,r){if(V(n.allOf.length,0))return pm(e,t,n,r);let i=pm(e,t,n,r),a=n.allOf.map(n=>Lm(e,t,n,Gf(n,If(i))));return a.every(e=>mt(e))?vm(a):ym(i,a)}function Sm(e,t,n,r){return V(e,`Decode`)?bm(e,t,n,r):xm(e,t,n,r)}function Cm(e,t,n,r){if(!_e(r))return r;for(let i of A(n.properties))!H(r,i)||zp(n.properties[i],i,r)||(r[i]=Lm(e,t,n.properties[i],r[i]));return pm(e,t,n,r)}function wm(e,t,n,r){let i=pm(e,t,n,r);if(!_e(i))return i;for(let r of A(n.properties))!H(i,r)||zp(n.properties[r],r,i)||(i[r]=Lm(e,t,n.properties[r],i[r]));return i}function Tm(e,t,n,r){return V(e,`Decode`)?Cm(e,t,n,r):wm(e,t,n,r)}function Em(e,t,n,r){if(!_e(r))return r;let i=new RegExp(Ge(n));for(let a of A(r))i.test(a)&&(r[a]=Lm(e,t,lt(n),r[a]));return pm(e,t,n,r)}function Dm(e,t,n,r){let i=pm(e,t,n,r);if(!_e(i))return i;let a=new RegExp(Ge(n));for(let r of A(i))a.test(r)&&(i[r]=Lm(e,t,lt(n),i[r]));return i}function Om(e,t,n,r){return V(e,`Decode`)?Em(e,t,n,r):Dm(e,t,n,r)}function km(e,t,n,r){return H(t,n.$ref)?Lm(e,t,t[n.$ref],r):r}function Am(e,t,n,r){return V(e,`Decode`)?pm(e,t,n,km(e,t,n,r)):km(e,t,n,pm(e,t,n,r))}function jm(e,t,n,r){if(!B(r))return r;for(let i=0;i<Math.min(n.items.length,r.length);i++)r[i]=Lm(e,t,n.items[i],r[i]);return pm(e,t,n,r)}function Mm(e,t,n,r){let i=pm(e,t,n,r);if(!B(i))return r;for(let r=0;r<Math.min(n.items.length,i.length);r++)i[r]=Lm(e,t,n.items[r],i[r]);return i}function Nm(e,t,n,r){return V(e,`Decode`)?jm(e,t,n,r):Mm(e,t,n,r)}function Pm(e,t,n,r){for(let i of n.anyOf)if(wf(t,i,r))return pm(e,t,n,Lm(e,t,i,r));return r}function Fm(e,t,n,r){let i=pm(e,t,n,r);for(let r of n.anyOf){let n=Lm(e,t,r,If(i));if(wf(t,r,n))return n}return i}function Im(e,t,n,r){return V(e,`Decode`)?Pm(e,t,n,r):Fm(e,t,n,r)}function Lm(e,t,n,r){return se(n)?gm(e,t,n,r):le(n)?_m(e,t,n,r):O(n)?Sm(e,t,n,r):vt(n)?Tm(e,t,n,r):Qe(n)?Om(e,t,n,r):M(n)?Am(e,t,n,r):je(n)?Nm(e,t,n,r):Je(n)?Im(e,t,n,r):pm(e,t,n,r)}var Rm=class extends Ef{constructor(e,t){super(`Decode`,e,t)}};function zm(e,t,n){if(!wf(e,t,n))throw new Rm(n,Tf(e,t,n));return n}function Bm(e,t,n){return Lm(`Decode`,e,I().unionPrioritySort?Wf(t):t,n)}const Vm=um([(e,t,n)=>If(n),(e,t,n)=>lm(e,t,n),(e,t,n)=>Qp(e,t,n),(e,t,n)=>Gf(e,t,n),(e,t,n)=>zm(e,t,n),(e,t,n)=>Bm(e,t,n)]);function Hm(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Vm(t,n,r)}var Um=class extends Ef{constructor(e,t){super(`Encode`,e,t)}};function Wm(e,t,n){if(!wf(e,t,n))throw new Um(n,Tf(e,t,n));return n}function Gm(e,t,n){return Lm(`Encode`,e,I().unionPrioritySort?Wf(t):t,n)}const Km=um([(e,t,n)=>If(n),(e,t,n)=>Gm(e,t,n),(e,t,n)=>lm(e,t,n),(e,t,n)=>Qp(e,t,n),(e,t,n)=>Gf(e,t,n),(e,t,n)=>Wm(e,t,n)]);function qm(...e){let[t,n,r]=Ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Km(t,n,r)}function Jm(e,t){return b(t)||nh(e,t.items)}function Ym(e,t){return b(t)||$m({...e,...t.$defs},xe(t.$ref))}function Xm(e,t){return b(t)||t.allOf.some(t=>nh(e,t))}function Zm(e,t){return b(t)||A(t.properties).some(n=>nh(e,t.properties[n]))}function Qm(e,t){return b(t)||nh(e,lt(t))}function $m(e,t){return rh.has(t.$ref)?!1:(rh.add(t.$ref),b(t)||H(e,t.$ref)&&nh(e,e[t.$ref]))}function eh(e,t){return b(t)||t.items.some(t=>nh(e,t))}function th(e,t){return b(t)||t.anyOf.some(t=>nh(e,t))}function nh(e,t){return se(t)?Jm(e,t):le(t)?Ym(e,t):O(t)?Xm(e,t):vt(t)?Zm(e,t):Qe(t)?Qm(e,t):M(t)?$m(e,t):je(t)?eh(e,t):Je(t)?th(e,t):b(t)}const rh=new Set;function ih(...e){let[t,n]=Ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return rh.clear(),nh(t,n)}var ah=class extends Error{constructor(e,t){super(t),this.type=e}};function oh(e,t){return ct(t.default)?t.default(t):mt(t.default)?If(t.default):t.default}function sh(e,t){if(Xs(t)&&!us(t))throw new ah(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=Ms(t)?t.minItems:0;return Array.from({length:n},()=>Oh(e,t.items))}function ch(e,t){return ys(t)?BigInt(t.exclusiveMinimum)+BigInt(1):As(t)?BigInt(t.minimum):BigInt(0)}function lh(e,t){return!1}function uh(e,t){let n=Oh(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function dh(e,t){return Oh({...e,...t.$defs},xe(t.$ref))}function fh(e,t){return Oh(e,Ne(t))}function ph(e,t){let n=Oh(e,t.returnType);return()=>n}function mh(e,t){return ys(t)&&De(t.exclusiveMinimum)?t.exclusiveMinimum+1:As(t)?t.minimum:0}function hh(e,t){return Oh(e,Ne(st(e,t)))}function gh(e,t){return t.const}function _h(e,t){throw new ah(t,`Cannot create TNever types`)}function vh(e,t){return null}function yh(e,t){return ys(t)&&De(t.exclusiveMinimum)?t.exclusiveMinimum+1:As(t)?t.minimum:0}function bh(e,t){return(ye(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:Oh(e,t.properties[r])}),{})}function xh(e,t){if(Ps(t)&&!us(t))throw new ah(t,`Record with the minProperties constraint must have a default annotation`);return{}}function Sh(e,t){return H(e,t.$ref)?Oh(e,e[t.$ref]):(()=>{throw new ah(t,`Unable to deref Ref`)})()}function Ch(e,t){if((Rs(t)||bs(t))&&!us(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=Ns(t)?t.minLength:0;return``.padEnd(n)}function wh(e,t){return Symbol()}function Th(e,t){let n=et(t.pattern);if(Le(n))throw new ah(t,`Unable to create TemplateLiteral due to infinite type expansion`);return Oh(e,n)}function Eh(e,t){return Array.from({length:t.minItems},(n,r)=>Oh(e,t.items[r]))}function Dh(e,t){if(V(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return Oh(e,t.anyOf[0])}function Oh(e,t){return us(t)?oh(e,t):se(t)?sh(e,t):We(t)?ch(e,t):j(t)?lh(e,t):ce(t)?uh(e,t):le(t)?dh(e,t):ae(t)?fh(e,t):k(t)?ph(e,t):E(t)?mh(e,t):O(t)?hh(e,t):ht(t)?gh(e,t):re(t)?_h(e,t):z(t)?vh(e,t):_t(t)?yh(e,t):vt(t)?bh(e,t):Qe(t)?xh(e,t):M(t)?Sh(e,t):Le(t)?Ch(e,t):dt(t)?wh(e,t):rt(t)?Th(e,t):je(t)?Eh(e,t):Ee(t)?void 0:Je(t)?Dh(e,t):(Be(t),void 0)}function kh(...e){let[t,n]=Ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Oh(t,n)}var Ah=class extends Ef{constructor(e,t){super(`Parse`,e,t)}};function jh(e,t,n){if(!wf(e,t,n))throw new Ah(n,Tf(e,t,n));return n}const Mh=um([(e,t,n)=>If(n),(e,t,n)=>lm(e,t,n),(e,t,n)=>Qp(e,t,n),(e,t,n)=>Gf(e,t,n),(e,t,n)=>jh(e,t,n)]);ze([x({type:te(`insert`),path:Te(),value:ge()}),Object({type:te(`update`),path:Te(),value:ge()}),x({type:te(`delete`),path:Te()})]);var Nh=class{constructor(e,t){this.hasCodec=ih(e,t),this.buildResult=xf(e,t),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(I().correctiveParse)return Mh(this.Context(),this.Type(),e);throw new Ah(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:Tf(this.Context(),this.Type(),e)}Clean(e){return Gf(this.Context(),this.Type(),e)}Convert(e){return Qp(this.Context(),this.Type(),e)}Create(){return kh(this.Context(),this.Type())}Default(e){return lm(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Hm(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?qm(this.Context(),this.Type(),e):this.Parse(e)}};function Ph(...e){let[t,n]=Ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new Nh(t,n)}const Fh=new WeakMap,Ih=Symbol.for(`TypeBox.Kind`);function Lh(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function Rh(e,t){switch(t){case`number`:return typeof e==`number`;case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`string`:return typeof e==`string`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!1}}function zh(e){try{return Gh(e)}catch{return}}function Bh(e,t){switch(t){case`number`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return typeof e==`boolean`?+!!e:e;case`integer`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isInteger(t))return t}return typeof e==`boolean`?+!!e:e;case`boolean`:if(e===null)return!1;if(typeof e==`string`){if(e===`true`)return!0;if(e===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return e;case`string`:return e===null?``:typeof e==`number`||typeof e==`boolean`?String(e):e;case`null`:return e===``||e===0||e===!1?null:e;default:return e}}function Vh(e,t){let n=t.properties,r=new Set(n?Object.keys(n):[]);if(n)for(let[t,r]of Object.entries(n))t in e&&(e[t]=Wh(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=Wh(i,t.additionalProperties))}function Hh(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=Wh(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=Wh(e[n],t.items)}function Uh(e,t){for(let n of t){let t=Wh(structuredClone(e),n);if(zh(n)?.Check(t))return t}return e}function Wh(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=Wh(n,e);Array.isArray(t.anyOf)&&(n=Uh(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=Uh(n,t.oneOf));let r=Lh(t),i=r.length>1&&r.some(e=>Rh(n,e));if(r.length>0&&!i)for(let e of r){let t=Bh(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&Vh(n,t),r.includes(`array`)&&Array.isArray(n)&&Hh(n,t),n}function Gh(e){let t=e,n=Fh.get(t);if(n)return n;let r=Ph(e);return Fh.set(t,r),r}function Kh(e){if(e.keyword===`required`){let t=e.params.requiredProperties?.[0];if(t){let n=e.instancePath.replace(/^\//,``).replace(/\//g,`.`);return n?`${n}.${t}`:t}}return e.instancePath.replace(/^\//,``).replace(/\//g,`.`)||`root`}function qh(e,t){let n=structuredClone(t.arguments);Qp(e.parameters,n);let r=Gh(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Ih)){let t=Wh(n,e.parameters);if(t!==n)if(typeof n==`object`&&n&&typeof t==`object`&&t){for(let e of Object.keys(n))delete n[e];Object.assign(n,t)}else return r.Check(t)?t:n}if(r.Check(n))return n;let i=r.Errors(n).map(e=>` - ${Kh(e)}: ${e.message}`).join(`
|
|
887
887
|
`)||`Unknown validation error`,a=`Validation failed for tool "${t.name}":\n${i}\n\nReceived arguments:\n${JSON.stringify(t.arguments,null,2)}`;throw Error(a)}function Jh(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function Yh(e,t,n,r,i,a){let o=[...e],s={...t,messages:[...t.messages,...e]};await r({type:`agent_start`}),await r({type:`turn_start`});for(let t of e)await r({type:`message_start`,message:t}),await r({type:`message_end`,message:t});return await Zh(s,o,n,i,r,a??Jh()),o}async function Xh(e,t,n,r,i){if(e.messages.length===0)throw Error(`Cannot continue: no messages in context`);if(e.messages[e.messages.length-1].role===`assistant`)throw Error(`Cannot continue from message role: assistant`);let a=[],o={...e};return await n({type:`agent_start`}),await n({type:`turn_start`}),await Zh(o,a,t,r,n,i??Jh()),a}async function Zh(e,t,n,r,i,a){let o=e,s=n,c=!0,l=await s.getSteeringMessages?.()||[];for(;;){let e=!0;for(;e||l.length>0;){if(c?c=!1:await i({type:`turn_start`}),l.length>0){for(let e of l)await i({type:`message_start`,message:e}),await i({type:`message_end`,message:e}),o.messages.push(e),t.push(e);l=[]}let n=await Qh(o,s,r,i,a);if(t.push(n),n.stopReason===`error`||n.stopReason===`aborted`){await i({type:`turn_end`,message:n,toolResults:[]}),await i({type:`agent_end`,messages:t});return}let u=n.content.filter(e=>e.type===`toolCall`),d=[];if(e=!1,u.length>0){let a=n.stopReason===`length`?await $h(u,i):await eg(o,n,s,r,i);d.push(...a.messages),e=!a.terminate;for(let e of d)o.messages.push(e),t.push(e)}await i({type:`turn_end`,message:n,toolResults:d});let f={message:n,toolResults:d,context:o,newMessages:t},p=await s.prepareNextTurn?.(f);if(p&&(o=p.context??o,s={...s,model:p.model??s.model,reasoning:p.thinkingLevel===void 0?s.reasoning:p.thinkingLevel===`off`?void 0:p.thinkingLevel}),await s.shouldStopAfterTurn?.({message:n,toolResults:d,context:o,newMessages:t})){await i({type:`agent_end`,messages:t});return}l=await s.getSteeringMessages?.()||[]}let n=await s.getFollowUpMessages?.()||[];if(n.length>0){l=n;continue}break}await i({type:`agent_end`,messages:t})}async function Qh(e,t,n,r,i){let a=e.messages;t.transformContext&&(a=await t.transformContext(a,n));let o=await t.convertToLlm(a),s={systemPrompt:e.systemPrompt,messages:o,tools:e.tools},c=(t.getApiKey?await t.getApiKey(t.model.provider):void 0)||t.apiKey,l=await i(t.model,s,{...t,apiKey:c,signal:n}),u=null,d=!1;for await(let t of l)switch(t.type){case`start`:u=t.partial,e.messages.push(u),d=!0,await r({type:`message_start`,message:{...u}});break;case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:u&&(u=t.partial,e.messages[e.messages.length-1]=u,await r({type:`message_update`,assistantMessageEvent:t,message:{...u}}));break;case`done`:case`error`:{let t=await l.result();return d?e.messages[e.messages.length-1]=t:e.messages.push(t),d||await r({type:`message_start`,message:{...t}}),await r({type:`message_end`,message:t}),t}}let f=await l.result();return d?e.messages[e.messages.length-1]=f:(e.messages.push(f),await r({type:`message_start`,message:{...f}})),await r({type:`message_end`,message:f}),f}async function $h(e,t){let n=[];for(let r of e){await t({type:`tool_execution_start`,toolCallId:r.id,toolName:r.name,args:r.arguments});let e={toolCall:r,result:cg(`Tool call "${r.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await lg(e,t);let i=ug(e);await dg(i,t),n.push(i)}return{messages:n,terminate:!1}}async function eg(e,t,n,r,i){let a=t.content.filter(e=>e.type===`toolCall`),o=a.some(t=>e.tools?.find(e=>e.name===t.name)?.executionMode===`sequential`);return n.toolExecution===`sequential`||o?tg(e,t,a,n,r,i):ng(e,t,a,n,r,i)}async function tg(e,t,n,r,i,a){let o=[],s=[];for(let c of n){await a({type:`tool_execution_start`,toolCallId:c.id,toolName:c.name,args:c.arguments});let n=await ag(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await sg(e,t,n,await og(n,i,a),r,i),await lg(l,a);let u=ug(l);if(await dg(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:rg(o)}}async function ng(e,t,n,r,i,a){let o=[];for(let s of n){await a({type:`tool_execution_start`,toolCallId:s.id,toolName:s.name,args:s.arguments});let n=await ag(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await lg(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{let o=await og(n,i,a),s=await sg(e,t,n,o,r,i);return await lg(s,a),s}),i?.aborted)break}let s=await Promise.all(o.map(e=>typeof e==`function`?e():Promise.resolve(e))),c=[];for(let e of s){let t=ug(e);await dg(t,a),c.push(t)}return{messages:c,terminate:rg(s)}}function rg(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function ig(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function ag(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:cg(`Tool ${n.name} not found`),isError:!0};try{let o=qh(a,ig(a,n));if(r.beforeToolCall){let a=await r.beforeToolCall({assistantMessage:t,toolCall:n,args:o,context:e},i);if(i?.aborted)return{kind:`immediate`,result:cg(`Operation aborted`),isError:!0};if(a?.block)return{kind:`immediate`,result:cg(a.reason||`Tool execution was blocked`),isError:!0}}return i?.aborted?{kind:`immediate`,result:cg(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:cg(e instanceof Error?e.message:String(e)),isError:!0}}}async function og(e,t,n){let r=[],i=!0;try{let a=await e.tool.execute(e.toolCall.id,e.args,t,t=>{i&&r.push(Promise.resolve(n({type:`tool_execution_update`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,args:e.toolCall.arguments,partialResult:t})))});return i=!1,await Promise.all(r),{result:a,isError:!1}}catch(e){return i=!1,await Promise.all(r),{result:cg(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function sg(e,t,n,r,i,a){let o=r.result,s=r.isError;if(i.afterToolCall)try{let r=await i.afterToolCall({assistantMessage:t,toolCall:n.toolCall,args:n.args,result:o,isError:s,context:e},a);r&&(o={...o,content:r.content??o.content,details:r.details??o.details,usage:r.usage??o.usage,terminate:r.terminate??o.terminate},s=r.isError??s)}catch(e){o=cg(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function cg(e){return{content:[{type:`text`,text:e}],details:{}}}async function lg(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function ug(e){return{role:`toolResult`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,...e.result.addedToolNames?.length?{addedToolNames:e.result.addedToolNames}:{},isError:e.isError,timestamp:Date.now()}}async function dg(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function fg(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const pg={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},mg={id:`unknown`,name:`unknown`,api:`unknown`,provider:`unknown`,baseUrl:``,reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function hg(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??mg,thinkingLevel:e?.thinkingLevel??`off`,get tools(){return t},set tools(e){t=e.slice()},get messages(){return n},set messages(e){n=e.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}var gg=class{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}drain(){if(this.mode===`all`){let e=this.messages.slice();return this.messages=[],e}let e=this.messages[0];return e?(this.messages=this.messages.slice(1),[e]):[]}clear(){this.messages=[]}},_g=class{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;beforeToolCall;afterToolCall;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let t=e??{};this._state=hg(t.initialState),this.convertToLlm=t.convertToLlm??fg,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??Jh(),this.getApiKey=t.getApiKey,this.onPayload=t.onPayload,this.onResponse=t.onResponse,this.beforeToolCall=t.beforeToolCall,this.afterToolCall=t.afterToolCall,this.prepareNextTurn=t.prepareNextTurn,this.prepareNextTurnWithContext=t.prepareNextTurnWithContext,this.steeringQueue=new gg(t.steeringMode??`one-at-a-time`),this.followUpQueue=new gg(t.followUpMode??`one-at-a-time`),this.sessionId=t.sessionId,this.thinkingBudgets=t.thinkingBudgets,this.transport=t.transport??`auto`,this.maxRetryDelayMs=t.maxRetryDelayMs,this.toolExecution=t.toolExecution??`parallel`}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){this._state.messages=[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,t){if(this.activeRun)throw Error(`Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.`);let n=this.normalizePromptInput(e,t);await this.runPromptMessages(n)}async continue(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before continuing.`);let e=this._state.messages[this._state.messages.length-1];if(!e)throw Error(`No messages to continue from`);if(e.role===`assistant`){let e=this.steeringQueue.drain();if(e.length>0){await this.runPromptMessages(e,{skipInitialSteeringPoll:!0});return}let t=this.followUpQueue.drain();if(t.length>0){await this.runPromptMessages(t);return}throw Error(`Cannot continue from message role: assistant`)}await this.runContinuation()}normalizePromptInput(e,t){if(Array.isArray(e))return e;if(typeof e!=`string`)return[e];let n=[{type:`text`,text:e}];return t&&t.length>0&&n.push(...t),[{role:`user`,content:n,timestamp:Date.now()}]}async runPromptMessages(e,t={}){await this.runWithLifecycle(async n=>{await Yh(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await Xh(this.createContextSnapshot(),this.createLoopConfig(),e=>this.processEvents(e),e,this.streamFunction)})}createContextSnapshot(){return{systemPrompt:this._state.systemPrompt,messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let t=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel===`off`?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async e=>this.prepareNextTurnWithContext?await this.prepareNextTurnWithContext(e,this.signal):await this.prepareNextTurn?.(this.signal):void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>t?(t=!1,[]):this.steeringQueue.drain(),getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error(`Agent is already processing.`);let t=new AbortController,n=()=>{},r=new Promise(e=>{n=e});this.activeRun={promise:r,resolve:n,abortController:t},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(t.signal)}catch(e){await this.handleRunFailure(e,t.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,t){let n={role:`assistant`,content:[{type:`text`,text:``}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:pg,stopReason:t?`aborted`:`error`,errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:`message_start`,message:n}),await this.processEvents({type:`message_end`,message:n}),await this.processEvents({type:`turn_end`,message:n,toolResults:[]}),await this.processEvents({type:`agent_end`,messages:[n]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case`message_start`:this._state.streamingMessage=e.message;break;case`message_update`:this._state.streamingMessage=e.message;break;case`message_end`:this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case`tool_execution_start`:{let t=new Set(this._state.pendingToolCalls);t.add(e.toolCallId),this._state.pendingToolCalls=t;break}case`tool_execution_end`:{let t=new Set(this._state.pendingToolCalls);t.delete(e.toolCallId),this._state.pendingToolCalls=t;break}case`turn_end`:e.message.role===`assistant`&&e.message.errorMessage&&(this._state.errorMessage=e.message.errorMessage);break;case`agent_end`:this._state.streamingMessage=void 0;break}let t=this.activeRun?.abortController.signal;if(!t)throw Error(`Agent listener invoked outside active run`);for(let n of this.listeners)await n(e,t)}};function vg(e){if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=10||r===0?Math.round(n):Math.round(n*10)/10} ${t[r]}`}function yg(e){let t=e.mimeType||`application/octet-stream`;return`${e.name} (${t}, ${vg(e.size)})`}function bg(e){let t=yg(e);return e.kind===`image`&&e.data?e.path?`[Attached image: ${t} — full-resolution copy saved to ${e.path}]`:`[Attached image: ${t}]`:e.kind===`text`&&e.text!==void 0?[`----- BEGIN ATTACHMENT ${t} -----`,e.text,`----- END ATTACHMENT ${e.name} -----`].join(`
|
|
@@ -5249,7 +5249,7 @@ Examples:
|
|
|
5249
5249
|
skill list
|
|
5250
5250
|
skill info bluebubbles
|
|
5251
5251
|
skill read bluebubbles
|
|
5252
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
5252
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-CgTYDcS2.js`).then(e=>e.t);try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${sG()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:lG(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
5253
5253
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:uG(r),stderr:``,exitCode:0}:{stdout:``,stderr:`skill: "${n}" not found\n`,exitCode:1}}case`read`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: read requires a skill name
|
|
5254
5254
|
`,exitCode:1};let r=await i.readSkillInstructions(e,n);return r===null?{stdout:``,stderr:`skill: no SKILL.md found for "${n}"\n`,exitCode:1}:{stdout:r+`
|
|
5255
5255
|
`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}async function pG(e,t){let n=`${nW}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){throw Error(yW(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=Nt(r.body);if(!i.data)return[];let a=new Map;for(let e of i.data){if(e.type!==`skill`)continue;let t=e.attributes,n=IW(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,i=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=a.get(o);if(s&&s.qualityScore!=null&&i!=null&&s.qualityScore>=i)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}`;a.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:i,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(a.values())}async function mG(e,t){let n=`${nW}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){return{error:`Tessl search failed: ${yW(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=Nt(r.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!i)return{error:`skill "${e}" not found on Tessl registry`};let a=IW(i.attributes.sourceUrl);if(!a)return{error:`skill "${e}" has no GitHub source URL`};let o=i.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:a.owner,repo:a.repo,skillPath:o,skillName:e}}const hG=[{label:`Tessl`,host:new URL(nW).host,fetch:pG},{label:`browse.sh`,host:new URL(rW).host,fetch:$W}];function gG(e){let t=[],n=e.reduce((e,t)=>Math.max(e,t.length),0);for(let r=0;r<n;r++)for(let n of e)r<n.length&&t.push(n[r]);return t}async function _G(e,t,n=1){let r=await Promise.allSettled(hG.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=gG(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=hG[e],r=t.reason instanceof Error?t.reason.message:String(t.reason);s+=`warning: ${n.label} registry unavailable (${n.host}): ${r}\n`}}if(o.length===0){let t=a?`${s}upskill: registries failed to respond\n`:s;return{stdout:`No skills found for "${e}"\n\nTry a different search term or browse the registries at https://tessl.io/registry or https://browse.sh\n`,stderr:t,exitCode:+!!a}}let c=o.length,l=Math.ceil(c/10),u=Math.max(1,Math.min(n,l)),d=(u-1)*10,f=o.slice(d,d+10),p=`Search results for "${e}" (page ${u}/${l}, ${c} total):\n\n`;for(let e of f){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;p+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(p+=` ${e.summary}\n`),p+=`
|
|
@@ -5275,7 +5275,7 @@ Examples:
|
|
|
5275
5275
|
`,{stdout:s,stderr:``,exitCode:0}}function wG(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
5276
5276
|
`,exitCode:1}:Mn(e)?null:{stdout:``,stderr:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters
|
|
5277
5277
|
`,exitCode:1}}function TG(e){let t={selectedSkills:[],listOnly:!1,installAll:!1,force:!1,sourceRef:``},n=0;for(;n<e.length;){let r=e[n];if(r===`--skill`)t.selectedSkills.push(e[++n]);else if(r===`--path`||r===`-p`){let r=e[++n];if(typeof r!=`string`||!Fn(r))return t.earlyReturn={stdout:``,stderr:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters
|
|
5278
|
-
`,exitCode:1},t;t.subPath=r}else if(r===`--list`)t.listOnly=!0;else if(r===`--all`)t.installAll=!0;else if(r===`--force`)t.force=!0;else if(r===`--branch`||r===`-b`){let r=wG(e[n+1]);if(r)return t.earlyReturn=r,t;t.branch=e[++n]}else r.startsWith(`-`)||(t.sourceRef=r);n++}return t}async function EG(e){let t=await(await import(`./skills-
|
|
5278
|
+
`,exitCode:1},t;t.subPath=r}else if(r===`--list`)t.listOnly=!0;else if(r===`--all`)t.installAll=!0;else if(r===`--force`)t.force=!0;else if(r===`--branch`||r===`-b`){let r=wG(e[n+1]);if(r)return t.earlyReturn=r,t;t.branch=e[++n]}else r.startsWith(`-`)||(t.sourceRef=r);n++}return t}async function EG(e){let t=await(await import(`./skills-CgTYDcS2.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${sG()}`,stderr:``,exitCode:0}:{stdout:lG(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function DG(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-CgTYDcS2.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);return e?{stdout:uG(e),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
|
|
5279
5279
|
`,stderr:``,exitCode:0}}async function OG(e,t,n,r,i,a,o){let s=``,c=``,l=0,u=e.length;for(let d=0;d<e.length;d++){let f=e[d],p=await kW(f.path,f.name,r,i,a),m=d+1,h=((Date.now()-o)/1e3).toFixed(1),g=(Date.now()-o)/m,_=m<u?` (~${Math.round((u-m)*g/1e3)}s remaining)`:``;p.ok?(s+=`[${m}/${u}] Installed "${f.name}" from ${t}/${n} (${h}s)${_}\n`,l++):(s+=`[${m}/${u}] Failed "${f.name}": ${p.error}${_}\n`,c+=`upskill: ${p.error}\n`)}return{output:s,errors:c,successCount:l}}async function kG(e,t,n,r,i,a,o,s){let c=``,l=``,u=0,d=e.length;for(let f=0;f<e.length;f++){let p=e[f],m=await RW(t,n,p.path,p.name,i,r,a,void 0,o),h=f+1,g=((Date.now()-s)/1e3).toFixed(1),_=(Date.now()-s)/h,v=h<d?` (~${Math.round((d-h)*_/1e3)}s remaining)`:``;m.exitCode===0?(c+=`[${h}/${d}] Installed "${p.name}" from ${t}/${n} (${g}s)${v}\n`,u++):(c+=`[${h}/${d}] Failed "${p.name}": ${m.stderr.trim()}${v}\n`,l+=m.stderr)}return{output:c,errors:l,successCount:u}}async function AG(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await RW(t,n,d.path,d.name,i,r,a,o,s);e.exitCode===0?(c+=e.stdout,u++):l+=e.stderr}return{output:c,errors:l,successCount:u}}function jG(e,t,n){let r=`Available skills in ${t}/${n}:\n\n`;for(let t of e)r+=` ${t.name.padEnd(30)} ${t.path}\n`;return r+=`\nFound ${e.length} skill(s)\n`,r}async function MG(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await wW(r),l=await LW(i,a,c,s,r,o);if(l.error)return{stdout:``,stderr:`upskill: failed to list skills: ${l.error}\n`,exitCode:1};if(l.skills.length===0)return{stdout:`No skills found in ${i}/${a}${s?`/`+s:``}\n`,stderr:``,exitCode:0};if(t.listOnly)return{stdout:jG(l.skills,i,a)+`\nTo install: upskill ${t.sourceRef} --skill <name>\nTo install all: upskill ${t.sourceRef} --all\n`,stderr:``,exitCode:0};let u=l.skills;if(t.selectedSkills.length>0){u=l.skills.filter(e=>t.selectedSkills.includes(e.name));for(let e of t.selectedSkills)if(!l.skills.find(t=>t.name===e))return{stdout:``,stderr:`upskill: skill "${e}" not found in ${i}/${a}\n`,exitCode:1}}else if(!t.installAll)return{stdout:jG(l.skills,i,a)+`\nTo install specific skills: upskill ${t.sourceRef} --skill <name>\nTo install all: upskill ${t.sourceRef} --all\n`,stderr:``,exitCode:0};let d=u.length,f=Date.now(),p=``,m=``,h=0;if(d>1){let e=await MW(i,a,r,o);if(e.status===`ok`){let r=await OG(u,i,a,NW(e.files),n,t.force,f);({output:p,errors:m,successCount:h}=r)}else{let e=await kG(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await AG(u,i,a,c,n,t.force,r,o));let g=((Date.now()-f)/1e3).toFixed(1);return h>0&&(p+=`\nInstalled ${h} skill(s)${d>1?` in ${g}s`:``}\n`,await OW()),{stdout:p,stderr:m,exitCode:+!!m}}function NG(e,t,n){return U(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return dG();if(r[0]===`tabs`)return SG(e,t,n,r.includes(`--json`));if(r[0]===`recommendations`)return CG(e,t,r.includes(`--install`));if(r[0]===`list`)return EG(e);if(r[0]===`info`||r[0]===`read`)return DG(r[0],r[1],e);if(r[0]===`search`)return PG(r,t);let a=TG(r);if(a.earlyReturn)return a.earlyReturn;if(!a.sourceRef)return dG();if(a.sourceRef.startsWith(`tessl:`))return FG(a.sourceRef,a.force,e,t);let o=nG(a.sourceRef);if(o)return oG(o.hostname,o.task,e,t,a.force);let s=zW(a.sourceRef);return s?MG(s,a,e,t):{stdout:``,stderr:`upskill: unrecognized source "${a.sourceRef}"\n\nExpected: owner/repo, tessl:<name>, or browse:<hostname>/<task>\n`,exitCode:1}})}async function PG(e,t){let n=[...e.slice(1)],r=n.indexOf(`--page`),i=1;r>=0&&(i=parseInt(n[r+1],10)||1,n.splice(r,2));let a=n.join(` `);return a?_G(a,t,i):dG()}async function FG(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
5280
5280
|
`,exitCode:1};let a=await mG(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await wW(r);return RW(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function IG(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
5281
5281
|
|
|
@@ -6602,7 +6602,7 @@ Common base URLs:
|
|
|
6602
6602
|
llama.cpp http://localhost:8080/v1
|
|
6603
6603
|
vLLM http://localhost:8000/v1
|
|
6604
6604
|
Jan http://localhost:1337/v1
|
|
6605
|
-
`}function r3(){return U(t3,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:n3(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-
|
|
6605
|
+
`}function r3(){return U(t3,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:n3(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-DemFH9QU.js`),{verifyConnection:a}=await import(`./local-llm-c6JxoVB5.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(t3);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
6606
6606
|
`,exitCode:1};let c=await a(s,t(t3)??void 0);if(!c.ok){let e=[`✗ Could not reach ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` error: ${c.error?.message??`unknown`}`];return c.error?.hint&&e.push(` hint: ${c.error.hint}`),{stdout:``,stderr:e.join(`
|
|
6607
6607
|
`)+`
|
|
6608
6608
|
`,exitCode:1}}if(o===`discover`){let e=n(t3)??``;return i(t3,e,s,c.models.join(`, `)),{stdout:[`✓ ${s} (${c.runtime.kind}${c.runtime.version?` ${c.runtime.version}`:``})`,` Saved ${c.models.length} model${c.models.length===1?``:`s`} to Settings:`,...c.models.map(e=>` • ${e}`)].join(`
|
|
@@ -6646,20 +6646,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
6646
6646
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
6647
6647
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
6648
6648
|
short name resolves on the PATH.
|
|
6649
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return u3(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return u3(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return u3(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
6649
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return u3(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return u3(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return u3(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-Dvfacvs3.js`).then(e=>e.r);if(await a(i,t.fs))return u3(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-CAAAFAry.js`).then(e=>e.n),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await m3(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>P3(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,protocolVersion:l.getNegotiatedProtocolVersion(),tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await z3(i,t);let m=await H3(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-CEf9N9jt.js`);e({name:i,serverUrl:r,auth:u})}return l3([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${c3}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
6650
6650
|
`)+`
|
|
6651
|
-
`)}async function m3(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
6652
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
6651
|
+
`)}async function m3(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-BGZXP38Z.js`).then(e=>e.r),c=await I3(r.oauthFetchImpl),l=r.oauthLauncher??await F3(),u=await i(e,n,c);s3.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await xi(),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt,scopes:m.scope}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,redirectUri:d,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function h3(e,t){if(e.includes(`--help`)||e.includes(`-h`))return l3(`usage: mcp list
|
|
6652
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-CEf9N9jt.js`);await n();let{listServers:r}=await import(`./store-Dvfacvs3.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return l3("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return l3(g3(o))}function g3(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
|
|
6653
6653
|
`)+`
|
|
6654
6654
|
`}async function _3(e,t){if(e[0]===`--help`||e[0]===`-h`)return l3(`usage: mcp search <query>
|
|
6655
6655
|
|
|
6656
6656
|
Case-insensitive substring search across the cached tools of every
|
|
6657
6657
|
registered MCP server. Matches tool name OR description and prints a
|
|
6658
6658
|
table of (server, tool, description, match-field) rows.
|
|
6659
|
-
`);if(e.length===0)return u3(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
6660
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
6659
|
+
`);if(e.length===0)return u3(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-CEf9N9jt.js`);await i();let{listServers:a}=await import(`./store-Dvfacvs3.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return l3("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return l3(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,v3(e.description),e.match]);return l3(g3(l))}function v3(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function y3(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?u3(`mcp delete: expected <name>`):l3(`usage: mcp delete <name>
|
|
6660
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-CEf9N9jt.js`);await r(n);let{deleteServer:a}=await import(`./store-Dvfacvs3.js`).then(e=>e.r),o=await a(n,t.fs);await B3(n,t),await V3(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-BGZXP38Z.js`).then(e=>e.r);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){s3.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?u3(`mcp delete: no server, alias, or account found for "${n}"`):l3([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
|
|
6661
6661
|
`)+`
|
|
6662
|
-
`)}async function b3(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?u3(`mcp invoke: expected <name>`):l3(C3());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
6662
|
+
`)}async function b3(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?u3(`mcp invoke: expected <name>`):l3(C3());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-CEf9N9jt.js`);await i(n);let{getServer:a}=await import(`./store-Dvfacvs3.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return u3(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return l3(w3(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return u3(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=x3(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return l3(T3(n,l));let p=E3(d,l.inputSchema);if(!p.ok)return u3(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-CAAAFAry.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>P3(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=A3(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function x3(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=S3(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=S3(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function S3(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function C3(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
6663
6663
|
|
|
6664
6664
|
mcp invoke <name> List tools on <name>.
|
|
6665
6665
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -6689,7 +6689,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
6689
6689
|
|
|
6690
6690
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
6691
6691
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
6692
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
6692
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-CEf9N9jt.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-Dvfacvs3.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return u3(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-CAAAFAry.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>P3(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return u3(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,protocolVersion:l.getNegotiatedProtocolVersion(),tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await H3(n,d,t);return l3(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function M3(e,t){if(e.includes(`--help`)||e.includes(`-h`))return l3(`usage: mcp auth <name> [--silent | --interactive]
|
|
6693
6693
|
|
|
6694
6694
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
6695
6695
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -6701,7 +6701,7 @@ Options:
|
|
|
6701
6701
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
6702
6702
|
directly. Use after revoking a refresh token or
|
|
6703
6703
|
when the AS no longer accepts the cached one.
|
|
6704
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return u3(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return u3(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
6704
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return u3(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return u3(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-CEf9N9jt.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-Dvfacvs3.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return u3(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return u3(`mcp auth: server "${r}" does not use OAuth`);if(!s)return u3(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-C3ZN8FcH.js`).then(e=>e.r),f=d(u);if(!f)return u3(`mcp auth: provider "${u}" is not registered`);if(a)return await N3(r,f,t);if(!f.onSilentRenew)return i?u3(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await N3(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return u3(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);s3.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?l3(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?u3(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await N3(r,f,t)}async function N3(e,t,n){if(!t.onOAuthLogin)return u3(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await F3(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?l3(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):u3(`mcp auth: interactive login for "${e}" did not complete`)}async function P3(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-BGZXP38Z.js`).then(e=>e.r),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-C3ZN8FcH.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){s3.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function F3(){let{createOAuthLauncher:e}=await import(`./oauth-service-bKcyWLK0.js`);return e()}async function I3(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-GabK83LB.js`).then(e=>e.o),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function L3(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-DC6FadkH.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DvmmimLY.js`).then(e=>e.n);return await t.create({dbName:n})}function R3(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
6705
6705
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
6706
6706
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
6707
6707
|
const escape = (s) => {
|
|
@@ -6715,7 +6715,7 @@ const r = await exec(cmd);
|
|
|
6715
6715
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
6716
6716
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
6717
6717
|
process.exit(r.exitCode || 0);
|
|
6718
|
-
`}async function z3(e,t){let n=await L3(t.fs);await n.mkdir(c3,{recursive:!0}),await n.writeFile(`${c3}/${e}.jsh`,R3(e)),t.scriptCatalog?.invalidateJsh()}async function B3(e,t){let n=await L3(t.fs),r=`${c3}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){s3.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function V3(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
6718
|
+
`}async function z3(e,t){let n=await L3(t.fs);await n.mkdir(c3,{recursive:!0}),await n.writeFile(`${c3}/${e}.jsh`,R3(e)),t.scriptCatalog?.invalidateJsh()}async function B3(e,t){let n=await L3(t.fs),r=`${c3}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){s3.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function V3(e,t){let{removeAppSprinkles:n}=await import(`./apps-Da6VEmJt.js`);await n(e,t.fs)}async function H3(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-Da6VEmJt.js`);return(await r(e,t,n.fs)).length}catch(t){return s3.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const U3=`/.cache/artificial-analysis.json`;async function W3(e,t=!1){if(e&&!t)try{let t=await e.readFile(U3),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=Tt(),a;try{a=await i(`https://artificialanalysis.ai/api/v2/data/llms/models`,{method:`GET`,headers:r})}catch{return[]}if(a.status===401||a.status<200||a.status>=300)return[];let o;try{let e=new TextDecoder().decode(a.body);o=JSON.parse(e)}catch{return[]}let s=(Array.isArray(o)?o:o?.data??o?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&s.length>0){let t={fetchedAt:Date.now(),models:s};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(U3,JSON.stringify(t))}catch{}}return s}function G3(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function K3(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=G3(e),a=t.find(e=>G3(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 q3(){return`models - list available LLM models
|
|
6719
6719
|
|
|
6720
6720
|
Usage: models [options]
|
|
6721
6721
|
|
|
@@ -6729,7 +6729,7 @@ Options:
|
|
|
6729
6729
|
-h, --help Show this help message
|
|
6730
6730
|
`}function J3(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function Y3(e){return`$${e.toFixed(2)}`}const X3=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Z3(e){let t=`${e.id} ${e.name??``}`;return!X3.test(t)}function Q3(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 $3(e){let t=new Map;for(let n of e){let e=Q3(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function e6(e,t,n,r,i){let a=i?K3(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 t6(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=`${Y3(e.cost.input)} / ${Y3(e.cost.output)}`,a=`${J3(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}`)}return i.push(`\n ${n.length} model${n.length===1?``:`s`} available.`),r&&i.push(` Intelligence data: artificialanalysis.ai`),i.join(`
|
|
6731
6731
|
`)+`
|
|
6732
|
-
`}function n6(e){return U(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-
|
|
6732
|
+
`}function n6(e){return U(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-DemFH9QU.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:q3(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=o(),_=s(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
|
|
6733
6733
|
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await W3(e,f),S.length===0&&(S=void 0));let C;if(h){let e=r();if(!e.includes(h))return{stdout:``,stderr:`Unknown provider: ${h}. Available: ${e.join(`, `)}\n`,exitCode:1};C=[h]}else C=u?[...new Set(v.map(e=>e.providerId))]:[g];let w=[],T=[];for(let e of C){let t=a(e).filter(Z3);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>e6(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=$3(n)),w.push(...n),!l){let t=i(e);T.push(t6(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
6734
6734
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
6735
6735
|
`);let E=`${x}:${b}`,D=`${g}:${_}`;return T.push(E===D?`Currently using: ${E}\n`:`Currently using: ${E} (selected ${D} — resolved to a different model)\n`),{stdout:T.join(`
|
|
@@ -6769,7 +6769,7 @@ Examples:
|
|
|
6769
6769
|
oauth-domain add adobe '*.da.live'
|
|
6770
6770
|
oauth-domain list adobe
|
|
6771
6771
|
oauth-domain remove adobe admin.da.live
|
|
6772
|
-
`}function d6(){return U(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:u6(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-
|
|
6772
|
+
`}function d6(){return U(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:u6(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-DemFH9QU.js`),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
|
|
6773
6773
|
`)+`
|
|
6774
6774
|
`,stderr:``,exitCode:0}}let e=r(),n=Object.entries(e).filter(([,e])=>e.length>0);return n.length===0?{stdout:`(no extra OAuth domains configured)
|
|
6775
6775
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -6841,7 +6841,7 @@ Examples:
|
|
|
6841
6841
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
6842
6842
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
6843
6843
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
6844
|
-
`}function y6(){return U(`oauth-token`,b6)}async function b6(e,t){let n=await import(`./account-store-
|
|
6844
|
+
`}function y6(){return U(`oauth-token`,b6)}async function b6(e,t){let n=await import(`./account-store-BGZXP38Z.js`).then(e=>e.r),r=await import(`./providers-C3ZN8FcH.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:v6(),stderr:``,exitCode:0};if(e.includes(`--list`))return W6(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return P6(e);if(e.includes(`--renew`))return F6(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return L6(e,t);let i=x6(e);if(!i.ok)return i.result;let a=S6(e),o=C6(e,n,r);if(!o.ok)return o.result;let s=T6(o.value,r.getRegisteredProviderConfig);if(!s.ok)return s.result;if(!a){let e=await E6(o.value,s.value,n.getOAuthAccountInfo,i.value);if(e)return e}return k6(o.value,s.value,i.value,n.getOAuthAccountInfo)}function x6(e){let t=e.indexOf(`--scope`);if(t<0)return{ok:!0,value:void 0};let n=e[t+1]?.trim();return!n||n.startsWith(`-`)?{ok:!1,result:U6(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function S6(e){let t=e.indexOf(`--force-login`);return t<0?!1:(e.splice(t,1),!0)}function C6(e,t,n){let r=e.indexOf(`--provider`);if(r>=0){let t=e[r+1];return t?{ok:!0,value:t}:{ok:!1,result:U6(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(w6(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>w6(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:U6(`oauth-token: no OAuth providers configured`)}}function w6(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function T6(e,t){let n=t(e);return n?w6(n)?{ok:!0,value:n}:{ok:!1,result:U6(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:U6(`oauth-token: unknown provider "${e}"`)}}async function E6(e,t,n,r){let i=n(e);return i&&!i.expired?D6(e,i,r):!i?.expired||!t.onSilentRenew||!await M6(t.onSilentRenew)?null:D6(e,n(e),r)}function D6(e,t,n){return n&&!_6(t?.scopes,n)?null:O6(e,t?.maskedValue)}function O6(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:U6(`oauth-token: no masked value for ${e} (try logging in again)`)}async function k6(e,t,n,r){try{return await A6(e,t,n)||j6(e,r)}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`[oauth-token] Provider ${e}: login failed:`,n),U6(`oauth-token: login failed: ${n}`)}}async function A6(e,t,n){let r=n?{scopes:n}:void 0;if(t.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:n}=await import(`./oauth-service-bKcyWLK0.js`),i=await n();return i?(await t.onOAuthLoginIntercepted(i,()=>{},r),null):U6(`oauth-token: provider "${e}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.`)}if(t.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-bKcyWLK0.js`);return await t.onOAuthLogin(e(),()=>{},r),null}return U6(`oauth-token: provider "${e}" has no OAuth login hook`)}function j6(e,t){let n=t(e);return n?.token?O6(e,n.maskedValue):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),U6(`oauth-token: login completed but no token was saved`))}async function M6(e){try{return await e()!==null}catch{return!1}}function N6(e,t,n,r){let i=e.filter(e=>!e.startsWith(`-`))[0];if(i)return i;let a=t();return n(a)?.onSilentRenew?a:r().find(e=>n(e)?.onSilentRenew)}async function P6(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./account-store-BGZXP38Z.js`).then(e=>e.r),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-C3ZN8FcH.js`).then(e=>e.r),o=N6(e,n,i,a);if(!o)return U6(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return U6(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return U6(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return U6(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return U6(`oauth-token --expire: failed to update "${o}": ${e instanceof Error?e.message:String(e)}`)}return{stdout:`oauth-token ${o}: stored token marked expired; next network op will trigger silent renewal.\n`,stderr:``,exitCode:0}}async function F6(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./account-store-BGZXP38Z.js`).then(e=>e.r),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-C3ZN8FcH.js`).then(e=>e.r),a=N6(e,t,r,i);if(!a)return U6(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return U6(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return U6(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${I6(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${I6(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
|
|
6845
6845
|
`)+`
|
|
6846
6846
|
`,stderr:``,exitCode:+!u}}function I6(e){if(!e)return`no token`;if(e.expired)return`expired`;if(e.expiresAt){let t=e.expiresAt-Date.now();if(t>0){let e=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4);return e>0?`valid, expires in ${e}h ${n}m`:`valid, expires in ${n}m`}}return`valid`}async function L6(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-bKcyWLK0.js`),i=await R6(e,t);if(!i.ok)return i.result;let a=n(i.value);if(!a.ok)return U6(`oauth-token: invalid intercept config: ${a.error}`);let o=await r();if(!o)return U6(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let s=await o(a.config);return s?{stdout:`${s}\n`,stderr:``,exitCode:0}:U6(`oauth-token: intercept timed out or was cancelled`)}function R6(e,t){let n=e.indexOf(`--from-file`);return n>=0?z6(e[n+1],t):B6(e)}async function z6(e,t){if(!e)return{ok:!1,result:U6(`oauth-token: --from-file requires a path`)};try{let n=t.fs.resolvePath(t.cwd,e),r=await t.fs.readFile(n),i=typeof r==`string`?r:new TextDecoder().decode(r);return{ok:!0,value:JSON.parse(i)}}catch(t){return{ok:!1,result:U6(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function B6(e){let t=H6(e,`--authorize-url`),n=H6(e,`--redirect-pattern`);if(!t)return{ok:!1,result:U6(`oauth-token: --authorize-url is required`)};if(!n)return{ok:!1,result:U6(`oauth-token: --redirect-pattern is required`)};let r=V6(e);return r.ok?{ok:!0,value:{authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.value.length>0?{rewrite:r.value}:{}}}:r}function V6(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]!==`--rewrite`)continue;let r=e[n+1];if(!r)return{ok:!1,result:U6(`oauth-token: --rewrite requires a value`)};let i=r.split(`=`);if(i.length<3)return{ok:!1,result:U6(`oauth-token: --rewrite "${r}" must be "<match>=<key>=<value>"`)};let[a,o,...s]=i;t.push({match:a,appendParams:{[o]:s.join(`=`)}})}return{ok:!0,value:t}}function H6(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function U6(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function W6(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
6847
6847
|
`,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`)}}t.scopes&&n.push(`scopes: ${t.scopes}`),a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
|
|
@@ -8590,7 +8590,7 @@ ${e}
|
|
|
8590
8590
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
8591
8591
|
${t}
|
|
8592
8592
|
---`);let a=ab(n);return a&&(i+=a),i}};const L9=r(`scoop-lifecycle-manager`);var Zse=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){L9.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){L9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)L9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{L9.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new Zn(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new Xse(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{L9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),L9.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),L9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return L9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.contexts.get(e);o||=(await this.createTab(e),this.contexts.get(e));let s=this.tabs.get(e);if(s?.status===`initializing`){if(L9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){L9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.contexts.get(e),s=this.tabs.get(e)}if(!o){L9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s&&(s.status=`processing`,s.lastActivity=new Date().toISOString(),this.tabs.set(e,s),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),L9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),L9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||qi(`spawn`,e.folder)}catch(n){L9.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){L9.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{L9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{L9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{L9.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&L9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),L9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){L9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();L9.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{L9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),L9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){L9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),qi(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&this.deps.messageRouter.flushOnIdle(e),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return await i.registerScoop(n),n}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);L9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),qi(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){L9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{L9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const R9=r(`scoop-message-router`);var Qse=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if(R9.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){R9.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);qi(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),R9.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);R9.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){R9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){R9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if(R9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){R9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{R9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(!(r?.status!==`ready`&&r?.status!==`processing`)){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`;return!e||e.isCone||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);R9.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);R9.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;if(n.reported||r<3e5)return;n.reported=!0;let i=`Lick queue remained deferred while scoop was busy for ${3e5/1e3}s`;R9.warn(`Busy lick queue may be starved`,{jid:e,error:i}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r})}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){R9.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){R9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){R9.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if(R9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){R9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){R9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=an(vn(ln(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){R9.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=s.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${xg(e.content,e.attachments)}`).join(`
|
|
8593
|
-
`),l=s.flatMap(e=>Sg(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=an(vn(ln(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer);await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f})}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys()){let t=this.deps.getTabs().get(e);this.recordBusyDeferralIfPresent(e);let n=(this.messageQueues.get(e)?.length??0)>0;t?.status===`ready`&&n&&!this.debounceStates.has(e)&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);R9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(this.cancelDebounce(e),t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{R9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{R9.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),R9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{R9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),R9.info(`All messages cleared`)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const z9=r(`orchestrator`);var $se=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new ub({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new Nb({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new jb({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Tb({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new _b({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>pn(e),saveMessage:e=>on(e)});lickRegistry=new pb({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Qse({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>on(e),deleteMessage:e=>cn(e),clearMessagesForScoop:e=>gn(e),clearAllMessages:()=>mn(),getMessagesSince:(e,t,n)=>fn(e,t,n),setState:(e,t)=>ree(e,t)},isExternalLickChannel:Ca});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Zse({getScoops:()=>this.scoops,getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>nee(e),deleteScoop:e=>hn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>zn(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await xn(),this.sharedFs=await Xn.create({dbName:`slicc-fs`}),this.sessionStore=new Tg,this.fsWatcher=new Yn,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new M_({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await yn();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await dn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new hb({onTaskRun:async(e,t)=>{z9.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),z9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);z9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}$n(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=P_(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setScoopExistenceResolver(e=>this.getScoops().some(t=>In(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await Xn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await ob(this.sharedFs).catch(e=>{z9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new M_({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),z9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return pn(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await import(`./frozen-archive-format-CqpMlNNW.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(rr)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&z9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,z9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new xa,t=this.sharedFs;return new Wv({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:()=>this.sessionStore?.loadAll()??Promise.resolve([]),loadUiChatSessions:async()=>{let t=await e.list();return(await Promise.all(t.map(t=>e.load(t)))).filter(e=>e!==null)},wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:cy(),snapshotStore:{read:e=>ty(t,e),write:(e,n)=>ey(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.12.1`})}};function ece(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var tce=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=V9(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name))}if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new Jt(`ENOENT`,`no such file or directory`,e);return B9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new Jt(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new Jt(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new Jt(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new Jt(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new Jt(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=V9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new Jt(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new Jt(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new Jt(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new Jt(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new Jt(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new Jt(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new Jt(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderProcFile(e,t){if(e===1)return sce(t);let n=this.pm.get(e);switch(t){case`status`:return nce(n);case`cmdline`:return rce(n);case`cwd`:return ice(n);case`stat`:return ace(n)}}};const B9=[`status`,`cmdline`,`cwd`,`stat`];function V9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function H9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function nce(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${oce(e)}`,`StartedAt:\t${new Date(e.startedAt).toISOString()}`];return e.finishedAt!==null&&t.push(`FinishedAt:\t${new Date(e.finishedAt).toISOString()}`),e.terminatedBy!==null&&t.push(`TerminatedBy:\t${e.terminatedBy}`),e.exitCode!==null&&t.push(`ExitCode:\t${e.exitCode}`),t.push(`Cmdline:\t${e.argv.join(` `)}`),t.join(`
|
|
8593
|
+
`),l=s.flatMap(e=>Sg(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=an(vn(ln(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer);await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f})}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys()){let t=this.deps.getTabs().get(e);this.recordBusyDeferralIfPresent(e);let n=(this.messageQueues.get(e)?.length??0)>0;t?.status===`ready`&&n&&!this.debounceStates.has(e)&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);R9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(this.cancelDebounce(e),t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{R9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{R9.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),R9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{R9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),R9.info(`All messages cleared`)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const z9=r(`orchestrator`);var $se=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new ub({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new Nb({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new jb({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Tb({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new _b({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>pn(e),saveMessage:e=>on(e)});lickRegistry=new pb({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Qse({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>on(e),deleteMessage:e=>cn(e),clearMessagesForScoop:e=>gn(e),clearAllMessages:()=>mn(),getMessagesSince:(e,t,n)=>fn(e,t,n),setState:(e,t)=>ree(e,t)},isExternalLickChannel:Ca});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Zse({getScoops:()=>this.scoops,getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>nee(e),deleteScoop:e=>hn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>zn(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await xn(),this.sharedFs=await Xn.create({dbName:`slicc-fs`}),this.sessionStore=new Tg,this.fsWatcher=new Yn,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new M_({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await yn();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await dn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new hb({onTaskRun:async(e,t)=>{z9.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),z9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);z9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}$n(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=P_(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setScoopExistenceResolver(e=>this.getScoops().some(t=>In(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await Xn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await ob(this.sharedFs).catch(e=>{z9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new M_({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),z9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return pn(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await import(`./frozen-archive-format-CqpMlNNW.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(rr)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&z9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,z9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new xa,t=this.sharedFs;return new Wv({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:()=>this.sessionStore?.loadAll()??Promise.resolve([]),loadUiChatSessions:async()=>{let t=await e.list();return(await Promise.all(t.map(t=>e.load(t)))).filter(e=>e!==null)},wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:cy(),snapshotStore:{read:e=>ty(t,e),write:(e,n)=>ey(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.13.0`})}};function ece(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var tce=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=V9(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name))}if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new Jt(`ENOENT`,`no such file or directory`,e);return B9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new Jt(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new Jt(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new Jt(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new Jt(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new Jt(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=V9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new Jt(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new Jt(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new Jt(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new Jt(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new Jt(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new Jt(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new Jt(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderProcFile(e,t){if(e===1)return sce(t);let n=this.pm.get(e);switch(t){case`status`:return nce(n);case`cmdline`:return rce(n);case`cwd`:return ice(n);case`stat`:return ace(n)}}};const B9=[`status`,`cmdline`,`cwd`,`stat`];function V9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function H9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function nce(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${oce(e)}`,`StartedAt:\t${new Date(e.startedAt).toISOString()}`];return e.finishedAt!==null&&t.push(`FinishedAt:\t${new Date(e.finishedAt).toISOString()}`),e.terminatedBy!==null&&t.push(`TerminatedBy:\t${e.terminatedBy}`),e.exitCode!==null&&t.push(`ExitCode:\t${e.exitCode}`),t.push(`Cmdline:\t${e.argv.join(` `)}`),t.join(`
|
|
8594
8594
|
`)+`
|
|
8595
8595
|
`}function rce(e){return e.argv.join(`\0`)+`\0`}function ice(e){return e.cwd+`
|
|
8596
8596
|
`}function ace(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
@@ -8599,4 +8599,4 @@ ${t}
|
|
|
8599
8599
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
8600
8600
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
8601
8601
|
`}}function cce(e={}){let t=e.channel===void 0;if(t&&!e.nonce)throw Error(`installSyncFsResponder: a nonce (or a test channel) is required`);let n=e.channel??new BroadcastChannel(Qz(e.nonce)),r=e=>n.postMessage(e),i=new Map,a=e=>{let t=e.data;if(t?.type!==`sync-fs-req`||typeof t.id!=`string`)return;let n=t;if(!qz(n.token))return;let a=i.get(n.id);if(a){r({type:$z,id:n.id}),a.result&&r({type:eB,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:$z,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:eB,id:n.id,...e})};(rB(n)?oB(n):Zz(n)).then(s).catch(e=>s({ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return n.addEventListener(`message`,a),{dispose:()=>{n.removeEventListener(`message`,a);for(let e of i.values())e.timer&&clearTimeout(e.timer);i.clear(),t&&n.close?.()}}}function lce(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function uce(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function dce(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}fce(e,t)}function fce(e,{orchestrator:t,log:n}){e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`&&(e.lickId=t.registerUpgradeLick(e));let r=Ia(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=lce(e),a=uce(e),o=e.type,s=t.getScoops(),c;if(c=e.targetScoop?s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):s.find(e=>e.isCone),!c){n.warn(`Lick target scoop not found`,e.targetScoop);return}let l={id:`${o}-${a}-${Date.now()}`,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:o,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l)}async function pce(e,t,n,r){let i=new Rr,a=new $se(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=kn(()=>n.emitTrayRuntimeStatus()),s=Ua(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function mce(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-_BMgmnMI.js`).then(e=>e.t);r(t=>e.getSessionCostsForCommand(t));let{getLickManager:i}=await import(`./lick-manager-Ce_d4NxJ.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??dce,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function hce(e){e.getScoops().some(e=>e.isCone)||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function gce(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;loe({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>YU(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>f9().slice(10,22),splitResult:(e,t)=>p9(e,t)})}async function _ce(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-D_PY6ku1.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-Dzuxa2F7.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
|
|
8602
|
-
`,r=``;try{let t=await i.readFile(e);r=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await i.writeFile(e,r+n)},log:e=>{a.info?.(`browser.websocket frame`,{payload:e})}}})}}async function vce(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-B21s2Gwz.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function W9(e,t,n){let r=e.getTransport();if(r.isExtensionBridge)return n.debug?.(`Skipping NavigationWatcher: extension-bridge transport rejects sessionless Target.* discovery; the service worker observes handoffs via chrome.webRequest`),null;try{let e=new gee(r,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})},yce(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function yce(e){let t=Tt();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>ece()}}function bce(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-BV6fn6QF.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function xce(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-Zdl2rqUw.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function Sce(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DTKmVPld.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function Cce(){return y()}async function wce(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await pce(t,n,r,i);if(d?Rg(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new tce(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await mce(c,e,o);d&&gce({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await _ce({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;Cce()&&(h=await vce(f,o,e.localLickWsUrl??null));let g=W9(n,f,o);d&&bce(d,f,o),a||await hce(c),d&&xce(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await Sce(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=cce({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await Tce({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function Tce(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}Ece({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Ece(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[l9]}const G9=`x-bypass-llm-proxy`;function Dce(e,t,n){return t?(r,i)=>{if(!Oce(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function Oce(e,t,n){if(Ace(e,t))return!0;let r=n?.()??null;return r?kce(e,r,t):!1}function kce(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function Ace(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function jce(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var Mce=class{transport;createShell;log;pm;defaultOwner;sessions=new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!Nce(e)||e.source!==`panel`)return;let t=e.payload;Pce(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?q9(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,q9(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function Nce(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function Pce(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var Fce=class extends C9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function Ice(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new Mce({transport:t,processManager:i,createShell:(e,a)=>new Fce(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Lce(e){let t=new Rce(e);return t.start(),{stop:()=>t.dispose()}}var Rce=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!zce(e)||e.source!==`panel`)return;let t=e.payload;if(Bce(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Vce(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new Jt(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new Jt(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(Hce(e.type),e.requestId,new Jt(`EACCES`,`vfs-rpc-host has no writable backend wired`),Uce(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new Jt(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new Jt(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new Jt(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function zce(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Bce(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function Vce(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function Hce(e){switch(e){case`vfs-write-file`:return`vfs-write-file-result`;case`vfs-mkdir`:return`vfs-mkdir-result`;case`vfs-rm`:return`vfs-rm-result`;case`vfs-flush`:return`vfs-flush-result`;case`vfs-list-mount-points`:return`vfs-list-mount-points-result`}}function Uce(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof Jt?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Wce(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Dce(e.bind(globalThis),t,Gce)}function Gce(){let e=Ct();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Kce(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let Y9=null,X9=null,Z9=null,Q9=null,$9=null;const qce=jce(e=>Jce(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&qce.handle(e.data)});async function Jce(e){zi(e.instanceId);try{Wce(),At(e.localApiBaseUrl??null),bt(e.bridgeToken??null),UU(e.syncFsBridgeEnabled??!1),wt(e.extensionDelegateId??null),Kce(e.localStorageSeed??{}),aa().catch(()=>{}),await s();let t=_a(e.kernelPort),n=new Ya(t),r=Ya.createCallbacks(n),a=new va(e.cdpPort);await a.connect();let o=new ki(a);Y9=await wce({container:{},browser:o,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=Y9.sharedFs?.getWatcher();if(u){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)u.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)l.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider(Fi(i));let f=await Yce({host:Y9,transport:t,browser:o,instanceId:e.instanceId});f&&(X9=f.stopTerminalHost,Z9=f.stopVfsRpcHost,Q9=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Vi(e),e}}async function Yce(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=Ice({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Lce({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Xce(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Xce(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CzwTkGxm.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-GabK83LB.js`).then(e=>e.o),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});
|
|
8602
|
+
`,r=``;try{let t=await i.readFile(e);r=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await i.writeFile(e,r+n)},log:e=>{a.info?.(`browser.websocket frame`,{payload:e})}}})}}async function vce(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-B21s2Gwz.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function W9(e,t,n){let r=e.getTransport();if(r.isExtensionBridge)return n.debug?.(`Skipping NavigationWatcher: extension-bridge transport rejects sessionless Target.* discovery; the service worker observes handoffs via chrome.webRequest`),null;try{let e=new gee(r,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})},yce(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function yce(e){let t=Tt();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>ece()}}function bce(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-COqMGgnC.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function xce(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-CNscsCCc.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function Sce(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DTKmVPld.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function Cce(){return y()}async function wce(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await pce(t,n,r,i);if(d?Rg(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new tce(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await mce(c,e,o);d&&gce({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await _ce({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;Cce()&&(h=await vce(f,o,e.localLickWsUrl??null));let g=W9(n,f,o);d&&bce(d,f,o),a||await hce(c),d&&xce(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await Sce(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=cce({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await Tce({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function Tce(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}Ece({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Ece(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[l9]}const G9=`x-bypass-llm-proxy`;function Dce(e,t,n){return t?(r,i)=>{if(!Oce(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function Oce(e,t,n){if(Ace(e,t))return!0;let r=n?.()??null;return r?kce(e,r,t):!1}function kce(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function Ace(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function jce(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var Mce=class{transport;createShell;log;pm;defaultOwner;sessions=new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!Nce(e)||e.source!==`panel`)return;let t=e.payload;Pce(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?q9(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,q9(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function Nce(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function Pce(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var Fce=class extends C9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function Ice(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new Mce({transport:t,processManager:i,createShell:(e,a)=>new Fce(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Lce(e){let t=new Rce(e);return t.start(),{stop:()=>t.dispose()}}var Rce=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!zce(e)||e.source!==`panel`)return;let t=e.payload;if(Bce(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Vce(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new Jt(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new Jt(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(Hce(e.type),e.requestId,new Jt(`EACCES`,`vfs-rpc-host has no writable backend wired`),Uce(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new Jt(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new Jt(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new Jt(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function zce(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Bce(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function Vce(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function Hce(e){switch(e){case`vfs-write-file`:return`vfs-write-file-result`;case`vfs-mkdir`:return`vfs-mkdir-result`;case`vfs-rm`:return`vfs-rm-result`;case`vfs-flush`:return`vfs-flush-result`;case`vfs-list-mount-points`:return`vfs-list-mount-points-result`}}function Uce(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof Jt?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Wce(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Dce(e.bind(globalThis),t,Gce)}function Gce(){let e=Ct();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Kce(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let Y9=null,X9=null,Z9=null,Q9=null,$9=null;const qce=jce(e=>Jce(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&qce.handle(e.data)});async function Jce(e){zi(e.instanceId);try{Wce(),At(e.localApiBaseUrl??null),bt(e.bridgeToken??null),UU(e.syncFsBridgeEnabled??!1),wt(e.extensionDelegateId??null),Kce(e.localStorageSeed??{}),aa().catch(()=>{}),await s();let t=_a(e.kernelPort),n=new Ya(t),r=Ya.createCallbacks(n),a=new va(e.cdpPort);await a.connect();let o=new ki(a);Y9=await wce({container:{},browser:o,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=Y9.sharedFs?.getWatcher();if(u){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)u.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)l.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider(Fi(i));let f=await Yce({host:Y9,transport:t,browser:o,instanceId:e.instanceId});f&&(X9=f.stopTerminalHost,Z9=f.stopVfsRpcHost,Q9=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Vi(e),e}}async function Yce(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=Ice({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Lce({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Xce(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Xce(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CzwTkGxm.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-GabK83LB.js`).then(e=>e.o),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});
|