@rtc-agent/component 0.3.3-rc.0 → 0.3.4-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{index.browser-CSVSBYm8.js → index.browser--lCoayDv.js} +2 -2
- package/dist/assets/{shared-worker-CvhUb451.js → shared-worker-Cqq_7YGD.js} +7482 -7500
- package/dist/{en-US-CSw9aKfI.js → en-US-CnYTczGF.js} +1 -1
- package/dist/{highlight-languages-B_Aeh-d5.js → highlight-languages-B80SN_bH.js} +1 -1
- package/dist/{index-C7C2NsSr.js → index-DbBD1iUE.js} +5 -5
- package/dist/index.js +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/stats.html +1 -1
- package/package.json +5 -5
|
@@ -8355,7 +8355,7 @@ const x6 = (t) => (u6((e, r) => v6(rk, e, r)), Tm = tk = t.sourceLocale, Em = ne
|
|
|
8355
8355
|
}), zl.reject(n));
|
|
8356
8356
|
}), zl.promise;
|
|
8357
8357
|
}, nk = Gt("I18n"), Ht = "zh-CN", Ar = ["en-US"], pw = {
|
|
8358
|
-
"en-US": async () => (await import("./en-US-
|
|
8358
|
+
"en-US": async () => (await import("./en-US-CnYTczGF.js")).default
|
|
8359
8359
|
}, { getLocale: Iv, setLocale: ik } = x6({
|
|
8360
8360
|
sourceLocale: Ht,
|
|
8361
8361
|
targetLocales: Ar,
|
|
@@ -69502,7 +69502,7 @@ class Pq {
|
|
|
69502
69502
|
}
|
|
69503
69503
|
function fP(t) {
|
|
69504
69504
|
return new SharedWorker(
|
|
69505
|
-
"" + new URL("assets/shared-worker-
|
|
69505
|
+
"" + new URL("assets/shared-worker-Cqq_7YGD.js", import.meta.url).href,
|
|
69506
69506
|
{
|
|
69507
69507
|
type: "module",
|
|
69508
69508
|
name: t == null ? void 0 : t.name
|
|
@@ -81708,7 +81708,7 @@ let Ps = class extends ur {
|
|
|
81708
81708
|
const [e, r, n] = await Promise.all([
|
|
81709
81709
|
import("./marked.esm-Dch69AxC.js"),
|
|
81710
81710
|
import("./purify.es-C-6FFqDW.js"),
|
|
81711
|
-
import("./highlight-languages-
|
|
81711
|
+
import("./highlight-languages-B80SN_bH.js")
|
|
81712
81712
|
]);
|
|
81713
81713
|
return {
|
|
81714
81714
|
marked: e.marked,
|
|
@@ -85059,7 +85059,7 @@ let bl = class extends ur {
|
|
|
85059
85059
|
const [e, r, n] = await Promise.all([
|
|
85060
85060
|
import("./marked.esm-Dch69AxC.js"),
|
|
85061
85061
|
import("./purify.es-C-6FFqDW.js"),
|
|
85062
|
-
import("./highlight-languages-
|
|
85062
|
+
import("./highlight-languages-B80SN_bH.js")
|
|
85063
85063
|
]);
|
|
85064
85064
|
return {
|
|
85065
85065
|
marked: e.marked,
|
|
@@ -97322,7 +97322,7 @@ function _G(t) {
|
|
|
97322
97322
|
}
|
|
97323
97323
|
let xv = null, wv = null, Sv = null;
|
|
97324
97324
|
async function xG() {
|
|
97325
|
-
return xv || (xv = (await import("./marked.esm-Dch69AxC.js")).marked), wv || (wv = (await import("./purify.es-C-6FFqDW.js")).default), Sv || (Sv = (await import("./highlight-languages-
|
|
97325
|
+
return xv || (xv = (await import("./marked.esm-Dch69AxC.js")).marked), wv || (wv = (await import("./purify.es-C-6FFqDW.js")).default), Sv || (Sv = (await import("./highlight-languages-B80SN_bH.js")).default), { marked: xv, DOMPurify: wv, hljs: Sv };
|
|
97326
97326
|
}
|
|
97327
97327
|
function wG(t, e) {
|
|
97328
97328
|
return t.replace(
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as s, D as t, a as o, E as n, F as r, b as i, R as c, S as l, c as d, d as T, e as g, f as m, h as L, i as h, j as A, k as u, l as F, m as S, n as p, o as C, p as E, q as v, r as I, t as R, u as f, v as w, w as x, x as B, y, z as V, A as _, B as z, G as M, H as P, I as k, J as D, K as G, L as O, M as U, N as b, O as K, P as N, Q as j, T as q } from "./index-
|
|
1
|
+
import { C as s, D as t, a as o, E as n, F as r, b as i, R as c, S as l, c as d, d as T, e as g, f as m, h as L, i as h, j as A, k as u, l as F, m as S, n as p, o as C, p as E, q as v, r as I, t as R, u as f, v as w, w as x, x as B, y, z as V, A as _, B as z, G as M, H as P, I as k, J as D, K as G, L as O, M as U, N as b, O as K, P as N, Q as j, T as q } from "./index-DbBD1iUE.js";
|
|
2
2
|
export {
|
|
3
3
|
s as CancelledError,
|
|
4
4
|
t as DEFAULT_ACTIVITY_BAR_CONFIG,
|
package/dist/index.umd.js
CHANGED
|
@@ -3310,7 +3310,7 @@ Name: ${r}
|
|
|
3310
3310
|
|
|
3311
3311
|
You can now run this script using:
|
|
3312
3312
|
- action: "run", name: "${r}"
|
|
3313
|
-
- Or reference it by path: ${s}`}}catch(s){return{success:!1,error:`Failed to save script: ${s instanceof Error?s.message:String(s)}`}}}async _runScript(e){const r=pi(e,"name");if(!r)return{success:!1,error:"name is required for run action"};const n=e.params||{},i=ga(e,"timeout")??3e4,s=pi(e,"title")??void 0;return this._executeCode(r,n,i,void 0,s)}async _evalScript(e){const r=pi(e,"code");if(!r)return{success:!1,error:"code is required for eval action"};const n=e.params||{},i=ga(e,"timeout")??3e4,s=pi(e,"title")??void 0;return this._executeCode(void 0,n,i,r,s)}async _executeCode(e,r,n,i,s){if(!this.rtcAgent)return{success:!1,error:"rtcAgent not initialized. Pass rtcAgent to ScriptTool constructor."};try{let o;if(i!==void 0)o=i;else{const I=`/scripts/${e}.ts`,P=await Vr.read(I);o=WU(P).code}const l={logs:[],warns:[],errors:[]},c=$U(this.rtcAgent,r,l,s||void 0),d=performance.now(),u=await KU(o,c,n,e),h=Math.round(performance.now()-d),g={};e&&(g.name=e),u!==void 0&&(g.result=u);const b=100;return l.logs.length>0&&(g.logs=l.logs.slice(0,b).map(V_)),l.warns.length>0&&(g.warnings=l.warns.slice(0,b).map(V_)),l.errors.length>0&&(g.errors=l.errors.slice(0,b).map(V_)),g.duration_ms=h,{success:!0,data:g}}catch(o){return o instanceof Error&&"isScriptTimeout"in o?{success:!1,error:o.message}:o instanceof Error&&"isScriptCompileError"in o?{success:!1,error:`Script compile error: ${o.message}`}:{success:!1,error:`Script execution failed: ${o instanceof Error?o.message:String(o)}`}}}}function rz(t){return[new JU,new XU,new ZU,new QU,new ez,new tz,new QO(t)]}const nz=er("ToolRegistry");class iz{constructor(e){sr(this,"tools",new Map);const r=rz(e);for(const n of r)this.register(n)}setRtcAgent(e){this.register(new QO(e))}register(e){this.tools.has(e.name)&&nz.warn(`Tool '${e.name}' is already registered and will be overwritten.`),this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getToolNames(){return Array.from(this.tools.keys())}async execute(e,r){const n=this.tools.get(e);if(!n)throw new Error(`Tool not found: ${e}`);return n.execute(r)}}const e4=new iz,Qn=er("RtcProcessor"),sz=1e3,t4=6e4,W_=10;class oz{constructor(e){sr(this,"persistence");sr(this,"processing",!1);sr(this,"pendingCheck",!1);sr(this,"retryCountMap",new Map);sr(this,"mode","edit");sr(this,"confirmDialog");sr(this,"askUserDialog");sr(this,"master");sr(this,"_lastSilentlySkippedRtcId");sr(this,"_abortController");this.persistence=e}setMode(e){this.mode=e}getMode(){return this.mode}setConfirmDialog(e){this.confirmDialog=e}setAskUserDialog(e){this.askUserDialog=e}setMaster(e){this.master=e}_isMasterAllowed(){return this.master===void 0||this.master.isMaster}cancel(){this._abortController?(Qn.debug("cancel() called, aborting processLoop"),this._abortController.abort()):Qn.debug("cancel() called, but no processLoop is running")}async onRtcUpdate(){if(this.processing){this.pendingCheck=!0;return}await this.processLoop()}async processLoop(){if(!this._isMasterAllowed()){Qn.debug("processLoop: not master, skipping");return}this._abortController=new AbortController;const e=this._abortController.signal;this.processing=!0,this._lastSilentlySkippedRtcId=void 0;try{for(;;){if(!this._isMasterAllowed()){Qn.debug("processLoop: lost master status during loop, exiting");break}if(e.aborted){Qn.debug("processLoop: cancelled, exiting");break}this.pendingCheck=!1;const r=await this.persistence.getNextRtcToProcess(void 0);if(!r){if(this.pendingCheck)continue;break}if(r.client_id===this._lastSilentlySkippedRtcId){Qn.warn(`processLoop: RTC ${r.client_id} returned again after silent skip, exiting loop to prevent infinite retry`);break}Qn.debug("processing RTC:",r.client_id,"tool:",r.tool_name,"sync_status:",r.sync_status);try{await this.processOne(r),Qn.debug("processOne completed successfully")}catch(n){if(n instanceof DOMException&&n.name==="AbortError")throw Qn.debug("processOne: sleep aborted by cancel(), propagating"),n;Qn.error("processOne failed:",n);const i=n instanceof Error?n.message:String(n);if(i.includes("connection")||i.includes("disconnected")){Qn.warn("connection error detected, exiting processLoop");break}await this.sleep(sz,e)}}}catch(r){if(r instanceof DOMException&&r.name==="AbortError")Qn.debug("processLoop: sleep aborted by cancel(), exiting");else throw r}finally{this.processing=!1,this._abortController=void 0}}async processOne(e){var r;if(e.sync_status==="failed"){const n=this.retryCountMap.get(e.client_id)||0;if(n>=W_){Qn.error(`RTC ${e.client_id} exceeded max submit retry count (${W_}), abandoning. The RTC remains in sync_status='failed' and will be retried on the next onRtcUpdate cycle.`),this.retryCountMap.delete(e.client_id),this._lastSilentlySkippedRtcId=e.client_id;return}const i=this.calculateBackoff(n);await this.sleep(i,(r=this._abortController)==null?void 0:r.signal);try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:e.status==="completed",result:e.result,error:e.error_message}),this.retryCountMap.delete(e.client_id)}catch(s){throw this.retryCountMap.set(e.client_id,n+1),s}}else{const n=e.tool_name;if(n==="askUser"){await this.processAskUser(e);return}const i=uR.needsConfirm(n,this.mode);let s=!0;if(i&&(s=await this.showConfirmDialog(e)),!s){try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!1,error:"User denied"})}catch(d){Qn.error("submitRtcResult (denied) failed, marking as synced to prevent retry:",d);try{await this.persistence.getEntityRepository().upsertRtc({client_id:e.client_id},"synced")}catch(u){Qn.error("Failed to mark RTC as synced:",u),this.retryCountMap.set(e.client_id,W_)}}return}let o,l=!0,c;try{const d=e.parameters||{},u=e4.execute(n,d);let h;const g=new Promise((I,P)=>{h=setTimeout(()=>P(new Error(`Tool execution timeout after ${t4}ms`)),t4)});let b;try{b=await Promise.race([u,g])}finally{clearTimeout(h)}u.catch(()=>{}),o=b.data,b.success||(l=!1,c=b.error)}catch(d){l=!1,c=d instanceof Error?d.message:String(d)}try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:l,result:o,error:c})}catch(d){Qn.error("submitRtcResult failed:",d)}}}async processAskUser(e){if(!this.askUserDialog){Qn.warn("askUserDialog not set, defaulting to reject");try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!1,error:"User declined to answer questions"})}catch(n){Qn.error("submitRtcResult (ask_user no dialog) failed:",n)}return}let r;try{r=await this.askUserDialog(e)}catch(n){Qn.error("askUserDialog threw:",n);try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!1,error:n instanceof Error?n.message:String(n)})}catch(i){Qn.error("submitRtcResult (ask_user error) failed:",i)}return}try{r===null?await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!1,error:"User declined to answer questions"}):await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!0,result:r})}catch(n){Qn.error("submitRtcResult (ask_user) failed:",n)}}calculateBackoff(e){return Math.min(1e3*Math.pow(2,e),3e4)}sleep(e,r){return new Promise((n,i)=>{if(r!=null&&r.aborted){i(new DOMException("Sleep aborted","AbortError"));return}const s=setTimeout(()=>{r==null||r.removeEventListener("abort",o),n()},e),o=()=>{clearTimeout(s),r==null||r.removeEventListener("abort",o),i(new DOMException("Sleep aborted","AbortError"))};r==null||r.addEventListener("abort",o,{once:!0})})}async showConfirmDialog(e){return this.confirmDialog?this.confirmDialog(e):(Qn.warn("confirmDialog not set, defaulting to reject"),!1)}}function r4(t){return new SharedWorker(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/shared-worker-CvhUb451.js").href:new URL("assets/shared-worker-CvhUb451.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{type:"module",name:t==null?void 0:t.name})}const Ln=er("WorkerBridge");function az(t){const e=t.toString(),r=e.match(/new URL\(\s*(["'`])([^"'`]+)\1/);if(r)return r[2];const n=e.match(/new SharedWorker\(\s*(["'`])([^"'`]+)\1/);if(n)return n[2];throw new Error("[WorkerBridge] Cannot extract worker URL from factory. Source: "+e.slice(0,300))}function n4(t,e){let r=0;return(...n)=>{const i=Date.now();i-r>=e&&(r=i,t(...n))}}const Bs=class Bs{constructor(e,r={}){this._auth=e,this._worker=null,this._core=null,this._initialized=!1,this._initPromise=null,this._operationCounter=0,this._connectionListeners=new Set,this._hasRestoredFromStorage=!1,this._yieldResolves=[],this._config=r,this._databaseName="default",this._lastProcessedSeq=0,this._callbacks={onUIUpdate:n=>{_u().publish(n.event,{skipPersist:!0,seqOverride:n.seq}),n.seq>this._lastProcessedSeq&&this._updateLastProcessedSeq(n.seq)},requestToken:async()=>{const n=await this._auth.getAccessTokenAsync();if(!n)throw new Error("[WorkerBridge] no access token available");return n},requestTokenRefresh:()=>this._auth.handleTokenExpired(),onConnectionStateChange:n=>{Ln.debug("[WorkerBridge] onConnectionStateChange called, state:",n.state,"reason:",n.reason,"listeners:",this._connectionListeners.size);for(const i of this._connectionListeners)try{i(n)}catch(s){Ln.error("connection listener error:",s)}},onGapFillState:n=>{Ln.debug("[BulkUpdate] WorkerBridge.onGapFillState called, isSyncing:",n);const i=_u();n?i.emitGapFillStart():i.emitGapFillEnd()},onStateGap:()=>{Ln.warn("catchUp: state gap detected — events were lost (likely TTL cleanup)"),this._lastProcessedSeq=0,this._saveLastProcessedSeq(),_u().emitGapFillEnd()},onAccountBanned:n=>{Ln.warn("Account banned:",n);try{sessionStorage.setItem("rtc-account-banned-pending",JSON.stringify({reason:n,timestamp:Date.now()}))}catch(s){Ln.debug("sessionStorage unavailable for ban state",s)}const i=document.querySelector("rtc-agent");i?(i.dispatchEvent(new CustomEvent("rtc-account-banned",{bubbles:!0,composed:!0,detail:{reason:n}})),Ln.warn("dispatched rtc-account-banned event from onAccountBanned callback")):Ln.error("rtc-agent element not found when handling account banned; ban state saved in sessionStorage")}},this._proxiedCallbacks=wh(this._callbacks)}static _getWorkerName(){return"rtc-agent-worker"}async initWorker(){let e=null;for(let r=0;r<=Bs.MAX_INIT_RETRIES;r++)try{r>0&&(Ln.warn(`Retrying worker initialization (attempt ${r+1}/${Bs.MAX_INIT_RETRIES+1})...`),await this._delay(Bs.INIT_RETRY_DELAY_MS*r)),await this._initWorkerOnce(),await this._verifyWorkerAlive();return}catch(n){e=n instanceof Error?n:new Error(String(n)),Ln.error(`Worker initialization attempt ${r+1} failed:`,e),this._cleanupFailedWorker()}throw new Error(`[WorkerBridge] Failed to initialize SharedWorker after ${Bs.MAX_INIT_RETRIES+1} attempts: ${e==null?void 0:e.message}`)}async _initWorkerOnce(){const e=Bs._getWorkerName();if(this._config.workerURL)Ln.info("Using custom workerURL:",this._config.workerURL),this._worker=new SharedWorker(this._config.workerURL,{name:e,type:"module"});else{const r=az(r4),n=typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:gs&&gs.tagName.toUpperCase()==="SCRIPT"&&gs.src||new URL("index.umd.js",document.baseURI).href,i=new URL(r,n).href,s=window.location.origin;let o;try{o=new URL(i).origin}catch(c){Ln.debug("Failed to parse worker URL origin, assuming same-origin:",c),o=s}const l=o!==s;if(Ln.info("worker init:",{workerURL:i,pageOrigin:s,workerOrigin:o,isCrossOrigin:l}),!l)this._worker=r4({name:e});else{let c;try{const h=await fetch(i,{cache:"default"});if(!h.ok)throw new Error(`HTTP ${h.status} ${h.statusText}`);c=await h.text()}catch(h){throw new Error(`[WorkerBridge] failed to fetch worker script from ${i}: ${h instanceof Error?h.message:h}`)}const d=new Blob([c],{type:"application/javascript"}),u=URL.createObjectURL(d);try{this._worker=new SharedWorker(u,{name:e,type:"module"})}finally{URL.revokeObjectURL(u)}}}this._core=yT(this._worker.port),this._worker.onerror=r=>{Ln.error("SharedWorker error:",{message:r.message,filename:r.filename,lineno:r.lineno,colno:r.colno,error:r.error})},this._worker.port.onmessageerror=r=>{Ln.error("port message error:",r)}}async _verifyWorkerAlive(){if(!this._core)throw new Error("[WorkerBridge] No core available for verification");let e;const r=new Promise((n,i)=>{e=setTimeout(()=>{const s=`Worker verification timed out after ${Bs.VERIFICATION_TIMEOUT_MS}ms. This may indicate a stale SharedWorker from a previous browser session (e.g., after force-killing a tab during debugging). To resolve: visit chrome://inspect/#workers, find and terminate the stale 'rtc-agent-worker' instance, then reload the page.`;i(new Error(s))},Bs.VERIFICATION_TIMEOUT_MS)});try{const n=await Promise.race([this._core.ping(),r]);if(n!=="pong")throw new Error(`Unexpected ping response: ${n}`);Ln.info("Worker verification successful")}catch(n){const i=n instanceof Error?n.message:"unknown error";throw new Error(`[WorkerBridge] Worker verification failed: ${i}`)}finally{e!==void 0&&clearTimeout(e)}}_cleanupFailedWorker(){if(this._worker){try{this._worker.port.close()}catch{}this._worker=null}this._core=null}_delay(e){return new Promise(r=>setTimeout(r,e))}get core(){return this._core}async init(e){if(this._initialized){Ln.warn("already initialized");return}if(this._initPromise)return this._initPromise;this._initPromise=this._doInit(e);try{await this._initPromise,this._initialized=!0}finally{this._initPromise=null}}async _doInit(e){if(!this._worker||!this._core)throw new Error("[WorkerBridge] init() called before initWorker()");const r=e.databaseName??"default",n=r!==this._databaseName;this._databaseName=r,(!this._hasRestoredFromStorage||n)&&(this._lastProcessedSeq=this._loadLastProcessedSeq(),this._hasRestoredFromStorage=!0),this._worker.port.start(),await this._core.init(e),await this._core.registerCallback(this._proxiedCallbacks),await this._doCatchUp()}async destroy(e=!1){var r;if((r=this._catchUpAbortController)==null||r.abort(),!!this._initialized&&!(!this._worker||!this._core)){try{await this._core.unregisterCallback(this._proxiedCallbacks)}catch(n){Ln.warn("unregisterCallback failed:",n)}if(this._connectionListeners.clear(),this._worker.port.close(),this._initialized=!1,this._yieldChannel&&(this._yieldChannel.port1.close(),this._yieldChannel.port2.close(),this._yieldChannel=void 0),this._yieldResolves.length=0,e){this._lastProcessedSeq=0,this._hasRestoredFromStorage=!1;try{sessionStorage.removeItem(this._getSessionStorageKey())}catch{}}}}async getConnectionState(){return this._core.getConnectionState()}onConnectionStateChange(e){return this._connectionListeners.add(e),()=>{this._connectionListeners.delete(e)}}installVirtualFSProxy(){const e=this._core;Vr.read=(r,n,i)=>e.virtualFSRead(r,n,i),Vr.write=(r,n,i="overwrite",s)=>e.virtualFSWrite(r,n,i,s),Vr.ls=r=>e.virtualFSLs(r),Vr.find=(r,n)=>e.virtualFSFind(r,n),Vr.grep=(r,n,i,s)=>e.virtualFSGrep(r,n,i,s),Vr.queryByType=r=>e.virtualFSQueryByType(r),Vr.exists=r=>e.virtualFSExists(r),Vr.remove=r=>e.virtualFSRemove(r)}async cacheFile(e,r,n,i,s){return this._core.cacheFile(e,r,n,i,s)}async cacheFilePending(e,r,n,i,s){return this._core.cacheFilePending(e,r,n,i,s)}async getCachedFile(e,r){return this._core.getCachedFile(e,r)}async evictExpiredCache(){return this._core.evictExpiredCache()}async evictCache(e){return this._core.evictCache(e)}async uploadFile(e,r,n,i,s,o,l,c){if(l!=null&&l.aborted)throw new DOMException("Upload aborted","AbortError");const d=`op-upload-${++this._operationCounter}`;let u;if(l){const g=()=>{this._core.cancelFileOperation(d)};l.addEventListener("abort",g,{once:!0}),u=()=>l.removeEventListener("abort",g)}const h=o?wh(n4(o,100)):void 0;try{return await this._core.uploadFile(e,r,n,i,s,d,h,c)}finally{u==null||u()}}async downloadFile(e,r,n,i,s){if(i!=null&&i.aborted)throw new DOMException("Download aborted","AbortError");const o=`op-download-${++this._operationCounter}`;let l;if(i){const d=()=>{this._core.cancelFileOperation(o)};i.addEventListener("abort",d,{once:!0}),l=()=>i.removeEventListener("abort",d)}const c=n?wh(n4(n,100)):void 0;try{return await this._core.downloadFile(e,r,c,o,s)}finally{l==null||l()}}async deleteFile(e,r){return this._core.deleteFile(e,r)}async calculateFileMD5(e){return this._core.calculateFileMD5(e)}async headFile(e,r){return this._core.headFile(e,r)}async getPresignedUrl(e,r,n){return this._core.getPresignedUrl(e,r,n)}async listFiles(e,r=100,n=0){return this._core.listFiles(e,r,n)}async countFiles(e){return this._core.countFiles(e)}async syncPendingFiles(){return this._core.syncPendingFiles()}async resumeInterruptedUploads(){return this._core.resumeInterruptedUploads()}async getCacheStats(){return this._core.getCacheStats()}async updateFileMetadata(e,r,n){return this._core.updateFileMetadata(e,r,n)}async _doCatchUp(){if(!this._core)return;this._catchUpAbortController=new AbortController;const e=this._catchUpAbortController.signal;try{let r=this._lastProcessedSeq,n=0,i=!0;for(;i&&!e.aborted;){const s=await this._core.getCatchUpEvents(r);if(e.aborted)break;if(s.hasGap){Ln.warn("catchUp: gap detected, triggering state refresh"),this._callbacks.onStateGap();return}if(s.entries.length===0)return;Ln.debug(`catchUp: replaying ${s.entries.length} events from seq ${r}`);const o=8;let l=performance.now();for(let c=0;c<s.entries.length&&!e.aborted;c++){const d=s.entries[c],u=d.seq;if(!(u<=this._lastProcessedSeq)){if(!this._isValidUIUpdateEvent(d.event)){Ln.warn("catchUp: skipping entry with invalid event structure");continue}try{this._callbacks.onUIUpdate({event:d.event,seq:u}),n++}catch(h){Ln.error("catchUp: failed to deliver event, stopping:",h);return}performance.now()-l>o&&(await this._yieldToMain(),l=performance.now())}}r=s.entries[s.entries.length-1].seq,i=s.hasMore}if(e.aborted){Ln.debug("catchUp: cancelled");return}n>0&&Ln.debug(`catchUp: delivered ${n} total events`)}catch(r){e.aborted||Ln.error("catchUp: failed to query events (non-fatal):",r)}finally{this._catchUpAbortController=void 0}}_yieldToMain(){return new Promise(e=>{this._yieldChannel||(this._yieldChannel=new MessageChannel,this._yieldChannel.port1.onmessage=()=>{const r=this._yieldResolves.shift();r&&r()}),this._yieldResolves.push(e),this._yieldChannel.port2.postMessage(null)})}_isValidUIUpdateEvent(e){if(!e||typeof e!="object")return!1;const r=e;return typeof r.entity=="string"&&typeof r.action=="string"&&typeof r.entityId=="string"}_updateLastProcessedSeq(e){this._lastProcessedSeq=e,this._saveLastProcessedSeq()}_getSessionStorageKey(){return`${Bs.SESSION_STORAGE_KEY_PREFIX}-${this._databaseName}`}_loadLastProcessedSeq(){try{const e=sessionStorage.getItem(this._getSessionStorageKey());if(e!==null){const r=parseInt(e,10);if(!isNaN(r)&&r>=0)return r}}catch{}return 0}_saveLastProcessedSeq(){try{sessionStorage.setItem(this._getSessionStorageKey(),String(this._lastProcessedSeq))}catch{Ln.debug("Failed to save lastProcessedSeq to sessionStorage (non-fatal)")}}};Bs.SESSION_STORAGE_KEY_PREFIX="rtc-ui-update-seq",Bs.MAX_INIT_RETRIES=3,Bs.INIT_RETRY_DELAY_MS=1e3,Bs.VERIFICATION_TIMEOUT_MS=5e3;let H_=Bs;const rp=er("MasterLock");class lz{constructor(e){this._isMaster=!1,this._controlled=!1,this._lockName=`rtc-agent-master-${e}`}get isMaster(){return this._isMaster}get isControlled(){return this._controlled}async acquire(){var e;if(this._controlled){rp.warn("already acquiring/acquired, ignoring");return}if(!this._isWebLocksAvailable()){rp.warn("Web Locks API not available, acting as always-master"),this._isMaster=!0,this._controlled=!0,(e=this.onAcquire)==null||e.call(this);return}this._controlled=!0,this._abortController=new AbortController,navigator.locks.request(this._lockName,{signal:this._abortController.signal},async()=>{var r,n;this._isMaster=!0,rp.info("acquired lock → became Master"),(r=this.onAcquire)==null||r.call(this),await new Promise(i=>{this._releaseResolve=i}),this._isMaster=!1,rp.info("released lock → lost Master"),(n=this.onRelease)==null||n.call(this)}).catch(r=>{r instanceof DOMException&&r.name==="AbortError"||rp.error("lock request error:",r)})}release(){this._controlled&&(this._releaseResolve&&(this._releaseResolve(),this._releaseResolve=void 0),!this._isMaster&&this._abortController&&this._abortController.abort(),this._controlled=!1)}_isWebLocksAvailable(){return typeof navigator<"u"&&"locks"in navigator}}const Ds=er("PersistenceController");function dte(t){return t}class cz{constructor(e){this._core=e}async connect(){Ds.info("connect() called"),await this._core.connect(),Ds.info("connect() completed, worker state:",await this._core.getConnectionState())}disconnect(){this._core.disconnect()}async reconnect(){await this._core.reconnect()}async listSessions(e,r){return this._core.listSessions(e,r)}async getSession(e){return this._core.getSession(e)}async listMessages(e,r,n,i){return this._core.listMessages(e,r,n,i)}async getMessage(e){return this._core.getMessage(e)}async listRtc(e,r,n){return this._core.listRtc(e,r,n)}async getNextRtcToProcess(e){return this._core.getNextRtcToProcess(e)}async sendMessage(e){return this._core.sendMessage(e)}async insertLocalMessage(e){return this._core.insertLocalMessage(e)}async stopTurn(e){return this._core.stopTurn(e)}async closeSession(e){return this._core.closeSession(e)}async openSession(e){return this._core.openSession(e)}async compactSession(e,r){return this._core.compactSession(e,r)}async submitRtcResult(e){return this._core.submitRtcResult(e)}async forkSession(e){return this._core.forkSession(e)}async deleteSession(e){return this._core.deleteSession(e)}async updateSessionTitle(e,r){return this._core.updateSessionTitle(e,r)}async close(){await this._core.close()}async flushAll(){return this._core.flushAll()}async initializeVirtualFS(e){await this._core.initializeVirtualFS(e??{})}getClient(){throw new Error("[WorkerPersistenceAdapter] getClient() is not available. Use PersistenceController.onConnectionStateChange() instead.")}getOffsetManager(){return{reset:()=>this._core.resetOffset()}}getEntityRepository(){throw new Error("[WorkerPersistenceAdapter] getEntityRepository() is not available.")}}const Ql=class Ql{constructor(e,r){this._connectGeneration=0,this._auth=r,e.addController(this)}set databaseName(e){this._databaseNameOverride=e}set workerURL(e){this._workerURL=e}get layer(){return this._layer}get isConnected(){return this._layer!==void 0}get workerBridge(){return this._workerBridge}get masterLock(){return this._masterLock}get fileStorage(){if(!this._fileStorage){if(!this._workerBridge)throw new Error("[PersistenceController] fileStorage requires an active connection. Call connect() first.");const e=this._auth.state.userId;if(!e)throw new Error("[PersistenceController] fileStorage requires userId from auth state.");this._fileStorage=new q2(this._workerBridge,e)}return this._fileStorage}hostConnected(){}hostDisconnected(){this.disconnect()}async connect(){if(Ds.debug("connect() called"),this._layer)return;if(this._connecting)return this._connecting;const e=lT(),r=this._auth.state.userId;if(Ds.debug("connect() userId:",r,"deviceId:",e),!r)throw new Error("[PersistenceController] connect() called without userId; refusing to open a shared database");const n={databaseName:this._databaseNameOverride?`${this._databaseNameOverride}-${r}`:`rtc-agent-${r}`,deviceId:e,userId:r,serverURL:Uo.serverURL,client:{endpoint:Uo.wsEndpoint,getToken:async()=>{const s=await this._auth.getAccessTokenAsync();if(!s)throw Ds.warn("getToken: no access token available"),new Error("No access token available");return s},onTokenExpired:()=>this._auth.handleTokenExpired(),onAccountBanned:s=>{Ds.warn("Account banned:",s)},deviceId:e,userId:r}},i=this._connectGeneration;return this._connecting=this._connectWorker(n).finally(()=>{this._connectGeneration===i&&(this._connecting=void 0)}),this._connecting}async _connectWorker(e){let r=null;for(let n=0;n<=Ql.MAX_CONNECT_RETRIES;n++)try{n>0&&(Ds.warn(`Retrying connection (attempt ${n+1}/${Ql.MAX_CONNECT_RETRIES+1})...`),await this._delay(Ql.CONNECT_RETRY_DELAY_MS*n)),await this._connectWorkerOnce(e);return}catch(i){r=i instanceof Error?i:new Error(String(i)),Ds.error(`Connection attempt ${n+1} failed:`,r),await this._cleanupFailedConnection()}throw new Error(`[PersistenceController] Failed to connect after ${Ql.MAX_CONNECT_RETRIES+1} attempts: ${r==null?void 0:r.message}`)}async _connectWorkerOnce(e){const r=new H_(this._auth,{workerURL:this._workerURL});if(this._workerBridge=r,await r.initWorker(),this._workerBridge!==r){await r.destroy().catch(()=>{});return}const{getToken:n,onTokenExpired:i,onAccountBanned:s,...o}=e.client,l={...e,client:o};if(await r.init(l),this._workerBridge!==r){await r.destroy().catch(()=>{});return}r.installVirtualFSProxy(),this._layer=new cz(r.core),await r.core.connect();const c=this._auth.state.userId;c&&(this._masterLock=new lz(c),this._masterLock.onAcquire=()=>{Ds.info("this Tab became Master")},this._masterLock.onRelease=()=>{Ds.info("this Tab lost Master")},this._masterLock.acquire())}async _cleanupFailedConnection(){if(this._workerBridge){try{await this._workerBridge.destroy()}catch(e){Ds.debug("Cleanup after failed connection (non-critical):",e)}this._workerBridge=void 0}this._layer=void 0,this._fileStorage=void 0}_delay(e){return new Promise(r=>setTimeout(r,e))}async disconnect(){var i;this._connectGeneration++;const e=this._connectGeneration;this._connecting&&(this._connecting=void 0);const r=this._layer,n=this._workerBridge;if(this._layer=void 0,this._workerBridge=void 0,r)try{await r.getOffsetManager().reset(),await r.close()}catch(s){Ds.error("disconnect error:",s)}if(n){(i=this._masterLock)==null||i.release(),this._masterLock=void 0,this._fileStorage=void 0;try{await n.destroy()}catch(s){Ds.error("WorkerBridge disconnect error:",s)}}this._connectGeneration!==e&&Ds.warn("disconnect interrupted by new connect, generation changed")}async getConnectionState(){return this._workerBridge?this._workerBridge.getConnectionState():"disconnected"}onConnectionStateChange(e){return this._workerBridge?this._workerBridge.onConnectionStateChange(e):()=>{}}};Ql.MAX_CONNECT_RETRIES=2,Ql.CONNECT_RETRY_DELAY_MS=2e3;let K_=Ql;const i4=er("EventBus");class s4{constructor(){this.handlers=new Map}on(e,r){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(r),()=>{var n;(n=this.handlers.get(e))==null||n.delete(r)}}once(e,r){const n=i=>(this.off(e,n),r(i));return this.on(e,n)}off(e,r){var n;(n=this.handlers.get(e))==null||n.delete(r)}emit(e,r){const n=this.handlers.get(e);if(!n)return;const i=Array.from(n);for(const s of i)try{s(r)}catch(o){i4.error(`Handler error for event '${e}':`,o)}}async emitAsync(e,r){const n=this.handlers.get(e);if(!n)return;const i=Array.from(n),s=[];for(const o of i)s.push(Promise.resolve(o(r)).catch(l=>{i4.error(`Async handler error for event '${e}':`,l)}));await Promise.all(s)}async emitAsyncStrict(e,r){const n=this.handlers.get(e);if(!n)return;const i=Array.from(n),s=[];for(const o of i)s.push(Promise.resolve(o(r)));await Promise.all(s)}clearAll(){this.handlers.clear()}clearEvent(e){this.handlers.delete(e)}}function o4(){return new s4}const To=o4(),uz=er("SkillController");class a4{constructor(e,r){this._registry=null,this._config={},this._unsubscribes=[],this._host=e,this._config=r||{},e.addController(this)}get value(){return{registry:this._registry}}get actions(){return{getRegistry:()=>this._registry,setRegistry:e=>{this._registry=e,this._host.requestUpdate(),this._bridgeToolRegistry(e)}}}_bridgeToolRegistry(e){const r=new Proxy({callFunction:(n,i)=>e.execute(n,i),readFile:n=>Vr.read(n),writeFile:(n,i)=>Vr.write(n,i).then(()=>{}),listDir:n=>Vr.ls(n)},{get(n,i){return i in n?n[i]:e[i]}});e4.setRtcAgent(r),uz.info("rtcAgent API bridged to ToolRegistry")}setConfig(e){this._config=e}hostConnected(){this._subscribeEvents()}hostDisconnected(){for(const e of this._unsubscribes)e();this._unsubscribes=[]}_subscribeEvents(){for(const n of this._unsubscribes)n();this._unsubscribes=[];const e=To.on("ui:toast",n=>{this._config.onToast&&this._config.onToast(n.message,n.type)});this._unsubscribes.push(e);const r=To.on("ui:confirm-request",n=>{this._config.onConfirmRequest&&this._config.onConfirmRequest(n.requestId,n.path,n.message)});this._unsubscribes.push(r)}respondToConfirm(e,r){To.emit("ui:confirm-response",{requestId:e,confirmed:r})}}class dz{constructor(e){this._toasts=[],this._timers=new Map,this._host=e,this._host.addController(this),this.actions={show:(r,n="info",i)=>this._show(r,n,i),remove:r=>this._remove(r)}}get toasts(){return this._toasts}hostConnected(){}hostDisconnected(){for(const e of this._timers.values())clearTimeout(e);this._timers.clear(),this._toasts.length>0&&(this._toasts=[],this._host.requestUpdate())}_show(e,r,n){const i=Date.now()+Math.random();this._toasts=[...this._toasts,{id:i,message:e,type:r,action:n}],this._host.requestUpdate();const s=r==="error"?0:r==="success"?2e3:2500;if(s>0){const o=setTimeout(()=>this._remove(i),s);this._timers.set(i,o)}}_remove(e){const r=this._timers.get(e);r!==void 0&&(clearTimeout(r),this._timers.delete(e)),this._toasts=this._toasts.filter(n=>n.id!==e),this._host.requestUpdate()}}const l4=er("ForkController");class fz{constructor(e){this._state=null,this._deps=null,this._host=e,this._host.addController(this),this.actions={requestFork:(r,n,i,s)=>this._requestFork(r,n,i,s),submitFork:r=>this._submitFork(r),clearFork:()=>this._clearFork()}}get state(){return this._state}get isActive(){return this._state!==null}setDeps(e){this._deps=e}hostConnected(){}hostDisconnected(){}_requestFork(e,r,n,i){var o;const s=i.length>30?i.slice(0,30)+"...":i;this._state={oldSessionClientId:e,oldMessageClientId:r,newSessionClientId:n,hintMessage:Me(wr`🔀 从「${s}」分叉`)},this._host.requestUpdate(),(o=this._deps)==null||o.clearMessages(),l4.debug("_requestFork: state set, transient params handled by tab property binding")}async _submitFork(e){if(!this._state||!this._deps)return;const r=`msg-${crypto.randomUUID()}`;try{await this._deps.executeFork({oldSessionClientId:this._state.oldSessionClientId,oldMessageClientId:this._state.oldMessageClientId,newSessionClientId:this._state.newSessionClientId,newMessageClientId:r,content:e})}catch(n){l4.error("forkSession failed:",n)}this._clearFork()}_clearFork(){var e;this._state&&((e=this._deps)==null||e.clearTransientParams(this._state.newSessionClientId)),this._state=null,this._host.requestUpdate()}}const c4=er("ActivityController");class pz{constructor(e){this._state={...ch},this.host=e,this.host.addController(this),this.actions={setActivity:r=>this._setActivity(r),showSidebar:()=>this._showSidebar(),hideSidebar:()=>this._hideSidebar(),toggleSidebar:()=>this._toggleSidebar(),reset:()=>this._reset()},this._restore()}get value(){return{state:this._state,actions:this.actions}}get active(){return this._state.active}get sidebarVisible(){return this._state.sidebarVisible}hostConnected(){}hostDisconnected(){}_restore(){try{const e=localStorage.getItem(Xr.activityBar);if(!e)return;const r=JSON.parse(e),n=i=>i==="files"||i==="chat"||i==="settings"||i==="functions";r&&typeof r=="object"&&(this._state={active:n(r.active)?r.active:ch.active,sidebarVisible:typeof r.sidebarVisible=="boolean"?r.sidebarVisible:ch.sidebarVisible})}catch(e){c4.debug("Failed to restore activity state:",e)}}_persist(){try{localStorage.setItem(Xr.activityBar,JSON.stringify(this._state))}catch(e){c4.debug("Failed to persist activity state:",e)}}_setActivity(e){this._state.active===e?this._toggleSidebar():(this._state={active:e,sidebarVisible:this._state.sidebarVisible},this._persist(),this.host.requestUpdate())}_showSidebar(){this._state.sidebarVisible||(this._state={...this._state,sidebarVisible:!0},this._persist(),this.host.requestUpdate())}_hideSidebar(){this._state.sidebarVisible&&(this._state={...this._state,sidebarVisible:!1},this._persist(),this.host.requestUpdate())}_toggleSidebar(){this._state={...this._state,sidebarVisible:!this._state.sidebarVisible},this._persist(),this.host.requestUpdate()}_reset(){this._state={...ch},this._persist(),this.host.requestUpdate()}}class hz{constructor(e){this._state={...L2},this._expandedPaths=new Set,this._loadingPaths=new Set,this._host=e,e.addController(this)}get state(){return this._state}get value(){return{state:this._state,actions:this.actions,isExpanded:e=>this._expandedPaths.has(e),isLoading:e=>this._loadingPaths.has(e),isSelected:e=>this._state.selectedPath===e}}get actions(){return{setRoot:e=>this._setRoot(e),toggleNode:e=>this._toggleNode(e),expandAll:()=>this._expandAll(),collapseAll:()=>this._collapseAll(),selectNode:e=>this._selectNode(e),setLoading:(e,r)=>this._setLoading(e,r),updateChildren:(e,r)=>this._updateChildren(e,r),reset:()=>this._reset()}}hostConnected(){}hostDisconnected(){this._reset()}_setRoot(e){this._state={...this._state,root:e},this._host.requestUpdate()}_toggleNode(e){this._expandedPaths.has(e)?this._expandedPaths.delete(e):this._expandedPaths.add(e),this._host.requestUpdate()}_expandAll(){this._state.root&&(this._collectFolderPaths(this._state.root,this._expandedPaths),this._host.requestUpdate())}_collapseAll(){this._expandedPaths.clear(),this._host.requestUpdate()}_selectNode(e){this._state={...this._state,selectedPath:e},this._host.requestUpdate()}_setLoading(e,r){r?this._loadingPaths.add(e):this._loadingPaths.delete(e),this._host.requestUpdate()}_updateChildren(e,r){if(!this._state.root)return;const n=this._updateNodeChildren(this._state.root,e,r);n&&(this._state={...this._state,root:n},this._host.requestUpdate())}_reset(){this._state={...L2},this._expandedPaths.clear(),this._loadingPaths.clear(),this._host.requestUpdate()}_collectFolderPaths(e,r){if(e.type==="folder"&&(r.add(e.path),e.children))for(const n of e.children)this._collectFolderPaths(n,r)}_updateNodeChildren(e,r,n){if(e.path===r)return{...e,children:n};if(e.type==="folder"&&e.children){const i=e.children.map(o=>this._updateNodeChildren(o,r,n)||o);if(i.some((o,l)=>o!==e.children[l]))return{...e,children:i}}return null}}const u4=er("EditorAreaController");class mz{constructor(e){this._tabs=[],this._activeFilePath="",this._host=e,this._host.addController(this),this.actions={openFile:(r,n,i)=>this._openFile(r,n,i),closeFile:r=>this._closeFile(r),closeAll:()=>this._closeAll(),switchTab:r=>this._switchTab(r),updateContent:(r,n)=>this._updateContent(r,n),saveFile:r=>this._saveFile(r),setViewMode:(r,n)=>this._setViewMode(r,n),setCursorPosition:(r,n)=>this._setCursorPosition(r,n),loadContent:(r,n)=>this._loadContent(r,n)},this._restore()}hostConnected(){}hostDisconnected(){this._cursorPersistTimer&&(clearTimeout(this._cursorPersistTimer),this._cursorPersistTimer=void 0)}_restore(){var e;try{const r=localStorage.getItem(Xr.editorArea);if(!r)return;const n=JSON.parse(r);if(!n||!Array.isArray(n.tabs))return;const i=o=>o==="edit"||o==="preview"||o==="split";this._tabs=n.tabs.map(o=>({filePath:o.filePath,content:"",isDirty:!1,cursorPosition:i(o.viewMode)?{line:1,column:1}:o.cursorPosition??{line:1,column:1},viewMode:i(o.viewMode)?o.viewMode:"edit"}));const s=this._tabs.some(o=>o.filePath===n.activeFilePath);this._activeFilePath=s?n.activeFilePath:((e=this._tabs[0])==null?void 0:e.filePath)??""}catch(r){u4.debug("Failed to restore editor area state:",r)}}_persist(){try{if(this._tabs.length===0){localStorage.removeItem(Xr.editorArea);return}const e={tabs:this._tabs.map(r=>({filePath:r.filePath,viewMode:r.viewMode,cursorPosition:r.cursorPosition})),activeFilePath:this._activeFilePath};localStorage.setItem(Xr.editorArea,JSON.stringify(e))}catch(e){u4.debug("Failed to persist editor area state:",e)}}get state(){return{tabs:this._tabs,activeFilePath:this._activeFilePath}}get tabs(){return this._tabs}get activeFilePath(){return this._activeFilePath}get activeTab(){return this._tabs.find(e=>e.filePath===this._activeFilePath)}_openFile(e,r,n="edit"){if(this._tabs.find(o=>o.filePath===e)){this._activeFilePath=e,this._persist(),this._host.requestUpdate();return}const s={filePath:e,content:r,isDirty:!1,cursorPosition:{line:1,column:1},viewMode:n};this._tabs=[...this._tabs,s],this._activeFilePath=e,this._persist(),this._host.requestUpdate()}_closeFile(e){const r=this._tabs.findIndex(i=>i.filePath===e);if(r===-1)return;const n=e===this._activeFilePath;if(this._tabs=this._tabs.filter(i=>i.filePath!==e),n)if(this._tabs.length===0)this._activeFilePath="";else{const i=Math.min(r,this._tabs.length-1);this._activeFilePath=this._tabs[i].filePath}this._persist(),this._host.requestUpdate()}_closeAll(){this._tabs=[],this._activeFilePath="",this._persist(),this._host.requestUpdate()}_switchTab(e){this._tabs.some(n=>n.filePath===e)&&(this._activeFilePath=e,this._persist(),this._host.requestUpdate())}_updateContent(e,r){this._tabs=this._tabs.map(n=>n.filePath!==e?n:{...n,content:r,isDirty:!0}),this._host.requestUpdate()}_saveFile(e){this._tabs=this._tabs.map(r=>r.filePath!==e?r:{...r,isDirty:!1}),this._persist(),this._host.requestUpdate()}_setViewMode(e,r){this._tabs=this._tabs.map(n=>n.filePath!==e?n:{...n,viewMode:r}),this._persist(),this._host.requestUpdate()}_setCursorPosition(e,r){const n=this._tabs.find(i=>i.filePath===e);n&&(n.cursorPosition.line===r.line&&n.cursorPosition.column===r.column||(this._tabs=this._tabs.map(i=>i.filePath!==e?i:{...i,cursorPosition:r}),this._host.requestUpdate(),!this._cursorPersistTimer&&(this._cursorPersistTimer=setTimeout(()=>{this._cursorPersistTimer=void 0,this._persist()},2e3))))}_loadContent(e,r){if(this._tabs.find(s=>s.filePath===e)){this._tabs=this._tabs.map(s=>s.filePath!==e?s:{...s,content:r,isDirty:!1}),this._host.requestUpdate();return}const i={filePath:e,content:r,isDirty:!1,cursorPosition:{line:1,column:1},viewMode:"edit"};this._tabs=[...this._tabs,i],this._activeFilePath||(this._activeFilePath=e),this._persist(),this._host.requestUpdate()}}function gz(t){var r;switch((r=t.split(".").pop())==null?void 0:r.toLowerCase()){case"md":return"Markdown";case"js":return"JavaScript";case"ts":return"TypeScript";case"json":return"JSON";case"html":return"HTML";case"css":return"CSS";case"txt":return"Plain Text";default:return"File"}}class yz{constructor(e,r){this._host=e,this._editorController=r,this._host.addController(this)}hostConnected(){}hostDisconnected(){}get info(){const e=this._editorController.activeTab;return e?{fileType:gz(e.filePath),encoding:"UTF-8",cursor:e.cursorPosition,saveStatus:e.isDirty?"unsaved":"saved"}:{fileType:"",encoding:"UTF-8",cursor:{line:1,column:1},saveStatus:"none"}}}class bz{constructor(e){this._state={rootNodes:[]},this._expanded=new Map,this.host=e,this.host.addController(this),this.actions={toggleExpand:r=>this._toggleExpand(r),expand:r=>this._setExpanded(r,!0),collapse:r=>this._setExpanded(r,!1),rebuildTree:r=>this._rebuildTree(r)},this._restoreExpanded()}get value(){return{state:this._state,actions:this.actions}}hostConnected(){}hostDisconnected(){}_restoreExpanded(){}_persistExpanded(){try{const e={};this._expanded.forEach((r,n)=>{r&&(e[n]=!0)}),Object.keys(e).length>0?localStorage.setItem(Xr.sessionTreeExpanded,JSON.stringify(e)):localStorage.removeItem(Xr.sessionTreeExpanded)}catch{}}_toggleExpand(e){const r=this._expanded.get(e)??!1;this._setExpanded(e,!r)}_setExpanded(e,r){this._expanded.set(e,r),this._persistExpanded(),this._rebuildTreeFromCache()}_rebuildTreeFromCache(){this._cachedSessions&&this._buildTree(this._cachedSessions)}_rebuildTree(e){this._cachedSessions=e,this._buildTree(e)}_buildTree(e){const r=e.filter(s=>!s.rootClientSessionId),n=new Map;for(const s of e)if(s.rootClientSessionId){const o=n.get(s.rootClientSessionId)??[];o.push(s),n.set(s.rootClientSessionId,o)}const i=r.map(s=>this._buildNode(s,n));i.sort((s,o)=>o.session.updatedAt-s.session.updatedAt),this._state={rootNodes:i},this.host.requestUpdate()}_buildNode(e,r){const n=(r.get(e.clientId)??[]).sort((i,s)=>i.createdAt-s.createdAt).map(i=>this._buildNode(i,r));return{session:e,children:n,isExpanded:this._expanded.get(e.clientId)??!1}}}const gy=er("SessionTabController"),G_="rtc:active-tab";class vz{constructor(e){this._state={tabs:[],activeSessionId:null},this.host=e,this.host.addController(this),this.actions={openOrActivate:(r,n,i)=>this._openOrActivate(r,n,i),closeTab:r=>this._closeTab(r),setActiveTab:r=>this._setActiveTab(r),clearAll:()=>this._clearAll(),updateTabTitles:r=>this.updateTabTitles(r),syncTabStatuses:r=>this.syncTabStatuses(r),markSaved:r=>this._markSaved(r),findUnsavedTab:()=>this._findUnsavedTab(),updateTabStatus:(r,n)=>this._updateTabStatus(r,n),restoreActiveFromStorage:()=>this._restoreActiveFromStorage(),getStoredActiveSessionId:()=>this._getStoredActiveSessionId(),setTransientParams:(r,n)=>this._setTransientParams(r,n),clearTransientParams:r=>this._clearTransientParams(r)}}get value(){return{state:this._state,actions:this.actions}}hostConnected(){}hostDisconnected(){}filterInvalidTabs(e){const r=this._state.tabs.length,n=this._state.tabs.filter(s=>e.has(s.sessionId)||s.isUnsaved===!0);let i=this._state.activeSessionId;return i&&!n.some(s=>s.sessionId===i)&&(i=n.length>0?n[0].sessionId:null),n.length!==r?(this._state={tabs:n,activeSessionId:i},this.host.requestUpdate(),!0):!1}updateTabTitles(e){let r=!1;const n=this._state.tabs.map(i=>{const s=e.get(i.sessionId);return s!==void 0&&s.trim()!==""&&s!==i.title?(r=!0,{...i,title:s,isDefault:!1,isUnsaved:!1}):i});return r&&(this._state={...this._state,tabs:n},this.host.requestUpdate()),r}syncTabStatuses(e){let r=!1;const n=this._state.tabs.map(i=>{const s=e.get(i.sessionId);return s!==void 0&&s!==i.status?(r=!0,{...i,status:s}):i});return r&&(this._state={...this._state,tabs:n},this.host.requestUpdate()),r}_isPlaceholderTitle(e){return!e||e===Me("未命名")||e===Me("新聊天")}_findUnsavedTab(){return this._state.tabs.find(e=>e.isUnsaved===!0)}_markSaved(e){const r=this._state.tabs.find(i=>i.sessionId===e);if(!r||r.isUnsaved!==!0)return;const n=this._state.tabs.map(i=>i.sessionId===e?{...i,isUnsaved:!1}:i);this._state={...this._state,tabs:n},this.host.requestUpdate()}_updateTabStatus(e,r){const n=this._state.tabs.find(s=>s.sessionId===e);if(!n||n.status===r)return;const i=this._state.tabs.map(s=>s.sessionId===e?{...s,status:r}:s);this._state={...this._state,tabs:i},this.host.requestUpdate()}_openOrActivate(e,r,n){const i=this._isPlaceholderTitle(r),s=(n==null?void 0:n.activate)??!0,o=(n==null?void 0:n.skipPersist)??!1,l=(n==null?void 0:n.initialInputValue)!==void 0||(n==null?void 0:n.noticeMessage)!==void 0?{initialInputValue:n==null?void 0:n.initialInputValue,noticeMessage:n==null?void 0:n.noticeMessage}:void 0,c=this._state.tabs.findIndex(d=>d.sessionId===e);if(c>=0){const d=this._state.tabs[c];if(i&&!d.isDefault&&d.title!==r){gy.debug("Protected tab title:",d.title),s&&this._state.activeSessionId!==e&&(this._state={...this._state,activeSessionId:e},o||this._persistActiveSessionId(e),this.host.requestUpdate());return}const u=this._state.tabs.map((g,b)=>{if(b!==c)return g;const I={...g,title:r,isDefault:!!i};return l&&(I.initialInputValue=l.initialInputValue,I.noticeMessage=l.noticeMessage,I.initialValueVersion=(g.initialValueVersion??0)+1),I}),h=s?e:this._state.activeSessionId;this._state={tabs:u,activeSessionId:h},s&&!o&&this._persistActiveSessionId(h)}else{const d={sessionId:e,title:r,isDefault:!!i,isUnsaved:(n==null?void 0:n.isUnsaved)??!1,...l?{initialInputValue:l.initialInputValue,noticeMessage:l.noticeMessage,initialValueVersion:1}:{}},u=[...this._state.tabs,d],h=s?e:this._state.activeSessionId;this._state={tabs:u,activeSessionId:h},s&&!o&&this._persistActiveSessionId(h)}this.host.requestUpdate()}_closeTab(e){const r=this._state.tabs.findIndex(s=>s.sessionId===e);if(r<0)return;const n=this._state.tabs.filter(s=>s.sessionId!==e);let i=this._state.activeSessionId;if(i===e){if(n.length===0)i=null;else{const s=Math.min(r,n.length-1);i=n[s].sessionId}this._persistActiveSessionId(i)}this._state={tabs:n,activeSessionId:i},this.host.requestUpdate()}_setActiveTab(e){e!==null&&e!==this._state.activeSessionId?(this._state={...this._state,activeSessionId:e},this._persistActiveSessionId(e),this.host.requestUpdate()):e===null&&this._state.activeSessionId!==null&&(this._state={...this._state,activeSessionId:null},this._persistActiveSessionId(null),this.host.requestUpdate())}_clearAll(){this._state={tabs:[],activeSessionId:null},this._persistActiveSessionId(null),this.host.requestUpdate()}_persistActiveSessionId(e){try{if(typeof window>"u"||!window.localStorage)return;e===null?window.localStorage.removeItem(G_):window.localStorage.setItem(G_,e)}catch{}}_getStoredActiveSessionId(){try{return typeof window>"u"||!window.localStorage?null:window.localStorage.getItem(G_)}catch{return null}}_setTransientParams(e,r){if(!this._state.tabs.find(s=>s.sessionId===e))return;const i=this._state.tabs.map(s=>s.sessionId===e?{...s,initialInputValue:r.initialInputValue,noticeMessage:r.noticeMessage,initialValueVersion:(s.initialValueVersion??0)+1}:s);this._state={...this._state,tabs:i},this.host.requestUpdate()}_clearTransientParams(e){const r=this._state.tabs.find(i=>i.sessionId===e);if(!r||r.initialInputValue===void 0&&r.noticeMessage===void 0)return;const n=this._state.tabs.map(i=>i.sessionId===e?{...i,initialInputValue:void 0,noticeMessage:void 0}:i);this._state={...this._state,tabs:n},this.host.requestUpdate()}_restoreActiveFromStorage(){const e=this._getStoredActiveSessionId();return e?this._state.tabs.some(r=>r.sessionId===e)?this._state.activeSessionId===e?(gy.debug("Already active:",e),!1):(gy.debug("Restoring active tab:",e),this._state={...this._state,activeSessionId:e},this.host.requestUpdate(),!0):(gy.debug("Stored id not in tabs:",e),!1):!1}}const d4=er("SettingsController");class _z{constructor(e){this._state={...nf},this.host=e,this.host.addController(this),this.actions={updateAppearance:r=>this._update("appearance",r),updateChat:r=>this._update("chat",r),updateFiles:r=>this._update("files",r),updateNotifications:r=>this._update("notifications",r),resetAll:()=>this._reset()},this._restore()}get value(){return{state:this._state,actions:this.actions}}hostConnected(){this._removeGlobalListeners(),this._themeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this._themeMediaListener=()=>{this._state.appearance.theme==="system"&&this._applyTheme()},this._themeMediaQuery.addEventListener("change",this._themeMediaListener),(this.host.closest("rtc-agent")||this.host).hasAttribute("theme")||this._applyTheme(),this._applyFontSize(),this._storageListener=()=>this._handleStorageChange(),window.addEventListener("storage",this._storageListener)}hostDisconnected(){this._removeGlobalListeners(),document.documentElement.style.removeProperty("--rtc-font-size-user")}_removeGlobalListeners(){this._storageListener&&(window.removeEventListener("storage",this._storageListener),this._storageListener=void 0),this._themeMediaQuery&&this._themeMediaListener&&(this._themeMediaQuery.removeEventListener("change",this._themeMediaListener),this._themeMediaListener=void 0)}_restore(){var e,r;try{const n=localStorage.getItem(Xr.settings);if(!n)return;const i=JSON.parse(n);this._state={appearance:{theme:this._validateTheme((e=i.appearance)==null?void 0:e.theme),fontSize:this._validateFontSize((r=i.appearance)==null?void 0:r.fontSize)},chat:{...nf.chat,...i.chat},files:{...nf.files,...i.files},notifications:{...nf.notifications,...i.notifications}}}catch(n){d4.debug("Failed to restore settings:",n)}}_update(e,r){const n=this._state;this._state={...this._state,[e]:{...this._state[e],...r}},this._persist(),this._applyDiff(n,this._state),this.host.requestUpdate()}_reset(){const e=this._state;this._state={...nf},this._persist(),this._applyDiff(e,this._state),this.host.requestUpdate()}_persist(){try{localStorage.setItem(Xr.settings,JSON.stringify(this._state))}catch(e){d4.debug("Failed to persist settings:",e)}}_applyDiff(e,r){e.appearance.theme!==r.appearance.theme&&this._applyTheme(),e.appearance.fontSize!==r.appearance.fontSize&&this._applyFontSize()}_applyTheme(){var i;const e=this._state.appearance.theme,r=e==="system"?(i=this._themeMediaQuery)!=null&&i.matches?"dark":"light":e,n=this.host.closest("rtc-agent")||this.host;"theme"in n&&(n.theme=r)}_applyFontSize(){const e=this._state.appearance.fontSize,r=Math.min(24,Math.max(12,e));document.documentElement.style.setProperty("--rtc-font-size-user",`${r}px`)}_handleStorageChange(){const e=this._state;this._restore(),this._applyDiff(e,this._state),this.host.requestUpdate()}_validateTheme(e){return e==="light"||e==="dark"||e==="system"?e:"system"}_validateFontSize(e){return Math.min(24,Math.max(12,typeof e=="number"?e:14))}}const xz="data:audio/mpeg;base64,//OEZAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAAQAAAJYAAQEBAQEBAsLCwsLCw9PT09PT1NTU1NTU1WVlZWVlZWWVlZWVlZW1tbW1tbd3d3d3d3mZmZmZmZmaSkpKSkpLKysrKystPT09PT097e3t7e3t7v7+/v7+/9/f39/f3///////8AAAA5TEFNRTMuMTAwAm4AAAAALjQAABRGJAPbTgAARgAACWCFGVdaAAAAAAAAAAAAAAAAAAAA//NkZAANhHcWAK1sAAAAAfgBQAAA/DDGVu25cP5PuudMdQd53QVIuxIRPsQBjKGjKAAufOHfPn1PGxMVIOfpTlWsiYzHjo0I8MqDiQFMRC0xjFRkxMFZMXULMJWRlnb93sMN16e33Cnt9wpAwXDBccCAkOB8QBEEMMCQ4J//h/l3qnY7GgAB+4JRKLhaNwwx//OUZA4cqedfH8zUAYAAAjQBgBAAljoAki78OGEga8ANe/I1AlAy/xhnf4NkAYCBwGFgIH+AwaFABquUghBYGPA8BjMFh1A6QkggBQYxIw6CEBjzYLgBkAtHHcQQQRFakqIVFkmCdogmQc3Jsc8rmIs0QqXjEcn8xHPImVCbJ8nCHESRKRBi8Uv7JkUNJgXDRRFiLJE0RZaiaMf+RQnDcwNCfUgXzeZmpSKJOomJOkysukVV/+X01l83PGZuaLTLjUEFmKnRSSqSSUkl//+gcJg0dBA3UaG7003Wmny8tAvIoqMSKl1ZqXaJdUlqf0DL//NkZAMOtM88v+5QAQAAAigBwAAArrQB+NavMZczzwpZTvKvSzkPNabCCAKYKAoGBo6HBp3nJp6a0RYHJeAb1kBoRAWVEkUROpo5w/UVjFExbkGPIO6aFZmnUaIOggo8mXz7mpmmX3UaIVNv109CxuiplmIkEIJlARFS+slKNJoHtFWnqqbM5Rag2gqPaiVn//NkZAgNtGMYCRuaNgA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VZ+EJLlInoWY3FUUuRIkWxprfFVlatjaFlZFqyLeqhrZVJZrxpZEki3/rIkSGCyJrf6jSK0LNSRJPjFVlYm24ERN5JoYwpMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqr/+5LEpgPbOgrmD20nSAAANIAAAASqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq",yy=er("NotificationController"),ec=class ec{constructor(e){this._state={...B2},this._sounds=new Map,this._lastNotifyTime=0,this._abortController=new AbortController,this.host=e,this.host.addController(this),this.actions={markAsRead:()=>this._markAsRead(),clearAll:()=>this._clearAll()}}get value(){return{state:this._state,actions:this.actions}}hostConnected(){this._preloadSounds(),this._subscribeToMessages()}hostDisconnected(){var e;(e=this._busUnsubscribe)==null||e.call(this),this._sounds.clear(),this._deferredSoundTimer&&(clearTimeout(this._deferredSoundTimer),this._deferredSoundTimer=void 0),this._idleCallbackId!==void 0&&(cancelIdleCallback(this._idleCallbackId),this._idleCallbackId=void 0),this._abortController.abort(),this._abortController=new AbortController,this.host.removeAttribute("data-notification")}_preloadSounds(){this._sounds.clear();const e={message:xz};for(const[i,s]of Object.entries(e))this._loadSound(i,s);const r={complete:wz,error:Sz},n=()=>{this._deferredSoundTimer!==void 0&&(clearTimeout(this._deferredSoundTimer),this._deferredSoundTimer=void 0),this._idleCallbackId=void 0;for(const[i,s]of Object.entries(r))this._loadSound(i,s)};this._idleCallbackId!==void 0&&(cancelIdleCallback(this._idleCallbackId),this._idleCallbackId=void 0),"requestIdleCallback"in window?(this._idleCallbackId=requestIdleCallback(n),this._deferredSoundTimer=setTimeout(()=>{this._idleCallbackId!==void 0&&(cancelIdleCallback(this._idleCallbackId),this._idleCallbackId=void 0),n()},ec.IDLE_FALLBACK_DELAY_MS)):this._deferredSoundTimer=setTimeout(n,ec.DEFERRED_SOUND_DELAY_MS)}_loadSound(e,r){const n=new Audio;n.preload="auto",n.addEventListener("canplaythrough",()=>{this.host.isConnected&&this._sounds.set(e,n)},{once:!0}),n.addEventListener("error",()=>{yy.warn(`Audio load failed (file may not exist): ${r}`),this._sounds.delete(e)},{once:!0}),n.src=r}_playSound(e){var i;const r=(i=this.settingsController)==null?void 0:i.value.state.notifications;if(!(r!=null&&r.soundEnabled))return;const n=this._sounds.get(e);n&&(n.currentTime=0,n.volume=1,n.play().catch(s=>{s.name==="NotAllowedError"?yy.warn("Audio playback blocked by browser; user interaction required"):yy.warn("Playback failed:",s)}))}_subscribeToMessages(){var r;(r=this._busUnsubscribe)==null||r.call(this);const e=_u();this._busUnsubscribe=e.subscribe("message",n=>{n.action==="created"&&n.field==="content"&&this._handleNewMessage(n)})}async _handleNewMessage(e){const r=Date.now();if(!(r-this._lastNotifyTime<ec.NOTIFY_THROTTLE_MS)){this._lastNotifyTime=r;try{const n=this._abortController.signal,i=this.persistence?await Promise.race([this.persistence.getMessage(e.entityId),new Promise((o,l)=>{if(n.aborted){l(new DOMException("Aborted","AbortError"));return}n.addEventListener("abort",()=>{l(new DOMException("Aborted","AbortError"))},{once:!0})})]):void 0;if(n.aborted)return;const s=i==null?void 0:i.session_client_id;if(!s||!this._shouldNotify(s))return;this._triggerNotification(e,s)}catch(n){if(n instanceof Error&&n.name==="AbortError")return;yy.error("Failed to handle message:",n)}}}_shouldNotify(e){var i,s;const r=(i=this.sessionController)==null?void 0:i.value.state.currentSessionId;if(r&&e===r)return!1;const n=(s=this.settingsController)==null?void 0:s.value.state.notifications;return!(!(n!=null&&n.soundEnabled)&&!(n!=null&&n.toastEnabled))}_triggerNotification(e,r){var i;this._playSound("message"),this._state={unreadCount:this._state.unreadCount+1,lastNotificationAt:Date.now()},this.host.requestUpdate(),((i=this.windowStateController)==null?void 0:i.value.state.mode)==="minimized"?this._animateMinimizeIcon():this._showToast(e,r)}_showToast(e,r){var d,u,h;const n=(d=this.settingsController)==null?void 0:d.value.state.notifications;if(!(n!=null&&n.toastEnabled))return;const i=e.newValue,s=gh(i),l=(((u=this.sessionController)==null?void 0:u.value.state.sessions)??[]).find(g=>g.clientId===r),c=(l==null?void 0:l.title)??Me("新消息");(h=this.toastController)==null||h.actions.show(`${c}: ${s}`,"info",{label:Me("查看"),onClick:()=>this._navigateToSession(r)})}_navigateToSession(e){var r;(r=this.sessionController)==null||r.actions.switchSession(e),this.actions.markAsRead(),this.host.dispatchEvent(new CustomEvent("rtc-notification-click",{bubbles:!0,composed:!0,detail:{sessionId:e}}))}_animateMinimizeIcon(){this.host.setAttribute("data-notification","active")}_clearAnimation(){this.host.removeAttribute("data-notification")}_markAsRead(){this._state={...this._state,unreadCount:0},this._clearAnimation(),this.host.requestUpdate()}_clearAll(){this._state={...B2},this._clearAnimation(),this.host.requestUpdate()}};ec.NOTIFY_THROTTLE_MS=300,ec.IDLE_FALLBACK_DELAY_MS=2e3,ec.DEFERRED_SOUND_DELAY_MS=500;let Y_=ec;class Tz{constructor(e,r){this.host=e,this.deps=r,this.host.addController(this),this._initializeHandlers()}hostConnected(){}hostDisconnected(){this.unbindEvents(this.host)}_initializeHandlers(){const{windowState:e,auth:r,session:n,message:i,persistence:s,toast:o,fork:l,activity:c,fileExplorer:d,editorArea:u,settings:h,sessionTab:g,autoSaveTimers:b,getRtcProcessor:I,setRtcProcessor:P,getUnsubConnection:C,setUnsubConnection:T,bumpConnectGeneration:w,setConnecting:S,fileTreeLoaded:v,setFileTreeLoaded:O,setInitialSessionLoadDone:N,loadFileTree:D,loadFolderChildren:B,handleFileOpen:Q,handleEditorSave:te,handleRestoreDefault:F,handleCommand:K,beforeMessageSend:ge,showRestoreConfirmDialog:Ie,handleLoginRequested:qe,dispatchClearActiveInput:Pe,getShadowRoot:he,findScrollableParent:me,scheduleAutoSave:G,log:re}=this.deps;this._boundOnMinimize=()=>e.actions.minimize(),this._boundOnMaximize=()=>e.actions.maximize(),this._boundOnRestore=()=>e.actions.restore(),this._boundOnLoginRequested=ye=>{qe(ye)},this._boundOnLogout=()=>{for(const V of b.values())clearTimeout(V);b.clear(),O(!1),N(!1),u.actions.closeAll(),g.actions.clearAll(),c.actions.setActivity("chat"),l.actions.clearFork();const ye=I();ye==null||ye.cancel(),P(void 0);const le=C();le==null||le(),T(void 0),w(),S(void 0),s.disconnect(),n.actions.reset(),i.actions.clearMessages()},this._boundOnAccountBanned=ye=>{re.warn("account banned, triggering logout");const le=ye.detail,V=le==null?void 0:le.reason;try{sessionStorage.removeItem("rtc-account-banned-pending")}catch{}o.actions.show(rT(V),"error"),r.actions.logout()},this._boundOnNewSession=()=>{l.actions.clearFork(),n.value.state.currentSessionId||i.actions.clearMessages()},this._boundOnSessionDeleteRequested=async ye=>{const{sessionId:le}=ye.detail;re.debug("session delete requested:",le);const V=await n.actions.deleteSession(le);if(V.ok)o.actions.show("会话已删除","success");else{const $={"delete-failed":"删除失败,请稍后重试"};o.actions.show($[V.error??""]??V.error??"删除失败","error")}},this._boundOnSessionRenameConfirmed=async ye=>{const{sessionId:le,title:V}=ye.detail;if(!V.trim())return;const $=await n.actions.renameSession(le,V.trim());if(!$.ok){const ne={"rename-failed":"重命名失败,请稍后重试"};o.actions.show(ne[$.error??""]??$.error??"重命名失败","error")}},this._boundOnInputSubmit=async ye=>{const V=ye.detail.contentData,ne=(Ae=>typeof Ae=="string"?Ae:"")(V.data),ce={message:{content:ne,metadata:void 0}};if(await ge(ce)){ce.message.content!==ne&&(V.data=ce.message.content);try{l.isActive?await l.actions.submitFork(V):await i.actions.sendMessage(V);const Ae=n.value.state.currentSessionId;Ae&&g.actions.markSaved(Ae)}catch(Ae){re.error("message submit failed:",Ae)}}},this._boundOnForkInitiated=ye=>{const{oldSessionClientId:le,oldMessageClientId:V,newSessionClientId:$,content:ne}=ye.detail;l.actions.requestFork(le,V,$,ne)},this._boundOnStopRequested=ye=>{const le=ye.detail;s.layer&&s.layer.stopTurn(le.sessionClientId)},this._boundOnResendMessage=ye=>{const V=ye.detail.message;V!=null&&V.clientId&&(V!=null&&V.content)&&i.actions.resendMessage(V.clientId,V.content)},this._boundOnToastRequested=ye=>{const le=ye.detail;o.actions.show(le.message,le.type)},this._boundOnToastClose=ye=>{const le=ye.detail;o.actions.remove(le.id)},this._boundOnCommandRequested=ye=>{const le=ye.detail;K(le.name,le.args)},this._boundOnActivityChange=ye=>{const{activity:le,toggleSidebar:V}=ye.detail;V?c.actions.toggleSidebar():(c.actions.setActivity(le),le==="settings"&&c.actions.showSidebar(),le==="files"&&!v()&&s.isConnected&&D())},this._boundOnFileSelect=ye=>{const{path:le}=ye.detail;Q(le)},this._boundOnFolderToggle=ye=>{const{path:le}=ye.detail;d.value.isExpanded(le)&&(re.debug("_boundOnFolderToggle: loading children for",le),B(le))},this._boundOnFileExplorerRefresh=()=>{D()},this._boundOnEditorAreaSave=ye=>{const{filePath:le}=ye.detail;te(le)},this._boundOnEditorAreaTabClose=ye=>{const{filePath:le}=ye.detail,V=b.get(le);V&&(clearTimeout(V),b.delete(le)),u.actions.closeFile(le)},this._boundOnEditorAreaTabSelect=ye=>{const{filePath:le}=ye.detail;u.actions.switchTab(le)},this._boundOnEditorAreaContentChange=ye=>{const{filePath:le,content:V}=ye.detail;u.actions.updateContent(le,V),h.value.state.files.autoSave&&G(le)},this._boundOnEditorAreaViewModeChange=ye=>{const{filePath:le,viewMode:V}=ye.detail;u.actions.setViewMode(le,V)},this._boundOnEditorAreaCursorMove=ye=>{const le=ye.detail,V=u.activeFilePath;V&&u.actions.setCursorPosition(V,le)},this._boundOnEditorAreaRestoreDefault=async ye=>{const{filePath:le}=ye.detail;if(!await Ie(le,he()))return;const $=await F(le);$.success?o.actions.show("已恢复默认内容","success"):o.actions.show($.error??"恢复失败","error")},this._boundOnChatLayoutSessionSelect=ye=>{const{sessionId:le}=ye.detail;re.debug("chat-layout session selected:",le)},this._boundOnChatLayoutTabActivate=ye=>{const{sessionId:le}=ye.detail;re.debug("chat-layout tab activated:",le)},this._boundOnChatLayoutTabClose=ye=>{const{sessionId:le}=ye.detail;re.debug("chat-layout tab closed:",le)},this._boundOnKeydown=ye=>{if(ye.key==="Escape"&&l.isActive){l.actions.clearFork(),Pe();return}if(!(c.active!=="files"||!(ye.metaKey||ye.ctrlKey))){if(ye.key==="s"||ye.key==="S"){const V=u.state.activeFilePath;V&&(ye.preventDefault(),te(V))}else if(ye.key==="w"||ye.key==="W"){const V=u.state.activeFilePath;V&&(ye.preventDefault(),u.actions.closeFile(V))}}},this._boundOnWheel=ye=>{const le=ye.composedPath()[0],V=le instanceof Element?le:null,$=V?me(V):null;if(!$){ye.preventDefault(),ye.stopPropagation();return}const{scrollTop:ne,scrollHeight:ce,clientHeight:Se,scrollLeft:Ae,scrollWidth:Ne,clientWidth:Xe}=$,be=ne<=0,Te=Math.ceil(ne+Se)>=ce,lt=ye.deltaY<0,it=ye.deltaY>0,Pt=ce>Se,We=Ae<=0,Ve=Math.ceil(Ae+Xe)>=Ne,Je=ye.deltaX<0||ye.shiftKey&&ye.deltaY<0,ot=ye.deltaX>0||ye.shiftKey&&ye.deltaY>0,Dt=Ne>Xe;(Pt&&(be&<||Te&&it)||Dt&&(We&&Je||Ve&&ot))&&(ye.preventDefault(),ye.stopPropagation())},this._boundOnDrawerClose=()=>{c.actions.hideSidebar()}}bindEvents(e){e.addEventListener("rtc-window-minimize",this._boundOnMinimize),e.addEventListener("rtc-window-maximize",this._boundOnMaximize),e.addEventListener("rtc-window-restore",this._boundOnRestore),e.addEventListener("rtc-auth-login-requested",this._boundOnLoginRequested),e.addEventListener("rtc-auth-logout",this._boundOnLogout),e.addEventListener("rtc-account-banned",this._boundOnAccountBanned),e.addEventListener("rtc-new-session",this._boundOnNewSession),e.addEventListener("rtc-session-delete-requested",this._boundOnSessionDeleteRequested),e.addEventListener("rtc-session-rename-confirmed",this._boundOnSessionRenameConfirmed),e.addEventListener("rtc-input-submit",this._boundOnInputSubmit),e.addEventListener("rtc-fork-initiated",this._boundOnForkInitiated),e.addEventListener("rtc-stop-requested",this._boundOnStopRequested),e.addEventListener("rtc-user-message-resend",this._boundOnResendMessage),e.addEventListener("rtc-toast-requested",this._boundOnToastRequested),e.addEventListener("rtc-toast-close",this._boundOnToastClose),e.addEventListener("rtc-command-requested",this._boundOnCommandRequested),e.addEventListener("activity-change",this._boundOnActivityChange),e.addEventListener("file-select",this._boundOnFileSelect),e.addEventListener("folder-toggle",this._boundOnFolderToggle),e.addEventListener("refresh-requested",this._boundOnFileExplorerRefresh),e.addEventListener("editor-area-save",this._boundOnEditorAreaSave),e.addEventListener("editor-area-tab-close",this._boundOnEditorAreaTabClose),e.addEventListener("editor-area-tab-select",this._boundOnEditorAreaTabSelect),e.addEventListener("editor-area-content-change",this._boundOnEditorAreaContentChange),e.addEventListener("editor-area-view-mode-change",this._boundOnEditorAreaViewModeChange),e.addEventListener("editor-area-cursor-move",this._boundOnEditorAreaCursorMove),e.addEventListener("editor-area-restore-default",this._boundOnEditorAreaRestoreDefault),e.addEventListener("rtc-chat-layout-session-select",this._boundOnChatLayoutSessionSelect),e.addEventListener("rtc-chat-layout-tab-activate",this._boundOnChatLayoutTabActivate),e.addEventListener("rtc-chat-layout-tab-close",this._boundOnChatLayoutTabClose),e.addEventListener("rtc-drawer-close",this._boundOnDrawerClose),e.addEventListener("keydown",this._boundOnKeydown),e.addEventListener("wheel",this._boundOnWheel,{passive:!1})}unbindEvents(e){e.removeEventListener("rtc-window-minimize",this._boundOnMinimize),e.removeEventListener("rtc-window-maximize",this._boundOnMaximize),e.removeEventListener("rtc-window-restore",this._boundOnRestore),e.removeEventListener("rtc-auth-login-requested",this._boundOnLoginRequested),e.removeEventListener("rtc-auth-logout",this._boundOnLogout),e.removeEventListener("rtc-account-banned",this._boundOnAccountBanned),e.removeEventListener("rtc-new-session",this._boundOnNewSession),e.removeEventListener("rtc-session-delete-requested",this._boundOnSessionDeleteRequested),e.removeEventListener("rtc-session-rename-confirmed",this._boundOnSessionRenameConfirmed),e.removeEventListener("rtc-input-submit",this._boundOnInputSubmit),e.removeEventListener("rtc-fork-initiated",this._boundOnForkInitiated),e.removeEventListener("rtc-stop-requested",this._boundOnStopRequested),e.removeEventListener("rtc-user-message-resend",this._boundOnResendMessage),e.removeEventListener("rtc-toast-requested",this._boundOnToastRequested),e.removeEventListener("rtc-toast-close",this._boundOnToastClose),e.removeEventListener("rtc-command-requested",this._boundOnCommandRequested),e.removeEventListener("activity-change",this._boundOnActivityChange),e.removeEventListener("file-select",this._boundOnFileSelect),e.removeEventListener("folder-toggle",this._boundOnFolderToggle),e.removeEventListener("refresh-requested",this._boundOnFileExplorerRefresh),e.removeEventListener("editor-area-save",this._boundOnEditorAreaSave),e.removeEventListener("editor-area-tab-close",this._boundOnEditorAreaTabClose),e.removeEventListener("editor-area-tab-select",this._boundOnEditorAreaTabSelect),e.removeEventListener("editor-area-content-change",this._boundOnEditorAreaContentChange),e.removeEventListener("editor-area-view-mode-change",this._boundOnEditorAreaViewModeChange),e.removeEventListener("editor-area-cursor-move",this._boundOnEditorAreaCursorMove),e.removeEventListener("editor-area-restore-default",this._boundOnEditorAreaRestoreDefault),e.removeEventListener("rtc-chat-layout-session-select",this._boundOnChatLayoutSessionSelect),e.removeEventListener("rtc-chat-layout-tab-activate",this._boundOnChatLayoutTabActivate),e.removeEventListener("rtc-chat-layout-tab-close",this._boundOnChatLayoutTabClose),e.removeEventListener("rtc-drawer-close",this._boundOnDrawerClose),e.removeEventListener("keydown",this._boundOnKeydown),e.removeEventListener("wheel",this._boundOnWheel)}get handlers(){return{onLoginRequested:this._boundOnLoginRequested}}}const f4=er("FunctionsController");class Ez{constructor(e){this._registry=null,this._state={...wb},this.host=e,this.host.addController(this),this.actions={refresh:()=>this._refresh()}}get value(){return{state:this._state,actions:this.actions}}hostConnected(){}hostDisconnected(){}setRegistry(e){this._registry=e,e?this._refresh():(this._state={...wb},this.host.requestUpdate())}_refresh(){if(!this._registry){this._state={...wb},this.host.requestUpdate();return}try{const e=this._registry.listFunctions(),r=this._registry.listGroups();this._state={functions:e,groups:r},f4.debug("Refreshed function list:",e.length,"functions,",r.length,"groups"),this.host.requestUpdate()}catch(e){f4.error("Failed to refresh function list:",e)}}}function J_(t,e){var o,l;const r=[];let n=t;for(;n!=null&&n._def;){const c=n._def.typeName||n._def.type;if(c==="ZodOptional"||c==="optional"||c==="ZodDefault"||c==="default")n=n._def.innerType;else break}const i=(n==null?void 0:n._def)&&(n._def.typeName==="ZodObject"||n._def.shape!==void 0&&typeof n._def.shape=="object"&&!Array.isArray(n._def.shape));if(!n||!n._def||!i)throw new Error("zodToParams expects a ZodObject schema (got: "+(((o=n==null?void 0:n._def)==null?void 0:o.typeName)||((l=n==null?void 0:n._def)==null?void 0:l.type)||"unknown")+")");const s=typeof n._def.shape=="function"?n._def.shape():n._def.shape;for(const[c,d]of Object.entries(s)){const u=Eo(d),{isOptional:h,description:g,example:b}=X_(d);r.push({name:c,schema:{...u,description:(e==null?void 0:e[c])||g||u.description,...b!==void 0?{example:b}:{}},required:!h,description:(e==null?void 0:e[c])||g})}return r}function X_(t){var c,d;const e=t._def;if(!e)return{isOptional:!1};let r=!1,n,i;const s=e.typeName||e.type;if((s==="ZodOptional"||s==="optional"||s==="ZodDefault"||s==="default")&&(r=!0,e.innerType)){const u=X_(e.innerType);n=u.description,i=u.example}e.description?n=e.description:t.description&&(n=t.description);const o=e.meta;(o==null?void 0:o.example)!==void 0?i=o.example:o!=null&&o.examples&&o.examples.length>0&&(i=o.examples[0]);const l=(c=t._zod)==null?void 0:c.bag;if(i===void 0&&(l==null?void 0:l.example)!==void 0?i=l.example:i===void 0&&(l!=null&&l.examples)&&l.examples.length>0&&(i=l.examples[0]),i===void 0&&(s==="ZodEnum"||s==="enum")&&((d=e.values)==null?void 0:d.length)>0&&(i=e.values[0]),i===void 0&&(s==="ZodDefault"||s==="default")&&typeof e.defaultValue=="function")try{i=e.defaultValue()}catch{}return{isOptional:r,description:n,example:i}}function Z_(t){return Eo(t)}function Eo(t){const e=t._def;if(!e)return{};const r=e.meta,n=r==null?void 0:r.format;switch(e.typeName||e.type){case"ZodString":case"string":{const s={type:"string"};if(e.checks)for(const o of e.checks){const l=o.def||o,c=o.kind||l.check,d=o.value??l.value;if((c==="min"||c==="minLength")&&(s.minLength=d),(c==="max"||c==="maxLength")&&(s.maxLength=d),c==="regex"){const u=o.regex||l.regex;u&&(s.pattern=u.source||u)}}return n&&(s.format=n),s}case"ZodNumber":case"number":{const s={type:"number"};let o=!1;if(e.checks)for(const l of e.checks){const c=l.def||l,d=l.kind||c.check,u=l.value??c.value;d==="min"&&(s.minimum=u),d==="max"&&(s.maximum=u),(d==="int"||c.type==="number"&&c.format==="safeint")&&(o=!0)}return o&&(s.type="integer"),n&&(s.format=n),s}case"ZodBoolean":case"boolean":return{type:"boolean"};case"ZodEnum":case"enum":return{type:"string",enum:e.values};case"ZodArray":case"array":return{type:"array",items:Eo(e.element||e.type)};case"ZodOptional":case"optional":return Eo(e.innerType);case"ZodDefault":case"default":return{...Eo(e.innerType),default:typeof e.defaultValue=="function"?e.defaultValue():e.defaultValue};case"ZodObject":case"object":{const s=typeof e.shape=="function"?e.shape():e.shape;if(!s)return{type:"object"};const o={},l=[];for(const[u,h]of Object.entries(s)){const g=Eo(h),b=X_(h);b.description&&!g.description&&(g.description=b.description),o[u]=g,b.isOptional||l.push(u)}const c={type:"object",properties:o};l.length>0&&(c.required=l);const d=e.description||t.description;return d&&(c.description=d),c}case"ZodVoid":case"void":return{type:"null"};case"ZodNull":case"null":return{type:"null"};case"ZodNullable":case"nullable":return{...Eo(e.innerType),nullable:!0};case"ZodRecord":case"record":{const s=e.valueType||e.type;return{type:"object",additionalProperties:s?Eo(s):{}}}case"ZodAny":case"any":return{};case"ZodUnknown":case"unknown":return{};case"ZodLiteral":case"literal":{const s=e.value,o=typeof s;return o==="string"?{type:"string",enum:[s]}:o==="number"?{type:"number",enum:[s]}:o==="boolean"?{type:"boolean",enum:[s]}:{enum:[s]}}case"ZodUnion":case"union":case"ZodDiscriminatedUnion":case"discriminatedUnion":{const s=e.options||[];return s.length===0?{}:{oneOf:s.map(l=>Eo(l))}}case"ZodIntersection":case"intersection":{const s=Eo(e.left),o=Eo(e.right);return{allOf:[s,o]}}case"ZodTuple":case"tuple":{const s=(e.items||[]).map(o=>Eo(o));return{type:"array",items:s.length>0?{oneOf:s}:{},minItems:s.length,maxItems:s.length}}default:return{}}}function by(t,e){const r=t._def;return r&&(r.meta={...r.meta,...e}),t}const p4=er("MarkdownGenerator");function tl(t){return t?t.$ref?`[${t.$ref.split("/").pop()||t.$ref}](${t.$ref})`:t.oneOf&&t.oneOf.length>0?t.oneOf.map(e=>tl(e)).join(" | "):t.type==="array"&&t.items?`${tl(t.items)}[]`:t.type==="object"&&t.properties?`{ ${Object.entries(t.properties).map(([r,n])=>`${r}: ${tl(n)}`).join(", ")} }`:t.type?t.format?`${t.type} (${t.format})`:t.type:t.format?t.format:"unknown":"unknown"}function vy(t,e,r,n,i=0){const s=[],o=" ".repeat(i),l=i>0?`└─ ${e}`:e,c=t.example!==void 0?`\`${JSON.stringify(t.example)}\``:"";if(t.type&&t.type!=="object"&&t.type!=="array"){const g=tl(t),b=n||t.description||"",I=r?"Yes":"No";return s.push(`| ${o}${l} | ${g} | ${I} | ${b} | ${c} |`),s}if(t.type==="array"&&t.items){const g=`${tl(t.items)}[]`,b=n||t.description||"",I=r?"Yes":"No";if(s.push(`| ${o}${l} | ${g} | ${I} | ${b} | ${c} |`),t.items.type==="object"&&t.items.properties){const P=t.items.required||[];for(const[C,T]of Object.entries(t.items.properties)){const w=P.includes(C);s.push(...vy(T,C,w,T.description,i+1))}}return s}if(t.type==="object"&&t.properties){const g=n||t.description||"",b=r?"Yes":"No";s.push(`| ${o}${l} | object | ${b} | ${g} | ${c} |`);const I=t.required||[];for(const[P,C]of Object.entries(t.properties)){const T=I.includes(P);s.push(...vy(C,P,T,C.description,i+1))}return s}const d=tl(t),u=n||t.description||"",h=r?"Yes":"No";return s.push(`| ${o}${l} | ${d} | ${h} | ${u} | ${c} |`),s}function Q_(t,e){var s,o,l,c,d;let r=`<!-- AUTO-GENERATED by rtc-agent FunctionRegistry. Do not edit manually. -->
|
|
3313
|
+
- Or reference it by path: ${s}`}}catch(s){return{success:!1,error:`Failed to save script: ${s instanceof Error?s.message:String(s)}`}}}async _runScript(e){const r=pi(e,"name");if(!r)return{success:!1,error:"name is required for run action"};const n=e.params||{},i=ga(e,"timeout")??3e4,s=pi(e,"title")??void 0;return this._executeCode(r,n,i,void 0,s)}async _evalScript(e){const r=pi(e,"code");if(!r)return{success:!1,error:"code is required for eval action"};const n=e.params||{},i=ga(e,"timeout")??3e4,s=pi(e,"title")??void 0;return this._executeCode(void 0,n,i,r,s)}async _executeCode(e,r,n,i,s){if(!this.rtcAgent)return{success:!1,error:"rtcAgent not initialized. Pass rtcAgent to ScriptTool constructor."};try{let o;if(i!==void 0)o=i;else{const I=`/scripts/${e}.ts`,P=await Vr.read(I);o=WU(P).code}const l={logs:[],warns:[],errors:[]},c=$U(this.rtcAgent,r,l,s||void 0),d=performance.now(),u=await KU(o,c,n,e),h=Math.round(performance.now()-d),g={};e&&(g.name=e),u!==void 0&&(g.result=u);const b=100;return l.logs.length>0&&(g.logs=l.logs.slice(0,b).map(V_)),l.warns.length>0&&(g.warnings=l.warns.slice(0,b).map(V_)),l.errors.length>0&&(g.errors=l.errors.slice(0,b).map(V_)),g.duration_ms=h,{success:!0,data:g}}catch(o){return o instanceof Error&&"isScriptTimeout"in o?{success:!1,error:o.message}:o instanceof Error&&"isScriptCompileError"in o?{success:!1,error:`Script compile error: ${o.message}`}:{success:!1,error:`Script execution failed: ${o instanceof Error?o.message:String(o)}`}}}}function rz(t){return[new JU,new XU,new ZU,new QU,new ez,new tz,new QO(t)]}const nz=er("ToolRegistry");class iz{constructor(e){sr(this,"tools",new Map);const r=rz(e);for(const n of r)this.register(n)}setRtcAgent(e){this.register(new QO(e))}register(e){this.tools.has(e.name)&&nz.warn(`Tool '${e.name}' is already registered and will be overwritten.`),this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getToolNames(){return Array.from(this.tools.keys())}async execute(e,r){const n=this.tools.get(e);if(!n)throw new Error(`Tool not found: ${e}`);return n.execute(r)}}const e4=new iz,Qn=er("RtcProcessor"),sz=1e3,t4=6e4,W_=10;class oz{constructor(e){sr(this,"persistence");sr(this,"processing",!1);sr(this,"pendingCheck",!1);sr(this,"retryCountMap",new Map);sr(this,"mode","edit");sr(this,"confirmDialog");sr(this,"askUserDialog");sr(this,"master");sr(this,"_lastSilentlySkippedRtcId");sr(this,"_abortController");this.persistence=e}setMode(e){this.mode=e}getMode(){return this.mode}setConfirmDialog(e){this.confirmDialog=e}setAskUserDialog(e){this.askUserDialog=e}setMaster(e){this.master=e}_isMasterAllowed(){return this.master===void 0||this.master.isMaster}cancel(){this._abortController?(Qn.debug("cancel() called, aborting processLoop"),this._abortController.abort()):Qn.debug("cancel() called, but no processLoop is running")}async onRtcUpdate(){if(this.processing){this.pendingCheck=!0;return}await this.processLoop()}async processLoop(){if(!this._isMasterAllowed()){Qn.debug("processLoop: not master, skipping");return}this._abortController=new AbortController;const e=this._abortController.signal;this.processing=!0,this._lastSilentlySkippedRtcId=void 0;try{for(;;){if(!this._isMasterAllowed()){Qn.debug("processLoop: lost master status during loop, exiting");break}if(e.aborted){Qn.debug("processLoop: cancelled, exiting");break}this.pendingCheck=!1;const r=await this.persistence.getNextRtcToProcess(void 0);if(!r){if(this.pendingCheck)continue;break}if(r.client_id===this._lastSilentlySkippedRtcId){Qn.warn(`processLoop: RTC ${r.client_id} returned again after silent skip, exiting loop to prevent infinite retry`);break}Qn.debug("processing RTC:",r.client_id,"tool:",r.tool_name,"sync_status:",r.sync_status);try{await this.processOne(r),Qn.debug("processOne completed successfully")}catch(n){if(n instanceof DOMException&&n.name==="AbortError")throw Qn.debug("processOne: sleep aborted by cancel(), propagating"),n;Qn.error("processOne failed:",n);const i=n instanceof Error?n.message:String(n);if(i.includes("connection")||i.includes("disconnected")){Qn.warn("connection error detected, exiting processLoop");break}await this.sleep(sz,e)}}}catch(r){if(r instanceof DOMException&&r.name==="AbortError")Qn.debug("processLoop: sleep aborted by cancel(), exiting");else throw r}finally{this.processing=!1,this._abortController=void 0}}async processOne(e){var r;if(e.sync_status==="failed"){const n=this.retryCountMap.get(e.client_id)||0;if(n>=W_){Qn.error(`RTC ${e.client_id} exceeded max submit retry count (${W_}), abandoning. The RTC remains in sync_status='failed' and will be retried on the next onRtcUpdate cycle.`),this.retryCountMap.delete(e.client_id),this._lastSilentlySkippedRtcId=e.client_id;return}const i=this.calculateBackoff(n);await this.sleep(i,(r=this._abortController)==null?void 0:r.signal);try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:e.status==="completed",result:e.result,error:e.error_message}),this.retryCountMap.delete(e.client_id)}catch(s){throw this.retryCountMap.set(e.client_id,n+1),s}}else{const n=e.tool_name;if(n==="askUser"){await this.processAskUser(e);return}const i=uR.needsConfirm(n,this.mode);let s=!0;if(i&&(s=await this.showConfirmDialog(e)),!s){try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!1,error:"User denied"})}catch(d){Qn.error("submitRtcResult (denied) failed, marking as synced to prevent retry:",d);try{await this.persistence.getEntityRepository().upsertRtc({client_id:e.client_id},"synced")}catch(u){Qn.error("Failed to mark RTC as synced:",u),this.retryCountMap.set(e.client_id,W_)}}return}let o,l=!0,c;try{const d=e.parameters||{},u=e4.execute(n,d);let h;const g=new Promise((I,P)=>{h=setTimeout(()=>P(new Error(`Tool execution timeout after ${t4}ms`)),t4)});let b;try{b=await Promise.race([u,g])}finally{clearTimeout(h)}u.catch(()=>{}),o=b.data,b.success||(l=!1,c=b.error)}catch(d){l=!1,c=d instanceof Error?d.message:String(d)}try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:l,result:o,error:c})}catch(d){Qn.error("submitRtcResult failed:",d)}}}async processAskUser(e){if(!this.askUserDialog){Qn.warn("askUserDialog not set, defaulting to reject");try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!1,error:"User declined to answer questions"})}catch(n){Qn.error("submitRtcResult (ask_user no dialog) failed:",n)}return}let r;try{r=await this.askUserDialog(e)}catch(n){Qn.error("askUserDialog threw:",n);try{await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!1,error:n instanceof Error?n.message:String(n)})}catch(i){Qn.error("submitRtcResult (ask_user error) failed:",i)}return}try{r===null?await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!1,error:"User declined to answer questions"}):await this.persistence.submitRtcResult({rtcClientId:e.client_id,success:!0,result:r})}catch(n){Qn.error("submitRtcResult (ask_user) failed:",n)}}calculateBackoff(e){return Math.min(1e3*Math.pow(2,e),3e4)}sleep(e,r){return new Promise((n,i)=>{if(r!=null&&r.aborted){i(new DOMException("Sleep aborted","AbortError"));return}const s=setTimeout(()=>{r==null||r.removeEventListener("abort",o),n()},e),o=()=>{clearTimeout(s),r==null||r.removeEventListener("abort",o),i(new DOMException("Sleep aborted","AbortError"))};r==null||r.addEventListener("abort",o,{once:!0})})}async showConfirmDialog(e){return this.confirmDialog?this.confirmDialog(e):(Qn.warn("confirmDialog not set, defaulting to reject"),!1)}}function r4(t){return new SharedWorker(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/shared-worker-Cqq_7YGD.js").href:new URL("assets/shared-worker-Cqq_7YGD.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{type:"module",name:t==null?void 0:t.name})}const Ln=er("WorkerBridge");function az(t){const e=t.toString(),r=e.match(/new URL\(\s*(["'`])([^"'`]+)\1/);if(r)return r[2];const n=e.match(/new SharedWorker\(\s*(["'`])([^"'`]+)\1/);if(n)return n[2];throw new Error("[WorkerBridge] Cannot extract worker URL from factory. Source: "+e.slice(0,300))}function n4(t,e){let r=0;return(...n)=>{const i=Date.now();i-r>=e&&(r=i,t(...n))}}const Bs=class Bs{constructor(e,r={}){this._auth=e,this._worker=null,this._core=null,this._initialized=!1,this._initPromise=null,this._operationCounter=0,this._connectionListeners=new Set,this._hasRestoredFromStorage=!1,this._yieldResolves=[],this._config=r,this._databaseName="default",this._lastProcessedSeq=0,this._callbacks={onUIUpdate:n=>{_u().publish(n.event,{skipPersist:!0,seqOverride:n.seq}),n.seq>this._lastProcessedSeq&&this._updateLastProcessedSeq(n.seq)},requestToken:async()=>{const n=await this._auth.getAccessTokenAsync();if(!n)throw new Error("[WorkerBridge] no access token available");return n},requestTokenRefresh:()=>this._auth.handleTokenExpired(),onConnectionStateChange:n=>{Ln.debug("[WorkerBridge] onConnectionStateChange called, state:",n.state,"reason:",n.reason,"listeners:",this._connectionListeners.size);for(const i of this._connectionListeners)try{i(n)}catch(s){Ln.error("connection listener error:",s)}},onGapFillState:n=>{Ln.debug("[BulkUpdate] WorkerBridge.onGapFillState called, isSyncing:",n);const i=_u();n?i.emitGapFillStart():i.emitGapFillEnd()},onStateGap:()=>{Ln.warn("catchUp: state gap detected — events were lost (likely TTL cleanup)"),this._lastProcessedSeq=0,this._saveLastProcessedSeq(),_u().emitGapFillEnd()},onAccountBanned:n=>{Ln.warn("Account banned:",n);try{sessionStorage.setItem("rtc-account-banned-pending",JSON.stringify({reason:n,timestamp:Date.now()}))}catch(s){Ln.debug("sessionStorage unavailable for ban state",s)}const i=document.querySelector("rtc-agent");i?(i.dispatchEvent(new CustomEvent("rtc-account-banned",{bubbles:!0,composed:!0,detail:{reason:n}})),Ln.warn("dispatched rtc-account-banned event from onAccountBanned callback")):Ln.error("rtc-agent element not found when handling account banned; ban state saved in sessionStorage")}},this._proxiedCallbacks=wh(this._callbacks)}static _getWorkerName(){return"rtc-agent-worker"}async initWorker(){let e=null;for(let r=0;r<=Bs.MAX_INIT_RETRIES;r++)try{r>0&&(Ln.warn(`Retrying worker initialization (attempt ${r+1}/${Bs.MAX_INIT_RETRIES+1})...`),await this._delay(Bs.INIT_RETRY_DELAY_MS*r)),await this._initWorkerOnce(),await this._verifyWorkerAlive();return}catch(n){e=n instanceof Error?n:new Error(String(n)),Ln.error(`Worker initialization attempt ${r+1} failed:`,e),this._cleanupFailedWorker()}throw new Error(`[WorkerBridge] Failed to initialize SharedWorker after ${Bs.MAX_INIT_RETRIES+1} attempts: ${e==null?void 0:e.message}`)}async _initWorkerOnce(){const e=Bs._getWorkerName();if(this._config.workerURL)Ln.info("Using custom workerURL:",this._config.workerURL),this._worker=new SharedWorker(this._config.workerURL,{name:e,type:"module"});else{const r=az(r4),n=typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:gs&&gs.tagName.toUpperCase()==="SCRIPT"&&gs.src||new URL("index.umd.js",document.baseURI).href,i=new URL(r,n).href,s=window.location.origin;let o;try{o=new URL(i).origin}catch(c){Ln.debug("Failed to parse worker URL origin, assuming same-origin:",c),o=s}const l=o!==s;if(Ln.info("worker init:",{workerURL:i,pageOrigin:s,workerOrigin:o,isCrossOrigin:l}),!l)this._worker=r4({name:e});else{let c;try{const h=await fetch(i,{cache:"default"});if(!h.ok)throw new Error(`HTTP ${h.status} ${h.statusText}`);c=await h.text()}catch(h){throw new Error(`[WorkerBridge] failed to fetch worker script from ${i}: ${h instanceof Error?h.message:h}`)}const d=new Blob([c],{type:"application/javascript"}),u=URL.createObjectURL(d);try{this._worker=new SharedWorker(u,{name:e,type:"module"})}finally{URL.revokeObjectURL(u)}}}this._core=yT(this._worker.port),this._worker.onerror=r=>{Ln.error("SharedWorker error:",{message:r.message,filename:r.filename,lineno:r.lineno,colno:r.colno,error:r.error})},this._worker.port.onmessageerror=r=>{Ln.error("port message error:",r)}}async _verifyWorkerAlive(){if(!this._core)throw new Error("[WorkerBridge] No core available for verification");let e;const r=new Promise((n,i)=>{e=setTimeout(()=>{const s=`Worker verification timed out after ${Bs.VERIFICATION_TIMEOUT_MS}ms. This may indicate a stale SharedWorker from a previous browser session (e.g., after force-killing a tab during debugging). To resolve: visit chrome://inspect/#workers, find and terminate the stale 'rtc-agent-worker' instance, then reload the page.`;i(new Error(s))},Bs.VERIFICATION_TIMEOUT_MS)});try{const n=await Promise.race([this._core.ping(),r]);if(n!=="pong")throw new Error(`Unexpected ping response: ${n}`);Ln.info("Worker verification successful")}catch(n){const i=n instanceof Error?n.message:"unknown error";throw new Error(`[WorkerBridge] Worker verification failed: ${i}`)}finally{e!==void 0&&clearTimeout(e)}}_cleanupFailedWorker(){if(this._worker){try{this._worker.port.close()}catch{}this._worker=null}this._core=null}_delay(e){return new Promise(r=>setTimeout(r,e))}get core(){return this._core}async init(e){if(this._initialized){Ln.warn("already initialized");return}if(this._initPromise)return this._initPromise;this._initPromise=this._doInit(e);try{await this._initPromise,this._initialized=!0}finally{this._initPromise=null}}async _doInit(e){if(!this._worker||!this._core)throw new Error("[WorkerBridge] init() called before initWorker()");const r=e.databaseName??"default",n=r!==this._databaseName;this._databaseName=r,(!this._hasRestoredFromStorage||n)&&(this._lastProcessedSeq=this._loadLastProcessedSeq(),this._hasRestoredFromStorage=!0),this._worker.port.start(),await this._core.init(e),await this._core.registerCallback(this._proxiedCallbacks),await this._doCatchUp()}async destroy(e=!1){var r;if((r=this._catchUpAbortController)==null||r.abort(),!!this._initialized&&!(!this._worker||!this._core)){try{await this._core.unregisterCallback(this._proxiedCallbacks)}catch(n){Ln.warn("unregisterCallback failed:",n)}if(this._connectionListeners.clear(),this._worker.port.close(),this._initialized=!1,this._yieldChannel&&(this._yieldChannel.port1.close(),this._yieldChannel.port2.close(),this._yieldChannel=void 0),this._yieldResolves.length=0,e){this._lastProcessedSeq=0,this._hasRestoredFromStorage=!1;try{sessionStorage.removeItem(this._getSessionStorageKey())}catch{}}}}async getConnectionState(){return this._core.getConnectionState()}onConnectionStateChange(e){return this._connectionListeners.add(e),()=>{this._connectionListeners.delete(e)}}installVirtualFSProxy(){const e=this._core;Vr.read=(r,n,i)=>e.virtualFSRead(r,n,i),Vr.write=(r,n,i="overwrite",s)=>e.virtualFSWrite(r,n,i,s),Vr.ls=r=>e.virtualFSLs(r),Vr.find=(r,n)=>e.virtualFSFind(r,n),Vr.grep=(r,n,i,s)=>e.virtualFSGrep(r,n,i,s),Vr.queryByType=r=>e.virtualFSQueryByType(r),Vr.exists=r=>e.virtualFSExists(r),Vr.remove=r=>e.virtualFSRemove(r)}async cacheFile(e,r,n,i,s){return this._core.cacheFile(e,r,n,i,s)}async cacheFilePending(e,r,n,i,s){return this._core.cacheFilePending(e,r,n,i,s)}async getCachedFile(e,r){return this._core.getCachedFile(e,r)}async evictExpiredCache(){return this._core.evictExpiredCache()}async evictCache(e){return this._core.evictCache(e)}async uploadFile(e,r,n,i,s,o,l,c){if(l!=null&&l.aborted)throw new DOMException("Upload aborted","AbortError");const d=`op-upload-${++this._operationCounter}`;let u;if(l){const g=()=>{this._core.cancelFileOperation(d)};l.addEventListener("abort",g,{once:!0}),u=()=>l.removeEventListener("abort",g)}const h=o?wh(n4(o,100)):void 0;try{return await this._core.uploadFile(e,r,n,i,s,d,h,c)}finally{u==null||u()}}async downloadFile(e,r,n,i,s){if(i!=null&&i.aborted)throw new DOMException("Download aborted","AbortError");const o=`op-download-${++this._operationCounter}`;let l;if(i){const d=()=>{this._core.cancelFileOperation(o)};i.addEventListener("abort",d,{once:!0}),l=()=>i.removeEventListener("abort",d)}const c=n?wh(n4(n,100)):void 0;try{return await this._core.downloadFile(e,r,c,o,s)}finally{l==null||l()}}async deleteFile(e,r){return this._core.deleteFile(e,r)}async calculateFileMD5(e){return this._core.calculateFileMD5(e)}async headFile(e,r){return this._core.headFile(e,r)}async getPresignedUrl(e,r,n){return this._core.getPresignedUrl(e,r,n)}async listFiles(e,r=100,n=0){return this._core.listFiles(e,r,n)}async countFiles(e){return this._core.countFiles(e)}async syncPendingFiles(){return this._core.syncPendingFiles()}async resumeInterruptedUploads(){return this._core.resumeInterruptedUploads()}async getCacheStats(){return this._core.getCacheStats()}async updateFileMetadata(e,r,n){return this._core.updateFileMetadata(e,r,n)}async _doCatchUp(){if(!this._core)return;this._catchUpAbortController=new AbortController;const e=this._catchUpAbortController.signal;try{let r=this._lastProcessedSeq,n=0,i=!0;for(;i&&!e.aborted;){const s=await this._core.getCatchUpEvents(r);if(e.aborted)break;if(s.hasGap){Ln.warn("catchUp: gap detected, triggering state refresh"),this._callbacks.onStateGap();return}if(s.entries.length===0)return;Ln.debug(`catchUp: replaying ${s.entries.length} events from seq ${r}`);const o=8;let l=performance.now();for(let c=0;c<s.entries.length&&!e.aborted;c++){const d=s.entries[c],u=d.seq;if(!(u<=this._lastProcessedSeq)){if(!this._isValidUIUpdateEvent(d.event)){Ln.warn("catchUp: skipping entry with invalid event structure");continue}try{this._callbacks.onUIUpdate({event:d.event,seq:u}),n++}catch(h){Ln.error("catchUp: failed to deliver event, stopping:",h);return}performance.now()-l>o&&(await this._yieldToMain(),l=performance.now())}}r=s.entries[s.entries.length-1].seq,i=s.hasMore}if(e.aborted){Ln.debug("catchUp: cancelled");return}n>0&&Ln.debug(`catchUp: delivered ${n} total events`)}catch(r){e.aborted||Ln.error("catchUp: failed to query events (non-fatal):",r)}finally{this._catchUpAbortController=void 0}}_yieldToMain(){return new Promise(e=>{this._yieldChannel||(this._yieldChannel=new MessageChannel,this._yieldChannel.port1.onmessage=()=>{const r=this._yieldResolves.shift();r&&r()}),this._yieldResolves.push(e),this._yieldChannel.port2.postMessage(null)})}_isValidUIUpdateEvent(e){if(!e||typeof e!="object")return!1;const r=e;return typeof r.entity=="string"&&typeof r.action=="string"&&typeof r.entityId=="string"}_updateLastProcessedSeq(e){this._lastProcessedSeq=e,this._saveLastProcessedSeq()}_getSessionStorageKey(){return`${Bs.SESSION_STORAGE_KEY_PREFIX}-${this._databaseName}`}_loadLastProcessedSeq(){try{const e=sessionStorage.getItem(this._getSessionStorageKey());if(e!==null){const r=parseInt(e,10);if(!isNaN(r)&&r>=0)return r}}catch{}return 0}_saveLastProcessedSeq(){try{sessionStorage.setItem(this._getSessionStorageKey(),String(this._lastProcessedSeq))}catch{Ln.debug("Failed to save lastProcessedSeq to sessionStorage (non-fatal)")}}};Bs.SESSION_STORAGE_KEY_PREFIX="rtc-ui-update-seq",Bs.MAX_INIT_RETRIES=3,Bs.INIT_RETRY_DELAY_MS=1e3,Bs.VERIFICATION_TIMEOUT_MS=5e3;let H_=Bs;const rp=er("MasterLock");class lz{constructor(e){this._isMaster=!1,this._controlled=!1,this._lockName=`rtc-agent-master-${e}`}get isMaster(){return this._isMaster}get isControlled(){return this._controlled}async acquire(){var e;if(this._controlled){rp.warn("already acquiring/acquired, ignoring");return}if(!this._isWebLocksAvailable()){rp.warn("Web Locks API not available, acting as always-master"),this._isMaster=!0,this._controlled=!0,(e=this.onAcquire)==null||e.call(this);return}this._controlled=!0,this._abortController=new AbortController,navigator.locks.request(this._lockName,{signal:this._abortController.signal},async()=>{var r,n;this._isMaster=!0,rp.info("acquired lock → became Master"),(r=this.onAcquire)==null||r.call(this),await new Promise(i=>{this._releaseResolve=i}),this._isMaster=!1,rp.info("released lock → lost Master"),(n=this.onRelease)==null||n.call(this)}).catch(r=>{r instanceof DOMException&&r.name==="AbortError"||rp.error("lock request error:",r)})}release(){this._controlled&&(this._releaseResolve&&(this._releaseResolve(),this._releaseResolve=void 0),!this._isMaster&&this._abortController&&this._abortController.abort(),this._controlled=!1)}_isWebLocksAvailable(){return typeof navigator<"u"&&"locks"in navigator}}const Ds=er("PersistenceController");function dte(t){return t}class cz{constructor(e){this._core=e}async connect(){Ds.info("connect() called"),await this._core.connect(),Ds.info("connect() completed, worker state:",await this._core.getConnectionState())}disconnect(){this._core.disconnect()}async reconnect(){await this._core.reconnect()}async listSessions(e,r){return this._core.listSessions(e,r)}async getSession(e){return this._core.getSession(e)}async listMessages(e,r,n,i){return this._core.listMessages(e,r,n,i)}async getMessage(e){return this._core.getMessage(e)}async listRtc(e,r,n){return this._core.listRtc(e,r,n)}async getNextRtcToProcess(e){return this._core.getNextRtcToProcess(e)}async sendMessage(e){return this._core.sendMessage(e)}async insertLocalMessage(e){return this._core.insertLocalMessage(e)}async stopTurn(e){return this._core.stopTurn(e)}async closeSession(e){return this._core.closeSession(e)}async openSession(e){return this._core.openSession(e)}async compactSession(e,r){return this._core.compactSession(e,r)}async submitRtcResult(e){return this._core.submitRtcResult(e)}async forkSession(e){return this._core.forkSession(e)}async deleteSession(e){return this._core.deleteSession(e)}async updateSessionTitle(e,r){return this._core.updateSessionTitle(e,r)}async close(){await this._core.close()}async flushAll(){return this._core.flushAll()}async initializeVirtualFS(e){await this._core.initializeVirtualFS(e??{})}getClient(){throw new Error("[WorkerPersistenceAdapter] getClient() is not available. Use PersistenceController.onConnectionStateChange() instead.")}getOffsetManager(){return{reset:()=>this._core.resetOffset()}}getEntityRepository(){throw new Error("[WorkerPersistenceAdapter] getEntityRepository() is not available.")}}const Ql=class Ql{constructor(e,r){this._connectGeneration=0,this._auth=r,e.addController(this)}set databaseName(e){this._databaseNameOverride=e}set workerURL(e){this._workerURL=e}get layer(){return this._layer}get isConnected(){return this._layer!==void 0}get workerBridge(){return this._workerBridge}get masterLock(){return this._masterLock}get fileStorage(){if(!this._fileStorage){if(!this._workerBridge)throw new Error("[PersistenceController] fileStorage requires an active connection. Call connect() first.");const e=this._auth.state.userId;if(!e)throw new Error("[PersistenceController] fileStorage requires userId from auth state.");this._fileStorage=new q2(this._workerBridge,e)}return this._fileStorage}hostConnected(){}hostDisconnected(){this.disconnect()}async connect(){if(Ds.debug("connect() called"),this._layer)return;if(this._connecting)return this._connecting;const e=lT(),r=this._auth.state.userId;if(Ds.debug("connect() userId:",r,"deviceId:",e),!r)throw new Error("[PersistenceController] connect() called without userId; refusing to open a shared database");const n={databaseName:this._databaseNameOverride?`${this._databaseNameOverride}-${r}`:`rtc-agent-${r}`,deviceId:e,userId:r,serverURL:Uo.serverURL,client:{endpoint:Uo.wsEndpoint,getToken:async()=>{const s=await this._auth.getAccessTokenAsync();if(!s)throw Ds.warn("getToken: no access token available"),new Error("No access token available");return s},onTokenExpired:()=>this._auth.handleTokenExpired(),onAccountBanned:s=>{Ds.warn("Account banned:",s)},deviceId:e,userId:r}},i=this._connectGeneration;return this._connecting=this._connectWorker(n).finally(()=>{this._connectGeneration===i&&(this._connecting=void 0)}),this._connecting}async _connectWorker(e){let r=null;for(let n=0;n<=Ql.MAX_CONNECT_RETRIES;n++)try{n>0&&(Ds.warn(`Retrying connection (attempt ${n+1}/${Ql.MAX_CONNECT_RETRIES+1})...`),await this._delay(Ql.CONNECT_RETRY_DELAY_MS*n)),await this._connectWorkerOnce(e);return}catch(i){r=i instanceof Error?i:new Error(String(i)),Ds.error(`Connection attempt ${n+1} failed:`,r),await this._cleanupFailedConnection()}throw new Error(`[PersistenceController] Failed to connect after ${Ql.MAX_CONNECT_RETRIES+1} attempts: ${r==null?void 0:r.message}`)}async _connectWorkerOnce(e){const r=new H_(this._auth,{workerURL:this._workerURL});if(this._workerBridge=r,await r.initWorker(),this._workerBridge!==r){await r.destroy().catch(()=>{});return}const{getToken:n,onTokenExpired:i,onAccountBanned:s,...o}=e.client,l={...e,client:o};if(await r.init(l),this._workerBridge!==r){await r.destroy().catch(()=>{});return}r.installVirtualFSProxy(),this._layer=new cz(r.core),await r.core.connect();const c=this._auth.state.userId;c&&(this._masterLock=new lz(c),this._masterLock.onAcquire=()=>{Ds.info("this Tab became Master")},this._masterLock.onRelease=()=>{Ds.info("this Tab lost Master")},this._masterLock.acquire())}async _cleanupFailedConnection(){if(this._workerBridge){try{await this._workerBridge.destroy()}catch(e){Ds.debug("Cleanup after failed connection (non-critical):",e)}this._workerBridge=void 0}this._layer=void 0,this._fileStorage=void 0}_delay(e){return new Promise(r=>setTimeout(r,e))}async disconnect(){var i;this._connectGeneration++;const e=this._connectGeneration;this._connecting&&(this._connecting=void 0);const r=this._layer,n=this._workerBridge;if(this._layer=void 0,this._workerBridge=void 0,r)try{await r.getOffsetManager().reset(),await r.close()}catch(s){Ds.error("disconnect error:",s)}if(n){(i=this._masterLock)==null||i.release(),this._masterLock=void 0,this._fileStorage=void 0;try{await n.destroy()}catch(s){Ds.error("WorkerBridge disconnect error:",s)}}this._connectGeneration!==e&&Ds.warn("disconnect interrupted by new connect, generation changed")}async getConnectionState(){return this._workerBridge?this._workerBridge.getConnectionState():"disconnected"}onConnectionStateChange(e){return this._workerBridge?this._workerBridge.onConnectionStateChange(e):()=>{}}};Ql.MAX_CONNECT_RETRIES=2,Ql.CONNECT_RETRY_DELAY_MS=2e3;let K_=Ql;const i4=er("EventBus");class s4{constructor(){this.handlers=new Map}on(e,r){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(r),()=>{var n;(n=this.handlers.get(e))==null||n.delete(r)}}once(e,r){const n=i=>(this.off(e,n),r(i));return this.on(e,n)}off(e,r){var n;(n=this.handlers.get(e))==null||n.delete(r)}emit(e,r){const n=this.handlers.get(e);if(!n)return;const i=Array.from(n);for(const s of i)try{s(r)}catch(o){i4.error(`Handler error for event '${e}':`,o)}}async emitAsync(e,r){const n=this.handlers.get(e);if(!n)return;const i=Array.from(n),s=[];for(const o of i)s.push(Promise.resolve(o(r)).catch(l=>{i4.error(`Async handler error for event '${e}':`,l)}));await Promise.all(s)}async emitAsyncStrict(e,r){const n=this.handlers.get(e);if(!n)return;const i=Array.from(n),s=[];for(const o of i)s.push(Promise.resolve(o(r)));await Promise.all(s)}clearAll(){this.handlers.clear()}clearEvent(e){this.handlers.delete(e)}}function o4(){return new s4}const To=o4(),uz=er("SkillController");class a4{constructor(e,r){this._registry=null,this._config={},this._unsubscribes=[],this._host=e,this._config=r||{},e.addController(this)}get value(){return{registry:this._registry}}get actions(){return{getRegistry:()=>this._registry,setRegistry:e=>{this._registry=e,this._host.requestUpdate(),this._bridgeToolRegistry(e)}}}_bridgeToolRegistry(e){const r=new Proxy({callFunction:(n,i)=>e.execute(n,i),readFile:n=>Vr.read(n),writeFile:(n,i)=>Vr.write(n,i).then(()=>{}),listDir:n=>Vr.ls(n)},{get(n,i){return i in n?n[i]:e[i]}});e4.setRtcAgent(r),uz.info("rtcAgent API bridged to ToolRegistry")}setConfig(e){this._config=e}hostConnected(){this._subscribeEvents()}hostDisconnected(){for(const e of this._unsubscribes)e();this._unsubscribes=[]}_subscribeEvents(){for(const n of this._unsubscribes)n();this._unsubscribes=[];const e=To.on("ui:toast",n=>{this._config.onToast&&this._config.onToast(n.message,n.type)});this._unsubscribes.push(e);const r=To.on("ui:confirm-request",n=>{this._config.onConfirmRequest&&this._config.onConfirmRequest(n.requestId,n.path,n.message)});this._unsubscribes.push(r)}respondToConfirm(e,r){To.emit("ui:confirm-response",{requestId:e,confirmed:r})}}class dz{constructor(e){this._toasts=[],this._timers=new Map,this._host=e,this._host.addController(this),this.actions={show:(r,n="info",i)=>this._show(r,n,i),remove:r=>this._remove(r)}}get toasts(){return this._toasts}hostConnected(){}hostDisconnected(){for(const e of this._timers.values())clearTimeout(e);this._timers.clear(),this._toasts.length>0&&(this._toasts=[],this._host.requestUpdate())}_show(e,r,n){const i=Date.now()+Math.random();this._toasts=[...this._toasts,{id:i,message:e,type:r,action:n}],this._host.requestUpdate();const s=r==="error"?0:r==="success"?2e3:2500;if(s>0){const o=setTimeout(()=>this._remove(i),s);this._timers.set(i,o)}}_remove(e){const r=this._timers.get(e);r!==void 0&&(clearTimeout(r),this._timers.delete(e)),this._toasts=this._toasts.filter(n=>n.id!==e),this._host.requestUpdate()}}const l4=er("ForkController");class fz{constructor(e){this._state=null,this._deps=null,this._host=e,this._host.addController(this),this.actions={requestFork:(r,n,i,s)=>this._requestFork(r,n,i,s),submitFork:r=>this._submitFork(r),clearFork:()=>this._clearFork()}}get state(){return this._state}get isActive(){return this._state!==null}setDeps(e){this._deps=e}hostConnected(){}hostDisconnected(){}_requestFork(e,r,n,i){var o;const s=i.length>30?i.slice(0,30)+"...":i;this._state={oldSessionClientId:e,oldMessageClientId:r,newSessionClientId:n,hintMessage:Me(wr`🔀 从「${s}」分叉`)},this._host.requestUpdate(),(o=this._deps)==null||o.clearMessages(),l4.debug("_requestFork: state set, transient params handled by tab property binding")}async _submitFork(e){if(!this._state||!this._deps)return;const r=`msg-${crypto.randomUUID()}`;try{await this._deps.executeFork({oldSessionClientId:this._state.oldSessionClientId,oldMessageClientId:this._state.oldMessageClientId,newSessionClientId:this._state.newSessionClientId,newMessageClientId:r,content:e})}catch(n){l4.error("forkSession failed:",n)}this._clearFork()}_clearFork(){var e;this._state&&((e=this._deps)==null||e.clearTransientParams(this._state.newSessionClientId)),this._state=null,this._host.requestUpdate()}}const c4=er("ActivityController");class pz{constructor(e){this._state={...ch},this.host=e,this.host.addController(this),this.actions={setActivity:r=>this._setActivity(r),showSidebar:()=>this._showSidebar(),hideSidebar:()=>this._hideSidebar(),toggleSidebar:()=>this._toggleSidebar(),reset:()=>this._reset()},this._restore()}get value(){return{state:this._state,actions:this.actions}}get active(){return this._state.active}get sidebarVisible(){return this._state.sidebarVisible}hostConnected(){}hostDisconnected(){}_restore(){try{const e=localStorage.getItem(Xr.activityBar);if(!e)return;const r=JSON.parse(e),n=i=>i==="files"||i==="chat"||i==="settings"||i==="functions";r&&typeof r=="object"&&(this._state={active:n(r.active)?r.active:ch.active,sidebarVisible:typeof r.sidebarVisible=="boolean"?r.sidebarVisible:ch.sidebarVisible})}catch(e){c4.debug("Failed to restore activity state:",e)}}_persist(){try{localStorage.setItem(Xr.activityBar,JSON.stringify(this._state))}catch(e){c4.debug("Failed to persist activity state:",e)}}_setActivity(e){this._state.active===e?this._toggleSidebar():(this._state={active:e,sidebarVisible:this._state.sidebarVisible},this._persist(),this.host.requestUpdate())}_showSidebar(){this._state.sidebarVisible||(this._state={...this._state,sidebarVisible:!0},this._persist(),this.host.requestUpdate())}_hideSidebar(){this._state.sidebarVisible&&(this._state={...this._state,sidebarVisible:!1},this._persist(),this.host.requestUpdate())}_toggleSidebar(){this._state={...this._state,sidebarVisible:!this._state.sidebarVisible},this._persist(),this.host.requestUpdate()}_reset(){this._state={...ch},this._persist(),this.host.requestUpdate()}}class hz{constructor(e){this._state={...L2},this._expandedPaths=new Set,this._loadingPaths=new Set,this._host=e,e.addController(this)}get state(){return this._state}get value(){return{state:this._state,actions:this.actions,isExpanded:e=>this._expandedPaths.has(e),isLoading:e=>this._loadingPaths.has(e),isSelected:e=>this._state.selectedPath===e}}get actions(){return{setRoot:e=>this._setRoot(e),toggleNode:e=>this._toggleNode(e),expandAll:()=>this._expandAll(),collapseAll:()=>this._collapseAll(),selectNode:e=>this._selectNode(e),setLoading:(e,r)=>this._setLoading(e,r),updateChildren:(e,r)=>this._updateChildren(e,r),reset:()=>this._reset()}}hostConnected(){}hostDisconnected(){this._reset()}_setRoot(e){this._state={...this._state,root:e},this._host.requestUpdate()}_toggleNode(e){this._expandedPaths.has(e)?this._expandedPaths.delete(e):this._expandedPaths.add(e),this._host.requestUpdate()}_expandAll(){this._state.root&&(this._collectFolderPaths(this._state.root,this._expandedPaths),this._host.requestUpdate())}_collapseAll(){this._expandedPaths.clear(),this._host.requestUpdate()}_selectNode(e){this._state={...this._state,selectedPath:e},this._host.requestUpdate()}_setLoading(e,r){r?this._loadingPaths.add(e):this._loadingPaths.delete(e),this._host.requestUpdate()}_updateChildren(e,r){if(!this._state.root)return;const n=this._updateNodeChildren(this._state.root,e,r);n&&(this._state={...this._state,root:n},this._host.requestUpdate())}_reset(){this._state={...L2},this._expandedPaths.clear(),this._loadingPaths.clear(),this._host.requestUpdate()}_collectFolderPaths(e,r){if(e.type==="folder"&&(r.add(e.path),e.children))for(const n of e.children)this._collectFolderPaths(n,r)}_updateNodeChildren(e,r,n){if(e.path===r)return{...e,children:n};if(e.type==="folder"&&e.children){const i=e.children.map(o=>this._updateNodeChildren(o,r,n)||o);if(i.some((o,l)=>o!==e.children[l]))return{...e,children:i}}return null}}const u4=er("EditorAreaController");class mz{constructor(e){this._tabs=[],this._activeFilePath="",this._host=e,this._host.addController(this),this.actions={openFile:(r,n,i)=>this._openFile(r,n,i),closeFile:r=>this._closeFile(r),closeAll:()=>this._closeAll(),switchTab:r=>this._switchTab(r),updateContent:(r,n)=>this._updateContent(r,n),saveFile:r=>this._saveFile(r),setViewMode:(r,n)=>this._setViewMode(r,n),setCursorPosition:(r,n)=>this._setCursorPosition(r,n),loadContent:(r,n)=>this._loadContent(r,n)},this._restore()}hostConnected(){}hostDisconnected(){this._cursorPersistTimer&&(clearTimeout(this._cursorPersistTimer),this._cursorPersistTimer=void 0)}_restore(){var e;try{const r=localStorage.getItem(Xr.editorArea);if(!r)return;const n=JSON.parse(r);if(!n||!Array.isArray(n.tabs))return;const i=o=>o==="edit"||o==="preview"||o==="split";this._tabs=n.tabs.map(o=>({filePath:o.filePath,content:"",isDirty:!1,cursorPosition:i(o.viewMode)?{line:1,column:1}:o.cursorPosition??{line:1,column:1},viewMode:i(o.viewMode)?o.viewMode:"edit"}));const s=this._tabs.some(o=>o.filePath===n.activeFilePath);this._activeFilePath=s?n.activeFilePath:((e=this._tabs[0])==null?void 0:e.filePath)??""}catch(r){u4.debug("Failed to restore editor area state:",r)}}_persist(){try{if(this._tabs.length===0){localStorage.removeItem(Xr.editorArea);return}const e={tabs:this._tabs.map(r=>({filePath:r.filePath,viewMode:r.viewMode,cursorPosition:r.cursorPosition})),activeFilePath:this._activeFilePath};localStorage.setItem(Xr.editorArea,JSON.stringify(e))}catch(e){u4.debug("Failed to persist editor area state:",e)}}get state(){return{tabs:this._tabs,activeFilePath:this._activeFilePath}}get tabs(){return this._tabs}get activeFilePath(){return this._activeFilePath}get activeTab(){return this._tabs.find(e=>e.filePath===this._activeFilePath)}_openFile(e,r,n="edit"){if(this._tabs.find(o=>o.filePath===e)){this._activeFilePath=e,this._persist(),this._host.requestUpdate();return}const s={filePath:e,content:r,isDirty:!1,cursorPosition:{line:1,column:1},viewMode:n};this._tabs=[...this._tabs,s],this._activeFilePath=e,this._persist(),this._host.requestUpdate()}_closeFile(e){const r=this._tabs.findIndex(i=>i.filePath===e);if(r===-1)return;const n=e===this._activeFilePath;if(this._tabs=this._tabs.filter(i=>i.filePath!==e),n)if(this._tabs.length===0)this._activeFilePath="";else{const i=Math.min(r,this._tabs.length-1);this._activeFilePath=this._tabs[i].filePath}this._persist(),this._host.requestUpdate()}_closeAll(){this._tabs=[],this._activeFilePath="",this._persist(),this._host.requestUpdate()}_switchTab(e){this._tabs.some(n=>n.filePath===e)&&(this._activeFilePath=e,this._persist(),this._host.requestUpdate())}_updateContent(e,r){this._tabs=this._tabs.map(n=>n.filePath!==e?n:{...n,content:r,isDirty:!0}),this._host.requestUpdate()}_saveFile(e){this._tabs=this._tabs.map(r=>r.filePath!==e?r:{...r,isDirty:!1}),this._persist(),this._host.requestUpdate()}_setViewMode(e,r){this._tabs=this._tabs.map(n=>n.filePath!==e?n:{...n,viewMode:r}),this._persist(),this._host.requestUpdate()}_setCursorPosition(e,r){const n=this._tabs.find(i=>i.filePath===e);n&&(n.cursorPosition.line===r.line&&n.cursorPosition.column===r.column||(this._tabs=this._tabs.map(i=>i.filePath!==e?i:{...i,cursorPosition:r}),this._host.requestUpdate(),!this._cursorPersistTimer&&(this._cursorPersistTimer=setTimeout(()=>{this._cursorPersistTimer=void 0,this._persist()},2e3))))}_loadContent(e,r){if(this._tabs.find(s=>s.filePath===e)){this._tabs=this._tabs.map(s=>s.filePath!==e?s:{...s,content:r,isDirty:!1}),this._host.requestUpdate();return}const i={filePath:e,content:r,isDirty:!1,cursorPosition:{line:1,column:1},viewMode:"edit"};this._tabs=[...this._tabs,i],this._activeFilePath||(this._activeFilePath=e),this._persist(),this._host.requestUpdate()}}function gz(t){var r;switch((r=t.split(".").pop())==null?void 0:r.toLowerCase()){case"md":return"Markdown";case"js":return"JavaScript";case"ts":return"TypeScript";case"json":return"JSON";case"html":return"HTML";case"css":return"CSS";case"txt":return"Plain Text";default:return"File"}}class yz{constructor(e,r){this._host=e,this._editorController=r,this._host.addController(this)}hostConnected(){}hostDisconnected(){}get info(){const e=this._editorController.activeTab;return e?{fileType:gz(e.filePath),encoding:"UTF-8",cursor:e.cursorPosition,saveStatus:e.isDirty?"unsaved":"saved"}:{fileType:"",encoding:"UTF-8",cursor:{line:1,column:1},saveStatus:"none"}}}class bz{constructor(e){this._state={rootNodes:[]},this._expanded=new Map,this.host=e,this.host.addController(this),this.actions={toggleExpand:r=>this._toggleExpand(r),expand:r=>this._setExpanded(r,!0),collapse:r=>this._setExpanded(r,!1),rebuildTree:r=>this._rebuildTree(r)},this._restoreExpanded()}get value(){return{state:this._state,actions:this.actions}}hostConnected(){}hostDisconnected(){}_restoreExpanded(){}_persistExpanded(){try{const e={};this._expanded.forEach((r,n)=>{r&&(e[n]=!0)}),Object.keys(e).length>0?localStorage.setItem(Xr.sessionTreeExpanded,JSON.stringify(e)):localStorage.removeItem(Xr.sessionTreeExpanded)}catch{}}_toggleExpand(e){const r=this._expanded.get(e)??!1;this._setExpanded(e,!r)}_setExpanded(e,r){this._expanded.set(e,r),this._persistExpanded(),this._rebuildTreeFromCache()}_rebuildTreeFromCache(){this._cachedSessions&&this._buildTree(this._cachedSessions)}_rebuildTree(e){this._cachedSessions=e,this._buildTree(e)}_buildTree(e){const r=e.filter(s=>!s.rootClientSessionId),n=new Map;for(const s of e)if(s.rootClientSessionId){const o=n.get(s.rootClientSessionId)??[];o.push(s),n.set(s.rootClientSessionId,o)}const i=r.map(s=>this._buildNode(s,n));i.sort((s,o)=>o.session.updatedAt-s.session.updatedAt),this._state={rootNodes:i},this.host.requestUpdate()}_buildNode(e,r){const n=(r.get(e.clientId)??[]).sort((i,s)=>i.createdAt-s.createdAt).map(i=>this._buildNode(i,r));return{session:e,children:n,isExpanded:this._expanded.get(e.clientId)??!1}}}const gy=er("SessionTabController"),G_="rtc:active-tab";class vz{constructor(e){this._state={tabs:[],activeSessionId:null},this.host=e,this.host.addController(this),this.actions={openOrActivate:(r,n,i)=>this._openOrActivate(r,n,i),closeTab:r=>this._closeTab(r),setActiveTab:r=>this._setActiveTab(r),clearAll:()=>this._clearAll(),updateTabTitles:r=>this.updateTabTitles(r),syncTabStatuses:r=>this.syncTabStatuses(r),markSaved:r=>this._markSaved(r),findUnsavedTab:()=>this._findUnsavedTab(),updateTabStatus:(r,n)=>this._updateTabStatus(r,n),restoreActiveFromStorage:()=>this._restoreActiveFromStorage(),getStoredActiveSessionId:()=>this._getStoredActiveSessionId(),setTransientParams:(r,n)=>this._setTransientParams(r,n),clearTransientParams:r=>this._clearTransientParams(r)}}get value(){return{state:this._state,actions:this.actions}}hostConnected(){}hostDisconnected(){}filterInvalidTabs(e){const r=this._state.tabs.length,n=this._state.tabs.filter(s=>e.has(s.sessionId)||s.isUnsaved===!0);let i=this._state.activeSessionId;return i&&!n.some(s=>s.sessionId===i)&&(i=n.length>0?n[0].sessionId:null),n.length!==r?(this._state={tabs:n,activeSessionId:i},this.host.requestUpdate(),!0):!1}updateTabTitles(e){let r=!1;const n=this._state.tabs.map(i=>{const s=e.get(i.sessionId);return s!==void 0&&s.trim()!==""&&s!==i.title?(r=!0,{...i,title:s,isDefault:!1,isUnsaved:!1}):i});return r&&(this._state={...this._state,tabs:n},this.host.requestUpdate()),r}syncTabStatuses(e){let r=!1;const n=this._state.tabs.map(i=>{const s=e.get(i.sessionId);return s!==void 0&&s!==i.status?(r=!0,{...i,status:s}):i});return r&&(this._state={...this._state,tabs:n},this.host.requestUpdate()),r}_isPlaceholderTitle(e){return!e||e===Me("未命名")||e===Me("新聊天")}_findUnsavedTab(){return this._state.tabs.find(e=>e.isUnsaved===!0)}_markSaved(e){const r=this._state.tabs.find(i=>i.sessionId===e);if(!r||r.isUnsaved!==!0)return;const n=this._state.tabs.map(i=>i.sessionId===e?{...i,isUnsaved:!1}:i);this._state={...this._state,tabs:n},this.host.requestUpdate()}_updateTabStatus(e,r){const n=this._state.tabs.find(s=>s.sessionId===e);if(!n||n.status===r)return;const i=this._state.tabs.map(s=>s.sessionId===e?{...s,status:r}:s);this._state={...this._state,tabs:i},this.host.requestUpdate()}_openOrActivate(e,r,n){const i=this._isPlaceholderTitle(r),s=(n==null?void 0:n.activate)??!0,o=(n==null?void 0:n.skipPersist)??!1,l=(n==null?void 0:n.initialInputValue)!==void 0||(n==null?void 0:n.noticeMessage)!==void 0?{initialInputValue:n==null?void 0:n.initialInputValue,noticeMessage:n==null?void 0:n.noticeMessage}:void 0,c=this._state.tabs.findIndex(d=>d.sessionId===e);if(c>=0){const d=this._state.tabs[c];if(i&&!d.isDefault&&d.title!==r){gy.debug("Protected tab title:",d.title),s&&this._state.activeSessionId!==e&&(this._state={...this._state,activeSessionId:e},o||this._persistActiveSessionId(e),this.host.requestUpdate());return}const u=this._state.tabs.map((g,b)=>{if(b!==c)return g;const I={...g,title:r,isDefault:!!i};return l&&(I.initialInputValue=l.initialInputValue,I.noticeMessage=l.noticeMessage,I.initialValueVersion=(g.initialValueVersion??0)+1),I}),h=s?e:this._state.activeSessionId;this._state={tabs:u,activeSessionId:h},s&&!o&&this._persistActiveSessionId(h)}else{const d={sessionId:e,title:r,isDefault:!!i,isUnsaved:(n==null?void 0:n.isUnsaved)??!1,...l?{initialInputValue:l.initialInputValue,noticeMessage:l.noticeMessage,initialValueVersion:1}:{}},u=[...this._state.tabs,d],h=s?e:this._state.activeSessionId;this._state={tabs:u,activeSessionId:h},s&&!o&&this._persistActiveSessionId(h)}this.host.requestUpdate()}_closeTab(e){const r=this._state.tabs.findIndex(s=>s.sessionId===e);if(r<0)return;const n=this._state.tabs.filter(s=>s.sessionId!==e);let i=this._state.activeSessionId;if(i===e){if(n.length===0)i=null;else{const s=Math.min(r,n.length-1);i=n[s].sessionId}this._persistActiveSessionId(i)}this._state={tabs:n,activeSessionId:i},this.host.requestUpdate()}_setActiveTab(e){e!==null&&e!==this._state.activeSessionId?(this._state={...this._state,activeSessionId:e},this._persistActiveSessionId(e),this.host.requestUpdate()):e===null&&this._state.activeSessionId!==null&&(this._state={...this._state,activeSessionId:null},this._persistActiveSessionId(null),this.host.requestUpdate())}_clearAll(){this._state={tabs:[],activeSessionId:null},this._persistActiveSessionId(null),this.host.requestUpdate()}_persistActiveSessionId(e){try{if(typeof window>"u"||!window.localStorage)return;e===null?window.localStorage.removeItem(G_):window.localStorage.setItem(G_,e)}catch{}}_getStoredActiveSessionId(){try{return typeof window>"u"||!window.localStorage?null:window.localStorage.getItem(G_)}catch{return null}}_setTransientParams(e,r){if(!this._state.tabs.find(s=>s.sessionId===e))return;const i=this._state.tabs.map(s=>s.sessionId===e?{...s,initialInputValue:r.initialInputValue,noticeMessage:r.noticeMessage,initialValueVersion:(s.initialValueVersion??0)+1}:s);this._state={...this._state,tabs:i},this.host.requestUpdate()}_clearTransientParams(e){const r=this._state.tabs.find(i=>i.sessionId===e);if(!r||r.initialInputValue===void 0&&r.noticeMessage===void 0)return;const n=this._state.tabs.map(i=>i.sessionId===e?{...i,initialInputValue:void 0,noticeMessage:void 0}:i);this._state={...this._state,tabs:n},this.host.requestUpdate()}_restoreActiveFromStorage(){const e=this._getStoredActiveSessionId();return e?this._state.tabs.some(r=>r.sessionId===e)?this._state.activeSessionId===e?(gy.debug("Already active:",e),!1):(gy.debug("Restoring active tab:",e),this._state={...this._state,activeSessionId:e},this.host.requestUpdate(),!0):(gy.debug("Stored id not in tabs:",e),!1):!1}}const d4=er("SettingsController");class _z{constructor(e){this._state={...nf},this.host=e,this.host.addController(this),this.actions={updateAppearance:r=>this._update("appearance",r),updateChat:r=>this._update("chat",r),updateFiles:r=>this._update("files",r),updateNotifications:r=>this._update("notifications",r),resetAll:()=>this._reset()},this._restore()}get value(){return{state:this._state,actions:this.actions}}hostConnected(){this._removeGlobalListeners(),this._themeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this._themeMediaListener=()=>{this._state.appearance.theme==="system"&&this._applyTheme()},this._themeMediaQuery.addEventListener("change",this._themeMediaListener),(this.host.closest("rtc-agent")||this.host).hasAttribute("theme")||this._applyTheme(),this._applyFontSize(),this._storageListener=()=>this._handleStorageChange(),window.addEventListener("storage",this._storageListener)}hostDisconnected(){this._removeGlobalListeners(),document.documentElement.style.removeProperty("--rtc-font-size-user")}_removeGlobalListeners(){this._storageListener&&(window.removeEventListener("storage",this._storageListener),this._storageListener=void 0),this._themeMediaQuery&&this._themeMediaListener&&(this._themeMediaQuery.removeEventListener("change",this._themeMediaListener),this._themeMediaListener=void 0)}_restore(){var e,r;try{const n=localStorage.getItem(Xr.settings);if(!n)return;const i=JSON.parse(n);this._state={appearance:{theme:this._validateTheme((e=i.appearance)==null?void 0:e.theme),fontSize:this._validateFontSize((r=i.appearance)==null?void 0:r.fontSize)},chat:{...nf.chat,...i.chat},files:{...nf.files,...i.files},notifications:{...nf.notifications,...i.notifications}}}catch(n){d4.debug("Failed to restore settings:",n)}}_update(e,r){const n=this._state;this._state={...this._state,[e]:{...this._state[e],...r}},this._persist(),this._applyDiff(n,this._state),this.host.requestUpdate()}_reset(){const e=this._state;this._state={...nf},this._persist(),this._applyDiff(e,this._state),this.host.requestUpdate()}_persist(){try{localStorage.setItem(Xr.settings,JSON.stringify(this._state))}catch(e){d4.debug("Failed to persist settings:",e)}}_applyDiff(e,r){e.appearance.theme!==r.appearance.theme&&this._applyTheme(),e.appearance.fontSize!==r.appearance.fontSize&&this._applyFontSize()}_applyTheme(){var i;const e=this._state.appearance.theme,r=e==="system"?(i=this._themeMediaQuery)!=null&&i.matches?"dark":"light":e,n=this.host.closest("rtc-agent")||this.host;"theme"in n&&(n.theme=r)}_applyFontSize(){const e=this._state.appearance.fontSize,r=Math.min(24,Math.max(12,e));document.documentElement.style.setProperty("--rtc-font-size-user",`${r}px`)}_handleStorageChange(){const e=this._state;this._restore(),this._applyDiff(e,this._state),this.host.requestUpdate()}_validateTheme(e){return e==="light"||e==="dark"||e==="system"?e:"system"}_validateFontSize(e){return Math.min(24,Math.max(12,typeof e=="number"?e:14))}}const xz="data:audio/mpeg;base64,//OEZAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAAQAAAJYAAQEBAQEBAsLCwsLCw9PT09PT1NTU1NTU1WVlZWVlZWWVlZWVlZW1tbW1tbd3d3d3d3mZmZmZmZmaSkpKSkpLKysrKystPT09PT097e3t7e3t7v7+/v7+/9/f39/f3///////8AAAA5TEFNRTMuMTAwAm4AAAAALjQAABRGJAPbTgAARgAACWCFGVdaAAAAAAAAAAAAAAAAAAAA//NkZAANhHcWAK1sAAAAAfgBQAAA/DDGVu25cP5PuudMdQd53QVIuxIRPsQBjKGjKAAufOHfPn1PGxMVIOfpTlWsiYzHjo0I8MqDiQFMRC0xjFRkxMFZMXULMJWRlnb93sMN16e33Cnt9wpAwXDBccCAkOB8QBEEMMCQ4J//h/l3qnY7GgAB+4JRKLhaNwwx//OUZA4cqedfH8zUAYAAAjQBgBAAljoAki78OGEga8ANe/I1AlAy/xhnf4NkAYCBwGFgIH+AwaFABquUghBYGPA8BjMFh1A6QkggBQYxIw6CEBjzYLgBkAtHHcQQQRFakqIVFkmCdogmQc3Jsc8rmIs0QqXjEcn8xHPImVCbJ8nCHESRKRBi8Uv7JkUNJgXDRRFiLJE0RZaiaMf+RQnDcwNCfUgXzeZmpSKJOomJOkysukVV/+X01l83PGZuaLTLjUEFmKnRSSqSSUkl//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qqqqqqqqqqqq",yy=er("NotificationController"),ec=class ec{constructor(e){this._state={...B2},this._sounds=new Map,this._lastNotifyTime=0,this._abortController=new AbortController,this.host=e,this.host.addController(this),this.actions={markAsRead:()=>this._markAsRead(),clearAll:()=>this._clearAll()}}get value(){return{state:this._state,actions:this.actions}}hostConnected(){this._preloadSounds(),this._subscribeToMessages()}hostDisconnected(){var e;(e=this._busUnsubscribe)==null||e.call(this),this._sounds.clear(),this._deferredSoundTimer&&(clearTimeout(this._deferredSoundTimer),this._deferredSoundTimer=void 0),this._idleCallbackId!==void 0&&(cancelIdleCallback(this._idleCallbackId),this._idleCallbackId=void 0),this._abortController.abort(),this._abortController=new AbortController,this.host.removeAttribute("data-notification")}_preloadSounds(){this._sounds.clear();const e={message:xz};for(const[i,s]of Object.entries(e))this._loadSound(i,s);const r={complete:wz,error:Sz},n=()=>{this._deferredSoundTimer!==void 0&&(clearTimeout(this._deferredSoundTimer),this._deferredSoundTimer=void 0),this._idleCallbackId=void 0;for(const[i,s]of Object.entries(r))this._loadSound(i,s)};this._idleCallbackId!==void 0&&(cancelIdleCallback(this._idleCallbackId),this._idleCallbackId=void 0),"requestIdleCallback"in window?(this._idleCallbackId=requestIdleCallback(n),this._deferredSoundTimer=setTimeout(()=>{this._idleCallbackId!==void 0&&(cancelIdleCallback(this._idleCallbackId),this._idleCallbackId=void 0),n()},ec.IDLE_FALLBACK_DELAY_MS)):this._deferredSoundTimer=setTimeout(n,ec.DEFERRED_SOUND_DELAY_MS)}_loadSound(e,r){const n=new Audio;n.preload="auto",n.addEventListener("canplaythrough",()=>{this.host.isConnected&&this._sounds.set(e,n)},{once:!0}),n.addEventListener("error",()=>{yy.warn(`Audio load failed (file may not exist): ${r}`),this._sounds.delete(e)},{once:!0}),n.src=r}_playSound(e){var i;const r=(i=this.settingsController)==null?void 0:i.value.state.notifications;if(!(r!=null&&r.soundEnabled))return;const n=this._sounds.get(e);n&&(n.currentTime=0,n.volume=1,n.play().catch(s=>{s.name==="NotAllowedError"?yy.warn("Audio playback blocked by browser; user interaction required"):yy.warn("Playback failed:",s)}))}_subscribeToMessages(){var r;(r=this._busUnsubscribe)==null||r.call(this);const e=_u();this._busUnsubscribe=e.subscribe("message",n=>{n.action==="created"&&n.field==="content"&&this._handleNewMessage(n)})}async _handleNewMessage(e){const r=Date.now();if(!(r-this._lastNotifyTime<ec.NOTIFY_THROTTLE_MS)){this._lastNotifyTime=r;try{const n=this._abortController.signal,i=this.persistence?await Promise.race([this.persistence.getMessage(e.entityId),new Promise((o,l)=>{if(n.aborted){l(new DOMException("Aborted","AbortError"));return}n.addEventListener("abort",()=>{l(new DOMException("Aborted","AbortError"))},{once:!0})})]):void 0;if(n.aborted)return;const s=i==null?void 0:i.session_client_id;if(!s||!this._shouldNotify(s))return;this._triggerNotification(e,s)}catch(n){if(n instanceof Error&&n.name==="AbortError")return;yy.error("Failed to handle message:",n)}}}_shouldNotify(e){var i,s;const r=(i=this.sessionController)==null?void 0:i.value.state.currentSessionId;if(r&&e===r)return!1;const n=(s=this.settingsController)==null?void 0:s.value.state.notifications;return!(!(n!=null&&n.soundEnabled)&&!(n!=null&&n.toastEnabled))}_triggerNotification(e,r){var i;this._playSound("message"),this._state={unreadCount:this._state.unreadCount+1,lastNotificationAt:Date.now()},this.host.requestUpdate(),((i=this.windowStateController)==null?void 0:i.value.state.mode)==="minimized"?this._animateMinimizeIcon():this._showToast(e,r)}_showToast(e,r){var d,u,h;const n=(d=this.settingsController)==null?void 0:d.value.state.notifications;if(!(n!=null&&n.toastEnabled))return;const i=e.newValue,s=gh(i),l=(((u=this.sessionController)==null?void 0:u.value.state.sessions)??[]).find(g=>g.clientId===r),c=(l==null?void 0:l.title)??Me("新消息");(h=this.toastController)==null||h.actions.show(`${c}: ${s}`,"info",{label:Me("查看"),onClick:()=>this._navigateToSession(r)})}_navigateToSession(e){var r;(r=this.sessionController)==null||r.actions.switchSession(e),this.actions.markAsRead(),this.host.dispatchEvent(new CustomEvent("rtc-notification-click",{bubbles:!0,composed:!0,detail:{sessionId:e}}))}_animateMinimizeIcon(){this.host.setAttribute("data-notification","active")}_clearAnimation(){this.host.removeAttribute("data-notification")}_markAsRead(){this._state={...this._state,unreadCount:0},this._clearAnimation(),this.host.requestUpdate()}_clearAll(){this._state={...B2},this._clearAnimation(),this.host.requestUpdate()}};ec.NOTIFY_THROTTLE_MS=300,ec.IDLE_FALLBACK_DELAY_MS=2e3,ec.DEFERRED_SOUND_DELAY_MS=500;let Y_=ec;class Tz{constructor(e,r){this.host=e,this.deps=r,this.host.addController(this),this._initializeHandlers()}hostConnected(){}hostDisconnected(){this.unbindEvents(this.host)}_initializeHandlers(){const{windowState:e,auth:r,session:n,message:i,persistence:s,toast:o,fork:l,activity:c,fileExplorer:d,editorArea:u,settings:h,sessionTab:g,autoSaveTimers:b,getRtcProcessor:I,setRtcProcessor:P,getUnsubConnection:C,setUnsubConnection:T,bumpConnectGeneration:w,setConnecting:S,fileTreeLoaded:v,setFileTreeLoaded:O,setInitialSessionLoadDone:N,loadFileTree:D,loadFolderChildren:B,handleFileOpen:Q,handleEditorSave:te,handleRestoreDefault:F,handleCommand:K,beforeMessageSend:ge,showRestoreConfirmDialog:Ie,handleLoginRequested:qe,dispatchClearActiveInput:Pe,getShadowRoot:he,findScrollableParent:me,scheduleAutoSave:G,log:re}=this.deps;this._boundOnMinimize=()=>e.actions.minimize(),this._boundOnMaximize=()=>e.actions.maximize(),this._boundOnRestore=()=>e.actions.restore(),this._boundOnLoginRequested=ye=>{qe(ye)},this._boundOnLogout=()=>{for(const V of b.values())clearTimeout(V);b.clear(),O(!1),N(!1),u.actions.closeAll(),g.actions.clearAll(),c.actions.setActivity("chat"),l.actions.clearFork();const ye=I();ye==null||ye.cancel(),P(void 0);const le=C();le==null||le(),T(void 0),w(),S(void 0),s.disconnect(),n.actions.reset(),i.actions.clearMessages()},this._boundOnAccountBanned=ye=>{re.warn("account banned, triggering logout");const le=ye.detail,V=le==null?void 0:le.reason;try{sessionStorage.removeItem("rtc-account-banned-pending")}catch{}o.actions.show(rT(V),"error"),r.actions.logout()},this._boundOnNewSession=()=>{l.actions.clearFork(),n.value.state.currentSessionId||i.actions.clearMessages()},this._boundOnSessionDeleteRequested=async ye=>{const{sessionId:le}=ye.detail;re.debug("session delete requested:",le);const V=await n.actions.deleteSession(le);if(V.ok)o.actions.show("会话已删除","success");else{const $={"delete-failed":"删除失败,请稍后重试"};o.actions.show($[V.error??""]??V.error??"删除失败","error")}},this._boundOnSessionRenameConfirmed=async ye=>{const{sessionId:le,title:V}=ye.detail;if(!V.trim())return;const $=await n.actions.renameSession(le,V.trim());if(!$.ok){const ne={"rename-failed":"重命名失败,请稍后重试"};o.actions.show(ne[$.error??""]??$.error??"重命名失败","error")}},this._boundOnInputSubmit=async ye=>{const V=ye.detail.contentData,ne=(Ae=>typeof Ae=="string"?Ae:"")(V.data),ce={message:{content:ne,metadata:void 0}};if(await ge(ce)){ce.message.content!==ne&&(V.data=ce.message.content);try{l.isActive?await l.actions.submitFork(V):await i.actions.sendMessage(V);const Ae=n.value.state.currentSessionId;Ae&&g.actions.markSaved(Ae)}catch(Ae){re.error("message submit failed:",Ae)}}},this._boundOnForkInitiated=ye=>{const{oldSessionClientId:le,oldMessageClientId:V,newSessionClientId:$,content:ne}=ye.detail;l.actions.requestFork(le,V,$,ne)},this._boundOnStopRequested=ye=>{const le=ye.detail;s.layer&&s.layer.stopTurn(le.sessionClientId)},this._boundOnResendMessage=ye=>{const V=ye.detail.message;V!=null&&V.clientId&&(V!=null&&V.content)&&i.actions.resendMessage(V.clientId,V.content)},this._boundOnToastRequested=ye=>{const le=ye.detail;o.actions.show(le.message,le.type)},this._boundOnToastClose=ye=>{const le=ye.detail;o.actions.remove(le.id)},this._boundOnCommandRequested=ye=>{const le=ye.detail;K(le.name,le.args)},this._boundOnActivityChange=ye=>{const{activity:le,toggleSidebar:V}=ye.detail;V?c.actions.toggleSidebar():(c.actions.setActivity(le),le==="settings"&&c.actions.showSidebar(),le==="files"&&!v()&&s.isConnected&&D())},this._boundOnFileSelect=ye=>{const{path:le}=ye.detail;Q(le)},this._boundOnFolderToggle=ye=>{const{path:le}=ye.detail;d.value.isExpanded(le)&&(re.debug("_boundOnFolderToggle: loading children for",le),B(le))},this._boundOnFileExplorerRefresh=()=>{D()},this._boundOnEditorAreaSave=ye=>{const{filePath:le}=ye.detail;te(le)},this._boundOnEditorAreaTabClose=ye=>{const{filePath:le}=ye.detail,V=b.get(le);V&&(clearTimeout(V),b.delete(le)),u.actions.closeFile(le)},this._boundOnEditorAreaTabSelect=ye=>{const{filePath:le}=ye.detail;u.actions.switchTab(le)},this._boundOnEditorAreaContentChange=ye=>{const{filePath:le,content:V}=ye.detail;u.actions.updateContent(le,V),h.value.state.files.autoSave&&G(le)},this._boundOnEditorAreaViewModeChange=ye=>{const{filePath:le,viewMode:V}=ye.detail;u.actions.setViewMode(le,V)},this._boundOnEditorAreaCursorMove=ye=>{const le=ye.detail,V=u.activeFilePath;V&&u.actions.setCursorPosition(V,le)},this._boundOnEditorAreaRestoreDefault=async ye=>{const{filePath:le}=ye.detail;if(!await Ie(le,he()))return;const $=await F(le);$.success?o.actions.show("已恢复默认内容","success"):o.actions.show($.error??"恢复失败","error")},this._boundOnChatLayoutSessionSelect=ye=>{const{sessionId:le}=ye.detail;re.debug("chat-layout session selected:",le)},this._boundOnChatLayoutTabActivate=ye=>{const{sessionId:le}=ye.detail;re.debug("chat-layout tab activated:",le)},this._boundOnChatLayoutTabClose=ye=>{const{sessionId:le}=ye.detail;re.debug("chat-layout tab closed:",le)},this._boundOnKeydown=ye=>{if(ye.key==="Escape"&&l.isActive){l.actions.clearFork(),Pe();return}if(!(c.active!=="files"||!(ye.metaKey||ye.ctrlKey))){if(ye.key==="s"||ye.key==="S"){const V=u.state.activeFilePath;V&&(ye.preventDefault(),te(V))}else if(ye.key==="w"||ye.key==="W"){const V=u.state.activeFilePath;V&&(ye.preventDefault(),u.actions.closeFile(V))}}},this._boundOnWheel=ye=>{const le=ye.composedPath()[0],V=le instanceof Element?le:null,$=V?me(V):null;if(!$){ye.preventDefault(),ye.stopPropagation();return}const{scrollTop:ne,scrollHeight:ce,clientHeight:Se,scrollLeft:Ae,scrollWidth:Ne,clientWidth:Xe}=$,be=ne<=0,Te=Math.ceil(ne+Se)>=ce,lt=ye.deltaY<0,it=ye.deltaY>0,Pt=ce>Se,We=Ae<=0,Ve=Math.ceil(Ae+Xe)>=Ne,Je=ye.deltaX<0||ye.shiftKey&&ye.deltaY<0,ot=ye.deltaX>0||ye.shiftKey&&ye.deltaY>0,Dt=Ne>Xe;(Pt&&(be&<||Te&&it)||Dt&&(We&&Je||Ve&&ot))&&(ye.preventDefault(),ye.stopPropagation())},this._boundOnDrawerClose=()=>{c.actions.hideSidebar()}}bindEvents(e){e.addEventListener("rtc-window-minimize",this._boundOnMinimize),e.addEventListener("rtc-window-maximize",this._boundOnMaximize),e.addEventListener("rtc-window-restore",this._boundOnRestore),e.addEventListener("rtc-auth-login-requested",this._boundOnLoginRequested),e.addEventListener("rtc-auth-logout",this._boundOnLogout),e.addEventListener("rtc-account-banned",this._boundOnAccountBanned),e.addEventListener("rtc-new-session",this._boundOnNewSession),e.addEventListener("rtc-session-delete-requested",this._boundOnSessionDeleteRequested),e.addEventListener("rtc-session-rename-confirmed",this._boundOnSessionRenameConfirmed),e.addEventListener("rtc-input-submit",this._boundOnInputSubmit),e.addEventListener("rtc-fork-initiated",this._boundOnForkInitiated),e.addEventListener("rtc-stop-requested",this._boundOnStopRequested),e.addEventListener("rtc-user-message-resend",this._boundOnResendMessage),e.addEventListener("rtc-toast-requested",this._boundOnToastRequested),e.addEventListener("rtc-toast-close",this._boundOnToastClose),e.addEventListener("rtc-command-requested",this._boundOnCommandRequested),e.addEventListener("activity-change",this._boundOnActivityChange),e.addEventListener("file-select",this._boundOnFileSelect),e.addEventListener("folder-toggle",this._boundOnFolderToggle),e.addEventListener("refresh-requested",this._boundOnFileExplorerRefresh),e.addEventListener("editor-area-save",this._boundOnEditorAreaSave),e.addEventListener("editor-area-tab-close",this._boundOnEditorAreaTabClose),e.addEventListener("editor-area-tab-select",this._boundOnEditorAreaTabSelect),e.addEventListener("editor-area-content-change",this._boundOnEditorAreaContentChange),e.addEventListener("editor-area-view-mode-change",this._boundOnEditorAreaViewModeChange),e.addEventListener("editor-area-cursor-move",this._boundOnEditorAreaCursorMove),e.addEventListener("editor-area-restore-default",this._boundOnEditorAreaRestoreDefault),e.addEventListener("rtc-chat-layout-session-select",this._boundOnChatLayoutSessionSelect),e.addEventListener("rtc-chat-layout-tab-activate",this._boundOnChatLayoutTabActivate),e.addEventListener("rtc-chat-layout-tab-close",this._boundOnChatLayoutTabClose),e.addEventListener("rtc-drawer-close",this._boundOnDrawerClose),e.addEventListener("keydown",this._boundOnKeydown),e.addEventListener("wheel",this._boundOnWheel,{passive:!1})}unbindEvents(e){e.removeEventListener("rtc-window-minimize",this._boundOnMinimize),e.removeEventListener("rtc-window-maximize",this._boundOnMaximize),e.removeEventListener("rtc-window-restore",this._boundOnRestore),e.removeEventListener("rtc-auth-login-requested",this._boundOnLoginRequested),e.removeEventListener("rtc-auth-logout",this._boundOnLogout),e.removeEventListener("rtc-account-banned",this._boundOnAccountBanned),e.removeEventListener("rtc-new-session",this._boundOnNewSession),e.removeEventListener("rtc-session-delete-requested",this._boundOnSessionDeleteRequested),e.removeEventListener("rtc-session-rename-confirmed",this._boundOnSessionRenameConfirmed),e.removeEventListener("rtc-input-submit",this._boundOnInputSubmit),e.removeEventListener("rtc-fork-initiated",this._boundOnForkInitiated),e.removeEventListener("rtc-stop-requested",this._boundOnStopRequested),e.removeEventListener("rtc-user-message-resend",this._boundOnResendMessage),e.removeEventListener("rtc-toast-requested",this._boundOnToastRequested),e.removeEventListener("rtc-toast-close",this._boundOnToastClose),e.removeEventListener("rtc-command-requested",this._boundOnCommandRequested),e.removeEventListener("activity-change",this._boundOnActivityChange),e.removeEventListener("file-select",this._boundOnFileSelect),e.removeEventListener("folder-toggle",this._boundOnFolderToggle),e.removeEventListener("refresh-requested",this._boundOnFileExplorerRefresh),e.removeEventListener("editor-area-save",this._boundOnEditorAreaSave),e.removeEventListener("editor-area-tab-close",this._boundOnEditorAreaTabClose),e.removeEventListener("editor-area-tab-select",this._boundOnEditorAreaTabSelect),e.removeEventListener("editor-area-content-change",this._boundOnEditorAreaContentChange),e.removeEventListener("editor-area-view-mode-change",this._boundOnEditorAreaViewModeChange),e.removeEventListener("editor-area-cursor-move",this._boundOnEditorAreaCursorMove),e.removeEventListener("editor-area-restore-default",this._boundOnEditorAreaRestoreDefault),e.removeEventListener("rtc-chat-layout-session-select",this._boundOnChatLayoutSessionSelect),e.removeEventListener("rtc-chat-layout-tab-activate",this._boundOnChatLayoutTabActivate),e.removeEventListener("rtc-chat-layout-tab-close",this._boundOnChatLayoutTabClose),e.removeEventListener("rtc-drawer-close",this._boundOnDrawerClose),e.removeEventListener("keydown",this._boundOnKeydown),e.removeEventListener("wheel",this._boundOnWheel)}get handlers(){return{onLoginRequested:this._boundOnLoginRequested}}}const f4=er("FunctionsController");class Ez{constructor(e){this._registry=null,this._state={...wb},this.host=e,this.host.addController(this),this.actions={refresh:()=>this._refresh()}}get value(){return{state:this._state,actions:this.actions}}hostConnected(){}hostDisconnected(){}setRegistry(e){this._registry=e,e?this._refresh():(this._state={...wb},this.host.requestUpdate())}_refresh(){if(!this._registry){this._state={...wb},this.host.requestUpdate();return}try{const e=this._registry.listFunctions(),r=this._registry.listGroups();this._state={functions:e,groups:r},f4.debug("Refreshed function list:",e.length,"functions,",r.length,"groups"),this.host.requestUpdate()}catch(e){f4.error("Failed to refresh function list:",e)}}}function J_(t,e){var o,l;const r=[];let n=t;for(;n!=null&&n._def;){const c=n._def.typeName||n._def.type;if(c==="ZodOptional"||c==="optional"||c==="ZodDefault"||c==="default")n=n._def.innerType;else break}const i=(n==null?void 0:n._def)&&(n._def.typeName==="ZodObject"||n._def.shape!==void 0&&typeof n._def.shape=="object"&&!Array.isArray(n._def.shape));if(!n||!n._def||!i)throw new Error("zodToParams expects a ZodObject schema (got: "+(((o=n==null?void 0:n._def)==null?void 0:o.typeName)||((l=n==null?void 0:n._def)==null?void 0:l.type)||"unknown")+")");const s=typeof n._def.shape=="function"?n._def.shape():n._def.shape;for(const[c,d]of Object.entries(s)){const u=Eo(d),{isOptional:h,description:g,example:b}=X_(d);r.push({name:c,schema:{...u,description:(e==null?void 0:e[c])||g||u.description,...b!==void 0?{example:b}:{}},required:!h,description:(e==null?void 0:e[c])||g})}return r}function X_(t){var c,d;const e=t._def;if(!e)return{isOptional:!1};let r=!1,n,i;const s=e.typeName||e.type;if((s==="ZodOptional"||s==="optional"||s==="ZodDefault"||s==="default")&&(r=!0,e.innerType)){const u=X_(e.innerType);n=u.description,i=u.example}e.description?n=e.description:t.description&&(n=t.description);const o=e.meta;(o==null?void 0:o.example)!==void 0?i=o.example:o!=null&&o.examples&&o.examples.length>0&&(i=o.examples[0]);const l=(c=t._zod)==null?void 0:c.bag;if(i===void 0&&(l==null?void 0:l.example)!==void 0?i=l.example:i===void 0&&(l!=null&&l.examples)&&l.examples.length>0&&(i=l.examples[0]),i===void 0&&(s==="ZodEnum"||s==="enum")&&((d=e.values)==null?void 0:d.length)>0&&(i=e.values[0]),i===void 0&&(s==="ZodDefault"||s==="default")&&typeof e.defaultValue=="function")try{i=e.defaultValue()}catch{}return{isOptional:r,description:n,example:i}}function Z_(t){return Eo(t)}function Eo(t){const e=t._def;if(!e)return{};const r=e.meta,n=r==null?void 0:r.format;switch(e.typeName||e.type){case"ZodString":case"string":{const s={type:"string"};if(e.checks)for(const o of e.checks){const l=o.def||o,c=o.kind||l.check,d=o.value??l.value;if((c==="min"||c==="minLength")&&(s.minLength=d),(c==="max"||c==="maxLength")&&(s.maxLength=d),c==="regex"){const u=o.regex||l.regex;u&&(s.pattern=u.source||u)}}return n&&(s.format=n),s}case"ZodNumber":case"number":{const s={type:"number"};let o=!1;if(e.checks)for(const l of e.checks){const c=l.def||l,d=l.kind||c.check,u=l.value??c.value;d==="min"&&(s.minimum=u),d==="max"&&(s.maximum=u),(d==="int"||c.type==="number"&&c.format==="safeint")&&(o=!0)}return o&&(s.type="integer"),n&&(s.format=n),s}case"ZodBoolean":case"boolean":return{type:"boolean"};case"ZodEnum":case"enum":return{type:"string",enum:e.values};case"ZodArray":case"array":return{type:"array",items:Eo(e.element||e.type)};case"ZodOptional":case"optional":return Eo(e.innerType);case"ZodDefault":case"default":return{...Eo(e.innerType),default:typeof e.defaultValue=="function"?e.defaultValue():e.defaultValue};case"ZodObject":case"object":{const s=typeof e.shape=="function"?e.shape():e.shape;if(!s)return{type:"object"};const o={},l=[];for(const[u,h]of Object.entries(s)){const g=Eo(h),b=X_(h);b.description&&!g.description&&(g.description=b.description),o[u]=g,b.isOptional||l.push(u)}const c={type:"object",properties:o};l.length>0&&(c.required=l);const d=e.description||t.description;return d&&(c.description=d),c}case"ZodVoid":case"void":return{type:"null"};case"ZodNull":case"null":return{type:"null"};case"ZodNullable":case"nullable":return{...Eo(e.innerType),nullable:!0};case"ZodRecord":case"record":{const s=e.valueType||e.type;return{type:"object",additionalProperties:s?Eo(s):{}}}case"ZodAny":case"any":return{};case"ZodUnknown":case"unknown":return{};case"ZodLiteral":case"literal":{const s=e.value,o=typeof s;return o==="string"?{type:"string",enum:[s]}:o==="number"?{type:"number",enum:[s]}:o==="boolean"?{type:"boolean",enum:[s]}:{enum:[s]}}case"ZodUnion":case"union":case"ZodDiscriminatedUnion":case"discriminatedUnion":{const s=e.options||[];return s.length===0?{}:{oneOf:s.map(l=>Eo(l))}}case"ZodIntersection":case"intersection":{const s=Eo(e.left),o=Eo(e.right);return{allOf:[s,o]}}case"ZodTuple":case"tuple":{const s=(e.items||[]).map(o=>Eo(o));return{type:"array",items:s.length>0?{oneOf:s}:{},minItems:s.length,maxItems:s.length}}default:return{}}}function by(t,e){const r=t._def;return r&&(r.meta={...r.meta,...e}),t}const p4=er("MarkdownGenerator");function tl(t){return t?t.$ref?`[${t.$ref.split("/").pop()||t.$ref}](${t.$ref})`:t.oneOf&&t.oneOf.length>0?t.oneOf.map(e=>tl(e)).join(" | "):t.type==="array"&&t.items?`${tl(t.items)}[]`:t.type==="object"&&t.properties?`{ ${Object.entries(t.properties).map(([r,n])=>`${r}: ${tl(n)}`).join(", ")} }`:t.type?t.format?`${t.type} (${t.format})`:t.type:t.format?t.format:"unknown":"unknown"}function vy(t,e,r,n,i=0){const s=[],o=" ".repeat(i),l=i>0?`└─ ${e}`:e,c=t.example!==void 0?`\`${JSON.stringify(t.example)}\``:"";if(t.type&&t.type!=="object"&&t.type!=="array"){const g=tl(t),b=n||t.description||"",I=r?"Yes":"No";return s.push(`| ${o}${l} | ${g} | ${I} | ${b} | ${c} |`),s}if(t.type==="array"&&t.items){const g=`${tl(t.items)}[]`,b=n||t.description||"",I=r?"Yes":"No";if(s.push(`| ${o}${l} | ${g} | ${I} | ${b} | ${c} |`),t.items.type==="object"&&t.items.properties){const P=t.items.required||[];for(const[C,T]of Object.entries(t.items.properties)){const w=P.includes(C);s.push(...vy(T,C,w,T.description,i+1))}}return s}if(t.type==="object"&&t.properties){const g=n||t.description||"",b=r?"Yes":"No";s.push(`| ${o}${l} | object | ${b} | ${g} | ${c} |`);const I=t.required||[];for(const[P,C]of Object.entries(t.properties)){const T=I.includes(P);s.push(...vy(C,P,T,C.description,i+1))}return s}const d=tl(t),u=n||t.description||"",h=r?"Yes":"No";return s.push(`| ${o}${l} | ${d} | ${h} | ${u} | ${c} |`),s}function Q_(t,e){var s,o,l,c,d;let r=`<!-- AUTO-GENERATED by rtc-agent FunctionRegistry. Do not edit manually. -->
|
|
3314
3314
|
|
|
3315
3315
|
`;r+=`# ${t.name}
|
|
3316
3316
|
|