sliccy 5.77.0 → 5.78.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/dist/node-server/_shared/tray-sync-protocol.d.ts +28 -1
- package/dist/node-server/_shared/tray-sync-protocol.d.ts.map +1 -1
- package/dist/node-server/_shared/tray-sync-protocol.js +1 -1
- package/dist/node-server/_shared/tray-sync-protocol.js.map +1 -1
- package/dist/ui/assets/{account-store-1C3olp0d.js → account-store-Be7SwcSO.js} +1 -1
- package/dist/ui/assets/{account-store-A6JIUEL-.js → account-store-DTWDY802.js} +1 -1
- package/dist/ui/assets/{adobe-mQz3iUA9.js → adobe-D6aBoEqh.js} +1 -1
- package/dist/ui/assets/{adobe-kWZNYII0.js → adobe-DZ6poAWr.js} +1 -1
- package/dist/ui/assets/{apps-CClJ0Nvu.js → apps-BF5YTR81.js} +1 -1
- package/dist/ui/assets/{azure-openai-DyAMz9cO.js → azure-openai-Bf8mIkxt.js} +1 -1
- package/dist/ui/assets/{azure-openai-dJzlyTjo.js → azure-openai-C81f6iVJ.js} +1 -1
- package/dist/ui/assets/{cdp-D9eDDEuA.js → cdp-sNqqsD81.js} +1 -1
- package/dist/ui/assets/{cerebras-BQEoURLe.js → cerebras-CDmzpOq1.js} +1 -1
- package/dist/ui/assets/{cerebras-C3Hn1f6X.js → cerebras-CmAS2dQE.js} +1 -1
- package/dist/ui/assets/{connect-surface-Cab11OlN.js → connect-surface-Dw22h-yx.js} +1 -1
- package/dist/ui/assets/{fs-C9TpsQVU.js → fs-C97LJui5.js} +2 -2
- package/dist/ui/assets/{fs-Wrp0-NXJ.js → fs-CfTHhKG8.js} +1 -1
- package/dist/ui/assets/{github-DalD1_ST.js → github-1nlcdZC1.js} +1 -1
- package/dist/ui/assets/{github-BqU3-V_7.js → github-B8Fy4_d0.js} +2 -2
- package/dist/ui/assets/{github-copilot-CdnxKRIz.js → github-copilot-BhPEatdf.js} +1 -1
- package/dist/ui/assets/{github-copilot-DLRn3zr5.js → github-copilot-CdPUJSil.js} +1 -1
- package/dist/ui/assets/{kernel-worker-B41WSEvS.js → kernel-worker-v6GOcJ2T.js} +21 -19
- package/dist/ui/assets/{local-llm-D6RQDZG0.js → local-llm-8aAdS6D4.js} +1 -1
- package/dist/ui/assets/{local-llm-Ctv3LxUm.js → local-llm-BS0QZDvU.js} +1 -1
- package/dist/ui/assets/{main-Dkeg3jxF.js → main-C7A9YUa_.js} +3 -3
- package/dist/ui/assets/main-cherry-BcFQ7E1u.js +1 -0
- package/dist/ui/assets/{mount-CxN5spi_.js → mount-BrgS-fqG.js} +1 -1
- package/dist/ui/assets/{mount-CyDAk_QJ.js → mount-CzhkcAS3.js} +2 -2
- package/dist/ui/assets/{mount-recovery-CDcDil6x.js → mount-recovery-P3CO-Jh3.js} +1 -1
- package/dist/ui/assets/{new-session-Bhkx8MnW.js → new-session-BcA7VrW6.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-Bi6A5JBQ.js → oauth-bootstrap-C6qx4787.js} +2 -2
- package/dist/ui/assets/{openai-codex-DXGnfKVU.js → openai-codex-BxqAHcQW.js} +1 -1
- package/dist/ui/assets/{openai-codex-CV-ayIGu.js → openai-codex-Dnxsu82m.js} +1 -1
- package/dist/ui/assets/{openrouter-CBASr9hL.js → openrouter-C1abS1Kj.js} +1 -1
- package/dist/ui/assets/{openrouter-8osSBFmn.js → openrouter-D5i_OSiL.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-DkDPBLxn.js → openrouter-oauth-CP1xrXkC.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-B3F5k3je.js → openrouter-oauth-DFhAA-CH.js} +1 -1
- package/dist/ui/assets/page-follower-tray-BrSvgCHw.js +5 -0
- package/dist/ui/assets/{panel-rpc-handlers-CB7QR59Y.js → panel-rpc-handlers-CaYVHpzm.js} +2 -2
- package/dist/ui/assets/{provider-DoFgejr4.js → provider-B-tRWluT.js} +1 -1
- package/dist/ui/assets/{provider-Ds96_3eP.js → provider-D7TX1cSi.js} +2 -2
- package/dist/ui/assets/{provider-settings-BFoX4PZM.js → provider-settings-B7usvoJ-.js} +1 -1
- package/dist/ui/assets/{provider-settings-BZ7P9aej.js → provider-settings-Dso8bqfm.js} +1 -1
- package/dist/ui/assets/{provider-store-access-BeUtLtRJ.js → provider-store-access-DxhbdzgB.js} +2 -2
- package/dist/ui/assets/provider-store-access-me3Zn32r.js +1 -0
- package/dist/ui/assets/{providers-Bjx2A7O7.js → providers-DWFfCVDH.js} +1 -1
- package/dist/ui/assets/{providers-Cp6-c8l2.js → providers-u6-lFi9k.js} +2 -2
- package/dist/ui/assets/{quick-llm-QkW5R99T.js → quick-llm-CVyENHe-.js} +1 -1
- package/dist/ui/assets/{remote-cdp-transport-Dmg2NdTA.js → remote-cdp-transport-CG3TFBoT.js} +1 -1
- package/dist/ui/assets/{session-freezer-Ja_Cnyg7.js → session-freezer-BqJUWp_E.js} +2 -2
- package/dist/ui/assets/{setup-standalone-prelude-HRdN12hy.js → setup-standalone-prelude-BCOHbACI.js} +2 -2
- package/dist/ui/assets/{setup-sudo-BagAf3je.js → setup-sudo-CEAT8Ofq.js} +2 -2
- package/dist/ui/assets/{skills-LPeorboB.js → skills-BLTaKjRv.js} +1 -1
- package/dist/ui/assets/{store-DHHj_uiD.js → store-QmpK1UDU.js} +1 -1
- package/dist/ui/assets/{sudo-CMCLlwKz.js → sudo-DsJ34DBZ.js} +1 -1
- package/dist/ui/assets/{tray-follower-status-CyJIKXH4.js → tray-follower-status-5SqDRLX8.js} +1 -1
- package/dist/ui/assets/{tray-sync-protocol-CxWJ329c.js → tray-sync-protocol-D44N11jm.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-ChCeiPPt.js → upgrade-detection-B2NfyFQR.js} +1 -1
- package/dist/ui/assets/{wc-extension-D-Lj_GzE.js → wc-extension-BzUiocaG.js} +2 -2
- package/dist/ui/assets/wc-follower-D6-l854p.js +17 -0
- package/dist/ui/assets/{wc-live-CyQbw_f8.js → wc-live-j7LC0QpG.js} +3 -3
- package/dist/ui/assets/{wc-nav-0T_ZQpcY.js → wc-nav-D07gjbsv.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-BMTFe5G7.js → wc-onboarding-Ge8twzbD.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-B7BWSV5j.js → wc-placeholder-Cx5bA08G.js} +2 -2
- package/dist/ui/assets/{wc-settings-CWYClrUw.js → wc-settings-C4zU5HMM.js} +2 -2
- package/dist/ui/assets/{wc-shell-Bh6BHoFv.js → wc-shell-fiwgganB.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-BG0zh9j9.js → wc-sprinkles-89Pe_Wdl.js} +2 -2
- package/dist/ui/assets/wc-transcript-export-B3p8LhYu.js +2 -0
- package/dist/ui/assets/wc-tray-D8sfYPHN.js +2 -0
- package/dist/ui/assets/{xai-grok-CvCcfVZx.js → xai-grok-DQif65Sm.js} +1 -1
- package/dist/ui/assets/{xai-grok-C3MjTyfG.js → xai-grok-YonQn_Qk.js} +1 -1
- package/dist/ui/index.html +7 -7
- package/dist/ui/packages/webapp/index.html +7 -7
- package/package.json +1 -1
- package/dist/ui/assets/main-cherry-D_hgi0by.js +0 -1
- package/dist/ui/assets/page-follower-tray-M061L6UY.js +0 -5
- package/dist/ui/assets/provider-store-access-COBoLFXp.js +0 -1
- package/dist/ui/assets/wc-follower-Bkm8bSJu.js +0 -17
- package/dist/ui/assets/wc-transcript-export-5Pmfejur.js +0 -2
- package/dist/ui/assets/wc-tray-BV-zy16U.js +0 -2
|
@@ -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-DWFfCVDH.js";import{a as l,c as u,d,f,h as p,i as m,l as h,m as g,n as _,p as v,r as y,s as b,t as x,u as S}from"./proxied-fetch-D8ebvbVd.js";import{a as C,i as w,n as T,r as E,s as D,t as ee}from"./src-BcePBv4G.js";import{$ as O,$t as te,An as k,At as A,Bt as j,Cn as M,Ct as ne,D as re,Dn as N,Dt as ie,E as ae,En as oe,Et as se,F as ce,Ft as P,G as F,Gt as le,Ht as ue,I as de,It as fe,J as pe,Jt as me,K as he,Kt as ge,L as I,Lt as L,Mn as _e,Mt as ve,Nn as R,Nt as ye,On as z,Ot as be,Pn as B,Pt as V,Q as xe,Qt as H,Rt as Se,Sn as Ce,St as U,Tn as we,Tt as Te,Ut as Ee,Vt as De,Wt as Oe,X as ke,Xt as Ae,Y as je,Yt as Me,Z as Ne,Zt as Pe,_n as Fe,_t as Ie,an as Le,at as Re,bn as ze,bt as Be,cn as Ve,ct as He,d as Ue,dn as We,dt as eee,en as Ge,et as Ke,fn as qe,ft as Je,gn as Ye,gt as Xe,hn as Ze,ht as Qe,in as tee,it as $e,jn as et,jt as tt,kn as nt,kt as rt,ln as it,lt as at,m as ot,mn as st,mt as ct,nn as W,nt as lt,on as ut,ot as dt,pn as ft,pt,q as mt,qt as ht,rn as gt,rt as _t,sn as vt,st as yt,tn as bt,tt as xt,un as G,ut as St,vn as Ct,vt as wt,w as Tt,wn as Et,wt as Dt,xn as Ot,xt as kt,yn as At,yt as jt,zt as Mt}from"./account-store-Be7SwcSO.js";import{t as Nt}from"./runtime-env-byAg9ij-.js";import{n as Pt,r as Ft,t as It}from"./fetch-body-DDu_AU5I.js";import{c as Lt,i as Rt,n as zt,o as Bt,r as Vt,s as Ht,t as Ut}from"./tray-follower-status-B191H1LK.js";import{a as Wt,i as Gt,n as Kt,r as qt}from"./transcript-limits-D0M7bLr9.js";import{n as Jt,o as Yt,s as Xt}from"./tool-ui-t6ocn6AG.js";import{a as Zt,i as Qt,n as $t,o as en,r as tn,t as nn}from"./backend-local-D4WZgy4J.js";import{t as rn}from"./types-idfTVsM8.js";import{n as an,t as on}from"./mime-types-D7IV6i7k.js";import{a as sn,i as cn,n as ln,r as un}from"./mount-BrgS-fqG.js";import{o as dn}from"./mount-table-store-CTrzlrNn.js";import{t as fn}from"./remote-cache-D59F5FOx.js";import{r as pn,t as mn}from"./mount-recovery-P3CO-Jh3.js";import{S as hn,a as gn,b as _n,g as vn,h as yn,i as bn,l as xn,m as Sn,n as Cn,o as wn,p as Tn,t as En,u as Dn,v as On,w as kn,x as An}from"./db-DjAqlQ2I.js";import{a as jn,n as Mn,r as Nn,s as Pn}from"./tray-runtime-config-GgP0BHji.js";import{a as Fn,i as In,n as Ln,o as Rn,r as zn}from"./runtime-mode-B8Tqab3Z.js";import{a as Bn,c as Vn,d as Hn,i as Un,l as Wn,n as Gn,o as Kn,s as qn,t as Jn,u as Yn}from"./lick-manager-wU1FKkH8.js";import{i as Xn,n as Zn,t as Qn}from"./path-utils-DU6QhF_k.js";import{u as $n}from"./transform-messages-Bp94o3FD.js";import{l as er,m as tr}from"./bedrock-camp-BO4bvAKs.js";import{t as nr}from"./__vite-browser-external-SwrSgYTf.js";import{a as rr,n as ir,r as nee}from"./fs-CfTHhKG8.js";import{a as ar,c as ree,i as K,n as iee,o as or,r as sr,s as cr}from"./cost-command-Cpg2Em0Q.js";import{a as lr,c as ur,d as dr,f as fr,i as pr,l as mr,m as hr,n as gr,o as _r,p as vr,r as yr,s as br,u as xr}from"./skills-BLTaKjRv.js";import{n as Sr,t as Cr}from"./llm-session-id-ZObKEXzb.js";import{a as wr,c as Tr,d as Er,f as Dr,i as Or,l as kr,n as Ar,o as jr,r as Mr,s as Nr,t as Pr,u as Fr}from"./installer-kDSMsl2T.js";import{n as Ir,t as Lr}from"./safe-buffer-C0pSmFaz.js";import{t as Rr}from"./global-db-DvmmimLY.js";import{a as zr,i as Br,r as Vr,t as Hr}from"./git-config-Lj0BT7Oc.js";import{t as Ur}from"./process-manager-B5dz0PkO.js";import{C as Wr,O as Gr,S as Kr,_ as qr,a as Jr,b as Yr,c as Xr,d as Zr,f as Qr,g as $r,h as ei,i as ti,k as ni,l as ri,m as ii,n as ai,o as oi,p as si,r as ci,s as li,t as ui,u as di,v as fi,x as pi,y as mi}from"./shared-pjIf7b3g.js";import{i as hi,r as gi,t as _i}from"./magick-wasm-Daq1kpb4.js";import{a as vi,i as yi,r as bi,t as xi}from"./script-catalog-BYXhqRAc.js";import{t as Si}from"./local-llm-8aAdS6D4.js";import{t as Ci}from"./client-BxYB_ioq.js";const wi=r(`cdp`);var Ti=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,wi.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(wi.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(),wi.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),wi.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;wi.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(wi.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;wi.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,wi.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):wi.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 Ei=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -4253,7 +4253,9 @@ ls -la /workspace/*.zip
|
|
|
4253
4253
|
- The local UI export ("Export transcript" in the avatar menu) produces the
|
|
4254
4254
|
same ZIP and triggers a browser download instead of writing to VFS.
|
|
4255
4255
|
- Followers (tray, Cherry) must request an export from the leader; the leader
|
|
4256
|
-
shows a one-time approval dialog before streaming the ZIP.
|
|
4256
|
+
shows a one-time approval dialog before streaming the ZIP. On a cloud
|
|
4257
|
+
(hosted-leader) session the leader is headless, so it delegates that prompt to
|
|
4258
|
+
the requesting follower — the approval appears on the user's own device.
|
|
4257
4259
|
`,Cb='---\nname: upgrade\ndescription: |\n Use this when you receive an `[Upgrade Event: x.y.z→a.b.c]` lick — fired on\n boot whenever the bundled SLICC version differs from the previous run. The\n lick renders a binary action card: `lick_confirm` to Update workspace files\n (three-way merge of bundled `vfs-root` files against the user\'s local edits)\n or `lick_dismiss` to clear it. Reviewing the changelog from GitHub is a\n separate step you can run first. Never auto-applies; the user resolves the\n card.\nallowed-tools: bash, read_file, write_file, edit_file\n---\n\n# Upgrade\n\nWhen SLICC boots and discovers that the bundled version (baked into the build at release time from the root `package.json`) differs from the version it was last seen running, it emits an `upgrade` lick to the cone. This skill describes how to react.\n\n## Event shape\n\nYou receive a message like:\n\n```text\n[Upgrade Event: 0.4.1→0.5.0]\n\nSLICC was upgraded from `0.4.1` to `0.5.0`.\nReleased: 2026-04-15T12:00:00Z\n\nUse the **upgrade** skill (...)\n```\n\nThe two version strings (`from`, `to`) are valid git tags on `https://github.com/ai-ecoverse/slicc` — the public source repository. The lick message carries a `Lick ID:` line — you resolve the card with that id.\n\n## What to do when you receive an upgrade lick\n\nThe runtime renders the upgrade lick as a binary action card automatically — you do not render a sprinkle. The card has exactly two outcomes, which you drive with the lick tools using the `Lick ID` from the message:\n\n- **`lick_confirm` → Update workspace files.** This is the primary action: run the three-way merge of bundled `vfs-root` content into the user\'s VFS (see below). Only confirm once the user has decided to pull the new files.\n- **`lick_dismiss` → clear the card.** Use this when the user wants to skip the merge; nothing is changed and the card mutes (✗). The lick will not fire again until the next upgrade.\n\nThe card flips to ✓ on confirm / muted ✗ on dismiss. Never auto-run the merge — the user must choose. Reviewing the changelog is **not** a card action; it is a separate step you can run first to help the user decide.\n\n## Changelog review (separate step — not a card action)\n\nBefore the user decides, you can fetch the GitHub compare API for the two tags and summarize the result. This is optional and independent of the card; it does not resolve the lick.\n\n```bash\n# The repo is public — no auth required for the compare endpoint.\ncurl -sSL "https://api.github.com/repos/ai-ecoverse/slicc/compare/v${FROM_VERSION}...v${TO_VERSION}" \\\n | node -e \'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const j=JSON.parse(s);console.log(j.commits.map(c=>"- "+c.commit.message.split("\\n")[0]).join("\\n"))})\'\n```\n\nShow the conventional-commit messages grouped by type (`feat`, `fix`, `chore`, ...). If the compare returns 404 (tags missing), fall back to the GitHub releases page URL: `https://github.com/ai-ecoverse/slicc/releases/tag/v${TO_VERSION}`.\n\n## Three-way merge (the `lick_confirm` / "Update workspace files" action)\n\nThe user\'s VFS may have local edits to bundled skills, sprinkles, or scripts. The three inputs to the merge are:\n\n- **base** = the bundled vfs-root file at the **previous** release tag (`v${FROM_VERSION}`). This is what the user originally received and is the common ancestor of both sides.\n- **ours** = the file currently in the user\'s VFS (which may equal `base` if untouched, or may carry local edits).\n- **theirs** = the bundled vfs-root file at the **new** release tag (`v${TO_VERSION}`).\n\nConcretely:\n\n1. Identify candidate paths under `/workspace/skills/` and `/shared/sprinkles/` that match bundled files. Per file:\n - Fetch `base` from `https://raw.githubusercontent.com/ai-ecoverse/slicc/v${FROM_VERSION}/packages/vfs-root/<rest-of-path>`.\n - Fetch `theirs` from `https://raw.githubusercontent.com/ai-ecoverse/slicc/v${TO_VERSION}/packages/vfs-root/<rest-of-path>`.\n - Read `ours` from the user\'s VFS at the equivalent runtime path (e.g. `/workspace/skills/<name>/SKILL.md`).\n2. Decide per file:\n - If `base == theirs`: nothing changed upstream → leave the user\'s file alone (no merge needed).\n - If `ours == base` and `base != theirs`: the user has not edited this file → safe fast-forward to `theirs`.\n - If `ours != base` and `base != theirs`: real 3-way merge. Write the three sides to `/tmp` and let `git merge-file` produce the result:\n ```bash\n git merge-file --stdout /tmp/ours /tmp/base /tmp/theirs > /tmp/merged\n ```\n Exit code 0 → clean merge; write `/tmp/merged` back to the VFS path. Non-zero exit means conflicts (`<<<<<<<` markers in the output) — surface the conflicting hunks and let the user pick.\n3. Present the per-file outcome as a summary table (`auto-applied`, `kept-local`, `needs-review`) and stop. Do not silently overwrite anything.\n\n## Do not\n\n- Do not run a merge before the user confirms. The merge runs only as the `lick_confirm` ("Update workspace files") action; if the user dismisses, do nothing.\n- Do not delete files that no longer exist in the new release — many users name-collide their own scripts with bundled ones; deletion is too dangerous to automate.\n- Do not modify files outside `/workspace/skills/`, `/shared/sprinkles/`, and `/shared/sounds/` without the user explicitly extending the scope.\n- Do not advance the bundled version marker yourself. The runtime advances it automatically once this lick has been routed; if the user dismisses, the lick will not fire again until the next upgrade.\n',wb=`---
|
|
4258
4260
|
name: welcome
|
|
4259
4261
|
description: |
|
|
@@ -5837,7 +5839,7 @@ Examples:
|
|
|
5837
5839
|
skill list
|
|
5838
5840
|
skill info bluebubbles
|
|
5839
5841
|
skill read bluebubbles
|
|
5840
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
5842
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-BLTaKjRv.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${_G()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:yG(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
5841
5843
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:bG(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
|
|
5842
5844
|
`,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+`
|
|
5843
5845
|
`,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 CG(e,t){let n=`${fW}/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(kW(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=Ft(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=KW(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 wG(e,t){let n=`${fW}/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: ${kW(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=Ft(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=KW(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 TG=[{label:`Tessl`,host:new URL(fW).host,fetch:CG},{label:`browse.sh`,host:new URL(pW).host,fetch:lG}];function EG(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 DG(e,t,n=1){let r=await Promise.allSettled(TG.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=EG(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=TG[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+=`
|
|
@@ -5863,7 +5865,7 @@ Examples:
|
|
|
5863
5865
|
`,{stdout:s,stderr:``,exitCode:0}}function PG(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
5864
5866
|
`,exitCode:1}:Vn(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
|
|
5865
5867
|
`,exitCode:1}}function FG(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`||!Wn(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
|
|
5866
|
-
`,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=PG(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 IG(e){let t=await(await import(`./skills-
|
|
5868
|
+
`,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=PG(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 IG(e){let t=await(await import(`./skills-BLTaKjRv.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${_G()}`,stderr:``,exitCode:0}:{stdout:yG(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function LG(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-BLTaKjRv.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);return e?{stdout:bG(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+`
|
|
5867
5869
|
`,stderr:``,exitCode:0}}async function RG(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 zW(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 zG(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 JW(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 BG(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await JW(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 VG(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 HG(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await PW(r),l=await qW(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:VG(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:VG(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 HW(i,a,r,o);if(e.status===`ok`){let r=await RG(u,i,a,UW(e.files),n,t.force,f);({output:p,errors:m,successCount:h}=r)}else{let e=await zG(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await BG(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 RW()),{stdout:p,stderr:m,exitCode:+!!m}}function UG(e,t,n){return K(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return xG();if(r[0]===`tabs`)return MG(e,t,n,r.includes(`--json`));if(r[0]===`recommendations`)return NG(e,t,r.includes(`--install`));if(r[0]===`list`)return IG(e);if(r[0]===`info`||r[0]===`read`)return LG(r[0],r[1],e);if(r[0]===`search`)return WG(r,t);let a=FG(r);if(a.earlyReturn)return a.earlyReturn;if(!a.sourceRef)return xG();if(a.sourceRef.startsWith(`tessl:`))return GG(a.sourceRef,a.force,e,t);let o=fG(a.sourceRef);if(o)return gG(o.hostname,o.task,e,t,a.force);let s=YW(a.sourceRef);return s?HG(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 WG(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?DG(a,t,i):xG()}async function GG(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
5868
5870
|
`,exitCode:1};let a=await wG(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await PW(r);return JW(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function KG(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
5869
5871
|
|
|
@@ -7103,7 +7105,7 @@ Common base URLs:
|
|
|
7103
7105
|
llama.cpp http://localhost:8080/v1
|
|
7104
7106
|
vLLM http://localhost:8000/v1
|
|
7105
7107
|
Jan http://localhost:1337/v1
|
|
7106
|
-
`}function l2(){return K(s2,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:c2(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-
|
|
7108
|
+
`}function l2(){return K(s2,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:c2(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-B7usvoJ-.js`),{verifyConnection:a}=await import(`./local-llm-8aAdS6D4.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(s2);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
7107
7109
|
`,exitCode:1};let c=await a(s,t(s2)??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(`
|
|
7108
7110
|
`)+`
|
|
7109
7111
|
`,exitCode:1}}if(o===`discover`){let e=n(s2)??``;return i(s2,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(`
|
|
@@ -7147,20 +7149,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
7147
7149
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
7148
7150
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
7149
7151
|
short name resolves on the PATH.
|
|
7150
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return g2(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return g2(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return g2(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
7152
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return g2(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return g2(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return g2(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-QmpK1UDU.js`).then(e=>e.r);if(await a(i,t.fs))return g2(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BxYB_ioq.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 b2(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>B2(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await K2(i,t);let m=await Y2(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-B-tRWluT.js`);e({name:i,serverUrl:r,auth:u})}return h2([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${m2}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
7151
7153
|
`)+`
|
|
7152
|
-
`)}async function b2(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await import(`./provider-settings-
|
|
7153
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
7154
|
+
`)}async function b2(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await import(`./provider-settings-B7usvoJ-.js`),c=await U2(r.oauthFetchImpl),l=r.oauthLauncher??await V2(),u=await i(e,n,c);p2.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await H2(),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function x2(e,t){if(e.includes(`--help`)||e.includes(`-h`))return h2(`usage: mcp list
|
|
7155
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-B-tRWluT.js`);await n();let{listServers:r}=await import(`./store-QmpK1UDU.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return h2("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 h2(S2(o))}function S2(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(`
|
|
7154
7156
|
`)+`
|
|
7155
7157
|
`}async function C2(e,t){if(e[0]===`--help`||e[0]===`-h`)return h2(`usage: mcp search <query>
|
|
7156
7158
|
|
|
7157
7159
|
Case-insensitive substring search across the cached tools of every
|
|
7158
7160
|
registered MCP server. Matches tool name OR description and prints a
|
|
7159
7161
|
table of (server, tool, description, match-field) rows.
|
|
7160
|
-
`);if(e.length===0)return g2(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
7161
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
7162
|
+
`);if(e.length===0)return g2(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-B-tRWluT.js`);await i();let{listServers:a}=await import(`./store-QmpK1UDU.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return h2("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 h2(`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,w2(e.description),e.match]);return h2(S2(l))}function w2(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function T2(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?g2(`mcp delete: expected <name>`):h2(`usage: mcp delete <name>
|
|
7163
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-B-tRWluT.js`);await r(n);let{deleteServer:a}=await import(`./store-QmpK1UDU.js`).then(e=>e.r),o=await a(n,t.fs);await q2(n,t),await J2(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./provider-settings-B7usvoJ-.js`);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){p2.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?g2(`mcp delete: no server, alias, or account found for "${n}"`):h2([`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(`
|
|
7162
7164
|
`)+`
|
|
7163
|
-
`)}async function E2(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?g2(`mcp invoke: expected <name>`):h2(k2());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
7165
|
+
`)}async function E2(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?g2(`mcp invoke: expected <name>`):h2(k2());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-B-tRWluT.js`);await i(n);let{getServer:a}=await import(`./store-QmpK1UDU.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return g2(`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 h2(A2(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return g2(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=D2(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return h2(j2(n,l));let p=M2(d,l.inputSchema);if(!p.ok)return g2(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-BxYB_ioq.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>B2(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=I2(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function D2(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=O2(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=O2(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 O2(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 k2(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
7164
7166
|
|
|
7165
7167
|
mcp invoke <name> List tools on <name>.
|
|
7166
7168
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -7190,7 +7192,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
7190
7192
|
|
|
7191
7193
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
7192
7194
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
7193
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
7195
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-B-tRWluT.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-QmpK1UDU.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return g2(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BxYB_ioq.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>B2(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return g2(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,sessionId:void 0,tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await Y2(n,d,t);return h2(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function R2(e,t){if(e.includes(`--help`)||e.includes(`-h`))return h2(`usage: mcp auth <name> [--silent | --interactive]
|
|
7194
7196
|
|
|
7195
7197
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
7196
7198
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -7202,7 +7204,7 @@ Options:
|
|
|
7202
7204
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
7203
7205
|
directly. Use after revoking a refresh token or
|
|
7204
7206
|
when the AS no longer accepts the cached one.
|
|
7205
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return g2(`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 g2(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
7207
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return g2(`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 g2(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-B-tRWluT.js`),s=await o(r),{getServer:c}=await import(`./store-QmpK1UDU.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return g2(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return g2(`mcp auth: server "${r}" does not use OAuth`);if(!s)return g2(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-DWFfCVDH.js`).then(e=>e.r),f=d(u);if(!f)return g2(`mcp auth: provider "${u}" is not registered`);if(a)return await z2(r,f,t);if(!f.onSilentRenew)return i?g2(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await z2(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 g2(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);p2.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?h2(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?g2(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await z2(r,f,t)}async function z2(e,t,n){if(!t.onOAuthLogin)return g2(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await V2(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?h2(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):g2(`mcp auth: interactive login for "${e}" did not complete`)}async function B2(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./provider-settings-B7usvoJ-.js`),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-DWFfCVDH.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){p2.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function V2(){let{createOAuthLauncher:e}=await import(`./oauth-service-BuEH8BXq.js`);return e()}async function H2(){if(Nt()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime?.id??``}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-BuEH8BXq.js`),{origin:t}=await e();return`${t}/auth/callback`}async function U2(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-D8ebvbVd.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 W2(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-CfTHhKG8.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 G2(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
7206
7208
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
7207
7209
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
7208
7210
|
const escape = (s) => {
|
|
@@ -7216,7 +7218,7 @@ const r = await exec(cmd);
|
|
|
7216
7218
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
7217
7219
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
7218
7220
|
process.exit(r.exitCode || 0);
|
|
7219
|
-
`}async function K2(e,t){let n=await W2(t.fs);await n.mkdir(m2,{recursive:!0}),await n.writeFile(`${m2}/${e}.jsh`,G2(e)),t.scriptCatalog?.invalidateJsh()}async function q2(e,t){let n=await W2(t.fs),r=`${m2}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){p2.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function J2(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
7221
|
+
`}async function K2(e,t){let n=await W2(t.fs);await n.mkdir(m2,{recursive:!0}),await n.writeFile(`${m2}/${e}.jsh`,G2(e)),t.scriptCatalog?.invalidateJsh()}async function q2(e,t){let n=await W2(t.fs),r=`${m2}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){p2.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function J2(e,t){let{removeAppSprinkles:n}=await import(`./apps-BF5YTR81.js`);await n(e,t.fs)}async function Y2(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-BF5YTR81.js`);return(await r(e,t,n.fs)).length}catch(t){return p2.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const X2=`/.cache/artificial-analysis.json`;async function Z2(e,t=!1){if(e&&!t)try{let t=await e.readFile(X2),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=_(),a;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(X2,JSON.stringify(t))}catch{}}return s}function Q2(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function $2(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=Q2(e),a=t.find(e=>Q2(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 e4(){return`models - list available LLM models
|
|
7220
7222
|
|
|
7221
7223
|
Usage: models [options]
|
|
7222
7224
|
|
|
@@ -7230,7 +7232,7 @@ Options:
|
|
|
7230
7232
|
-h, --help Show this help message
|
|
7231
7233
|
`}function t4(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function n4(e){return`$${e.toFixed(2)}`}const r4=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function i4(e){let t=`${e.id} ${e.name??``}`;return!r4.test(t)}function a4(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 o4(e){let t=new Map;for(let n of e){let e=a4(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function s4(e,t,n,r,i){let a=i?$2(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 c4(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=`${n4(e.cost.input)} / ${n4(e.cost.output)}`,a=`${t4(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(`
|
|
7232
7234
|
`)+`
|
|
7233
|
-
`}function l4(e){return K(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-
|
|
7235
|
+
`}function l4(e){return K(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-B7usvoJ-.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:e4(),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.
|
|
7234
7236
|
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await Z2(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(i4);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>s4(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=o4(n)),w.push(...n),!l){let t=i(e);T.push(c4(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
7235
7237
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
7236
7238
|
`);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(`
|
|
@@ -7270,7 +7272,7 @@ Examples:
|
|
|
7270
7272
|
oauth-domain add adobe '*.da.live'
|
|
7271
7273
|
oauth-domain list adobe
|
|
7272
7274
|
oauth-domain remove adobe admin.da.live
|
|
7273
|
-
`}function v4(){return K(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:_4(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-
|
|
7275
|
+
`}function v4(){return K(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:_4(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-B7usvoJ-.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(`
|
|
7274
7276
|
`)+`
|
|
7275
7277
|
`,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)
|
|
7276
7278
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -7334,7 +7336,7 @@ Examples:
|
|
|
7334
7336
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
7335
7337
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
7336
7338
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
7337
|
-
`}function b4(){return K(`oauth-token`,x4)}async function x4(e,t){let n=await import(`./provider-settings-
|
|
7339
|
+
`}function b4(){return K(`oauth-token`,x4)}async function x4(e,t){let n=await import(`./provider-settings-B7usvoJ-.js`),r=await import(`./providers-DWFfCVDH.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:y4(),stderr:``,exitCode:0};if(e.includes(`--list`))return U4(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return N4(e);if(e.includes(`--renew`))return P4(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return I4(e,t);let i=S4(e);if(!i.ok)return i.result;let a=C4(e,n,r);if(!a.ok)return a.result;let o=T4(a.value,r.getRegisteredProviderConfig);if(!o.ok)return o.result;if(!i.value){let e=await E4(a.value,o.value,n.getOAuthAccountInfo);if(e)return e}return O4(a.value,o.value,i.value,n.getOAuthAccountInfo)}function S4(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:H4(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function C4(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:H4(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(w4(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>w4(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:H4(`oauth-token: no OAuth providers configured`)}}function w4(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function T4(e,t){let n=t(e);return n?w4(n)?{ok:!0,value:n}:{ok:!1,result:H4(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:H4(`oauth-token: unknown provider "${e}"`)}}async function E4(e,t,n){let r=n(e);return r&&!r.expired?D4(e,r.maskedValue):!r?.expired||!t.onSilentRenew?null:j4(e,t.onSilentRenew,n)}function D4(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:H4(`oauth-token: no masked value for ${e} (try logging in again)`)}async function O4(e,t,n,r){try{return await k4(e,t,n)||A4(e,r)}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`[oauth-token] Provider ${e}: login failed:`,n),H4(`oauth-token: login failed: ${n}`)}}async function k4(e,t,n){let r=n?{scopes:n}:void 0;if(t.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:n}=await import(`./oauth-service-BuEH8BXq.js`),i=await n();return i?(await t.onOAuthLoginIntercepted(i,()=>{},r),null):H4(`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-BuEH8BXq.js`);return await t.onOAuthLogin(e(),()=>{},r),null}return H4(`oauth-token: provider "${e}" has no OAuth login hook`)}function A4(e,t){let n=t(e);return n?.token?D4(e,n.maskedValue):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),H4(`oauth-token: login completed but no token was saved`))}async function j4(e,t,n){try{return await t()===null?null:D4(e,n(e)?.maskedValue)}catch{return null}}function M4(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 N4(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./provider-settings-B7usvoJ-.js`),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-DWFfCVDH.js`).then(e=>e.r),o=M4(e,n,i,a);if(!o)return H4(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return H4(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return H4(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return H4(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return H4(`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 P4(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-B7usvoJ-.js`),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-DWFfCVDH.js`).then(e=>e.r),a=M4(e,t,r,i);if(!a)return H4(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return H4(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return H4(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${F4(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: ${F4(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(`
|
|
7338
7340
|
`)+`
|
|
7339
7341
|
`,stderr:``,exitCode:+!u}}function F4(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 I4(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-BuEH8BXq.js`),i=await L4(e,t);if(!i.ok)return i.result;let a=n(i.value);if(!a.ok)return H4(`oauth-token: invalid intercept config: ${a.error}`);let o=await r();if(!o)return H4(`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}:H4(`oauth-token: intercept timed out or was cancelled`)}function L4(e,t){let n=e.indexOf(`--from-file`);return n>=0?R4(e[n+1],t):z4(e)}async function R4(e,t){if(!e)return{ok:!1,result:H4(`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:H4(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function z4(e){let t=V4(e,`--authorize-url`),n=V4(e,`--redirect-pattern`);if(!t)return{ok:!1,result:H4(`oauth-token: --authorize-url is required`)};if(!n)return{ok:!1,result:H4(`oauth-token: --redirect-pattern is required`)};let r=B4(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 B4(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:H4(`oauth-token: --rewrite requires a value`)};let i=r.split(`=`);if(i.length<3)return{ok:!1,result:H4(`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 V4(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function H4(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function U4(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
7340
7342
|
`,stderr:``,exitCode:0};let a=[];for(let e of i){let t=r(e);if(!t)a.push(`${e} (no token)`);else if(t.expired){let n=t.userName?` as ${t.userName}`:``;a.push(`${e} (expired${n})`)}else{let n=[];if(t.userName?n.push(`logged in as ${t.userName}`):n.push(`logged in`),t.expiresAt){let e=t.expiresAt-Date.now();if(e>0){let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4);t>0?n.push(`expires in ${t}h`):n.push(`expires in ${r}m`)}}a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
|
|
@@ -8975,7 +8977,7 @@ ${e}
|
|
|
8975
8977
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
8976
8978
|
${t}
|
|
8977
8979
|
---`);let a=zb(n);return a&&(i+=a),i}};const L9=r(`scoop-lifecycle-manager`);var Jne=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 nee(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 qne(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),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=[]){let a=this.contexts.get(e);a||=(await this.createTab(e),this.contexts.get(e));let o=this.tabs.get(e);if(o?.status===`initializing`){if(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}a=this.contexts.get(e),o=this.tabs.get(e)}if(!a){L9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),o&&(o.status=`processing`,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),L9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await a.prompt(t,i)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),L9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||Ht(`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)),Ht(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let 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}),Ht(`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 Yne=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e)}async handleMessage(e){if(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}`);Ht(`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}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){R9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.deps.getTabs().get(e.chatJid);if(R9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){R9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),i=this.deps.getTabs().get(e.chatJid)}catch{R9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){R9.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){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);if(R9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){R9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${i_(e.content,e.attachments)}`).join(`
|
|
8978
|
-
`),c=o.flatMap(e=>a_(e.attachments));this.messageQueues.set(e,[]);let l=o[o.length-1];this.lastAgentTimestamp.set(e,l.timestamp),await this.deps.db.setState(`lastAgentTs_${e}`,l.timestamp),await this.deps.sendPrompt(e,s,l.senderId,l.senderName,c)}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys())this.deps.getTabs().get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);R9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{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,[]),R9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){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.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),R9.info(`All messages cleared`)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await this.deps.db.deleteMessage(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await this.deps.db.deleteMessage(t)}};const z9=r(`orchestrator`);var Xne=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Wb({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new dx({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new lx({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new ax({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 Zb({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Tn(e),saveMessage:e=>_n(e)});lickRegistry=new qb({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 Yne({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i??[]),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>_n(e),deleteMessage:e=>bn(e),clearMessagesForScoop:e=>Cn(e),clearAllMessages:()=>En(),getMessagesSince:(e,t,n)=>Sn(e,t,n),setState:(e,t)=>kn(e,t)},isExternalLickChannel:Yi});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Jne({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=>An(e),deleteScoop:e=>gn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Jn(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await On(),this.sharedFs=await ir.create({dbName:`slicc-fs`}),this.sessionStore=new c_,this.fsWatcher=new rr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new hv({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await xn();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await yn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Yb({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)}sr(()=>this.getSessionCosts()),this.unregisterExportService=_v(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=>Gn(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 ir.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await Bb(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 hv({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 Tn(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&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 pa,t=this.sharedFs;return new Ry({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:nb(),snapshotStore:{read:e=>Yy(t,e),write:(e,n)=>Jy(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:`5.77.0`})}};function Zne(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var Qne=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 rn(`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 rn(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new rn(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new rn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new rn(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new rn(`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 rn(`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 rn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new rn(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new rn(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new rn(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new rn(`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 rn(`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 ire(t);let n=this.pm.get(e);switch(t){case`status`:return $ne(n);case`cmdline`:return ere(n);case`cwd`:return tre(n);case`stat`:return nre(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 $ne(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${rre(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(`
|
|
8980
|
+
`),c=o.flatMap(e=>a_(e.attachments));this.messageQueues.set(e,[]);let l=o[o.length-1];this.lastAgentTimestamp.set(e,l.timestamp),await this.deps.db.setState(`lastAgentTs_${e}`,l.timestamp),await this.deps.sendPrompt(e,s,l.senderId,l.senderName,c)}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys())this.deps.getTabs().get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);R9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{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,[]),R9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){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.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),R9.info(`All messages cleared`)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await this.deps.db.deleteMessage(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await this.deps.db.deleteMessage(t)}};const z9=r(`orchestrator`);var Xne=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Wb({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new dx({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new lx({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new ax({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 Zb({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Tn(e),saveMessage:e=>_n(e)});lickRegistry=new qb({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 Yne({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i??[]),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>_n(e),deleteMessage:e=>bn(e),clearMessagesForScoop:e=>Cn(e),clearAllMessages:()=>En(),getMessagesSince:(e,t,n)=>Sn(e,t,n),setState:(e,t)=>kn(e,t)},isExternalLickChannel:Yi});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Jne({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=>An(e),deleteScoop:e=>gn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Jn(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await On(),this.sharedFs=await ir.create({dbName:`slicc-fs`}),this.sessionStore=new c_,this.fsWatcher=new rr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new hv({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await xn();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await yn(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Yb({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)}sr(()=>this.getSessionCosts()),this.unregisterExportService=_v(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=>Gn(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 ir.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await Bb(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 hv({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 Tn(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&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 pa,t=this.sharedFs;return new Ry({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:nb(),snapshotStore:{read:e=>Yy(t,e),write:(e,n)=>Jy(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:`5.78.0`})}};function Zne(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var Qne=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 rn(`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 rn(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new rn(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new rn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new rn(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new rn(`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 rn(`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 rn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new rn(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new rn(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new rn(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new rn(`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 rn(`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 ire(t);let n=this.pm.get(e);switch(t){case`status`:return $ne(n);case`cmdline`:return ere(n);case`cwd`:return tre(n);case`stat`:return nre(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 $ne(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${rre(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(`
|
|
8979
8981
|
`)+`
|
|
8980
8982
|
`}function ere(e){return e.argv.join(`\0`)+`\0`}function tre(e){return e.cwd+`
|
|
8981
8983
|
`}function nre(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
@@ -8984,4 +8986,4 @@ ${t}
|
|
|
8984
8986
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
8985
8987
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
8986
8988
|
`}}function are(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return typeof n==`string`&&/^E[A-Z]+$/.test(n)?{ok:!1,errno:n,message:t}:{ok:!1,errno:`EIO`,message:t}}async function ore(e){let t=iU(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return are(e)}}function sre(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(pB(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(!iU(n.token))return;let a=i.get(n.id);if(a){r({type:mB,id:n.id}),a.result&&r({type:hB,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:mB,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),3e4),r({type:hB,id:n.id,...e})};ore(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 cre(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 lre(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 ure(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}dre(e,t)}function dre(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=ca(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=cre(e),a=lre(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 fre(e,t,n,r){let i=new Ur,a=new Xne(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=Rn(()=>n.emitTrayRuntimeStatus()),s=Vt(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function pre(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-Cpg2Em0Q.js`).then(e=>e.t);r(()=>e.getSessionCosts());let{getLickManager:i}=await import(`./lick-manager-wU1FKkH8.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??ure,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function mre(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 hre(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;ste({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>aW(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>f9().slice(10,22),splitResult:(e,t)=>p9(e,t)})}async function gre(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))+`
|
|
8987
|
-
`,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 _re(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-CFKIh9aE.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 vre(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 oee(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})},yre(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function yre(e){let t=_();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:()=>Zne()}}function bre(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-CDcDil6x.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 xre(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-ChCeiPPt.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 Sre(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.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 Cre(){return R()}async function wre(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 fre(t,n,r,i);if(d?x_(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new Qne(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await pre(c,e,o);d&&hre({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await gre({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;Cre()&&(h=await _re(f,o,e.localLickWsUrl??null));let g=vre(n,f,o);d&&bre(d,f,o),a||await mre(c),d&&xre(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await Sre(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=sre({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 Tre({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 Tre(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)}Ere({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Ere(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 W9=`x-bypass-llm-proxy`;function Dre(e,t,n){return t?(r,i)=>{if(!Ore(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(W9)||a.set(W9,`1`),e(r,{...i,headers:a})}:e}function Ore(e,t,n){if(Are(e,t))return!0;let r=n?.()??null;return r?kre(e,r,t):!1}function kre(e,t,n){let r=G9(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 Are(e,t){let n=G9(e);try{return new URL(n,t).origin===t}catch{return!0}}function G9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function jre(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 Mre=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(!Nre(e)||e.source!==`panel`)return;let t=e.payload;Pre(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?K9(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,K9(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 Nre(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function K9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function Pre(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 Fre=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 Ire(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new Mre({transport:t,processManager:i,createShell:(e,a)=>new Fre(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 Lre(e){let t=new Rre(e);return t.start(),{stop:()=>t.dispose()}}var Rre=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(!zre(e)||e.source!==`panel`)return;let t=e.payload;if(Bre(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(q9(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 rn(`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 rn(`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(Vre(e.type),e.requestId,new rn(`EACCES`,`vfs-rpc-host has no writable backend wired`),Hre(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 rn(`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 rn(`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 rn(`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 zre(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Bre(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 q9(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 Vre(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 Hre(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof rn?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Ure(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Dre(e.bind(globalThis),t,Wre)}function Wre(){let e=m();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Gre(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 Kre=jre(e=>qre(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Kre.handle(e.data)});async function qre(e){Vi(e.instanceId);try{Ure(),S(e.localApiBaseUrl??null),u(e.bridgeToken??null),$U(e.syncFsBridgeEnabled??!1),h(e.extensionDelegateId??null),Gre(e.localStorageSeed??{}),Rt().catch(()=>{}),await s();let t=Ki(e.kernelPort),n=new Ca(t),r=Ca.createCallbacks(n),a=new qi(e.cdpPort);await a.connect();let o=new ji(a);Y9=await wre({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 d=Y9.sharedFs?.getWatcher();if(d){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)d.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:f}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=f({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider(Li(i));let p=await Jre({host:Y9,transport:t,browser:o,instanceId:e.instanceId});p&&(X9=p.stopTerminalHost,Z9=p.stopVfsRpcHost,Q9=p.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Ui(e),e}}async function Jre(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=Ire({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Lre({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Yre(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Yre(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DGq5bX3t.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-D8ebvbVd.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())});
|
|
8989
|
+
`,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 _re(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-CFKIh9aE.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 vre(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 oee(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})},yre(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function yre(e){let t=_();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:()=>Zne()}}function bre(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-P3CO-Jh3.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 xre(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-B2NfyFQR.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 Sre(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.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 Cre(){return R()}async function wre(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 fre(t,n,r,i);if(d?x_(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new Qne(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await pre(c,e,o);d&&hre({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await gre({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;Cre()&&(h=await _re(f,o,e.localLickWsUrl??null));let g=vre(n,f,o);d&&bre(d,f,o),a||await mre(c),d&&xre(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await Sre(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=sre({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 Tre({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 Tre(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)}Ere({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Ere(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 W9=`x-bypass-llm-proxy`;function Dre(e,t,n){return t?(r,i)=>{if(!Ore(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(W9)||a.set(W9,`1`),e(r,{...i,headers:a})}:e}function Ore(e,t,n){if(Are(e,t))return!0;let r=n?.()??null;return r?kre(e,r,t):!1}function kre(e,t,n){let r=G9(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 Are(e,t){let n=G9(e);try{return new URL(n,t).origin===t}catch{return!0}}function G9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function jre(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 Mre=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(!Nre(e)||e.source!==`panel`)return;let t=e.payload;Pre(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?K9(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,K9(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 Nre(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function K9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function Pre(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 Fre=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 Ire(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new Mre({transport:t,processManager:i,createShell:(e,a)=>new Fre(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 Lre(e){let t=new Rre(e);return t.start(),{stop:()=>t.dispose()}}var Rre=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(!zre(e)||e.source!==`panel`)return;let t=e.payload;if(Bre(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(q9(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 rn(`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 rn(`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(Vre(e.type),e.requestId,new rn(`EACCES`,`vfs-rpc-host has no writable backend wired`),Hre(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 rn(`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 rn(`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 rn(`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 zre(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Bre(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 q9(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 Vre(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 Hre(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof rn?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Ure(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Dre(e.bind(globalThis),t,Wre)}function Wre(){let e=m();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Gre(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 Kre=jre(e=>qre(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Kre.handle(e.data)});async function qre(e){Vi(e.instanceId);try{Ure(),S(e.localApiBaseUrl??null),u(e.bridgeToken??null),$U(e.syncFsBridgeEnabled??!1),h(e.extensionDelegateId??null),Gre(e.localStorageSeed??{}),Rt().catch(()=>{}),await s();let t=Ki(e.kernelPort),n=new Ca(t),r=Ca.createCallbacks(n),a=new qi(e.cdpPort);await a.connect();let o=new ji(a);Y9=await wre({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 d=Y9.sharedFs?.getWatcher();if(d){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)d.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:f}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=f({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider(Li(i));let p=await Jre({host:Y9,transport:t,browser:o,instanceId:e.instanceId});p&&(X9=p.stopTerminalHost,Z9=p.stopVfsRpcHost,Q9=p.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Ui(e),e}}async function Jre(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=Ire({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Lre({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Yre(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Yre(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DGq5bX3t.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-D8ebvbVd.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())});
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./logger-LESFN7Hj.js";import{b as n}from"./account-store-
|
|
1
|
+
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./logger-LESFN7Hj.js";import{b as n}from"./account-store-Be7SwcSO.js";import{n as r}from"./event-stream-qbAZIAKV.js";import{p as i}from"./bedrock-camp-BO4bvAKs.js";import{r as a,s as o}from"./legacy-api-aliases-sqlB2uHc.js";var s=e({config:()=>d,detectRuntime:()=>C,discoverModels:()=>S,originOf:()=>b,register:()=>y,verifyConnection:()=>E});const c=t(`local-llm`),l=`local-llm`,u=`${l}-unconfigured`,d={id:l,name:`Local LLM (OpenAI-compatible)`,description:[`Connect to any OpenAI-compatible local model server.`,``,`Common base URLs:`,` • Ollama http://localhost:11434/v1`,` • LM Studio http://localhost:1234/v1`,` • llama.cpp http://localhost:8080/v1`,` • vLLM http://localhost:8000/v1`,` • mlx_lm http://localhost:8080/v1`,` • Jan http://localhost:1337/v1`,``,`Ollama needs OLLAMA_ORIGINS=* (or chrome-extension://*) so the`,`browser can reach it. macOS: launchctl setenv OLLAMA_ORIGINS "*".`].join(`
|
|
2
2
|
`),requiresApiKey:!1,optionalApiKey:!0,apiKeyPlaceholder:`Leave empty for local servers, or paste a key for hosted endpoints`,apiKeyEnvVar:`LOCAL_LLM_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`http://localhost:11434/v1`,baseUrlDescription:`Ollama: 11434 • LM Studio: 1234 • llama.cpp/mlx: 8080 • vLLM: 8000 • Jan: 1337. Trailing /v1 required.`,requiresDeployment:!0,deploymentPlaceholder:`llama3.1:8b, qwen2.5-coder:14b`,deploymentDescription:`Comma-separated model IDs from your server. List them with: curl <baseUrl>/models | jq -r .data[].id`,getModelIds:()=>{let e=f(n(l));return e.length===0?[{id:u,name:`Local LLM (set base URL + model IDs in Settings)`,api:`openai`}]:e.map(e=>({id:e,name:e,api:`openai`,input:[`text`],context_window:32e3,max_tokens:4096}))}};function f(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const p=`${l}-openai`;function m(e){return{...e,api:`openai-completions`}}function h(e){let t=e??{};return!t.apiKey||t.apiKey.length===0?{...t,apiKey:`local`}:t}const g=(e,t,n={})=>e.id===u?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?a(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`),_=(e,t,n)=>e.id===u?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?o(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`);function v(e,t){let n=r(),i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t,timestamp:Date.now()};return queueMicrotask(()=>{n.push({type:`error`,reason:`error`,error:i}),n.end()}),n}function y(){i({api:p,stream:g,streamSimple:_})}function b(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e.replace(/\/v1\/?$/,``).replace(/\/+$/,``)}}function x(e){let t=e.replace(/\/+$/,``);try{let e=new URL(t);if(e.pathname===``||e.pathname===`/`)return`${t}/v1`}catch{}return t}async function S(e,t,n){let r=`${x(e)}/models`,i={Accept:`application/json`};t&&t.length>0&&(i.Authorization=`Bearer ${t}`);let a=await fetch(r,{method:`GET`,headers:i,signal:n});if(!a.ok)throw Error(`GET ${r} -> ${a.status} ${a.statusText}`);let o=await a.json();return Array.isArray(o.data)?o.data.map(e=>e.id??``).filter(e=>e.length>0):[]}async function C(e,t){let n=b(e),r=await T(`${n}/api/version`,t);if(r&&typeof r.version==`string`)return{kind:`ollama`,version:r.version};let i=await T(`${n}/api/v0/models`,t);if(i&&i.object===`list`)return{kind:`lmstudio`};let a=await T(`${n}/props`,t);if(a&&`build_info`in a)return{kind:`llamacpp`,version:a.build_info?.version};let o=w(e);return o===`11434`?{kind:`ollama`}:o===`1234`?{kind:`lmstudio`}:o===`8000`?{kind:`vllm`}:o===`1337`?{kind:`jan`}:{kind:`unknown`}}function w(e){try{return new URL(e).port||null}catch{return null}}async function T(e,t){try{let n=await fetch(e,{method:`GET`,signal:t});return n.ok?await n.json():null}catch{return null}}async function E(e,t,n){let r={kind:`unknown`};try{r=await C(e,n)}catch{}try{let i=await S(e,t,n);return{ok:!0,runtime:r,models:i}}catch(t){let n=t instanceof Error?t.message:String(t),i=D(n,r.kind);return c.warn(`verifyConnection failed`,{baseUrl:e,runtime:r.kind,message:n}),{ok:!1,runtime:r,models:[],error:i}}}function D(e,t){let n=e.toLowerCase();return n.includes(`failed to fetch`)||n.includes(`networkerror`)?t===`ollama`?{kind:`cors`,message:e,hint:'Ollama rejects requests from non-localhost origins by default. Set OLLAMA_ORIGINS=* (or chrome-extension://*) and restart Ollama. macOS: `launchctl setenv OLLAMA_ORIGINS "*"` then quit and relaunch the Ollama app.'}:{kind:`connection`,message:e,hint:`Server unreachable. Check the URL and that the server is running.`}:n.includes(` 401`)||n.includes(` 403`)?{kind:`auth`,message:e,hint:`Server returned an auth error. If your endpoint requires a key, set it in Settings.`}:/-> \d{3} /.test(e)?{kind:`http`,message:e}:{kind:`unknown`,message:e}}export{s as n,d as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as e}from"./account-store-
|
|
1
|
+
import{b as e}from"./account-store-DTWDY802.js";import{n as t}from"./event-stream-qbAZIAKV.js";import{a as n}from"./compat-aVSWLlYQ.js";import{r,s as i}from"./legacy-api-aliases-IllWZ-uu.js";import{t as a}from"./logger-DDBAeTLF.js";var o=a(`local-llm`),s=`local-llm`,c=`local`,l=`${s}-unconfigured`,u={id:s,name:`Local LLM (OpenAI-compatible)`,description:[`Connect to any OpenAI-compatible local model server.`,``,`Common base URLs:`,` • Ollama http://localhost:11434/v1`,` • LM Studio http://localhost:1234/v1`,` • llama.cpp http://localhost:8080/v1`,` • vLLM http://localhost:8000/v1`,` • mlx_lm http://localhost:8080/v1`,` • Jan http://localhost:1337/v1`,``,`Ollama needs OLLAMA_ORIGINS=* (or chrome-extension://*) so the`,`browser can reach it. macOS: launchctl setenv OLLAMA_ORIGINS "*".`].join(`
|
|
2
2
|
`),requiresApiKey:!1,optionalApiKey:!0,apiKeyPlaceholder:`Leave empty for local servers, or paste a key for hosted endpoints`,apiKeyEnvVar:`LOCAL_LLM_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`http://localhost:11434/v1`,baseUrlDescription:`Ollama: 11434 • LM Studio: 1234 • llama.cpp/mlx: 8080 • vLLM: 8000 • Jan: 1337. Trailing /v1 required.`,requiresDeployment:!0,deploymentPlaceholder:`llama3.1:8b, qwen2.5-coder:14b`,deploymentDescription:`Comma-separated model IDs from your server. List them with: curl <baseUrl>/models | jq -r .data[].id`,getModelIds:()=>{let t=d(e(s));return t.length===0?[{id:l,name:`Local LLM (set base URL + model IDs in Settings)`,api:`openai`}]:t.map(e=>({id:e,name:e,api:`openai`,input:[`text`],context_window:32e3,max_tokens:4096}))}};function d(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}var f=`openai-completions`,p=`${s}-openai`;function m(e){return{...e,api:f}}function h(e){let t=e??{};return!t.apiKey||t.apiKey.length===0?{...t,apiKey:c}:t}var g=(e,t,n={})=>e.id===l?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?r(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`),_=(e,t,n)=>e.id===l?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?i(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`);function v(e,n){let r=t(),i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:n,timestamp:Date.now()};return queueMicrotask(()=>{r.push({type:`error`,reason:`error`,error:i}),r.end()}),r}function y(){n({api:p,stream:g,streamSimple:_})}function b(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e.replace(/\/v1\/?$/,``).replace(/\/+$/,``)}}function x(e){let t=e.replace(/\/+$/,``);try{let e=new URL(t);if(e.pathname===``||e.pathname===`/`)return`${t}/v1`}catch{}return t}async function S(e,t,n){let r=`${x(e)}/models`,i={Accept:`application/json`};t&&t.length>0&&(i.Authorization=`Bearer ${t}`);let a=await fetch(r,{method:`GET`,headers:i,signal:n});if(!a.ok)throw Error(`GET ${r} -> ${a.status} ${a.statusText}`);let o=await a.json();return Array.isArray(o.data)?o.data.map(e=>e.id??``).filter(e=>e.length>0):[]}async function C(e,t){let n=b(e),r=await T(`${n}/api/version`,t);if(r&&typeof r.version==`string`)return{kind:`ollama`,version:r.version};let i=await T(`${n}/api/v0/models`,t);if(i&&i.object===`list`)return{kind:`lmstudio`};let a=await T(`${n}/props`,t);if(a&&`build_info`in a)return{kind:`llamacpp`,version:a.build_info?.version};let o=w(e);return o===`11434`?{kind:`ollama`}:o===`1234`?{kind:`lmstudio`}:o===`8000`?{kind:`vllm`}:o===`1337`?{kind:`jan`}:{kind:`unknown`}}function w(e){try{return new URL(e).port||null}catch{return null}}async function T(e,t){try{let n=await fetch(e,{method:`GET`,signal:t});return n.ok?await n.json():null}catch{return null}}async function E(e,t,n){let r={kind:`unknown`};try{r=await C(e,n)}catch{}try{let i=await S(e,t,n);return{ok:!0,runtime:r,models:i}}catch(t){let n=t instanceof Error?t.message:String(t),i=D(n,r.kind);return o.warn(`verifyConnection failed`,{baseUrl:e,runtime:r.kind,message:n}),{ok:!1,runtime:r,models:[],error:i}}}function D(e,t){let n=e.toLowerCase();return n.includes(`failed to fetch`)||n.includes(`networkerror`)?t===`ollama`?{kind:`cors`,message:e,hint:'Ollama rejects requests from non-localhost origins by default. Set OLLAMA_ORIGINS=* (or chrome-extension://*) and restart Ollama. macOS: `launchctl setenv OLLAMA_ORIGINS "*"` then quit and relaunch the Ollama app.'}:{kind:`connection`,message:e,hint:`Server unreachable. Check the URL and that the server is running.`}:n.includes(` 401`)||n.includes(` 403`)?{kind:`auth`,message:e,hint:`Server returned an auth error. If your endpoint requires a key, set it in Settings.`}:/-> \d{3} /.test(e)?{kind:`http`,message:e}:{kind:`unknown`,message:e}}export{u as config,C as detectRuntime,S as discoverModels,b as originOf,y as register,E as verifyConnection};
|