import{n as e}from"./rolldown-runtime-DkW27tQK.js";import{Ci as t,Di as n,Ei as r,Gt as i,Jt as a,Qt as o,Sn as s,Xt as c,Yt as l,ai as u,an as d,bn as f,ci as p,di as m,dt as h,ki as g,kn as _,mi as v,pi as y,pt as ee,qt as te,ui as ne,un as re,vn as ie,wn as ae,yn as b}from"./control-ui-foundation-CeFMP1Ly.js";import{$ as oe,Ac as se,Bc as ce,C as le,Ca as ue,Cc as de,Da as fe,Dc as x,E as pe,Ea as me,Ec as he,G as ge,Ic as _e,It as ve,Mt as ye,Na as be,Nc as xe,Nt as Se,Pc as Ce,Qa as we,Sa as Te,Sc as Ee,Vc as De,W as Oe,Xa as ke,_o as Ae,_t as je,bc as S,ct as Me,fs as C,go as Ne,gt as Pe,hc as Fe,ja as Ie,jc as Le,jt as Re,mc as w,ms as T,nt as ze,pc as Be,ps as Ve,rt as He,st as Ue,tt as We,uo as Ge,vo as Ke,vt as qe,w as Je,wa as Ye}from"./control-ui-core-pH6nakZ-.js";import{G as E,J as D,W as Xe}from"./lit-runtime-BEtFSUCp.js";import{At as Ze,B as Qe,Pn as $e,Tt as et,Xt as tt,Z as nt,Zt as rt,jt as it,qn as at,wt as ot,zn as st}from"./control-ui-core-DGVkFhVB.js";import{Et as ct,Ht as lt,Lt as ut,Rt as dt,St as ft,qt as O,v as pt,w as mt}from"./control-ui-core-Br5DB0Zj.js";import{Bn as ht,Gn as k,Kn as A,Ot as gt,Rn as _t,Un as vt,X as yt,Z as bt,bt as xt,jt as St,kt as Ct,qn as wt,vt as Tt,yt as Et}from"./control-ui-boot-wpHCbPL9.js";import{As as Dt,Bi as Ot,Bu as kt,Fd as At,Fi as jt,Gu as Mt,Hi as Nt,Ku as Pt,Mi as Ft,Ml as It,Ni as Lt,Nu as Rt,Ol as j,Os as zt,Pu as Bt,Qr as Vt,Ri as Ht,Ui as Ut,Vi as Wt,Wi as Gt,Y as Kt,_d as qt,an as Jt,bd as Yt,fi as Xt,ks as Zt,li as Qt,mi as $t,pi as en,pl as tn,qi as nn,qu as rn,ui as an,zi as on}from"./control-ui-boot-Cdpgu1Gm.js";import{D as sn,T as M,_ as cn,b as ln,d as un,h as dn,m as fn,x as pn}from"./config-runtime-C4gfjhZc.js";import{a as mn,c as hn,i as gn,o as _n}from"./control-ui-boot-9_2QGLIL.js";import{Bn as vn,vn as yn,yn as bn}from"./control-ui-boot-B1lcIXow.js";import{C as xn,D as Sn,E as Cn,S as wn,T as Tn,f as En,m as Dn}from"./control-ui-boot-Clhp68JE.js";import{$ as N,G as On,J as kn,K as An,Y as jn,_ as Mn,b as Nn,bt as Pn,et as Fn,f as In,h as Ln,ht as Rn,m as zn,mt as Bn,p as Vn,pt as Hn,q as Un,tt as Wn,v as Gn,y as Kn,yt as qn}from"./control-ui-boot-J-x6DHHT.js";import{C as Jn,D as Yn,E as Xn,S as Zn,T as Qn,Tt as $n,_ as er,_t as tr,b as nr,ct as rr,d as ir,f as ar,g as or,gt as sr,m as cr,p as lr,st as ur,v as dr,w as fr,wt as pr,x as mr,y as hr}from"./control-ui-boot-BPFwXC8p.js";import{n as gr,t as _r}from"./control-ui-boot-DdPrPuw0.js";function P(e,t){if(!e.has(t))return;let n=e.get(t);return e.delete(t),e.set(t,n),n}function F(e,t,n){for(e.delete(t),e.set(t,n);e.size>20;){let t=e.keys().next().value;if(typeof t!=`string`)break;e.delete(t)}}function vr(e,t,n){if(e.has(t))return P(e,t);let r=n();return F(e,t,r),r}function yr(){return(yr=e((()=>{})))()}function br(e,t){t===void 0?console.debug(`[chat-snapshot-cache] ${e}`):console.debug(`[chat-snapshot-cache] ${e}`,t)}function xr(){try{return globalThis.indexedDB??null}catch(e){return br(`IndexedDB is unavailable`,e),null}}function Sr(e){return new Promise((t,n)=>{let r=e.open(Dr,kr);r.addEventListener(`upgradeneeded`,()=>{let e=r.result;for(let t of Array.from(e.objectStoreNames))e.deleteObjectStore(t);e.createObjectStore(I,{keyPath:`sessionKey`}),e.createObjectStore(Or,{keyPath:`sessionKey`})}),r.addEventListener(`success`,()=>t(r.result)),r.addEventListener(`error`,()=>n(r.error??Error(`IndexedDB open failed`))),r.addEventListener(`blocked`,()=>n(Error(`IndexedDB open was blocked`)))})}function Cr(e){return new Promise(t=>{try{let n=e.deleteDatabase(Dr);n.addEventListener(`success`,()=>t(!0)),n.addEventListener(`error`,()=>t(!1)),n.addEventListener(`blocked`,()=>t(!1))}catch{t(!1)}})}async function wr(){let e=xr();if(!e)return null;let t;try{t=await Sr(e)}catch(n){if(br(`resetting cache after IndexedDB open failure`,n),!await Cr(e))return null;try{t=await Sr(e)}catch(e){return br(`IndexedDB cache remains unavailable`,e),null}}if(t.addEventListener(`versionchange`,()=>t.close()),t.objectStoreNames.length===2&&t.objectStoreNames.contains(`snapshots`)&&t.objectStoreNames.contains(`snapshotMetadata`))return t;if(t.close(),br(`resetting cache after IndexedDB schema mismatch`),!await Cr(e))return null;try{let t=await Sr(e);return t.addEventListener(`versionchange`,()=>t.close()),t}catch(e){return br(`IndexedDB cache reset failed`,e),null}}async function Tr(e){e?.close();let t=xr();t&&!await Cr(t)&&br(`IndexedDB cache reset was blocked`)}async function Er(e){let t=await wr();if(t)try{await new Promise(n=>{let r=t.transaction([I,Or],`readwrite`);r.addEventListener(`complete`,()=>n()),r.addEventListener(`error`,()=>n()),r.addEventListener(`abort`,()=>n()),r.objectStore(I).delete(e),r.objectStore(Or).delete(e)})}catch{}finally{t.close()}}var Dr,I,Or,kr;function Ar(){return(Ar=e((()=>{Dr=`openclaw-chat-snapshots`,I=`snapshots`,Or=`snapshotMetadata`,kr=2})))()}function L(e,n){let r=x(n.sessionKey),i=n.agentId?.trim(),a=i?t(i):r?t(r.agentId):de(n.sessionKey)?_e(e):xe(e),o=he(n.sessionKey),s=r?o.split(`:`).slice(2).join(`:`):o,c=Le(e);return`agent:${a}:${de(n.sessionKey)||s===`main`||s===c?Be:s}`}function jr(){try{return globalThis.indexedDB??null}catch{return null}}async function Mr(e){await je({sessionKey:e}),await Er(e)}async function Nr(){let e=jr();if(e)try{await new Promise(t=>{let n=e.deleteDatabase(Dr);n.addEventListener(`success`,()=>t()),n.addEventListener(`error`,()=>t()),n.addEventListener(`blocked`,()=>t())})}catch{}}async function Pr(){await je({}),await Nr()}function Fr(){return(Fr=e((()=>{S(),Ar(),Pe()})))()}function Ir(e,t){ii.set(e,t)}function Lr(e,t){e.delete(t),ii.get(e)?.delete(t)}function Rr(e,t){e.chatMessages=t.messages,e.chatHistoryPagination=t.pagination,e.currentSessionId=t.sessionId,e.chatDisplayedLeafEntryId=t.displayedLeafEntryId}function zr(e,t,n){ii.get(e)?.write(t,n)}function Br(e,t,n,r,i){let a=L(t,n),o=P(e,a);if(!o)return;if(i){let t=ri.get(e);if(t||(t=new WeakSet,ri.set(e,t)),t.has(i))return;t.add(i)}let s=Yr(r);if(s===null){Lr(e,a);return}let c=i?vt(_t({},o.snapshot.messages),{type:`messagePersisted`,message:r,envelope:i}).messages.slice():[...o.snapshot.messages,r],l={...o.snapshot.deltaCursor===void 0?{}:{deltaCursor:o.snapshot.deltaCursor},...Object.hasOwn(o.snapshot,`displayedLeafEntryId`)?{displayedLeafEntryId:o.snapshot.displayedLeafEntryId}:{},messages:c,pagination:o.snapshot.pagination,sessionId:o.snapshot.sessionId};if(i){Ur(e,t,n,l);return}let u=o.weight+s+ +(o.snapshot.messages.length>0);if(u>ei){Ur(e,t,n,l);return}F(e,a,{snapshot:l,weight:u}),$r(e),zr(e,a,l)}function Vr(e,t,n){return Wr(e,t,n)?.messages??[]}function Hr(e,t,n){Lr(e,L(t,n))}function Ur(e,t,n,r){let i=L(t,n),a=P(e,i);if(a?.snapshot.messages===r.messages&&a.snapshot.deltaCursor===r.deltaCursor&&a.snapshot.sessionId===r.sessionId&&a.snapshot.displayedLeafEntryId===r.displayedLeafEntryId&&Qr(a.snapshot.pagination,r.pagination))return;if(r.messages.length===0&&r.sessionId===null&&!r.pagination.hasMore&&(r.pagination.totalMessages??0)===0&&r.pagination.completeSnapshot!==!0){Lr(e,i);return}let o=Kr(r);if(!o){Lr(e,i);return}F(e,i,o),$r(e),zr(e,i,o.snapshot)}function Wr(e,t,n){return P(e,L(t,n))?.snapshot??null}function Gr(e){let t=qr(e.messages);return t?Jr(e.deltaCursor,e.pagination,e.sessionId,e.displayedLeafEntryId,t.reduce((e,t)=>e+t,0),t.length):null}function Kr(e){let t=qr(e.messages);if(!t)return null;let n=t.reduce((e,t)=>e+t,0),r=0;for(;;){let i=r===0?e.pagination:Xr(e.pagination,e.messages,r);if(!i)return null;let a=Jr(e.deltaCursor,i,e.sessionId,e.displayedLeafEntryId,n,t.length-r);if(a!==null&&a<=ei)return r===0?{snapshot:e,weight:a}:{snapshot:{...e.deltaCursor===void 0?{}:{deltaCursor:e.deltaCursor},...Object.hasOwn(e,`displayedLeafEntryId`)?{displayedLeafEntryId:e.displayedLeafEntryId}:{},messages:e.messages.slice(r),pagination:{...i},sessionId:e.sessionId},weight:a};if(r>=e.messages.length)return null;let o=wt(e.messages[r]);if(n-=t[r]??0,r+=1,o!==null)for(;r1?{hasMore:!0,nextOffset:a,totalMessages:r}:{hasMore:!1,totalMessages:r}}function Zr(e){try{return JSON.stringify(e)?.length??0}catch{return null}}function Qr(e,t){return e.hasMore!==t.hasMore||e.totalMessages!==t.totalMessages?!1:e.hasMore&&t.hasMore?e.nextOffset===t.nextOffset:!e.hasMore&&!t.hasMore&&e.completeSnapshot===t.completeSnapshot}function $r(e){let t=0;for(let n of e.values())t+=n.weight;for(;t>ti;){let n=e.keys().next().value;if(typeof n!=`string`)break;t-=e.get(n)?.weight??0,e.delete(n)}}var ei,ti,ni,ri,ii;function ai(){return(ai=e((()=>{ht(),k(),yr(),Fr(),ei=12582912,ti=25165824,ni=new WeakMap,ri=new WeakMap,ii=new WeakMap})))()}function oi(e,t){let n=[],r=e.trim();r&&n.push({type:`text`,text:r});for(let e of t??[]){let t=ye(e);if(!t)continue;if(e.mimeType.startsWith(`image/`)){n.push({type:`image`,url:t,source:{type:`url`,url:t}});continue}let r=e.mimeType.trim().toLowerCase(),i=r.startsWith(`video/`)||(r===``||r===`application/octet-stream`)&&Rt(e.fileName??``);n.push({type:`attachment`,attachment:{url:t,kind:e.mimeType.startsWith(`audio/`)?`audio`:i?`video`:`document`,label:e.fileName?.trim()||`Attached file`,mimeType:e.mimeType}})}return n}function si(e){let t=oi(e.text,e.attachments);return t.length===0?null:{role:`user`,content:t,timestamp:e.createdAt,__openclaw:{...e.runId?{idempotencyKey:`${e.runId}:user`}:{},...e.pending?{kind:`pending-send`,id:e.pending.id,...e.pending.state?{state:e.pending.state}:{},...e.pending.error?{error:e.pending.error}:{}}:{},...e.replyToId?{replyToId:e.replyToId}:{},...e.sender?.id?{senderId:e.sender.id}:{},...e.sender?.identity?{senderIdentity:e.sender.identity}:{},...e.sender?.name?{senderName:e.sender.name}:{},...e.sender?.username?{senderUsername:e.sender.username}:{},...e.sender?.profileAvatarUrl?{senderProfileAvatarUrl:e.sender.profileAvatarUrl}:{},...e.sequence===void 0?{}:{seq:e.sequence}}}}function ci(){return(ci=e((()=>{Bt(),Se()})))()}function li(e,t,n,r){return t&&e&&typeof e==`object`&&_i.set(e,{runId:t,...n?{afterBoundaryRunId:n}:{},...r?{disposition:r}:{}}),e}function ui(e,t){return!!(e&&typeof e==`object`&&_i.get(e)?.runId===t)}function di(e){return e&&typeof e==`object`?_i.get(e)?.runId??null:null}function fi(e){return e&&typeof e==`object`?_i.get(e)?.afterBoundaryRunId??null:null}function pi(e){return e&&typeof e==`object`?_i.get(e)?.disposition??null:null}function mi(e){let t=f(e.payload),n=A(t?.message,{messageId:t?.messageId}),r=n?.role===`assistant`&&!n.isImported?n.id:null;!e.runIdBeforeApply||!e.matchesChat||e.event.hasActiveRun===!0||!r||vi.set(e.host,{historyApplied:!1,messageId:r,runId:e.event.clientRunId??e.event.runId??e.runIdBeforeApply,sessionKey:e.event.key})}function hi(e){let t=vi.get(e.host),n=!!(t&&w(t.sessionKey,e.sessionKey)&&e.visibleMessages.some(e=>{let n=A(e);return n?.role===`assistant`&&!n.isImported&&n.id===t.messageId}));return!t||!n?e.previousMessages:(vi.set(e.host,{...t,historyApplied:!0}),e.previousMessages.filter(e=>!ui(e,t.runId)))}function gi(e,t){let n=vi.get(e);return n?.runId===t&&n.historyApplied}var _i,vi;function yi(){return(yi=e((()=>{k(),S(),_i=new WeakMap,vi=new WeakMap})))()}function bi(e,t){return JSON.stringify([e,t])}function xi(e,t,n,r){if(!n)return;let i=r?bi(r,n):n;t.has(i)||(t.add(i),e.push({id:n,...r?{runId:r}:{}}))}function Si(e){return mn(e.type)||_n(e.type)}function Ci(e){let t=f(e);if(!t)return[];let n=[],r=new Set,i=Array.isArray(t.content)?t.content.filter(e=>!!e&&typeof e==`object`):[],a=hn({...t,id:void 0}),o=A(t)?.runId??g(t.runId),s=t.role;(typeof s==`string`&&nn(s).toLowerCase()===`tool`||Di.some(e=>!!g(t[e]))||i.some(Si))&&xi(n,r,a,o);for(let e of i)Si(e)&&xi(n,r,hn(e)??a,g(e.runId)??o);return n}function wi(e){return Array.isArray(e.toolStreamOrder)?e.toolStreamOrder.filter(e=>typeof e==`string`&&!!e.trim()).map(t=>{let n=f(e.toolStreamById?.get(t)),r=f(n?.message),i=g(n?.toolCallId)??(r?hn(r):void 0)??t,a=g(n?.runId)??g(r?.runId);return a?{identity:t,id:i,runId:a}:{identity:t,id:i}}):[]}function Ti(e,t){let n=t.filter(t=>t.id===e.id&&(!e.runId||!t.runId||t.runId===e.runId));return n.length===1?n[0]?.identity:void 0}function Ei(e,t){let n=wi(t),r=new Set;if(n.length===0)return r;let i=e.findLastIndex(e=>{let t=f(e)?.role;return typeof t==`string`&&nn(t).toLowerCase()===`user`});for(let t of e.slice(i+1))for(let e of Ci(t)){let t=Ti(e,n);t&&r.add(t)}return r}var Di;function Oi(){return(Oi=e((()=>{k(),gn(),Gt(),Di=[`toolName`,`tool_name`]})))()}function ki(e,t=e.length){for(let n=t-1;n>=0;--n)if(A(e[n])?.role===`user`)return n;return-1}function Ai(e){let t=f(f(e)?.__openclaw);return g(t?.steerTargetRunId)??null}function ji(e){for(let t of e){let e=N(t);if(e?.startsWith(`send:`))return e.slice(5)}return null}function Mi(e){for(let t of e){let e=Ai(t);if(e)return e}return null}function Ni(e,t){let n=new Map,r=new Map;for(let[i,a]of e.entries()){let e=t(a),o=ji(e);o&&!n.has(o)&&n.set(o,i);let s=Mi(e);if(s){let e=r.get(s)??[];e.push(i),r.set(s,e)}}let i=new Map,a=new Map;for(let[e,t]of r){let r=n.get(e);if(r!==void 0)for(let e of t)e<=r||(i.set(r,e),a.set(e,r),r=e)}return{continuationTurnIndexes:i,precedingContinuationTurnIndexes:a}}function Pi(e,t){for(let n=e.length-1;n>=0;--n){if(A(e[n])?.role!==`user`||Ai(e[n])!==t)continue;let r=N(e[n]);if(r?.startsWith(`send:`))return{index:n,runId:r.slice(5)}}return null}function Fi(e){let t=e.chatStreamSegments??[];for(let e=t.length-1;e>=0;--e){let n=g(t[e]?.boundaryRunId);if(n)return n}}function Ii(e,t){let n=t.afterBoundaryRunId?`send:${t.afterBoundaryRunId}`:null,r=n?e.findIndex(e=>N(e)===n):-1,i=t.boundaryRunId?`send:${t.boundaryRunId}`:null,a=i?e.findIndex(e=>N(e)===i):-1;if(a>=0)return{start:r>=0?r+1:ki(e,a)+1,end:a};if(r>=0){let t=e.findIndex((e,t)=>t>r&&A(e)?.role===`user`);return{start:r+1,end:t>=0?t:e.length}}let o=t.runId?`send:${t.runId}`:null,s=o?e.findIndex(e=>N(e)===o):-1;if(s>=0){let t=e.findIndex((e,t)=>t>s&&A(e)?.role===`user`);return{start:s+1,end:t>=0?t:e.length}}let c=e.length;return{start:ki(e,c)+1,end:c}}function Li(e,t,n,r,i){for(let a=n;at)return a}return r}function Ri(e,t,n,r){let i=null;for(let n=t-1;n>=0&&(i=r(e[n]),i==null);--n);let a=null;for(let n=t;n=a?i+(a-i)/2:e}if(a!=null&&n>=a){let e=a-1;return i!=null&&e<=i?i+(a-i)/2:e}return n}function zi(e,t,n,r=e.length){let i=-1;for(let a=0;a=0?i:ki(e,r)+1;return Bi(e.slice(a,r).map(e=>{let t=A(e);return t?.role===`assistant`&&(!t.runId||t.runId===n)&&!An(e)?j(e):null}),t)}function Bi(e,t){let n=0;for(let r of e){if(!r)continue;let e=t.slice(n);if(e.startsWith(r)){n+=r.length;continue}if(r.startsWith(e))return null;let i=n>0?/^\s+/u.exec(e)?.[0]:void 0;if(i&&e.slice(i.length).startsWith(r)){n+=i.length+r.length;continue}if(i&&r.startsWith(e.slice(i.length)))return null;if(n>0)break}return t.slice(n)}function Vi(e,t){let n=e.chatMessages,r=e.chatRunId;if(!Array.isArray(n)||!r)return null;let i=Pi(n,r);if(!i||i.index<=0)return null;let a=zi(n,t,r,i.index);return a===t?null:{boundaryRunId:i.runId,prefix:a===null?t:t.slice(0,t.length-a.length)}}function Hi(e,t){if(Array.isArray(e.content)){let n=!1,r=e.content.flatMap(e=>{let r=f(e);return!r||r.type!==`text`&&r.type!==`input_text`&&r.type!==`output_text`||typeof r.text!=`string`?[e]:n?[]:(n=!0,[{...r,text:t}])});if(n)return{...e,content:r}}return typeof e.content==`string`?{...e,content:t}:typeof e.text==`string`?{...e,text:t}:e}function Ui(e,t){return!!(e?.boundaryRunId&&t.startsWith(e.prefix))}function Wi(e,t){let n=j(e);if(!n)return{kind:`none`};let r=null,i=[],a=null;for(let[e,n]of(t.chatStreamSegments??[]).entries()){if(en(n)&&typeof n.text==`string`){let t=an(r,n.text);t!==r&&i.push(e),r=t}let t=g(n.boundaryRunId);t&&r&&(a={boundaryRunId:t,prefix:r,segmentIndexes:[...i]})}let o=Vi(t,n),s=Ui(a,n)?a:Ui(o,n)?o:null;if(!s)return{kind:`none`};let c=n.slice(s.prefix.length).trimStart();return{kind:`split`,afterBoundaryRunId:s.boundaryRunId,replacedSegmentIndexes:s===o&&a?a.segmentIndexes:[],tailMessage:c?Hi(e,c):null}}function Gi(e){let t=e.messages;if(!t)return;let n=t.findIndex(t=>N(t)===`send:${e.boundaryRunId}`),r=e.afterBoundaryRunId??e.runId,i=t.findIndex(e=>N(e)===`send:${r}`);if(!(i<0||n<=i))for(let e=i+1;e=0&&(r=g(n[e]?.boundaryRunId),!r);--e);let i=typeof e.chatStream==`string`,a=i&&!!e.chatStream?.trim(),o=t.boundaryRunId?Gi({messages:e.chatMessages,runId:t.runId,boundaryRunId:t.boundaryRunId,afterBoundaryRunId:r})??t.boundaryRunId:void 0;if(o){let e=n.findLastIndex(e=>e.boundaryRunId);n=n.map((t,n)=>n<=e||t.boundaryRunId?t:{...t,boundaryRunId:o})}if(a&&(n=[...n,{text:e.chatStream??``,ts:e.chatStreamStartedAt??t.timestamp??Date.now(),runId:t.runId,...r?{afterBoundaryRunId:r}:{},...o?{boundaryRunId:o}:{},...t.toolCallId?{toolCallId:t.toolCallId}:{},...t.persisted?{persisted:!0}:{}}]),t.boundaryRunId&&!n.some(e=>e.boundaryRunId===t.boundaryRunId)){let i=o===t.boundaryRunId?r:o;n=[...n,{text:``,ts:e.chatStreamStartedAt??t.timestamp??Date.now(),runId:t.runId,boundaryRunId:t.boundaryRunId,boundaryMarker:!0,...i?{afterBoundaryRunId:i}:{}}]}e.chatStreamSegments=n,i&&(e.chatStream=null,e.chatStreamStartedAt=null)}function qi(){return(qi=e((()=>{k(),It(),jn(),On()})))()}function Ji(e){return e===void 0?void 0:Yi[e]}var Yi;function Xi(){return(Xi=e((()=>{Yi={main_session_restart_recovery:{icon:`cpu`,labelKey:`chat.systemNotice.restartRecovery.label`,summaryKey:`chat.systemNotice.restartRecovery.summary`},"restart-sentinel":{icon:`cpu`,labelKey:`chat.systemNotice.gatewayRestarted.label`},cli_harness_context:{icon:`cpu`,labelKey:`chat.systemNotice.cliHarnessContext.label`,collapsedBody:!0,startsTurn:!1}}})))()}function Zi(e){return!e||e.startsWith(`/`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function Qi(e){return Array.from(e).map(e=>{if(e===`\\`)return`\\\\`;let t=e.codePointAt(0);return t!==void 0&&(t<=31||t>=127&&t<=159)?`\\u{${t.toString(16).padStart(4,`0`)}}`:e}).join(``)}function $i(e){let t=f(e);if(!t||!Array.isArray(t.paths)||t.paths.length===0)return;let n=t.paths.filter(e=>typeof e==`string`&&Zi(e));if(!(n.length!==t.paths.length||typeof t.stagedResultRef!=`string`||!/^refs\/openclaw\/worker-results\/[A-Za-z0-9-]+$/u.test(t.stagedResultRef)||t.totalCount!==void 0&&(!Number.isSafeInteger(t.totalCount)||t.totalCount!_r(e)):e.paths.includes(t)&&!_r(t)?t:void 0;if(!n)return;let r=ia(`${e.stagedResultRef}:${n}`),i=ia(e.stagedResultRef),a=ia(`:(top,literal)${n}`);return{inspect:`git show ${r}`,takeCloud:`git checkout ${i} -- ${a}`}}var oa,sa;function ca(){return(ca=e((()=>{gr(),oa=`cloud-workspace-conflict`,sa=5})))()}function la(e){return globalThis.addEventListener(Ga,e),()=>globalThis.removeEventListener(Ga,e)}function ua(){return Ya}function da(e,t){let n=`${e}\u0000${t}`;return`t${tn(n).toString(36)}${n.length.toString(36)}`}function fa(e){if(e==null)return null;if(typeof e==`string`)return a(e,Na);try{let t=JSON.stringify(e);return typeof t==`string`?a(t,Na):null}catch{return null}}function pa(e,t){if(!e.has(t))return;let n=e.get(t);if(n!==void 0)return e.delete(t),e.set(t,n),n}function ma(e,t,n,r){for(e.delete(t),e.set(t,n);e.size>r;)e.delete(e.keys().next().value)}function ha(e,t){let n=pa(e,t);return n===void 0?!1:n<=Date.now()?(e.delete(t),!1):!0}function ga(e){ma(Ja,e,Date.now()+La,Ia)}function _a(){Ya+=1,typeof globalThis.dispatchEvent==`function`&&globalThis.dispatchEvent(new Event(Ga))}function va(){let e=qa.size>0;qa.clear(),Ja.clear(),e&&_a()}function ya(e,t){return`${e}\u0000${t??``}`}function ba(e,t){ma(z,e,{expiresAt:Date.now()+Va,resumeAfterKey:t,cursorMissingHistoryOwner:null,cursorMissingHistoryVersion:null},Ba)}function xa(e,t){let n=pa(z,e);if(!n)return 0;if(n.expiresAt>Date.now())return null;if(n.resumeAfterKey===null)return z.delete(e),0;let r=t.findIndex(e=>e.key===n.resumeAfterKey);return r>=0?(z.delete(e),r+1):n.cursorMissingHistoryVersion===null?(n.cursorMissingHistoryOwner=to,n.cursorMissingHistoryVersion=no,null):n.cursorMissingHistoryOwner===to&&n.cursorMissingHistoryVersion===no?null:(z.delete(e),0)}function Sa(e){let t=!1;for(let[n,r]of B)r.ownerKey===e&&(B.delete(n),t=!0);t&&ba(e,null)}function Ca(e){let t=0;for(let n of B.values())n.ownerKey===e&&(t+=1);for(let n of R.values())n.ownerKey===e&&(t+=1);return t}function wa(){Za&&=(clearTimeout(Za),null)}function Ta(){H+=1,U=null,B.clear(),R.clear(),z.clear(),wa()}function Ea(){if(Za||U!==null||B.size===0||Xa)return;let e=H;Za=setTimeout(()=>{if(Za=null,e!==H){Ea();return}Ma(e)},Ha)}function Da(e,t){let n=Lt(e,t);if(n===`command`){let e=f(t),n=typeof e?.command==`string`?e.command.trim():``,r=jt(n).trim();if(r.length=Ra||R.size+B.size>=za){ba(n,null);return}B.set(t.key,{key:t.key,ownerKey:n,name:e,input:t.input,sessionKey:V,agentId:$a,client:Qa}),(r+1>=Ra||R.size+B.size>=za)&&ba(n,t.key),Ea()}async function Ma(e){if(e!==H||U!==null)return;let t=B.values().next().value;if(!t)return;let n=[];for(let e of B.values())e.client===t.client&&e.sessionKey===t.sessionKey&&e.agentId===t.agentId&&n.length({id:e.key,name:e.name,input:e.input}))});if(e!==H)return;if(r?.disabled===!0){Xa=!0,B.clear(),wa();return}let i=f(r?.titles),a=!1;for(let e of n){let t=i?.[e.key],n=typeof t==`string`?t.trim():``;n?(Ja.delete(e.key),ma(qa,e.key,n,Fa),a=!0):ga(e.key)}if(!a){Sa(t.ownerKey);return}_a()}catch{if(e!==H)return;for(let e of n)ga(e.key);Sa(t.ownerKey)}finally{for(let e of n)R.get(e.key)===e&&R.delete(e.key);U===r&&(U=null),Ea()}}var Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,R,Ja,z,Ya,Xa,B,Za,Qa,V,$a,eo,to,no,H,U;function ro(){return(ro=e((()=>{Ft(),Na=2e3,Pa=24,Fa=128,Ia=128,La=3e5,Ra=48,za=96,Ba=za,Va=3e5,Ha=250,Ua=12,Wa=120,Ga=`openclaw:tool-titles-changed`,Ka={},qa=new Map,R=new Map,Ja=new Map,z=new Map,Ya=0,Xa=!1,B=new Map,Za=null,Qa=null,V=null,$a=null,eo=!0,to=Ka,no=0,H=0,U=null})))()}function io(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.trunc(e):void 0}function ao(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0&&e<=65536?e:void 0}function oo(e){let t=(Array.isArray(e)?e:[]).flatMap(e=>ae(e)&&e.code===`update-required`&&e.action===`update-and-reconnect`&&e.updateCommand===`openclaw update`&&e.headlessReconnectCommand===`openclaw node restart`?[e]:[]);return t.length>0?t:void 0}function so(e){return Array.isArray(e)?e.length===1&&(e[0]===`worker-turn`||e[0]===`remote-exec`)?[e[0]]:e.length===2&&e[0]===`worker-turn`&&e[1]===`remote-exec`?[`worker-turn`,`remote-exec`]:[]:[]}function co(e,t){return e.executionModes?.includes(t)===!0}function lo(e){return(Array.isArray(e)?e:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e,n=g(t.id),r=g(t.providerId);if(!n||!r)return[];let i=t.trust===`persistent`||t.trust===`disposable`?t.trust:void 0,a=uo(t.machines);return[{id:n,providerId:r,trust:i,...Object.hasOwn(t,`executionModes`)?{executionModes:so(t.executionModes)}:{},...a.length>0?{machines:a}:{}}]}).toSorted((e,t)=>e.id.localeCompare(t.id))}function uo(e){let t=new Map;for(let n of(Array.isArray(e)?e:[]).slice(0,32)){if(!ae(n))continue;let e=g(n.id),r=g(n.label);if(!e||e.length>128||!r||r.length>128||t.has(e))continue;let i=ao(n.cpu),a=ao(n.memoryGb);t.set(e,{id:e,label:r,...i===void 0?{}:{cpu:i},...a===void 0?{}:{memoryGb:a},...typeof n.default==`boolean`?{default:n.default}:{}})}return[...t.values()]}function fo(e){return typeof e==`string`&&go.has(e)}function po(e){return typeof e==`number`&&Number.isSafeInteger(e)}function mo(e){if(!ae(e)||Object.keys(e).some(e=>e!==`total`&&e!==`available`)||!po(e.total)||!po(e.available))return;let t=e.total,n=e.available;return t>=1&&t<=1024&&n>=0&&n<=t?{total:t,available:n}:void 0}function ho(e){return(Array.isArray(e)?e:[]).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e,n=g(t.id),r=g(t.type);if(!n||r!==`local`&&r!==`node`&&r!==`worker`||!fo(t.status))return[];let i=t.status,a=g(t.label),s=g(t.platform),l=t.trust===`persistent`||t.trust===`disposable`?t.trust:void 0,u=c(t.capabilities),d=Array.isArray(t.invocableCommands)?o(t.invocableCommands).filter(e=>e.length<=128).slice(0,128):void 0,f=io(t.lastConnectedAtMs),p=io(t.lastDisconnectedAtMs),m=io(t.lastSeenAtMs),h=g(t.lastSeenReason),_=oo(t.issues),v=mo(t.workerSlots);return[{id:n,type:r,status:i,...a?{label:a}:{},...s?{platform:s}:{},...typeof t.sessionHost==`boolean`?{sessionHost:t.sessionHost}:{},...v?{workerSlots:v}:{},...f===void 0?{}:{lastConnectedAtMs:f},...p===void 0?{}:{lastDisconnectedAtMs:p},...m===void 0?{}:{lastSeenAtMs:m},...h?{lastSeenReason:h}:{},...l?{trust:l}:{},...u?{capabilities:u}:{},...d?{invocableCommands:d}:{},..._?{issues:_}:{}}]}).toSorted((e,t)=>e.id.localeCompare(t.id))}var go;function _o(){return(_o=e((()=>{l(),go=new Set([`available`,`unavailable`,`starting`,`stopping`,`error`])})))()}async function vo(e){let t=await e.request(`environments.list`,{});return{profiles:lo(t?.profiles),environments:ho(t?.environments)}}function yo(e,t){return D` `}function bo(e){return D` `}function xo(e){return e.profiles.map(t=>{let n=e.profileDisabledReason?.(t);return yo({value:`cloud:${t.id}`,label:O(`newSession.cloudWorker`,{profile:t.id}),icon:e.icon,facts:t.trust===`disposable`?[O(`newSession.environmentDisposable`)]:t.trust===`persistent`?[O(`newSession.environmentPersistent`)]:void 0,checked:e.selectedId===t.id,disabled:e.disabled||!!n,title:(e.disabled?e.disabledReason:n)??O(`newSession.cloudWorkerProvider`,{provider:t.providerId}),onSelect:()=>e.onSelect(t.id)},e.submitting)})}function So(e){let t=e.cpu===void 0?void 0:String(e.cpu),n=e.memoryGb===void 0?void 0:String(e.memoryGb);return t&&n?O(`newSession.machineShape`,{cpu:t,memory:n}):t?O(`newSession.machineCpu`,{cpu:t}):n?O(`newSession.machineMemory`,{memory:n}):void 0}function Co(e){return e.machines.map(t=>yo({value:`machine:${t.id}`,label:t.label,sub:So(t),facts:t.default?[O(`newSession.machineDefault`)]:void 0,checked:e.selectedId===t.id,keepOpen:!0,onSelect:()=>e.onSelect(t.id)},e.submitting))}function wo(){return(wo=e((()=>{Xe(),dt(),lt(),_o()})))()}function To(e){let t=x(e)?.rest.match(ne)?.[1];return t?t.toLowerCase().replaceAll(`-`,``):null}function Eo(e,t){let n=To(e.key);return!n||!n.startsWith(t.shortId.toLowerCase().replaceAll(`-`,``))?!1:!t.slugHint||y(e.displayName)===t.slugHint}function Do(e,n,r){let i=new URLSearchParams(n.search).get(Ye)?.trim(),a=zt(e.gateway,n.pathname),o=i??a,s=!!(a&&a===o);if(o){let a=()=>{i&&Dt(e.gateway,n.pathname,i)},c=me(e,o,r.agentId);if(c&&Eo(c,r))return a(),{sessionKey:c.key,row:c};let l=To(o),u=x(o)?.agentId;if(s&&l?.startsWith(r.shortId.toLowerCase().replaceAll(`-`,``))&&u&&t(u)===t(r.agentId))return a(),{sessionKey:o}}}function Oo(){return(Oo=e((()=>{v(),Zt(),fe(),S()})))()}function ko(){window.dispatchEvent(new CustomEvent(pt))}var Ao;function jo(){return(jo=e((()=>{mt(),Vt(),Ao=ge(Oe.debugOverlay)})))()}function Mo(e){return new URLSearchParams(e.search).get(`draft`)||void 0}function No(e){return new URLSearchParams(e.search).get(Te)===`1`}function Po(e,t={}){let n=new URLSearchParams(e.search);for(let[e,r]of new URLSearchParams(t.search))n.set(e,r);n.delete(`draft`),n.delete(Te);let r=n.toString();return{...e,...t,search:r?`?${r}`:``}}function Fo(e){return{draft:Mo(e),...No(e)?{focusComposer:!0}:{}}}function Io(e){let t=new URLSearchParams,n=Mo(e);return n&&t.set(`draft`,n),No(e)&&t.set(Te,`1`),t.size>0?`?`+t.toString():``}function Lo(e,t,n=e?.sessionKey){return!e||!w(n,e.sessionKey)||t===e?void 0:e.draft}function Ro(){return(Ro=e((()=>{fe(),S()})))()}function zo(e,t,n){return{columns:[{id:e,panes:[{id:t,sessionKey:n}],paneWeights:[1]}],columnWeights:[1],activePaneId:t}}function Bo(e,t,n){return _(e[t],n)}function Vo(e,t,n){let r=Bo(e,t,`${n} before divider`);return r/(r+Bo(e,t+1,`${n} after divider`))}function W(e){return{columns:e.columns.map(e=>({...e,panes:e.panes.map(e=>({...e})),paneWeights:[...e.paneWeights]})),columnWeights:[...e.columnWeights],activePaneId:e.activePaneId}}function Ho(e){return`c${e.columns.reduce((e,t)=>Math.max(e,ze(t.id,`c`)),0)+1}`}function Uo(e){return`p${Go(e).reduce((e,t)=>Math.max(e,ze(t.id,`p`)),0)+1}`}function Wo(e,t){for(let[n,r]of e.columns.entries()){let e=r.panes.findIndex(e=>e.id===t),i=r.panes[e];if(i)return{column:r,columnIndex:n,pane:i,paneIndex:e}}return null}function Go(e){return e.columns.flatMap(e=>e.panes)}function Ko(e,t){if(!t)return Go(e);let n=Wo(e,e.activePaneId)?.pane;return n?[n]:[]}function qo(e,t,n,r){let i=Wo(e,t),a=W(e);if(!i)return a;let o=Uo(e);if(r===`left`||r===`right`){let t=_(a.columnWeights[i.columnIndex],`split column weight for located pane`),s=i.columnIndex+ +(r===`right`);a.columns.splice(s,0,{id:Ho(e),panes:[{id:o,sessionKey:n}],paneWeights:[1]}),a.columnWeights.splice(i.columnIndex,1,t/2,t/2)}else{let e=a.columns[i.columnIndex];if(!e)return a;let t=_(e.paneWeights[i.paneIndex],`split pane weight for located pane`),s=i.paneIndex+ +(r===`down`);e.panes.splice(s,0,{id:o,sessionKey:n}),e.paneWeights.splice(i.paneIndex,1,t/2,t/2)}return a.activePaneId=o,a}function Jo(e,t){let n=Wo(e,t);if(!n)return W(e);let r=W(e),i=r.columns[n.columnIndex];if(!i)return r;let a=r.activePaneId===t,o=r.activePaneId;if(a&&(o=i.panes[n.paneIndex-1]?.id??r.columns[n.columnIndex-1]?.panes.at(-1)?.id??r.columns.flatMap(e=>e.panes).find(e=>e.id!==t)?.id??``),i.panes.splice(n.paneIndex,1),i.paneWeights.splice(n.paneIndex,1),i.panes.length===0?(r.columns.splice(n.columnIndex,1),r.columnWeights.splice(n.columnIndex,1)):i.paneWeights=We(i.paneWeights),!(Go(r).length<=1))return r.columnWeights=We(r.columnWeights),r.activePaneId=o,r}function Yo(e,t,n){let r=W(e),i=Wo(r,t)?.pane;return i&&(i.sessionKey=n),r}function Xo(e,t){let n=W(e);return Wo(e,t)&&(n.activePaneId=t),n}function Zo(e,t,n){if(t.kind===`split`){let r=n?Go(e).find(e=>e.sessionKey===n):void 0;return n&&!r?e:qo(e,r?.id??e.activePaneId,t.sessionKey,t.direction)}let r=Go(e).find(e=>e.sessionKey===t.sessionKey);return r?t.kind===`close-pane`?Jo(e,r.id):Xo(e,r.id):e}function Qo(e,t,n){let r=[...e];if(t<0||t+1>=e.length)return r;let i=e[t],a=e[t+1];if(i===void 0||a===void 0)return r;let o=i+a,s=Math.max(ts,Math.min(.85,n));return r[t]=o*s,r[t+1]=o*(1-s),r}function $o(e,t,n){let r=W(e);return r.columnWeights=Qo(r.columnWeights,t,n),r}function es(e,t,n,r){let i=W(e),a=i.columns.find(e=>e.id===t);return a&&(a.paneWeights=Qo(a.paneWeights,n,r)),i}var ts;function ns(){return(ns=e((()=>{i(),oe(),ts=.15})))()}function rs(e){return e.connected&&e.client&&!e.client.recoveryScopeReady?null:{...Mt(e,e.sessionKey),gatewayOwner:Pt(e.settings?.gatewayUrl).gatewayOwner,recoveryScope:e.client?.recoveryScope?.trim()||void 0}}function is(e,t){return t.id===e.source.id&&t.sendRunId===e.source.sendRunId&&t.sendAttempts===e.source.sendAttempts&&t.sendState===e.source.sendState&&t.agentId===e.source.agentId&&t.sessionKey===e.source.sessionKey&&t.orderKey===e.source.orderKey&&t.attachmentPayload?.key===e.source.attachmentPayload?.key}function as(e){let t=e.chatQueuedEdit,n=rs(e);return!t||!n||t.gatewayOwner!==n.gatewayOwner||t.recoveryScope!==n.recoveryScope||rn(t)!==rn(n)?null:t}function os(e,t){let n=Pt(e.settings?.gatewayUrl).gatewayOwner;return Hn(e,e=>e.chatQueuedEdit?.id===t&&e.chatQueuedEdit.gatewayOwner===n&&rn(e.chatQueuedEdit)===rn(Mt(e,e.sessionKey)))}function ss(e,t){return os(e,t)}function cs(e,t){return os(e,t)}function ls(e,t){return os(e,t)}function us(e,t){let n=rs(e),r=qn(e,t);return!n||!r||!Yt(r)||r.attachmentStorageError||r.attachments?.some(e=>!Re(e))||r.localCommandName||as(e)||os(e,t)?`unavailable`:(e.chatQueuedEdit={...n,attachments:r.attachments??[],draftText:r.text,id:t,orderKey:qt(r),revision:0,...r.replyToId?{replyToId:r.replyToId}:{},source:{...r},sourceWasDurable:Rn(e,t)},`started`)}function ds(e,t){let n=as(e);return n?(n.draftText=t,n.revision+=1,!0):!1}function fs(e){return as(e)?(e.chatQueuedEdit=null,!0):!1}function ps(e,t,n=[],r){let i=r??as(e);if(r&&e.chatQueuedEdit!==i||!i)return;if(!t){let t=qn(e,i.id);if(i.sourceWasDurable||Rn(e,i.id)||!t||!is(i,t))return}e.chatQueuedEdit=null,Pn(e,i.id,i.sessionKey);let a=new Set(n.map(e=>e.id));ve(i.attachments.filter(e=>!a.has(e.id)))}var ms,hs,gs,_s,vs;function ys(){return(ys=e((()=>{kt(),Se(),Bn(),vn(),ms=`A queued message is being edited in another pane. Finish or cancel that edit before editing it here.`,hs=`A queued message is being edited in another pane. Finish or cancel that edit before removing it.`,gs=`A queued message is being edited in another pane. Finish or cancel that edit before reordering it.`,_s=`A queued message is being edited in another pane. Finish or cancel that edit before retrying it.`,vs=`A queued message is being edited in another pane. Finish or cancel that edit before steering it.`})))()}function bs(e,t){let i=n(t);if(!i)return null;let a=n(e);if(a){let e=`${a}/`;return`${a}/${(r(i).startsWith(r(e))?i.slice(e.length).trim():i)||i}`}let o=i.indexOf(`/`);if(o>0){let e=i.slice(0,o).trim(),t=i.slice(o+1).trim();if(e&&t)return`${e}/${t}`}return i}function xs(e,t){if(Array.isArray(e)){let t=e.map(e=>n(e)).filter(e=>!!e).map(e=>C(e));if(t.length>0)return t}if(!Array.isArray(t))return[];let r=[];for(let e of t){let t=b(e),i=n(t?.provider),a=n(t?.model);if(!i||!a)continue;let o=C(n(t?.reason)?.replace(/_/g,` `)??n(t?.code)??(typeof t?.status==`number`?`HTTP ${t.status}`:null)??n(t?.error)??`error`),s=bs(i,a)??`${i}/${a}`;r.push(`${s}: ${Ve(o)}`)}return r}function Ss(e){let t=b(e);if(!t)return null;if(typeof t.text==`string`)return t.text;if(!Array.isArray(t.content))return null;let n=[];for(let e of t.content){let t=b(e);t?.type===`text`&&typeof t.text==`string`&&t.text&&n.push(t.text)}return n.length>0?n.join(` `):null}function Cs(e){if(e==null)return null;if(typeof e==`number`||typeof e==`boolean`)return String(e);let t=Ss(e),n;if(typeof e==`string`)n=e;else if(t)n=t;else try{n=JSON.stringify(e,null,2)}catch{n=le(e)}let r=pe(n,ic);return r.truncated?`${r.text}\n\n… truncated (${r.total} chars, showing first ${r.text.length}).`:r.text}function ws(e){let t=b(e),n=t?.added,r=t?.removed;return typeof n==`number`&&Number.isInteger(n)&&n>=0&&typeof r==`number`&&Number.isInteger(r)&&r>=0?{added:n,removed:r}:void 0}function Ts(e,t){let r=b(b(t.result)?.details);if(r?.changedModel!==!0)return;let i=n(r.sessionKey)??e.sessionKey,a=n(r.agentId);!a||!ce(e,i,a)||e.sessions.refreshReplacement(a)}function Es(e){let t=[];return t.push({type:`toolcall`,name:e.name,arguments:e.args??{},...e.details===void 0?{}:{details:e.details}}),(e.output||e.resultReceived)&&t.push({type:`toolresult`,name:e.name,text:e.output??``,...e.details===void 0?{}:{details:e.details},...e.isError===void 0?{}:{isError:e.isError},...e.exitCode===void 0?{}:{exitCode:e.exitCode}}),{role:`assistant`,toolCallId:e.toolCallId,runId:e.runId,content:t,timestamp:e.startedAt,__openclawToolStreamLive:!0,__openclawToolStreamResultReceived:e.resultReceived===!0,...e.resultReceived!==!0&&e.liveDiffStat?{__openclawToolStreamDiffStat:e.liveDiffStat}:{},__openclawToolStreamReceivedAt:e.receivedAt}}function Ds(e){if(e.toolStreamOrder.length<=nc)return;let t=e.toolStreamOrder.length-nc,n=e.toolStreamOrder.splice(0,t);for(let t of n)e.toolStreamById.delete(t)}function Os(e){e.chatToolMessages=e.toolStreamOrder.map(t=>e.toolStreamById.get(t)?.message).filter(e=>!!e)}function ks(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null)}function As(e){ks(e),Os(e)}function js(e,t=!1){if(t){As(e);return}e.toolStreamSyncTimer??=window.setTimeout(()=>{As(e),e.requestUpdate?.()},rc)}function Ms(e){ks(e),e.toolStreamById.clear(),e.toolStreamOrder=[],e.activityEventSeqById?.clear(),e.chatToolMessages=[],e.chatStreamSegments=[],e.knownAgentRunIds?.clear(),e.waitingApprovalStatuses?.clear()}function Ns(e,t){ks(e);let n=new Set;for(let r of e.toolStreamOrder)e.toolStreamById.get(r)?.runId===t&&n.add(r);for(let t of n)e.toolStreamById.delete(t);let r=`tool:[${JSON.stringify(t)},`;for(let t of e.activityEventSeqById?.keys()??[])t.startsWith(r)&&e.activityEventSeqById?.delete(t);e.toolStreamOrder=e.toolStreamOrder.filter(e=>!n.has(e)),Os(e),e.chatStreamSegments=e.chatStreamSegments.filter(e=>e.runId!==t),e.knownAgentRunIds?.delete(t);for(let[n,r]of e.waitingApprovalStatuses??[])r.runId===t&&e.waitingApprovalStatuses?.delete(n)}function Ps(e,t){return`tool:${JSON.stringify([e,t])}`}function Fs(e,t){return`${e}:review:${JSON.stringify(t)}`}function Is(e,t){let r=Number.isSafeInteger(t.seq)?t.seq:0;if(t.stream===`tool`){let i=n(t.data?.toolCallId);if(!i)return!0;let a=Ps(t.runId,i),o=`${a}:result`,s=e.activityEventSeqById?.get(o),c=n(t.data?.phase);if(c!==`result`&&s!==void 0&&r<=s)return!1;let l=c===`review`?n(b(t.data.review)?.id):void 0,u=e.activityEventSeqById?.get(`${a}:review-floor`);if(l&&u!==void 0&&r<=u)return!1;let d=l?Fs(a,l):a,f=e.activityEventSeqById?.get(d);if(f!==void 0&&r<=f)return!1;let p=e.activityEventSeqById??=new Map;if(p.set(d,r),c===`result`){p.set(o,r);for(let e of p.keys())e.startsWith(`${a}:review:`)&&p.delete(e)}return!0}if(t.stream!==`item`||t.data?.kind!==`preamble`)return!0;let i=n(t.data.itemId)??n(t.data.id)??`latest`,a=`preamble:${t.runId}:${i}`,o=e.activityEventSeqById?.get(a);return o!==void 0&&r<=o?!1:((e.activityEventSeqById??=new Map).set(a,r),!0)}function Ls(e){let t=e.localRunId?e.usageByRun?.get(e.localRunId):void 0;if(t!==void 0)return t;for(let t of e.activeRunIds??[]){let n=e.usageByRun?.get(t);if(n!==void 0)return n}return null}function Rs(e){if(e.localRunId)return e.localRunId;let t=new Set(e.activeRunIds??[]);return e.queue?.find(e=>e.sendState===`waiting-reconnect`&&typeof e.sendRunId==`string`&&t.has(e.sendRunId))?.sendRunId??null}function zs(e,t){let r=e.waitingApprovalStatuses??=new Map,i=e.waitingApprovalResolvedIds??=new Set,a=new Set(t.map(e=>e.id));for(let e of i)a.has(e)||i.delete(e);let o=t.filter(t=>t.kind===`exec`&&t.request.sessionKey&&ce(e,t.request.sessionKey,t.request.agentId)),s=new Set(o.map(e=>e.id)),c=!1;for(let e of r.keys())s.has(e)||(r.delete(e),c=!0);if(r.size>0)return c;for(let t of o){let a=n(t.request.runId);!a||!e.knownAgentRunIds?.has(a)||i.has(t.id)||(r.set(t.id,{approvalId:t.id,toolCallId:null,runId:a}),c=!0)}return c}function Bs(e){e.compactionClearTimer!=null&&(window.clearTimeout(e.compactionClearTimer),e.compactionClearTimer=null)}function Vs(e,t=ac,n){e.compactionClearTimer=window.setTimeout(()=>{let t=e.compactionStatus;n?.phase&&t?.phase!==n.phase||n?.runId&&t?.runId!==n.runId||(e.compactionStatus=null,e.compactionClearTimer=null,e.requestUpdate?.())},t)}function Hs(e,t,n){let r=n===`complete`;e.compactionStatus={phase:n,runId:t,startedAt:n===`active`?Date.now():e.compactionStatus?.startedAt??(r?null:Date.now()),completedAt:r?Date.now():null},Vs(e,r?ac:oc,{phase:n,runId:t})}function Us(e,t){if(!t||t.operation!==`compact`)return;let r=n(t.sessionKey),i=n(t.agentId)??void 0;if(!r||!ce(e,r,i))return;let a=n(t.operationId)??`session-compact:${r}`,o=e;if(t.phase===`start`){Bs(o),Hs(o,a,`active`);return}if(t.phase===`end`&&!(o.compactionStatus?.runId&&o.compactionStatus.runId!==a)){if(Bs(o),t.completed===!0){Hs(o,a,`complete`);return}o.compactionStatus=null}}function Ws(e,t){let n=t.data??{},r=typeof n.phase==`string`?n.phase:``,i=n.completed===!0;if(Bs(e),r===`start`){Hs(e,t.runId,`active`);return}if(r===`end`){if(n.willRetry===!0&&i){Hs(e,t.runId,`retrying`);return}if(i){Hs(e,t.runId,`complete`);return}e.compactionStatus=null}}function Gs(e,t){let r=t.data??{},i=n(r.phase);(i===`end`||i===`error`)&&Ks(e,t,{allowSessionScopedWhenIdle:!0}).accepted&&e.compactionStatus?.phase===`retrying`&&(e.compactionStatus.runId&&e.compactionStatus.runId!==t.runId||Hs(e,t.runId,`complete`))}function Ks(e,t,r){let i=typeof t.sessionKey==`string`?t.sessionKey:void 0;return i&&!ce(e,i,n(t.agentId))?{accepted:!1}:!e.chatRunId&&r?.allowSessionScopedWhenIdle&&i?{accepted:!0,sessionKey:i}:e.chatRunId&&t.runId!==e.chatRunId||!e.chatRunId?{accepted:!1}:{accepted:!0,sessionKey:i}}function qs(e,t){if(t.stream!==`usage`)return!1;let r=n(t.sessionKey);if(r){if(!ce(e,r,n(t.agentId)))return!0}else if(!e.chatRunId||t.runId!==e.chatRunId)return!0;let i=t.data?.outputTokens;if(typeof i!=`number`||!Number.isFinite(i))return!0;let a=Math.floor(i);if(a<0)return!0;let o=e.chatRunUsageById?.get(t.runId);return o!==void 0&&a<=o||(e.chatRunUsageById=new Map(e.chatRunUsageById).set(t.runId,a)),!0}function Js(e,t){let r=t.data??{},i=t.stream===`fallback`?`fallback`:n(r.phase);if(t.stream===`lifecycle`&&i!==`fallback`&&i!==`fallback_cleared`||!Ks(e,t,{allowSessionScopedWhenIdle:!0}).accepted)return;let a=bs(r.selectedProvider,r.selectedModel)??bs(r.fromProvider,r.fromModel),o=bs(r.activeProvider,r.activeModel)??bs(r.toProvider,r.toModel),s=bs(r.previousActiveProvider,r.previousActiveModel)??n(r.previousActiveModel);if(!a||!o||i===`fallback`&&a===o)return;let c=n(r.reasonSummary)??n(r.reason),l=c?C(c):null,u=xs(r.attemptSummaries,r.attempts);e.fallbackClearTimer!=null&&(window.clearTimeout(e.fallbackClearTimer),e.fallbackClearTimer=null),e.fallbackStatus={phase:i===`fallback_cleared`?`cleared`:`active`,selected:a,active:i===`fallback_cleared`?a:o,previous:i===`fallback_cleared`?s??(o===a?void 0:o):void 0,reason:l??void 0,attempts:u,occurredAt:Date.now()},e.fallbackClearTimer=window.setTimeout(()=>{e.fallbackStatus=null,e.fallbackClearTimer=null,e.requestUpdate?.()},sc)}function Ys(e,t){let r=n(t.data?.phase);if(r!==`waiting-approval`&&r!==`approval-resolved`)return!1;let i=n(t.data?.approvalId),a=n(t.sessionKey);if(!i||!a)return!0;if(r===`waiting-approval`){let r=e.waitingApprovalStatuses??=new Map;return e.waitingApprovalResolvedIds?.delete(i),r.set(i,{approvalId:i,toolCallId:n(t.data?.toolCallId),runId:t.runId}),!0}return(e.waitingApprovalResolvedIds??=new Set).add(i),e.waitingApprovalStatuses?.delete(i),!0}function Xs(e){if(e.stream!==`item`)return null;let t=e.data??{};if(t.kind!==`preamble`)return null;let n=(typeof t.itemId==`string`&&t.itemId.trim()?t.itemId:typeof t.id==`string`&&t.id.trim()?t.id:null)?.trim(),r=Zs(t.progressText);return!r&&!n?null:{text:r,...n?{itemId:n}:{}}}function Zs(e){if(typeof e!=`string`)return``;let t=$n(e).text.trim(),n=t.replace(/^[\s*_`~]+|[\s*_`~]+$/gu,``).trim();return/^NO_REPLY$/iu.test(n)?``:t}function Qs(e,t){let n=Xs(t);if(!n)return!1;if(!Ks(e,t,{allowSessionScopedWhenIdle:!0}).accepted)return!0;if(n.itemId&&e.chatMessages?.some(e=>{let r=Un(e);return r?.itemId===n.itemId&&r?.runId===t.runId}))return e.chatStreamSegments=e.chatStreamSegments.filter(e=>e.itemId!==n.itemId||e.runId!==t.runId),!0;if(n.itemId&&!n.text.trim())return e.chatStreamSegments=e.chatStreamSegments.filter(e=>e.itemId!==n.itemId),!0;let r=n.itemId?e.chatStreamSegments.findIndex(e=>e.itemId===n.itemId):-1;if(r>=0)return e.chatStreamSegments[r]&&(e.chatStreamSegments=e.chatStreamSegments.map((e,i)=>i===r?{...e,text:n.text,runId:t.runId}:e)),!0;let i=e.chatStreamSegments[e.chatStreamSegments.length-1];return!n.itemId&&i&&!i.toolCallId&&i.text===n.text||(e.chatStreamSegments=[...e.chatStreamSegments,{text:n.text,ts:t.ts,runId:t.runId,...n.itemId?{itemId:n.itemId}:{}}]),!0}function $s(e,t){let r=t.stream===`notice`;if(!r&&t.stream!==`codex_app_server.guardian`)return!1;if(!Ks(e,t,{allowSessionScopedWhenIdle:!0}).accepted)return!0;let i=t.data??{},a=n(i.phase),o=n(i.status),s=n(i.reviewId),c=n(i.threadId),l=n(i.turnId),u=s??(c&&l&&typeof i.startedAtMs==`number`&&Number.isFinite(i.startedAtMs)?i.startedAtMs:t.seq),d=`${r?`system`:`guardian`}:${t.runId}:`+(a===`warning`?`warning:${t.seq}`:`${c??`thread`}:${l??`turn`}:${u}`),f=e.guardianNotices??[],p=a===`strict_review_required`?`strict-review-required`:a===`warning`?`warning`:a===`started`&&o===`inProgress`?`reviewing`:a===`completed`&&o===`approved`?`approved`:a===`completed`&&[`denied`,`timedOut`,`aborted`].includes(o??``)?`denied`:null;if(!p)return!0;let m=n(i.targetItemId);if((a===`started`||a===`completed`)&&m)return a===`completed`&&(e.guardianNotices=f.filter(e=>e.key!==d)),!0;let h={key:d,runId:t.runId,timestamp:t.ts,kind:p};r&&(h.source=`system`);for(let e of[`command`,`riskLevel`,`rationale`,`message`]){let t=n(i[e]);t&&(h[e]=t)}let g=f.findIndex(e=>e.key===h.key);return e.guardianNotices=g===-1?[...f.slice(-49),h]:f.map((e,t)=>t===g?h:e),!0}function ec(e,t,n,r){let i=n.toolCallId,a=Ps(t.runId,i),o=e.activityEventSeqById??=new Map,s=e=>o.get(Fs(a,e.id))??0,c=`${a}:review-floor`,l=Wt(n.details),u=Math.max(o.get(c)??0,...l.map(s)),d=[...l.filter(e=>e.id!==r.id),r].toSorted((e,t)=>s(e)-s(t)),f=d.slice(0,-16),p=d.slice(-16);if(f.length>0){o.set(c,Math.max(o.get(c)??0,...f.map(s)));for(let e of f)o.delete(Fs(a,e.id))}let m=Ot(t.data),h=Nt(p),g=Ot(n.details),_=g===`denied`?`denied`:m??h??void 0;n.details=Ut(n.details,p,_&&t.seq>=u?_:g),n.message=Es(n),js(e,!0)}function tc(e,t){if(!t)return!1;let r=typeof t.sessionKey==`string`?t.sessionKey:void 0;if(r&&!ce(e,r,n(t.agentId))||!Is(e,t))return!1;if(t.stream===`lifecycle`||t.stream===`tool`){let r=n(t.runId);r&&(e.knownAgentRunIds??=new Set).add(r)}if(qs(e,t)||$s(e,t))return!0;if(t.stream===`compaction`)return Ws(e,t),!0;if(t.stream===`lifecycle`){let n=t.data?.phase;if((n===`start`||n===`end`||n===`error`)&&e.chatRunUsageById?.has(t.runId)){let n=new Map(e.chatRunUsageById);n.delete(t.runId),e.chatRunUsageById=n}return Ys(e,t)?!0:(Gs(e,t),Js(e,t),!0)}if(t.stream===`fallback`)return Js(e,t),!0;if(Qs(e,t))return!0;if(t.stream!==`tool`)return!1;let i=t.data??{},a=typeof i.toolCallId==`string`?i.toolCallId:``;if(!a)return!1;let o=bi(t.runId,a),s=e.toolStreamById.get(o),c=typeof i.phase==`string`?i.phase:``,l=c===`review`?on(i.review):null;if(c===`review`&&!l)return!0;let u=c!==`start`&&s?.name&&s.name!==`tool`?s.name:n(i.name)??s?.name??`tool`;c===`start`&&t.runId===e.chatRunId&&(e.chatRunStartup={state:`activity`,runId:t.runId});let d=c===`start`?i.args:void 0,f=c===`update`?Cs(i.partialResult):c===`result`?Cs(i.result):void 0,p=c===`result`?b(i.result)?.details:void 0,m=Ot(i)??Ot(p),h=m?Ut(p,[],m):p,g=c===`result`&&typeof i.isError==`boolean`?i.isError:void 0,_=(c===`result`?b(i.result):void 0)?.exitCode,v=typeof _==`number`&&Number.isInteger(_)?_:void 0,y=c===`input_delta`?ws(i.diff):void 0;u===`session_status`&&c===`result`&&Ts(e,i);let ee=Date.now();if(!s)Ki(e,{runId:t.runId,toolCallId:a,timestamp:ee}),s={toolCallId:a,runId:t.runId,sessionKey:r,name:u,args:d,output:f||void 0,...h===void 0?{}:{details:h},...g===void 0?{}:{isError:g},...v===void 0?{}:{exitCode:v},...y?{liveDiffStat:y}:{},...c===`result`?{resultReceived:!0}:{},startedAt:typeof t.ts==`number`?t.ts:ee,receivedAt:ee,message:{}},e.toolStreamById.set(o,s),e.toolStreamOrder.push(o);else{if(s.name=u,d!==void 0&&(s.args=d),f!==void 0&&(s.output=f||void 0),p!==void 0||m){let e=Ot(s.details),t=e===`denied`?`denied`:m??e,n=Wt(s.details);s.details=n.length?Ut(p,n,t):h}g!==void 0&&(s.isError=g),v!==void 0&&(s.exitCode=v),y&&(s.liveDiffStat=y),c===`result`&&(s.liveDiffStat=void 0,s.resultReceived=!0)}return l?(Ds(e),ec(e,t,s,l),!0):(s.message=Es(s),Ds(e),js(e,c===`result`),!0)}var nc,rc,ic,ac,oc,sc;function cc(){return(cc=e((()=>{pr(),Ht(),T(),Je(),S(),On(),qi(),Oi(),nc=50,rc=80,ic=12e4,ac=5e3,oc=3e5,sc=8e3})))()}function lc(e){return(typeof e==`string`?e.trim():``)||null}function uc(e,t){e.lastError=t,e.chatError=t}function dc(e){return!!(e.chatSending||e.chatRunId)}function fc(e,t,n){if(e.chatRunStatus?.runId===t||e.lastLocalTerminalReconcile?.runId===t||Cn(e,{type:`runDelta`,runId:t}).runs[t]?.status!==`streaming`)return;let r=e.chatRunId===t,i=r&&typeof e.chatStream==`string`;e.chatRunId=t,Sn(e,t),r||(e.chatRunError=null,e.chatRunStartup=null),i||(e.chatStream=``,e.chatStreamStartedAt=n)}function pc(e,t,n){Sn(e,n),e.chatRunError={summary:Ve(t),...n?{runId:n}:{}}}function mc(e){return!!(e.chatRunId||e.sessionsResult?.sessions.some(t=>w(t.key,e.sessionKey)&&we(t)))}function hc(e){return mc(e)||!!e.sessionsResult?.sessions.some(t=>w(t.key,e.sessionKey)&&t.hasActiveSubagentRun===!0)}function gc(e){return Rc.has(r(e.trim()))}function _c(e,t){return de(t)||Ee(e)&&Ce(e,t)!==null?{}:{clearQueued:!0}}async function vc(e,t){try{return t.runId===null?await e.request(`sessions.abort`,{key:t.sessionKey,...t.agentId?{agentId:t.agentId}:{},...t.clearQueued?{clearQueued:!0}:{}}):t.sessionAbortable?await e.request(`sessions.abort`,{key:t.sessionKey,...t.agentId?{agentId:t.agentId}:{},runId:t.runId}):await e.request(`chat.abort`,{sessionKey:t.sessionKey,...t.agentId?{agentId:t.agentId}:{},runId:t.runId}),{ok:!0}}catch(e){return{ok:!1,error:e}}}function yc(e,t){let n=e.chatRunSessionAbortable===!0,r=e.chatRunId??null,i={sourceClient:t,sessionKey:e.sessionKey,...Ge(e,e.sessionKey)};return r?{...i,runId:r,...n?{sessionAbortable:!0}:{}}:{...i,runId:null,..._c(e,e.sessionKey)}}async function bc(e){let t=e.client;if(!t||!e.connected)return!1;let n=await vc(t,yc(e,t));return n.ok||uc(e,yn(n.error)),n.ok}async function xc(e){let t=e.pendingAbort,n=e.client;if(!t||!n||!e.connected||(e.pendingAbort=null,t.sourceClient!==n))return!1;let r=Nn({client:n,hello:e.hello,phase:`connected`},!0).abort;if(!r.allowed)return uc(e,r.reason),!1;let i=await vc(n,t);return i.ok?!0:(uc(e,yn(i.error)),!1)}async function Sc(e,t){let n=e.connected?null:e.client,r=n?yc(e,n):null,i=r?.runId?r:null;if(!e.connected&&!i){uc(e,O(`chat.questions.disconnected`));return}if(t?.preserveDraft||(e.chatMessage=``,Dn(e)),i){e.pendingAbort=i;return}await bc(e)}function Cc(e){e!=null&&globalThis.clearTimeout(e)}function wc(e){return e.toolStreamById instanceof Map&&Array.isArray(e.toolStreamOrder)&&Array.isArray(e.chatToolMessages)&&Array.isArray(e.chatStreamSegments)}function Tc(e){Cc(e.chatRunStatusClearTimer),e.chatRunStatusClearTimer=null,e.chatRunStatus=null}function Ec(e,t){Cc(e.chatRunStatusClearTimer),e.chatRunStatusClearTimer=globalThis.setTimeout(()=>{let n=e.chatRunStatus;n?.phase===t.phase&&n.runId===t.runId&&n.sessionKey===t.sessionKey&&n.occurredAt===t.occurredAt&&(e.chatRunStatus=null,e.chatRunStatusClearTimer=null,Fc(e)||e.requestUpdate?.())},Lc)}function Dc(e,t){t?e.knownAgentRunIds?.delete(t):e.knownAgentRunIds?.clear(),(!t||e.chatRunStartup?.runId===t)&&(e.chatRunStartup=null),Cc(e.compactionClearTimer),e.compactionClearTimer=null,e.compactionStatus&&=null,Cc(e.fallbackClearTimer),e.fallbackClearTimer=null,e.fallbackStatus&&=null;for(let[n,r]of e.waitingApprovalStatuses??[])(!t||!r.runId||r.runId===t)&&e.waitingApprovalStatuses?.delete(n)}function Oc(e,t){let n=new Set,r=lc(t.sessionKey)??e.sessionKey;r&&n.add(r),De(e,`global`,r)&&n.add(`global`);for(let t of e.sessionsResult?.sessions??[])De(e,t.key,r,t.agentId)&&n.add(t.key);for(let e of t.sessionKeys??[]){let t=lc(e);t&&n.add(t)}return n}function kc(e,t,n){if(!t.outcome)return;let r=Oc(e,t);if(r.size===0)return;let i=t.sessionStatus??(t.outcome===`done`?`done`:`killed`),a={sessionKeys:[...r],runId:t.runId??e.chatRunId??null,status:i,endedAt:n};e.sessionsResult&&=ke(e.sessionsResult,a),e.sessions?.reconcileRunTerminal?.(a)}function Ac(e,t,n){if(!t.yielded)return;let r={sessionKeys:[...Oc(e,t)],runId:t.runId??e.chatRunId??null,status:`running`,endedAt:n};e.sessionsResult&&=ke(e.sessionsResult,r),e.sessions?.reconcileRunTerminal?.(r)}function jc(e,t={}){let n=Date.now(),r=t.runId??e.chatRunId??null,i=lc(t.sessionKey)??e.sessionKey;if((t.clearIndicators??!0)&&Dc(e,r),t.clearChatStream&&(e.chatStream=null,e.chatStreamStartedAt=null),t.clearLocalRun&&(e.chatRunId&&(e.chatRunLifecycleGeneration=(e.chatRunLifecycleGeneration??0)+1),e.chatRunId=null,e.chatRunSessionAbortable=void 0),wc(e)&&(t.clearToolStream?Ms(e):t.clearToolStreamForRun&&r&&Ns(e,r)),t.outcome){let a={phase:t.outcome,runId:r,sessionKey:i,occurredAt:n};kc(e,t,n),t.armLocalTerminalReconcile&&(e.lastLocalTerminalReconcile={sessionKey:i,runId:r,phase:t.outcome,sessionStatus:t.sessionStatus??(t.outcome===`done`?`done`:`killed`)}),t.publishRunStatus!==!1&&(e.chatRunStatus=a,Ec(e,a))}else t.yielded?(Ac(e,t,n),e.lastLocalTerminalReconcile=null,Tc(e)):t.clearRunStatus&&Tc(e);t.requestUpdate!==!1&&e.requestUpdate?.()}function Mc(e){return e.sessionsResult?.sessions.find(t=>De(e,t.key,e.sessionKey,t.agentId))}function Nc(e){let t=e.lastLocalTerminalReconcile;if(!t||t.sessionKey!==e.sessionKey)return!1;let n=Mc(e);return!n||!we(n)?!1:t.runId==null||n.activeRunIds?.length!==1||n.activeRunIds[0]!==t.runId?(e.lastLocalTerminalReconcile=null,!1):(kc(e,{outcome:t.phase,sessionStatus:t.sessionStatus,sessionKey:t.sessionKey,runId:t.runId},Date.now()),e.requestUpdate?.(),!0)}function Pc(e,t={}){if(!e.chatRunId&&e.chatStream==null)return Nc(e);let n=Mc(e);return n?Ic(e,n,t):!1}function Fc(e){if(e.chatRunId){let t=Mc(e);if(t?.lastRunId===e.chatRunId)return Ic(e,t,{publishRunStatus:!1})}return e.lastLocalTerminalReconcile!=null&&!e.chatRunId&&e.chatStream==null&&Pc(e,{publishRunStatus:!1})}function Ic(e,t,n={}){if(!De(e,t.key,e.sessionKey,t.agentId)||!e.chatRunId&&e.chatStream==null||t.hasActiveRun===!0||we(t)||t.hasActiveRun!==!1&&t.status===`running`)return!1;let r=t.status!==void 0;return t.hasActiveRun!==!1&&!r?!1:(jc(e,{outcome:t.status===`done`?`done`:`interrupted`,sessionStatus:t.status===`running`||t.status===void 0?`killed`:t.status,runId:e.chatRunId,sessionKey:e.sessionKey,sessionKeys:[t.key],clearLocalRun:!0,clearChatStream:!0,clearToolStreamForRun:!0,publishRunStatus:n.publishRunStatus}),!0)}var Lc,Rc;function zc(){return(zc=e((()=>{lt(),T(),be(),S(),Kn(),bn(),xn(),En(),cc(),Lc=5e3,Rc=new Set([`/stop`,`stop`,`esc`,`abort`,`wait`,`exit`])})))()}function Bc(e){let t=G.get(e);if(t)return G.delete(e),G.set(e,t),t;let n=new Map;for(G.set(e,n);G.size>el;){let e=G.keys().next().value;if(typeof e!=`string`)break;G.delete(e)}return n}function Vc(e,t){let n=Bc(e),r=P(n,t);if(r!==void 0)return r;for(let[e,r]of n)if(w(e,t))return n.delete(e),F(n,t,r),r}function Hc(e,t,n){let r=Bc(e);for(let e of r.keys())w(e,t)&&r.delete(e);F(r,t,{scrollTop:Math.max(0,n.scrollTop),anchorToEnd:n.anchorToEnd})}function Uc(e){let t=Math.max(0,e.scrollHeight-e.clientHeight),n=Math.min(Math.max(0,e.scrollTop),t);return{scrollTop:n,anchorToEnd:t-n<=8}}function Wc(e){e.chatScrollFrame!=null&&(cancelAnimationFrame(e.chatScrollFrame),e.chatScrollFrame=null)}function Gc(e){e.chatScrollGeneration+=1,e.chatScrollCommitCleanup?.(),e.chatScrollCommitCleanup=null,Wc(e)}function Kc(e,t){e.chatNewMessagesBelow!==t&&(e.chatNewMessagesBelow=t,e.renderLifecycle.invalidate())}function qc(e,t=!1,n=!1,r={}){Wc(e);let i=e.chatScrollGeneration;e.chatScrollFrame=requestAnimationFrame(()=>{if(e.chatScrollFrame=null,i!==e.chatScrollGeneration)return;let a=e.chatScrollElement?.();if(!a)return;let o=a.scrollHeight-a.scrollTop-a.clientHeight,s=a.scrollHeight>(e.chatLastScrollHeight??0)+1;e.chatLastScrollHeight=a.scrollHeight;let c=r.contentChanged??r.source!==`resize`,l=r.source===`manual`,u=t&&!e.chatHasAutoScrolled;if(!(l||u||!e.chatFollowLocked&&(r.source===`resize`||e.chatUserNearBottom||o<$c))){(c||r.source===`resize`&&s)&&Kc(e,!0);return}let d=Jt(n?`smooth`:`auto`);e.chatScrollToEnd?.({behavior:d,source:l?`manual`:`auto`})&&(u&&(e.chatHasAutoScrolled=!0),e.chatFollowLocked=!1,e.chatUserNearBottom=!0,Kc(e,!1))})}function Jc(e,t=!1,n=!1,r={}){Gc(e);let i=e.chatScrollGeneration,a=!1,o=e.renderLifecycle.afterCommit(()=>{a=!0,i===e.chatScrollGeneration&&(e.chatScrollCommitCleanup=null,qc(e,t,n,r))});a||(e.chatScrollCommitCleanup=o)}function Yc(e,t){let n=t.currentTarget;n&&Zc(e,n)}function Xc(e){Gc(e);let t=e.chatScrollElement?.();t&&Zc(e,t,!0)}function Zc(e,t,n=!1){let r=Math.max(0,t.scrollTop),i=r-e.chatLastScrollTop;e.chatLastScrollTop=r,e.chatLastScrollHeight=t.scrollHeight;let a=n||i<0;if(e.chatIsProgrammaticScroll?.()&&!a)return;let o=t.scrollHeight-t.scrollTop-t.clientHeight;a&&o>8?(e.chatHasAutoScrolled=!0,e.chatFollowLocked=!0):o<=8&&(e.chatFollowLocked=!1),e.chatUserNearBottom=!e.chatFollowLocked&&o<$c,Kc(e,t.scrollHeight-t.clientHeight>8&&o>8)}function Qc(e){Gc(e),e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0,e.chatFollowLocked=!1,e.chatLastScrollTop=0,e.chatLastScrollHeight=0,e.chatNewMessagesBelow=!1}var $c,el,G;function tl(){return(tl=e((()=>{S(),yr(),$c=450,el=8,G=new Map})))()}function nl(e,n,r){if(e===n)return!0;let i=x(e);return!!(r&&de(n)&&i?.rest===`global`&&t(i.agentId)===t(r))}function rl(e,t,n){let r=e.presentation,i={id:e.id,request:{command:r.kind===`exec`?r.commandText:r.title,agentId:r.agentId??null,sessionKey:t,allowedDecisions:r.allowedDecisions},...n&&n!==t?{sourceSessionKey:n}:{},createdAtMs:e.createdAtMs,expiresAtMs:e.expiresAtMs};return r.kind===`exec`?{...i,kind:`exec`,request:{...i.request,host:r.host??null}}:r.kind===`plugin`?{...i,kind:`plugin`,pluginTitle:r.title,pluginDescription:r.description,pluginSeverity:r.severity,pluginId:r.pluginId??null}:{...i,kind:`system-agent`,pluginTitle:r.title,pluginDescription:r.description,proposalHash:r.proposalHash}}function il(e,t,n){if(!St(Et,e))return[];let r=Ct(Et,e);return nl(r.sessionKey,t,n)?r.approvals.filter(e=>e.status===`pending`).map(e=>rl(e,t,e.sourceSessionKey)):[]}function al(e,t,n,r){if(!St(Tt,t))return null;let i=Ct(Tt,t),a=n??i.sessionKey;if(!nl(i.sessionKey,a,r))return null;if(i.phase===`terminal`)return e.filter(e=>e.id!==i.approval.id);let o=e.filter(e=>e.id!==i.approval.id);return o.push(rl(i.approval,a,i.sourceSessionKey)),o.toSorted((e,t)=>e.createdAtMs-t.createdAtMs)}function ol(){return(ol=e((()=>{gt(),xt(),S()})))()}function sl(e){let t=e;return t.toolStreamById instanceof Map&&Array.isArray(t.toolStreamOrder)&&Array.isArray(t.chatToolMessages)&&Array.isArray(t.chatStreamSegments)?t:null}function cl(e){let t=e;return Array.isArray(t.toolStreamOrder)?t.toolStreamOrder.filter(e=>g(e)!==void 0):[]}function ll(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!(!n||typeof n!=`object`)&&r(n.role)===`user`)return t}return-1}function ul(e,t){let n=sl(e);if(!n)return;let r=t?.preserveStreamSegments?[...n.chatStreamSegments]:null;Ms(n),r&&(n.chatStreamSegments=r)}function dl(e,t){let n=sl(e);n&&Ns(n,t)}function fl(e){let t=e;Array.isArray(t.chatStreamSegments)&&(t.chatStreamSegments=[])}function pl(e,t=e,n=Date.now(),r=`current`,i,a,o){return{role:`assistant`,content:[{type:`text`,text:e}],timestamp:n,openclawStreamFallback:{replacementText:t,source:r,...i?{itemId:i}:{},...a?{runId:a}:{},...o?{afterBoundaryRunId:o}:{}}}}function ml(e){return f(f(e)?.openclawStreamFallback)}function hl(e){let t=ml(e);return t&&!g(t.itemId)?t:null}function gl(e,t){let n=A(t),r=(n?.role===`assistant`?n.runId:null)??di(t),i=fi(t)??void 0;if(r)for(let t=e.length-1;t>=0;--t){let n=e[t],a=hl(n);if(!(!a||g(a.runId)!==r)){i=g(a.afterBoundaryRunId)??i;break}}let a=Ii(e,{...r?{runId:r}:{},...i?{afterBoundaryRunId:i}:{}}),o=j(t)?.trim()??``,s=new Set,c=[],l=0;for(let t=a.start;tvl(e)===t)}function bl(e,t){let n=e,r=wi(e),i=[],a=null,o=Array.isArray(n.chatStreamSegments)?n.chatStreamSegments:[],s=0,c;for(let[e,n]of o.entries()){if(!n||typeof n.text!=`string`)continue;let o=typeof n.toolCallId==`string`&&n.toolCallId.trim()?n.toolCallId.trim():null,l=Xt(n),u=l&&typeof n.itemId==`string`?n.itemId.trim():void 0,d=l?void 0:r[s],f=g(n.runId)??d?.runId,p=g(n.afterBoundaryRunId)??c,m=g(n.boundaryRunId);!l&&n.boundaryMarker!==!0&&n.persisted!==!0&&(s+=1);let h=en(n),_=_l(h?$t(n.text,a):n.text,t.isHiddenStreamText);_&&n.persisted!==!0&&i.push({text:_,replacementText:n.text,source:`segment`,segmentIndex:e,timestamp:typeof n.ts==`number`&&Number.isFinite(n.ts)?n.ts:Date.now(),...u?{itemId:u}:{},...f?{runId:f}:{},...p?{afterBoundaryRunId:p}:{},...m?{boundaryRunId:m}:{},toolCallId:o??d?.id}),h&&(a=an(a,n.text)),m&&(c=m)}if(t.includeCurrent!==!1&&typeof e.chatStream==`string`){let n=_l($t(e.chatStream,a),t.isHiddenStreamText);n&&i.push({text:n,replacementText:e.chatStream,source:`current`,timestamp:e.chatStreamStartedAt??Date.now(),...e.chatRunId?{runId:e.chatRunId}:{},...c?{afterBoundaryRunId:c}:{}})}return i}function xl(e,t){if(typeof e.chatStream!=`string`)return null;let n=e,r=Array.isArray(n.chatStreamSegments)?n.chatStreamSegments:[],i=Qt(r);return _l($t(e.chatStream,i),t)}function Sl(e,t,n,r,i=e.length){if(t.itemId)return yl(e,t.itemId,r,i);let a=e.slice(r,i).map(e=>{let r=A(e);return r?.role&&r.role!==`assistant`||r?.runId&&t.runId&&r.runId!==t.runId||n(e)||An(e)?null:j(e)?.trim()??null});return[t.replacementText,t.text].some(e=>!!e.trim()&&!Bi(a,e.trim()))}function Cl(e,t){let n=ll(e)+1;return e.slice(n).some(e=>!e||typeof e!=`object`||r(e.role)!==`assistant`||t(e)?!1:!!j(e)?.trim())}function wl(e,t,n){let r=bl(t,n),i=n.persistCommentary===!0?r:r.filter(e=>!e.itemId);return r.length>0&&(i.length>0||Cl(e,n.isHiddenAssistantMessage))&&i.every(t=>{let r=Ii(e,t);return Sl(e,t,n.isHiddenAssistantMessage,r.start,r.end)})}function Tl(e,t){return bl(e,t).length>0}function El(e,t,n){let r=j(e)?.trim();if(!r)return!1;let i=bl(t,{includeCurrent:!0,isHiddenStreamText:n.isHiddenStreamText}).filter(e=>n.persistCommentary===!0||!e.itemId);if(i.length===0)return!1;let a=0;for(let[e,t]of i.entries()){let n=t.text.trim(),i=r.indexOf(n,a);if(i<0||e===0&&i!==0)return!1;a=i+n.length}return!0}function Dl(e,t,n,r,i,a){let o=wi(t),s=i?Ti({id:i,...a?{runId:a}:{}},o):void 0,c=s?new Set([s]):i?new Set:new Set(o.map(e=>e.identity));if(c.size===0)return-1;for(let t=n;t{let t=Ti(e,o);return t!==void 0&&c.has(t)}))return t;return-1}function Ol(e){if(!e||typeof e!=`object`)return null;let t=e;return d(t.timestamp)??d(t.ts)??null}function kl(e,t,n){let r=e,i=n.persistCommentary===!0,a=n.replacementMessages;for(let e of bl(t,n)){if(!i&&e.itemId)continue;let o=a?.length?[...r,...a]:r,s=Ii(o,e);if(Sl(o,e,n.isHiddenAssistantMessage,s.start,s.end))continue;let c=o===r?s:Ii(r,e),l=e.source===`segment`&&e.toolCallId?Dl(r,t,c.start,c.end,e.toolCallId,e.runId):-1;if(n.requirePersistedTool&&l<0)continue;let u=l>=0?l:e.source===`segment`?Li(r,e.timestamp,c.start,c.end,Ol):c.end,d=pl(e.text,e.replacementText,Ri(r,u,e.timestamp,Ol),e.source,e.itemId,e.runId,e.afterBoundaryRunId);r=[...r.slice(0,u),d,...r.slice(u)]}return r}function Al(){return(Al=e((()=>{k(),re(),It(),On(),qi(),yi(),Oi(),cc()})))()}function jl(e,t,n){return e.flatMap((e,r)=>n(e,r)?!(e.runId&&t&&e.runId!==t)&&en(e)?[{...e,persisted:!0}]:[]:[e])}function Ml(e,t){if(!e.chatStreamSegments||t.length===0)return;let n=new Set(t);e.chatStreamSegments=jl(e.chatStreamSegments,e.chatRunId,(e,t)=>n.has(t))}function Nl(e){let t=e.chatRunId;if(!t)return;let n=e.chatStream??Qt(e.chatStreamSegments??[]);if(!n)return;let r=zi((e.chatMessages??[]).filter(e=>{let n=A(e);return n?.role===`assistant`&&n.id&&!n.isImported&&n.runId===t&&!Un(e)}),n,t),i=n.slice(0,n.length-(r?.length??0));if(!i)return;let a=e.chatStreamSegments??[],o=e.chatStream===null?n:Qt(a),s=e=>e.persisted!==!0&&e.runId===t&&en(e)&&i.startsWith(e.text);if(a.some(s)&&(a=jl(a,t,s),e.chatStreamSegments=a),an(o,i)===o)return;let c=a.at(-1),l=c?.persisted&&c.runId===t&&!c.boundaryRunId&&!c.toolCallId;e.chatStreamSegments=[...l?a.slice(0,-1):a,{...l?c:{},text:i,ts:e.chatStreamStartedAt??Date.now(),runId:t,persisted:!0}]}function Pl(e,t){let n=Un(t);!n||!e.chatStreamSegments||Ml(e,e.chatStreamSegments.flatMap((e,t)=>{let r=g(e.runId),i=!n.runId||!r||n.runId===r;return g(e.itemId)===n.itemId&&i?[t]:[]}))}function Fl(e,t,n){if(!Array.isArray(t.chatStreamSegments))return!1;let r=new Set;for(let i of bl(t,{includeCurrent:!1,isHiddenStreamText:n.isHiddenStreamText})){if(i.segmentIndex===void 0||i.itemId&&n.persistCommentary!==!0)continue;let t=Ii(e,i);Sl(e,i,n.isHiddenAssistantMessage,t.start,t.end)&&r.add(i.segmentIndex)}return r.size!==0&&(t.chatStreamSegments=jl(t.chatStreamSegments,t.chatRunId,(e,t)=>r.has(t)),!0)}function Il(e,t){if(t.size===0)return;let n=wi(e);if(e.toolStreamById instanceof Map)for(let n of t)e.toolStreamById.delete(n);if(Array.isArray(e.toolStreamOrder)&&(e.toolStreamOrder=e.toolStreamOrder.filter(e=>typeof e==`string`&&!t.has(e))),Array.isArray(e.chatToolMessages)&&(e.chatToolMessages=e.chatToolMessages.filter(e=>Ci(e).every(e=>{let r=Ti(e,n);return r===void 0||!t.has(r)}))),!Array.isArray(e.chatStreamSegments))return;let r=0;e.chatStreamSegments=jl(e.chatStreamSegments,e.chatRunId,e=>{if(e.boundaryMarker===!0||e.persisted===!0)return!1;let i=g(e.toolCallId),a=Xt(e),o=a?void 0:n[r];a||(r+=1);let s=g(e.runId),c=i?Ti({id:i,...s?{runId:s}:{}},n):o?.identity;return!!(c&&t.has(c))})}function Ll(){return(Ll=e((()=>{k(),On(),qi(),Al(),Oi()})))()}function Rl(e,t,n,r,i){if(t.kind!==`live`)return null;if(t.activeRunId)return i&&i!==t.activeRunId?null:t.activeRunId;let a=e.lastLocalTerminalReconcile,o=a?.sessionKey===e.sessionKey?a.runId:null;if(!o)return null;if(i)return i===o?o:null;let s=wn(e,e.chatMessages,r).runs[o]?.message,c=j(s)?.trim();return c&&c===j(n)?.trim()?o:null}function zl(e,t,n,r){let i=ie(t);if(!i)return;let a=i.message,o=A(a,i);if(!o)return;let s=Tn(e,{agentId:Gn(e)}),c=!!(o.role===`assistant`&&o.sequence!==null&&o.runId&&r.kind===`live`&&r.activeRunId&&o.runId!==r.activeRunId),l=o.runId===i.runId?o.runId:null,u=o.role===`assistant`&&o.id&&!o.isImported&&(l||!o.runId&&n!==!0)?Rl(e,r,a,s,l):null;if(r.kind===`live`&&o.role!==`user`&&!c&&!u||o.isImported&&!o.externalSource&&wt(a)===null||!o.id&&!o.idempotencyKey&&o.sequence===null)return;let d=ie(a);if(!d)return;let f=ie(d.__openclaw),p={...d,__openclaw:{...f,...o.id?{id:o.id}:{},...o.idempotencyKey?{idempotencyKey:o.idempotencyKey}:{},...o.sequence===null?{}:{seq:o.sequence},...l?{runId:l}:{}}},m=Cn(e,{type:`messagePersisted`,message:p,envelope:u?{...i,runId:u}:i},{scope:s,runActive:n});o.role===`assistant`&&m.messages.includes(p)&&(Pl(e,p),u&&n===!1&&(e.chatStream=null,e.chatStreamStartedAt=null,dl(e,u)),Nl(e));let h=Ai(p),g=e.chatRunId,_=h?Pi(m.messages,h):null;o.role===`user`&&(n===!0||n===void 0&&g===h)&&o.runId&&h&&(!g||g===h||g===o.runId)&&_?.runId===o.runId&&Fi(e)!==o.runId&&(e.chatRunId=h,Ki(e,{runId:h,boundaryRunId:o.runId}))}function Bl(){return(Bl=e((()=>{k(),It(),Mn(),xn(),qi(),Al(),Ll()})))()}function K(e){return structuredClone(e)}function Vl(){return{id:`side-panel-column`,side:`right`,panels:[],activePanelId:``,height:au,width:iu}}function Hl(e){return Math.min(su,Math.max(260,e))}function Ul(e){return Math.min(cu,Math.max(220,e))}function Wl(e){return e.dock===`bottom`?`bottom`:`right`}function Gl(e,t){return e.open===!0&&e.columns.some(e=>e.panels.find(t=>t.id===e.activePanelId)?.slot===t)}function Kl(e,t){let n=new Set(e.columns.flatMap(e=>e.panels.map(e=>e.id)));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r+=1;return`${t}-${r}`}function ql(e,t){for(let n of e.columns){let e=n.panels.findIndex(e=>e.id===t);if(e<0)continue;let r=n.panels.splice(e,1)[0];return n.activePanelId===t&&(n.activePanelId=n.panels[Math.min(e,n.panels.length-1)]?.id??``),r}return null}function Jl(e,t){let n=K(e),r=n.columns.flatMap(e=>e.panels).find(e=>e.slot===t);if(r){n.open=!0;let e=n.columns.find(e=>e.panels.includes(r));return e&&(e.activePanelId=r.id),n}let i={id:Kl(n,t),slot:t},a=n.columns[0]??=Vl();return a.panels.push(i),a.activePanelId=i.id,n.open=!0,n}function Yl(e,t){let n=K(e),r=n.columns.flatMap(e=>e.panels).find(e=>e.slot===t);return r&&(ql(n,r.id),n.columns.every(e=>e.panels.length===0)&&(n.open=!1)),n.columns.length===0&&(n.open=!1),n}function Xl(e,t){let n=K(e),r=n.columns.find(e=>e.panels.some(e=>e.id===t));return r&&(r.activePanelId=t,n.open=!0),n}function Zl(e,t,n,r){let i=K(e),a=i.columns[0]?.panels;if(!a||t===n)return i;let o=a.findIndex(e=>e.id===t),s=a.findIndex(e=>e.id===n);if(o<0||s<0)return i;let[c]=a.splice(o,1),l=a.findIndex(e=>e.id===n);return a.splice(l+ +(r===`after`),0,c),i}function Ql(e,t){let n=K(e);return t&&(n.columns[0]??=Vl()),n.open=t,n}function $l(e,t){return{...K(e),expanded:t}}function eu(e,t){return{...K(e),dock:t}}function tu(e,t,n){let r=K(e),i=r.columns.find(e=>e.id===t);return i&&Number.isFinite(n)&&(Wl(r)===`bottom`?i.height=Ul(n):i.width=Hl(n)),r}function nu(e,t){let n=K(e);if(!Number.isFinite(t)||t<=0)return n;let r=n.columns[0];if(!r)return n;if(n.columns=[r],Wl(n)===`bottom`)return r.height=Ul(r.height),n;let i=Math.max(260,Math.min(su,t*.6)),a=Math.max(0,t-lu-uu);return 260>a?null:(r.width=Math.min(i,a,Hl(r.width)),n)}function ru(e,t){return t<680}var iu,au,ou,su,cu,lu,uu;function du(){return(du=e((()=>{Me(),iu=480,au=360,ou=`openclaw-sidebar-geometry-commit`,su=1200,cu=800,lu=312,uu=4})))()}function fu(e){return e?.split(`;`,1)[0]?.trim().toLowerCase()??``}function pu(e){try{let t=new URL(e,window.location.href);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.origin===window.location.origin}catch{return!1}}function mu(e){if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?:px)?$/iu.test(e.trim()))return null;let t=Number.parseFloat(e);return Number.isFinite(t)?t:null}function hu(e){if(!Nu.has(e.name)||/^on/iu.test(e.name)||e.namespaceURI&&e.name!==`xmlns`)return!1;let t=e.value.trim();switch(e.name){case`d`:return Lu.test(t);case`points`:case`viewBox`:return Iu.test(t);case`fill`:case`stroke`:return Pu.test(t);case`clip-rule`:case`fill-rule`:return/^(?:evenodd|nonzero)$/u.test(t);case`stroke-linecap`:return/^(?:butt|round|square)$/u.test(t);case`stroke-linejoin`:return/^(?:bevel|miter|round)$/u.test(t);case`transform`:return/^(?:\s*(?:matrix|rotate|scale|skewX|skewY|translate)\(\s*[0-9eE+.,\s-]+\)\s*)+$/u.test(t);case`cx`:case`cy`:case`height`:case`opacity`:case`r`:case`rx`:case`ry`:case`stroke-miterlimit`:case`stroke-width`:case`width`:case`x`:case`x1`:case`x2`:case`y`:case`y1`:case`y2`:return Fu.test(t);case`preserveAspectRatio`:return/^(?:none|x(?:Min|Mid|Max)Y(?:Min|Mid|Max)(?:\s+(?:meet|slice))?)$/u.test(t);case`xmlns`:return t===ju;case`aria-hidden`:case`focusable`:return/^(?:false|true)$/u.test(t);case`role`:return t===`img`;case`aria-label`:return/^[^<>&]{0,256}$/u.test(t);default:return!1}}async function gu(e){let t=new Image;return t.decoding=`async`,await new Promise((n,r)=>{let i=window.setTimeout(()=>{t.src=``,r(Error(`plugin SVG decode timed out`))},Eu);t.addEventListener(`load`,()=>{window.clearTimeout(i),n()},{once:!0}),t.addEventListener(`error`,()=>{window.clearTimeout(i),r(Error(`plugin SVG decode failed`))},{once:!0}),t.src=e}),t}function _u(e){let t=e.getAttribute(`viewBox`);if(t){let e=t.trim().split(/[\s,]+/u).map(e=>Number(e)),n=e[2],r=e[3];return e.length!==4||e.some(e=>!Number.isFinite(e))||!n||!r||n<=0||r<=0||n>Au||r>Au?null:{width:n,height:r}}let n=mu(e.getAttribute(`width`)??``),r=mu(e.getAttribute(`height`)??``);return!n||!r||n<=0||r<=0||n>Au||r>Au?null:{width:n,height:r}}async function vu(e){let t=await e.text();if(/Du)return null;let a=0;for(let e of i){if(e.namespaceURI!==ju||!Mu.has(e.localName.toLowerCase()))return null;for(let t of Array.from(e.attributes)){if(!hu(t))return null;(t.name===`d`||t.name===`points`)&&(a+=t.value.length)}}if(a>Ou||i.reduce((e,t)=>e+(t.getAttribute(`d`)?.match(/[a-z]/giu)?.length??0),0)>ku)return null;let o=_u(r);return o?{blob:new Blob([new XMLSerializer().serializeToString(r)],{type:`image/svg+xml`}),...o}:null}async function yu(e){let t=await vu(e);if(!t)return null;let n=Math.min(q/t.width,q/t.height),r=Math.max(1,Math.round(t.width*n)),i=Math.max(1,Math.round(t.height*n)),a=URL.createObjectURL(t.blob);try{let e=await gu(a),t=document.createElement(`canvas`);t.width=q,t.height=q;let n=t.getContext(`2d`);return n?(n.drawImage(e,Math.round((q-r)/2),Math.round((q-i)/2),r,i),await new Promise(e=>{t.toBlob(e,`image/png`)})):null}finally{URL.revokeObjectURL(a)}}function bu(e){e.bodyUsed||e.body?.cancel().catch(()=>void 0)}async function xu(e,t){if(!pu(e.gatewayUrl))return null;let n=et(e.auth),r=n.length>0?n:[``];for(let n of r){let r={Accept:`image/avif,image/webp,image/png,image/jpeg,image/gif,image/svg+xml`};n&&(r.Authorization=`Bearer ${n}`);let i=await fetch(t,{method:`GET`,headers:r,credentials:`same-origin`,signal:e.signal});if(!i.ok){if(bu(i),i.status===401||i.status===403)continue;return null}let a=fu(i.headers.get(`content-type`));if(!Tu.has(a))return bu(i),null;let o=await i.blob(),s=a===`image/svg+xml`?await yu(o):o;return s?URL.createObjectURL(s):null}return null}function Su(e){return xu(e,ur(`pluginIcon`,e.resourceBasePath,e.pluginId))}function Cu(e){return xu(e,ur(`catalogIcon`,e.resourceBasePath,e.iconUrl))}function wu(e){return xu(e,ur(`linkFavicon`,e.resourceBasePath,e.hostname))}var Tu,q,Eu,Du,Ou,ku,Au,ju,Mu,Nu,Pu,Fu,Iu,Lu;function Ru(){return(Ru=e((()=>{rr(),ot(),Tu=new Set([`image/png`,`image/svg+xml`,`image/x-icon`]),q=256,Eu=5e3,Du=4,Ou=8192,ku=1024,Au=4096,ju=`http://www.w3.org/2000/svg`,Mu=new Set([`circle`,`desc`,`ellipse`,`g`,`line`,`path`,`polygon`,`polyline`,`rect`,`svg`,`title`]),Nu=new Set(`aria-hidden.aria-label.clip-rule.cx.cy.d.fill.fill-rule.focusable.height.opacity.points.preserveAspectRatio.r.role.rx.ry.stroke.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-width.transform.viewBox.width.x.x1.x2.xmlns.y.y1.y2`.split(`.`)),Pu=/^(?:none|currentColor|#[0-9a-f]{3,8})$/iu,Fu=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/iu,Iu=/^[0-9eE+.,\s-]+$/u,Lu=/^[0-9a-zA-Z+.,\s-]+$/u})))()}function zu(e,t,n){let r=e.length>0&&t?.recoveryScopeReady===!0&&!n;return{profiles:r?[]:e,unsupported:r}}function Bu(e,t,n){return t?vo(e).then(e=>({...e,profiles:n?e.profiles:[]})):Promise.resolve({profiles:[],environments:[]})}var Vu;function Hu(){return(Hu=e((()=>{wo(),Vu=[1e3,3e3,1e4,3e4,6e4]})))()}function Uu(){return{entries:[],nextEntryId:1,userEntryId:null,userEntryAwaitingFinal:!1,userEntryAwaitingFinalStartedAtMs:null,assistantEntryId:null}}function Wu(e,t){let n=t.text;if(t.final?n.trim()===``:n===``)return e;let r=t.nowMs??Date.now();if(t.role===`assistant`){let i=qu(e,`user`,r);return Gu(i,t.role,i.assistantEntryId,n,t.final,r)}let i=e.userEntryId,a=i!==null&&Ju(e,i,n,t.final,r),o=i===null||a?qu(e,`assistant`,r):e;return Gu(a&&i!==null?{...qu(o,`user`,r),userEntryId:null,userEntryAwaitingFinal:!1,userEntryAwaitingFinalStartedAtMs:null}:o,t.role,a?null:i,n,t.final,r)}function Gu(e,t,n,r,i,a){if(n===null){let n=`rt-${e.nextEntryId}`,o=[...e.entries,{id:n,role:t,text:Zu(r.trimStart()),isStreaming:!i}].slice(-60);return Ku({...e,entries:o,nextEntryId:e.nextEntryId+1},t,n,i,a)}let o=e.entries.findIndex(e=>e.id===n);if(o===-1)return Gu(e,t,null,r,i,a);let s=e.entries[o];if(!s)return Gu(e,t,null,r,i,a);let c=Zu(t===`assistant`?Yu(s.text,r,i):Xu(s.text,r,i)),l=s.text===c&&s.isStreaming===!i?e.entries:e.entries.map((e,t)=>t===o?{...e,text:c,isStreaming:!i}:e);return Ku({...e,entries:l},t,n,i,a)}function Ku(e,t,n,r,i){return t===`user`?{...e,userEntryId:r?null:n,userEntryAwaitingFinal:!1,userEntryAwaitingFinalStartedAtMs:null}:{...e,assistantEntryId:r?null:n}}function qu(e,t,n=Date.now()){let r=t===`user`?e.userEntryId:e.assistantEntryId;if(r===null)return e;let i=e.entries.map(e=>e.id===r&&e.isStreaming?{...e,isStreaming:!1}:e);return t===`user`?{...e,entries:i,userEntryAwaitingFinal:!0,userEntryAwaitingFinalStartedAtMs:n}:{...e,entries:i,assistantEntryId:null}}function Ju(e,t,n,r,i){let a=e.entries.find(e=>e.id===t);if(!a||a.isStreaming)return!1;let o=a.text;return!(o.trim()===``||n.trim()===``||n[0]&&/\s/.test(n[0])||n===o||n.startsWith(o)||o.endsWith(n)||r&&e.userEntryAwaitingFinal&&(e.userEntryAwaitingFinalStartedAtMs===null?1/0:i-e.userEntryAwaitingFinalStartedAtMs)<=sd&&Qu(o,n))}function Yu(e,t,n){return e.trim()===``?t.trimStart():n&&(t===e||t.startsWith(e)||Qu(e,t))?t:`${e}${t}`}function Xu(e,t,n){if(e.trim()===``)return t.trimStart();if(t===``||t===e||e.endsWith(t))return e;if(t.startsWith(e))return t;if(t[0]&&/\s/.test(t[0]))return`${e}${t}`;if(n&&Qu(e,t))return t;let r=nd(e,t),i=r>0?t.slice(r):t;return i===``?e:`${e}${r>0||!rd(e,i)?``:` `}${i}`}function Zu(e){if(e.length<=id)return e;let t=e.indexOf(od),n=te(e,0,t>=255&&t<=ad?t:ad).replace(/[\uD800-\uDBFF]$/,``),r=id-n.length-3,i=te(e,-r);return`${n}${od}${i}`}function Qu(e,t){let n=$u(e),r=$u(t);if(n.length===0||r.length===0||n[0]!==r[0])return!1;if(n.length>1&&r.length>1&&n[1]===r[1])return!0;let i=ed(e),a=ed(t),o=td(i,a),s=Math.min(i.length,a.length);return o>=6&&o/Math.max(1,s)>=.45}function $u(e){return[...e.toLowerCase().matchAll(/[\p{L}\p{N}]+/gu)].map(e=>e[0])}function ed(e){return e.toLowerCase().replace(/\s+/g,` `).trim()}function td(e,t){let n=Math.min(e.length,t.length),r=0;for(;r=3;--e)if(n.endsWith(r.slice(0,e)))return e;return 0}function rd(e,t){let n=e.at(-1),r=t[0];return!n||!r||/\s/.test(n)||/\s/.test(r)?!1:/[\p{L}\p{N}.!?,:;)\]}"'’”]/u.test(n)&&/[\p{L}\p{N}]/u.test(r)}var id,ad,od,sd;function cd(){return(cd=e((()=>{id=8e3,ad=256,od=` … `,sd=1500})))()}function ld(e,t){let n=[],r=new Set;for(let i of e){let e=i.deviceId.trim();i.kind!==t||!e||e==="default"||r.has(e)||(r.add(e),n.push({deviceId:e,label:i.label.trim()||O(t===`audioinput`?`chat.composer.microphoneFallback`:`chat.composer.cameraFallback`,{number:String(n.length+1)})}))}return n}function ud(e,t){let n=e.filter(e=>e.kind===t);return n.length===0||n.some(e=>!e.deviceId||!e.label)}function dd(e){return e instanceof DOMException||e instanceof Error&&e.name===`OverconstrainedError`?e.name:void 0}function fd(e){return wd[dd(e)??``]??`failed`}function pd(e,t){let[n,r]=Cd[e];return O(t===`audioinput`?n:r)}function md(e){let t=globalThis.navigator?.mediaDevices;return t?.addEventListener?(t.addEventListener(`devicechange`,e),()=>t.removeEventListener(`devicechange`,e)):()=>void 0}function hd(e){return pd(fd(e),`audioinput`)}async function gd(e,t){let n=globalThis.navigator?.mediaDevices;if(!n?.enumerateDevices)return{devices:[],permissionRequired:!1,issue:`list-unsupported`};let r;try{r=await n.enumerateDevices()}catch(e){return{devices:[],permissionRequired:!1,issue:fd(e)}}let i=ud(r,t);if(!e||!i||!n.getUserMedia)return{devices:ld(r,t),permissionRequired:i,issue:null};try{return(await n.getUserMedia(t===`audioinput`?{audio:!0}:{video:!0})).getTracks().forEach(e=>e.stop()),r=await n.enumerateDevices(),{devices:ld(r,t),permissionRequired:ud(r,t),issue:null}}catch(e){return{devices:ld(r,t),permissionRequired:i,issue:fd(e)}}}async function _d(e){return gd(e,`audioinput`)}async function vd(e){return gd(e,`videoinput`)}function yd(e){let t=e?.trim();return{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,...t?{deviceId:{exact:t}}:{}}}function J(e){return e.reason instanceof Error?e.reason:new DOMException(`Realtime Talk input cancelled`,`AbortError`)}async function bd(e,t){if(t?.aborted)throw J(t);let n=e();if(!t)return await n;let r=()=>void 0,i=new Promise((e,n)=>{let i=()=>n(J(t));t.addEventListener(`abort`,i,{once:!0}),r=()=>t.removeEventListener(`abort`,i)});try{return await Promise.race([n,i])}catch(e){throw t.aborted?(n.then(e=>e.getTracks().forEach(e=>e.stop()),()=>void 0),J(t)):e}finally{r()}}async function xd(e,t={}){let n=globalThis.navigator?.mediaDevices;if(!n?.getUserMedia)throw Error(O(`chat.composer.realtimeTalkRequiresMicrophone`));let r;try{r={stream:await bd(()=>n.getUserMedia({audio:yd(e)}),t.signal)}}catch(t){let n=dd(t);if(!n||n===`AbortError`)throw t;r={failure:e?.trim()&&n===`OverconstrainedError`?O(`chat.composer.selectedMicrophoneUnavailable`):hd(t)}}if(`failure`in r)throw Error(r.failure);let{stream:i}=r;if(t.signal?.aborted)throw i.getTracks().forEach(e=>e.stop()),J(t.signal);return i}async function Sd(e,t={}){let n=globalThis.navigator?.mediaDevices;if(!n?.getUserMedia)throw Error(O(`chat.composer.cameraAccessFailed`));let r=e?.trim(),i;try{let e=await bd(()=>n.getUserMedia({video:!r||{deviceId:{exact:r}}}),t.signal);if(t.signal?.aborted)throw e.getTracks().forEach(e=>e.stop()),J(t.signal);i={stream:e}}catch(e){if(t.signal?.aborted)throw J(t.signal);let n=dd(e);i={failure:r&&n===`OverconstrainedError`?O(`chat.composer.selectedCameraUnavailable`):pd(fd(e),`videoinput`)}}if(`failure`in i)throw Error(i.failure);return i.stream}var Cd,wd,Td;function Ed(){return(Ed=e((()=>{lt(),Cd={"list-unsupported":[`chat.composer.microphoneListUnsupported`,`chat.composer.cameraListUnsupported`],"none-found":[`chat.composer.microphoneNoneFound`,`chat.composer.cameraNoneFound`],"permission-blocked":[`chat.composer.microphonePermissionBlocked`,`chat.composer.cameraPermissionBlocked`],busy:[`chat.composer.microphoneBusy`,`chat.composer.cameraBusy`],"page-inactive":[`chat.composer.microphonePageInactive`,`chat.composer.cameraPageInactive`],failed:[`chat.composer.microphoneAccessFailed`,`chat.composer.cameraAccessFailed`]},wd={NotAllowedError:`permission-blocked`,NotFoundError:`none-found`,NotReadableError:`busy`,InvalidStateError:`page-inactive`},Td=class{constructor(e){this.onEnded=e,this.controller=null,this.media=null}get stream(){return this.media}async open(e){this.stop();let t=new AbortController;this.controller=t;try{let n=await xd(e,{signal:t.signal});if(t.signal.aborted)throw n.getTracks().forEach(e=>e.stop()),J(t.signal);this.media=n;let r=()=>{this.controller===t&&(this.stop(),this.onEnded(O(`chat.composer.microphoneStopped`)))};for(let e of n.getTracks())e.addEventListener(`ended`,r,{signal:t.signal});return n}catch(e){throw this.controller===t&&this.stop(),e}}stop(){let e=this.controller,t=this.media;this.controller=null,this.media=null,e?.abort(),t?.getTracks().forEach(e=>e.stop())}}})))()}var Dd;function Od(){return(Od=e((()=>{Dd=class{constructor(){this.listeners=new Set,this.currentLevel=0}get value(){return this.currentLevel}set(e){let t=Math.round((Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)*100)/100;if(t!==this.currentLevel){this.currentLevel=t;for(let e of this.listeners)e(t)}}subscribe(e){return this.listeners.add(e),e(this.currentLevel),()=>this.listeners.delete(e)}}})))()}function kd(e){let t=``,n=32768;for(let r=0;r0;)--s,c>>=1;let l=o>>s+3&15;t[n]=~(a|s<<4|l)&255}return t}function Nd(e){let t=0,n=0;for(let r of e){let e=Number.isFinite(r)?r:0;t=Math.max(t,Math.abs(e)),n+=e*e}return{peak:t,rms:e.length>0?Math.sqrt(n/e.length):0}}function Pd(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(Math.floor(e.byteLength/2));for(let e=0;e{Id=class{constructor(){this.source=null,this.processor=null,this.sink=null}start(e,t,n){this.stop(),this.source=t.createMediaStreamSource(e),this.processor=t.createScriptProcessor(4096,1,1),this.sink=t.createGain(),this.sink.gain.value=0,this.processor.onaudioprocess=e=>n(e.inputBuffer.getChannelData(0)),this.source.connect(this.processor),this.processor.connect(this.sink),this.sink.connect(t.destination)}stop(){this.processor&&=(this.processor.onaudioprocess=null,this.processor.disconnect(),null),this.sink?.disconnect(),this.sink=null,this.source?.disconnect(),this.source=null}},Ld=class{constructor(){this.level=0,this.noiseFloor=.01}sample(e){let t=Nd(e),n=.65*t.rms+.35*t.peak;n<=Math.max(.02,this.noiseFloor*2)&&(this.noiseFloor=.95*this.noiseFloor+.05*n);let r=Math.max(0,n-this.noiseFloor*1.5),i=Math.min(1,Math.sqrt(r/.18)),a=i>this.level?.65:.18;return this.level=a*i+(1-a)*this.level,this.level<.01&&(this.level=0),this.level}reset(){this.level=0,this.noiseFloor=.01}},Rd=class{constructor(e){this.onLevel=e,this.context=null,this.source=null,this.analyser=null,this.timer=null,this.ownsContext=!1,this.levelMeter=new Ld,this.samples=new Float32Array(512),this.lastLevel=-1}start(e,t){this.stop(!1);try{let n=t??new AudioContext;this.context=n,this.ownsContext=!t;let r=n.createMediaStreamSource(e);this.source=r;let i=n.createAnalyser();this.analyser=i,i.fftSize=this.samples.length,i.smoothingTimeConstant=0,r.connect(i),this.timer=globalThis.setInterval(()=>this.publishCurrentLevel(),100),this.publishCurrentLevel()}catch{this.stop()}}stop(e=!0){this.timer!==null&&(globalThis.clearInterval(this.timer),this.timer=null),this.source?.disconnect(),this.source=null,this.analyser?.disconnect(),this.analyser=null,this.ownsContext&&this.context?.close(),this.context=null,this.ownsContext=!1,this.levelMeter.reset(),this.lastLevel=-1,e&&this.onLevel(0)}publishCurrentLevel(){if(!this.analyser)return;this.samples.fill(0),this.analyser.getFloatTimeDomainData(this.samples);let e=Math.round(this.levelMeter.sample(this.samples)*100)/100;e!==this.lastLevel&&(this.lastLevel=e,this.onLevel(e))}},zd=10,Bd=320,Vd=class{constructor(){this.playhead=0,this.sources=new Set}get queuedUntil(){return this.playhead}get isPlaying(){return this.sources.size>0}play(e,t,n){if(!t)return`ignored`;let r=Math.max(t.currentTime,this.playhead),i=Math.max(0,r-t.currentTime),a=zd-i,o=Fd(e),s=Math.floor(o/2);if(this.sources.size>=Bd||a<=0||s/n>a)return`overflow`;let c;try{c=Pd(Ad(e))}catch{return`ignored`}if(c.length===0)return`ignored`;let l=r+c.length/n;if(l-t.currentTime>zd)return`overflow`;let u=t.createBuffer(1,c.length,n);u.getChannelData(0).set(c);let d=t.createBufferSource();return this.sources.add(d),d.addEventListener(`ended`,()=>this.sources.delete(d)),d.buffer=u,d.connect(t.destination),d.start(r),this.playhead=l,`queued`}stop(e){let t=[...this.sources];this.sources.clear(),this.playhead=e?.currentTime??0;for(let e of t)try{e.stop()}catch{}}}})))()}function Ud(e,t){let n=0,r=0,i,a=Gd(e,t);return r=>{if(!e.callbacks.onTalkEvent)return;let s=o(r);n+=1,e.callbacks.onTalkEvent({id:`${a}:${n}`,type:r.type,sessionId:a,turnId:s,captureId:r.captureId,seq:n,timestamp:new Date().toISOString(),mode:`realtime`,transport:t.transport,brain:`agent-consult`,provider:t.provider,final:r.final,callId:r.callId,itemId:r.itemId,parentId:r.parentId,payload:r.payload??null}),(r.type===`turn.ended`||r.type===`turn.cancelled`||r.type===`session.replaced`||r.type===`session.closed`)&&(i=void 0)};function o(e){return e.type===`turn.started`||Wd(e.type)?(i=e.turnId??i??`turn-${++r}`,i):e.turnId}}function Wd(e){return e===`turn.ended`||e===`turn.cancelled`||e.startsWith(`input.audio.`)||e.startsWith(`transcript.`)||e.startsWith(`output.`)||e.startsWith(`tool.`)}function Gd(e,t){let n=t.sessionId;return typeof n==`string`&&n.trim()?n.trim():`relaySessionId`in t&&t.relaySessionId.trim()?t.relaySessionId:`${e.sessionKey}:${t.provider}:${t.transport}`}function Kd(e){if(!e||typeof e!=`object`)return``;let t=e;return typeof t.text==`string`?t.text:(Array.isArray(t.content)?t.content:[]).map(e=>{if(!e||typeof e!=`object`)return``;let t=e;return t.type===`text`&&typeof t.text==`string`?t.text:``}).filter(Boolean).join(` `).trim()}function qd(e){if(!e)return;let t=e.error?.trim();if(e.status===`error`)return Error(t||`OpenClaw tool call failed`);if(e.status!==`timeout`||e.pendingError)return;let n=e.stopReason?.trim(),r=e.timeoutPhase?.trim(),i=e.livenessState?.trim();if(e.endedAt!==void 0||t!==void 0||e.aborted===!0||i!==void 0&&i.length>0||e.yielded===!0||n!==void 0&&n.length>0||r===`preflight`||r===`provider`||r===`post_turn`||e.providerStarted===!0)return Error(t||`OpenClaw tool call timed out`)}function Jd(e){return new Promise((t,n)=>{if(e.signal?.aborted){n(new DOMException(`OpenClaw tool call aborted`,`AbortError`));return}let r=window.setTimeout(()=>{u(Error(`OpenClaw tool call timed out`))},e.timeoutMs),i=!1,a=!1,o,s=()=>{u(new DOMException(`OpenClaw tool call aborted`,`AbortError`))};e.signal?.addEventListener(`abort`,s,{once:!0});let c=()=>void 0,l=e=>{i||(i=!0,f(),t(e))},u=e=>{i||(i=!0,f(),n(e))},d=()=>{a||(a=!0,e.client.request(`agent.wait`,{runId:e.runId,timeoutMs:e.timeoutMs}).then(e=>{if(i)return;let t=qd(e);if(t){u(t);return}e?.status!==`timeout`&&(o=window.setTimeout(()=>{l(`OpenClaw finished with no text.`)},tf))}).catch(e=>{u(e instanceof Error?e:Error(String(e)))}))};c=e.client.addEventListener(t=>{if(t.event!==`chat`)return;let n=t.payload;if(!(!n||n.runId!==e.runId)){if(Yd(e.emitTalkEvent,n),n.state===`final`){let e=Kd(n.message);if(e){l(e);return}d()}else n.state===`aborted`?u(new DOMException(n.errorMessage??`OpenClaw tool call aborted`,`AbortError`)):n.state===`error`&&u(Error(n.errorMessage??`OpenClaw tool call failed`))}});function f(){window.clearTimeout(r),o!==void 0&&window.clearTimeout(o),e.signal?.removeEventListener(`abort`,s),c()}})}function Yd(e,t){if(!e||t.stream!==`tool`)return;let n=t.data&&typeof t.data==`object`?t.data:{},r=typeof n.phase==`string`?n.phase:void 0,i=typeof n.name==`string`?n.name:void 0;e({type:`tool.progress`,callId:typeof n.toolCallId==`string`?n.toolCallId:void 0,payload:{runId:t.runId,...i?{name:i}:{},...r?{phase:r}:{}}})}async function Xd(e){let t=e.text.trim();if(!t)return;let n=e.sessionId&&e.sessionId.trim()?e.ctx.client.request(`talk.session.steer`,{sessionId:e.sessionId,sessionKey:e.ctx.sessionKey,text:t,...e.mode?{mode:e.mode}:{}}):e.ctx.client.request(`talk.client.steer`,{sessionKey:e.ctx.sessionKey,text:t,...e.mode?{mode:e.mode}:{}});try{let t=await n;e.onControlResult?.(t),Qd(t,e.speakControlResult,e.suppressSpeechForModes),e.emitTalkEvent?.({type:`tool.progress`,payload:{name:`openclaw_agent_control`,result:t},final:t&&typeof t==`object`&&`mode`in t?t.mode===`status`||t.mode===`cancel`:void 0})}catch(t){e.emitTalkEvent?.({type:`tool.error`,payload:{message:C(t)},final:!0})}}async function Zd(e){if(e.signal?.aborted)return;let t,n;try{let r=hr(e.args);if(t=e.sessionId&&e.sessionId.trim()?await e.ctx.client.request(`talk.session.steer`,{sessionId:e.sessionId,sessionKey:e.ctx.sessionKey,text:r.text,mode:r.mode}):await e.ctx.client.request(`talk.client.steer`,{sessionKey:e.ctx.sessionKey,text:r.text,mode:r.mode}),e.signal?.aborted)return;n={type:`tool.progress`,callId:e.callId,payload:{name:`openclaw_agent_control`,result:t},final:t&&typeof t==`object`&&`mode`in t?t.mode===`status`||t.mode===`cancel`:void 0}}catch(r){let i=C(r);if(n={type:`tool.error`,callId:e.callId,payload:{message:i},final:!0},t={error:i},e.signal?.aborted||ef(r))return}await e.submit(e.callId,t),!e.signal?.aborted&&e.emitTalkEvent?.(n)}function Qd(e,t,n){if(!t||!e||typeof e!=`object`)return;let r=e,i=typeof r.mode==`string`?r.mode:void 0;if(i&&n?.includes(i))return;let a=typeof r.message==`string`?r.message.trim():``;(r.speak===!0&&r.suppress!==!0||r.ok===!0&&i===`steer`&&r.suppress===!0)&&a&&t(er(a))}async function $d(e){let{ctx:t,callId:n,submit:r}=e;t.callbacks.onStatus?.(`thinking`);let i,a=!1,o=!1,s=!1,c=async e=>{o||(o=!0,await r(n,e),s=!0)},l=async()=>{e.submitAbortResult!==!1&&await c(or())},u=()=>{a=!0,i&&t.client.request(`chat.abort`,{sessionKey:t.sessionKey,runId:i})};if(e.signal?.aborted){await l();return}e.signal?.addEventListener(`abort`,u,{once:!0});try{let r=typeof e.args==`string`?JSON.parse(e.args||`{}`):e.args??{};if(await t.flushTranscriptWrites?.(),e.signal?.aborted){await l();return}let a=await t.client.request(`talk.client.toolCall`,{sessionKey:t.sessionKey,...t.voiceSessionId?{voiceSessionId:t.voiceSessionId}:{},callId:n,name:mr,args:r,...e.relaySessionId?{relaySessionId:e.relaySessionId}:{}});if(i=a.runId??a.idempotencyKey,!i)throw Error(`OpenClaw realtime tool call did not return a run id`);if(e.signal?.aborted){u(),await l();return}await c({result:await Jd({client:t.client,runId:i,timeoutMs:12e4,emitTalkEvent:e.emitTalkEvent,signal:e.signal})})}catch(t){if(o)throw t;if(a||e.signal?.aborted||ef(t)){await l();return}await c({error:C(t)})}finally{e.signal?.removeEventListener(`abort`,u),s&&!a&&!e.signal?.aborted&&t.callbacks.onStatus?.(`listening`)}}function ef(e){return typeof DOMException<`u`&&e instanceof DOMException&&e.name===`AbortError`||typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`}var tf;function nf(){return(nf=e((()=>{Zn(),dr(),T(),tf=500})))()}function rf(e){try{return(JSON.stringify(e)?.length??0)*2}catch{return 262145}}var af,of,sf,cf,lf,uf,df,ff,pf;function mf(){return(mf=e((()=>{yt(),lt(),T(),Hd(),Ed(),nf(),af=.02,of=.08,sf=2,cf=4,lf=8e3,uf=8e3,df=32,ff=262144,pf=class{constructor(e,t){this.session=e,this.ctx=t,this.input=new Td(e=>this.failAudioAppend(e)),this.inputContext=null,this.outputContext=null,this.inputMeter=null,this.inputPump=new Id,this.unsubscribe=null,this.closed=!1,this.audioAppendAbortController=null,this.pendingAudioAppends=new Set,this.outputQueue=new Vd,this.toolAbortControllers=new Map,this.completedToolCalls=new Set,this.submittingToolCalls=new Set,this.delayedToolResults=new Set,this.markAckTimers=new Set,this.cancelRequestedForPlayback=!1,this.activeOutputTurnId=null,this.playbackOverflowed=!1,this.pendingOutputCancellations=0,this.speechFramesDuringPlayback=0,this.activated=!1,this.pendingActivationEvents=[],this.pendingActivationEventBytes=0,this.startupError=null}async start(){if(!navigator.mediaDevices?.getUserMedia)throw Error(`Realtime Talk requires browser microphone access`);if(this.session.audio.inputEncoding!==`pcm16`||this.session.audio.outputEncoding!==`pcm16`)throw Error(`Gateway-relay realtime Talk currently requires PCM16 audio`);this.closed=!1,this.activated=!1,this.pendingActivationEvents=[],this.pendingActivationEventBytes=0,this.startupError=null,this.unsubscribe=this.ctx.client.addEventListener(e=>{e.event===`talk.event`&&this.handleIncomingRelayEvent(e.payload)});let e;try{e=await this.input.open(this.ctx.inputDeviceId)}catch(e){let t=this.currentStartupError();if(t)throw t;if(this.closed)return`cancelled`;throw e}let t=this.currentStartupError();if(t)throw this.input.stop(),t;return this.closed?`cancelled`:(this.inputContext=new AudioContext({sampleRate:this.session.audio.inputSampleRateHz}),this.outputContext=new AudioContext({sampleRate:this.session.audio.outputSampleRateHz}),this.abortPendingAudioAppends(),this.audioAppendAbortController=new AbortController,this.ctx.callbacks.onInputLevel&&(this.inputMeter=new Rd(this.ctx.callbacks.onInputLevel),this.inputMeter.start(e,this.inputContext)),this.startMicrophonePump(),`ready`)}activate(){if(this.closed||this.activated)return;this.activated=!0;let e=this.pendingActivationEvents;this.pendingActivationEvents=[],this.pendingActivationEventBytes=0;for(let t of e){try{this.handleRelayEvent(t)}catch(e){throw this.stop(),e}if(this.closed)return}}stop(){let e=this.closed;this.stopLocal(),e||this.ctx.client.request(`talk.session.close`,{sessionId:this.session.relaySessionId},{timeoutMs:uf}).catch(()=>void 0)}stopLocal(){this.closed=!0,this.input.stop(),this.activated=!1,this.pendingActivationEvents=[],this.pendingActivationEventBytes=0,this.unsubscribe?.(),this.unsubscribe=null,this.inputPump.stop(),this.abortPendingAudioAppends(),this.inputMeter?.stop(),this.inputMeter=null,this.markAckTimers.forEach(e=>window.clearTimeout(e)),this.markAckTimers.clear(),this.discardDelayedToolResults(),this.abortConsults(),this.playbackOverflowed=!1,this.activeOutputTurnId=null,this.stopOutput(),this.inputContext?.close(),this.inputContext=null,this.outputContext?.close(),this.outputContext=null}startMicrophonePump(){!this.input.stream||!this.inputContext||this.inputPump.start(this.input.stream,this.inputContext,e=>{if(this.closed)return;this.detectBargeInSpeech(e)&&this.cancelOutputForBargeIn();let t=this.audioAppendAbortController;if(!t||t.signal.aborted||this.pendingOutputCancellations)return;if(this.pendingAudioAppends.size>=cf){this.failAudioAppend(`Realtime Talk audio input fell behind`);return}let n=jd(e),r=this.ctx.client.request(`talk.session.appendAudio`,{sessionId:this.session.relaySessionId,audioBase64:kd(n),timestamp:Math.round((this.inputContext?.currentTime??0)*1e3)},{signal:t.signal,timeoutMs:lf}).catch(e=>this.failAudioAppend(e));this.pendingAudioAppends.add(r),r.finally(()=>{this.pendingAudioAppends.delete(r)})})}abortPendingAudioAppends(){this.audioAppendAbortController?.abort(),this.audioAppendAbortController=null,this.pendingAudioAppends.clear()}failAudioAppend(e){if(!this.closed)try{this.ctx.callbacks.onStatus?.(`error`,C(e))}finally{this.stop()}}currentStartupError(){return this.startupError}handleIncomingRelayEvent(e){if(e.relaySessionId!==this.session.relaySessionId||this.closed)return;if(this.activated){this.handleRelayEvent(e);return}if(e.type===`error`&&(this.lastRelayError=e.message?C(e.message):`Realtime relay failed`),e.type===`close`){this.startupError=Error(e.reason===`error`?this.lastRelayError??`Realtime relay closed before browser setup completed`:`Realtime relay closed before browser setup completed`),this.stopLocal();return}let t=rf(e);if(this.pendingActivationEvents.length>=df||t>ff-this.pendingActivationEventBytes){this.startupError=Error(`Realtime relay emitted too much data before browser setup completed`),this.stop();return}this.pendingActivationEvents.push(e),this.pendingActivationEventBytes+=t}handleRelayEvent(e){if(e.relaySessionId!==this.session.relaySessionId||this.closed)return;let t=e.type===`close`;try{switch(e.talkEvent&&this.ctx.callbacks.onTalkEvent?.(e.talkEvent),e.type){case`ready`:this.ctx.callbacks.onStatus?.(`listening`);return;case`audio`:if(e.audioBase64&&!this.playbackOverflowed){let t=e.talkEvent?.turnId?.trim();if(!t){this.ctx.callbacks.onStatus?.(`error`,O(`chat.composer.realtimeTalkMissingTurnIdentity`)),this.stop();return}this.activeOutputTurnId=t,this.cancelRequestedForPlayback=!1,this.speechFramesDuringPlayback=0,this.playPcm16(e.audioBase64)}return;case`clear`:if(e.talkEvent?.turnId&&e.talkEvent.turnId!==this.activeOutputTurnId)return;this.playbackOverflowed=!1,this.stopOutput({releaseDelayedToolResults:this.pendingOutputCancellations===0}),this.activeOutputTurnId=null,e.talkEvent?.type===`turn.cancelled`&&this.abortConsults();return;case`mark`:e.markName&&this.scheduleMarkAck(e.markName);return;case`transcript`:e.role&&e.text&&this.ctx.callbacks.onTranscript?.({role:e.role,text:e.text,final:e.final??!1});return;case`toolCall`:this.handleToolCall(e).catch(e=>{this.reportToolResultSubmissionError(e)});return;case`toolCallCancelled`:this.cancelToolCall(e.callId);return;case`toolResult`:this.isFinalToolResult(e)&&this.completeToolCall(e.callId);return;case`error`:this.lastRelayError=e.message?C(e.message):`Realtime relay failed`,this.ctx.callbacks.onStatus?.(`error`,this.lastRelayError);return;case`close`:this.abortConsults(),this.ctx.callbacks.onStatus?.(e.reason===`error`?`error`:`idle`,e.reason===`error`?this.lastRelayError??`Realtime relay closed`:void 0)}}finally{t&&!this.closed&&this.stopLocal()}}playPcm16(e){this.outputQueue.play(e,this.outputContext,this.session.audio.outputSampleRateHz)===`overflow`&&(this.playbackOverflowed=!0,this.cancelOutput(`playback-overflow`,!1))}stopOutput(e={}){this.outputQueue.stop(this.outputContext),this.speechFramesDuringPlayback=0,(e.releaseDelayedToolResults??!0)&&this.flushDelayedToolResults()}scheduleMarkAck(e){let t=this.outputPlaybackDelayMs();if(t>0){let n=window.setTimeout(()=>{this.markAckTimers.delete(n),this.scheduleMarkAck(e)},t);this.markAckTimers.add(n);return}this.closed||this.ctx.client.request(`talk.session.acknowledgeMark`,{sessionId:this.session.relaySessionId,markName:e}).catch(e=>this.reportToolResultSubmissionError(e))}async handleToolCall(e){let t=e.callId?.trim(),n=e.name?.trim();if(!t||!n)return;if(n===`openclaw_agent_control`){let n=this.startToolExecution(t);try{await Zd({ctx:this.ctx,callId:t,args:e.args??{},sessionId:this.session.relaySessionId,signal:n.signal,submit:(e,t)=>this.submitToolResult(e,t)})}finally{this.finishToolExecution(t,n)}return}if(n!==`openclaw_agent_consult`){await this.submitToolResult(t,{error:`Tool "${n}" not available in browser Talk`});return}let r=this.startToolExecution(t);try{if(e.forced){if(await this.submitToolResult(t,{status:`working`,tool:mr,message:`Tell the person briefly that you are checking, then wait for the final OpenClaw result before answering with the actual result.`},{willContinue:!0}),this.completedToolCalls.has(t))return;if(r.signal.aborted){await this.submitToolResult(t,{status:`cancelled`});return}}await $d({ctx:this.ctx,callId:t,args:e.args??{},relaySessionId:this.session.relaySessionId,signal:r.signal,submit:(e,t)=>this.submitToolResult(e,t)})}finally{this.finishToolExecution(t,r)}}async submitToolResult(e,t,n){if(this.completedToolCalls.has(e))return;let r=n?.suppressResponse!==!0&&n?.willContinue!==!0;if(!this.closed&&r&&(this.pendingOutputCancellations>0||this.outputPlaybackDelayMs()>0)){this.scheduleDelayedToolResult({callId:e,result:t,...n?{options:n}:{}});return}await this.sendToolResultNow(e,t,n)}async sendToolResultNow(e,t,n){if(!this.completedToolCalls.has(e)){this.submittingToolCalls.add(e);try{await this.ctx.client.request(`talk.session.submitToolResult`,{sessionId:this.session.relaySessionId,callId:e,result:t,...n?{options:n}:{}})}finally{this.submittingToolCalls.delete(e)}}}outputPlaybackDelayMs(){return this.outputContext?Math.max(0,Math.ceil((this.outputQueue.queuedUntil-this.outputContext.currentTime)*1e3)):0}scheduleDelayedToolResult(e){this.delayedToolResults.add(e),this.rescheduleDelayedToolResult(e)}rescheduleDelayedToolResult(e){if(this.closed){this.discardDelayedToolResult(e);return}if(this.pendingOutputCancellations>0)return;let t=this.outputPlaybackDelayMs();if(t>0){e.timer=window.setTimeout(()=>{e.timer=void 0,this.rescheduleDelayedToolResult(e)},t);return}this.discardDelayedToolResult(e),this.sendToolResultNow(e.callId,e.result,e.options).catch(e=>{this.reportToolResultSubmissionError(e)})}flushDelayedToolResults(){for(let e of this.delayedToolResults)this.discardDelayedToolResult(e),this.closed||this.sendToolResultNow(e.callId,e.result,e.options).catch(e=>{this.reportToolResultSubmissionError(e)})}pauseDelayedToolResults(){for(let e of this.delayedToolResults)e.timer!==void 0&&(window.clearTimeout(e.timer),e.timer=void 0)}discardDelayedToolResults(){for(let e of this.delayedToolResults)this.discardDelayedToolResult(e)}discardDelayedToolResult(e){e.timer!==void 0&&(window.clearTimeout(e.timer),e.timer=void 0),this.delayedToolResults.delete(e)}reportToolResultSubmissionError(e){if(this.closed)return;let t=C(e);this.lastRelayError=t,this.ctx.callbacks.onStatus?.(`error`,t)}completeToolCall(e){let t=e?.trim();t&&(this.completedToolCalls.add(t),!this.submittingToolCalls.has(t)&&(this.toolAbortControllers.get(t)?.abort(),this.toolAbortControllers.delete(t)))}cancelToolCall(e){let t=e?.trim();if(t){this.completedToolCalls.add(t),this.toolAbortControllers.get(t)?.abort(),this.toolAbortControllers.delete(t);for(let e of this.delayedToolResults)e.callId===t&&this.discardDelayedToolResult(e)}}startToolExecution(e){let t=new AbortController;return this.toolAbortControllers.set(e,t),t}finishToolExecution(e,t){this.toolAbortControllers.get(e)===t&&this.toolAbortControllers.delete(e)}isFinalToolResult(e){let t=e.talkEvent;return!(t?.type===`tool.progress`||t?.type===`tool.result`&&t.final===!1)}cancelOutputForBargeIn(){this.cancelOutput(`barge-in`)}cancelOutput(e,t=!0){if(t&&!this.outputQueue.isPlaying||this.cancelRequestedForPlayback)return;let n=this.activeOutputTurnId;if(!n){this.ctx.callbacks.onStatus?.(`error`,O(`chat.composer.realtimeTalkMissingTurnIdentity`)),this.stop();return}this.cancelRequestedForPlayback=!0,this.pendingOutputCancellations+=1,this.pauseDelayedToolResults(),this.stopOutput({releaseDelayedToolResults:!1}),this.ctx.client.request(`talk.session.cancelOutput`,{sessionId:this.session.relaySessionId,reason:e,turnId:n}).then(e=>{if(!bt(e)||(e.status===void 0||e.status===`applied`)&&e.turnId!==void 0&&e.turnId!==n)throw Error(O(`chat.composer.realtimeTalkCancellationRejected`));--this.pendingOutputCancellations,this.pendingOutputCancellations===0&&this.flushDelayedToolResults()}).catch(e=>{--this.pendingOutputCancellations,this.reportToolResultSubmissionError(e),this.stop()})}abortConsults(){for(let e of this.toolAbortControllers.values())e.abort();this.toolAbortControllers.clear()}detectBargeInSpeech(e){if(!this.outputQueue.isPlaying||this.cancelRequestedForPlayback)return this.speechFramesDuringPlayback=0,!1;let t=Nd(e);return t.rms>=af&&t.peak>=of?this.speechFramesDuringPlayback+=1:this.speechFramesDuringPlayback=0,this.speechFramesDuringPlayback>=sf}}})))()}var hf;function gf(){return(gf=e((()=>{hf=class{constructor(e){this.options=e,this.stream=null,this.video=null,this.setupController=null,this.handleTrackEnded=()=>this.release()}async setEnabled(e){if(!e){this.release();return}if(this.options.isClosed())throw Error(`Realtime Talk session is closed`);if(this.hasLiveTrack())return;this.setupController?.abort();let t=new AbortController;this.setupController=t;let n;try{n=await this.options.acquire(this.options.getDeviceId(),t.signal)}catch(e){if(this.options.isClosed()||t.signal.aborted)return;throw e}finally{this.setupController===t&&(this.setupController=null)}if(this.options.isClosed()||t.signal.aborted){n.getTracks().forEach(e=>e.stop());return}this.stream=n,n.getVideoTracks().forEach(e=>e.addEventListener(`ended`,this.handleTrackEnded,{once:!0}));let r=document.createElement(`video`);r.autoplay=!0,r.muted=!0,r.playsInline=!0,r.srcObject=n,this.video=r,this.options.onStream(n),r.play().catch(()=>void 0),this.options.onAcquired?.()}async switchDevice(e){let t=e?.trim()||void 0,n=this.stream?.getVideoTracks()[0]?.getSettings?.().deviceId?.trim()||this.options.getDeviceId(),r=this.stream!==null||this.setupController!==null;if(this.options.setDeviceId(t),r){this.release();try{await this.setEnabled(!0)}catch(e){if(!this.options.isClosed()&&n!==t){this.options.setDeviceId(n);try{await this.setEnabled(!0)}catch{}}throw e}}}hasLiveTrack(){return this.stream?.getVideoTracks().some(e=>e.readyState===`live`)===!0}hasUsableTrack(){return this.stream?.getVideoTracks().some(e=>e.readyState===`live`&&e.enabled&&!e.muted)===!0}release(){this.setupController?.abort(),this.setupController=null,this.options.onReleased?.(),this.stream?.getVideoTracks().forEach(e=>{e.removeEventListener(`ended`,this.handleTrackEnded),e.stop()}),this.stream=null,this.video&&=(this.video.srcObject=null,null),this.options.onStream(null)}hostDisconnected(){this.release()}}})))()}function _f(e){let t;try{t=new URL(e.websocketUrl)}catch{throw Error(`Invalid Google Live WebSocket URL`)}if(t.protocol!==`wss:`)throw Error(`Google Live WebSocket URL must use wss://`);if(t.hostname.toLowerCase()!==yf)throw Error(`Untrusted Google Live WebSocket host`);if(t.username||t.password)throw Error(`Google Live WebSocket URL must not include credentials`);if(!bf.test(t.pathname))throw Error(`Untrusted Google Live WebSocket path`);return t.search=``,t.searchParams.set(`access_token`,e.clientSecret),t.toString()}function vf(e){let t;for(let n of e)try{n()}catch(e){t??=e instanceof Error?e:Error(`Realtime Talk cleanup failed`,{cause:e})}if(t)throw t}var yf,bf,xf,Sf;function Cf(){return(Cf=e((()=>{yf=`generativelanguage.googleapis.com`,bf=/^\/ws\/google\.ai\.generativelanguage\.v[0-9a-z]+\.GenerativeService\.BidiGenerateContent(?:Constrained)?$/,xf=3e4,Sf=class{constructor(){this.state=`idle`,this.socket=null,this.waiter=null,this.error=null}get currentState(){return this.state}get isActive(){return this.state===`active`}get setupComplete(){return this.state===`ready`||this.state===`active`}begin(e){return this.state=`connecting`,this.socket=e,this.error=null,new Promise((e,t)=>{this.waiter={resolve:e,reject:t}})}markReady(e){return this.state!==`connecting`||this.socket!==e?!1:(this.state=`ready`,this.takeWaiter()?.resolve(`ready`),!0)}finishStart(e){if(this.error)throw this.error;return this.state===`cancelled`?`cancelled`:e}activate(){if(this.state===`active`)return!1;if(this.error)throw this.error;if(this.state===`cancelled`||this.state===`idle`)return!1;if(this.state!==`ready`)throw Error(`Google Live transport activated before setup completed`);return this.state=`active`,!0}failStartup(e,t){return this.socket!==e||this.state!==`connecting`&&this.state!==`ready`?!1:(this.state=`failed`,this.error=t,this.takeWaiter()?.reject(t),!0)}cancel(){this.state!==`cancelled`&&this.state!==`failed`&&(this.state=`cancelled`,this.takeWaiter()?.resolve(`cancelled`))}takeWaiter(){let e=this.waiter;return this.waiter=null,e}}})))()}var wf,Tf,Ef;function Df(){return(Df=e((()=>{cr(),T(),nf(),wf=1024,Tf=1024,Ef=class{constructor(e){this.options=e,this.pendingCalls=new Map,this.seenCallIds=new Set,this.abortControllers=new Map}release(){let e=[...this.abortControllers.values()];this.abortControllers.clear(),this.pendingCalls.clear(),this.seenCallIds.clear();for(let t of e)t.abort()}hasPendingConsult(){for(let e of this.pendingCalls.values())if(!e.cancelled&&e.name===`openclaw_agent_consult`)return!0;return!1}async handleCall(e){if(this.options.isClosed())return;let t=e.name?.trim(),n=e.id?.trim();if(!(!t||!n||this.seenCallIds.has(n))){if(this.seenCallIds.size>=Tf){this.options.failConnection(`Google Live tool-call session limit exceeded`);return}if(this.pendingCalls.size>=wf){this.options.failConnection(`Google Live pending tool-call limit exceeded`);return}if(this.seenCallIds.add(n),this.pendingCalls.set(n,{name:t,cancelled:!1}),!this.isSupportedTool(t)){let e=`Tool "${t}" is not available in browser Talk`;if(!this.submitResult(n,{error:e}))return;this.options.emitTalkEvent({type:`tool.error`,callId:n,final:!0,payload:{name:t,message:e}});return}if(this.options.emitTalkEvent({type:`tool.call`,callId:n,payload:{name:t,args:e.args??{}}}),t===`openclaw_agent_control`){await this.runControl(n,e.args);return}if(t===`describe_view`){this.submitDescribeView(n);return}await this.runConsult(n,e.args)}}cancel(e){for(let t of e??[]){let e=t.trim(),n=this.pendingCalls.get(e);if(!e||!n||n.cancelled)continue;n.cancelled=!0;let r=this.abortControllers.get(e);r?r.abort():this.pendingCalls.delete(e)}}isSupportedTool(e){return e===`openclaw_agent_control`||e===`describe_view`||e===`openclaw_agent_consult`}async runControl(e,t){let n=this.startExecution(e);try{await Zd({ctx:this.createActiveContext(),callId:e,args:t??{},signal:n.signal,emitTalkEvent:this.options.emitTalkEvent,submit:(e,t)=>{this.submitResult(e,t)}})}finally{this.finishExecution(e,n)}}submitDescribeView(e){let t=this.options.isDescribeViewActive();this.submitResult(e,t?{ok:!0,cameraStreamActive:!0}:{ok:!1,error:`camera is off`})&&this.options.emitTalkEvent({type:t?`tool.result`:`tool.error`,callId:e,final:!0,payload:{name:lr,cameraStreamActive:t}})}async runConsult(e,t){let n=this.startExecution(e);try{await $d({ctx:this.createActiveContext(),callId:e,args:t??{},signal:n.signal,submitAbortResult:!1,emitTalkEvent:this.options.emitTalkEvent,submit:(e,t)=>{this.submitResult(e,t)}})}finally{this.finishExecution(e,n)}}createActiveContext(){let{ctx:e}=this.options;return{...e,callbacks:{onStatus:(t,n)=>{this.options.isClosed()||e.callbacks.onStatus?.(t,n)},onTranscript:t=>{this.options.isClosed()||e.callbacks.onTranscript?.(t)},onTalkEvent:t=>{this.options.isClosed()||e.callbacks.onTalkEvent?.(t)}}}}submitResult(e,t){let n=this.pendingCalls.get(e);if(!n||n.cancelled)return!1;try{this.options.sendResult(e,n.name,t)}catch(e){return this.options.failConnection(C(e)),!1}return this.pendingCalls.delete(e),!0}startExecution(e){let t=new AbortController;return this.abortControllers.set(e,t),t}finishExecution(e,t){this.abortControllers.get(e)===t&&this.abortControllers.delete(e);let n=this.pendingCalls.get(e);n?.cancelled&&(this.pendingCalls.delete(e),n.name===`openclaw_agent_consult`&&!this.options.isClosed()&&!this.hasPendingConsult()&&this.options.ctx.callbacks.onStatus?.(`listening`))}}})))()}async function Of(e,t,n){if(!e?.srcObject)throw Error(`Camera preview is unavailable`);if(e.readyState{let r,i=i=>{r!==void 0&&(globalThis.clearTimeout(r),r=void 0,e.removeEventListener(`loadeddata`,a),i?n(i):t())},a=()=>i();r=globalThis.setTimeout(()=>i(Error(`Camera preview did not become ready`)),5e3),e.addEventListener(`loadeddata`,a),e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&i()})}var Af;function jf(){return(jf=e((()=>{Af=8})))()}function Mf(e){return{realtimeInput:{video:e}}}function Nf(e){if(!e)return!0;let t=e.startsWith(`models/`)?e.slice(7):e;return t.startsWith(`gemini-3.1-`)&&t.includes(`-live`)}async function Pf(e){let t=e;return typeof t==`string`?t:(typeof Blob<`u`&&t instanceof Blob&&(t=await t.arrayBuffer()),Ff(t)?new TextDecoder().decode(new Uint8Array(t)):ArrayBuffer.isView(t)?new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):String(t))}function Ff(e){return e instanceof ArrayBuffer||Object.prototype.toString.call(e)===`[object ArrayBuffer]`}var If,Lf,Rf,zf,Bf;function Vf(){return(Vf=e((()=>{T(),Hd(),gf(),Cf(),Df(),Ed(),nf(),jf(),If=1e3,Lf=524288,Rf=262144,zf=new TextEncoder,Bf=class{constructor(e,t){this.session=e,this.ctx=t,this.ws=null,this.setupTimeout=null,this.input=new Td(e=>{let t=this.ws;t&&this.failConnection(t,e)}),this.inputContext=null,this.outputContext=null,this.inputMeter=null,this.inputPump=new Id,this.closed=!1,this.lifecycle=new Sf,this.cameraPublished=!1,this.videoFramesActive=!1,this.hasSentVideoFrame=!1,this.videoFrameTimer=null,this.outputQueue=new Vd,this.pendingTranscripts={user:{text:``,byteCount:0},assistant:{text:``,byteCount:0}},this.emitTalkEvent=Ud(t,e),this.toolOwner=new Ef({ctx:t,emitTalkEvent:this.emitTalkEvent,isClosed:()=>this.closed,failConnection:e=>{let t=this.ws;t&&this.failConnection(t,e)},isDescribeViewActive:()=>this.videoFramesActive&&this.hasSentVideoFrame&&this.camera.hasUsableTrack(),sendResult:(e,t,n)=>this.sendToolResult(e,t,n),sendControlSpeechMessage:e=>this.sendControlSpeechMessage(e),stopOutputForSuppressedControl:e=>this.stopOutputForSuppressedControl(e)}),this.camera=new hf({acquire:(e,t)=>Sd(e,{signal:t}),getDeviceId:()=>this.ctx.videoDeviceId,setDeviceId:e=>this.ctx.videoDeviceId=e,isClosed:()=>this.closed,onStream:e=>{if(e){if(!this.lifecycle.isActive)return;this.cameraPublished=!0,this.ctx.callbacks.onVideoStream?.(e)}else this.cameraPublished&&(this.cameraPublished=!1,this.ctx.callbacks.onVideoStream?.(null))},onAcquired:()=>{this.lifecycle.isActive&&this.startVideoFrames()},onReleased:()=>this.stopVideoFrames()})}async start(){if(!navigator.mediaDevices?.getUserMedia||typeof WebSocket>`u`)throw Error(`Realtime Talk requires browser WebSocket and microphone access`);if(this.session.protocol!==`google-live-bidi`)throw Error(`Unsupported realtime WebSocket protocol: ${this.session.protocol}`);let e=_f(this.session);this.closed=!1,this.cameraPublished=!1;try{await this.input.open(this.ctx.inputDeviceId)}catch(e){if(this.closed)return`cancelled`;throw e}if(this.closed)return`cancelled`;this.inputContext=new AudioContext({sampleRate:this.session.audio.inputSampleRateHz}),this.outputContext=new AudioContext({sampleRate:this.session.audio.outputSampleRateHz});let t=new WebSocket(e);this.ws=t,t.binaryType=`arraybuffer`;let n=this.lifecycle.begin(t);return this.setupTimeout=globalThis.setTimeout(()=>{this.closed||this.ws!==t||(this.setupTimeout=null,this.failConnection(t,`Realtime connection timed out after ${xf}ms`))},xf),t.addEventListener(`open`,()=>{this.closed||this.ws!==t||this.send(this.session.initialMessage??{setup:{}})}),t.addEventListener(`message`,e=>{this.handleMessage(t,e.data)}),t.addEventListener(`close`,()=>{this.failConnection(t,`Realtime connection closed`)}),t.addEventListener(`error`,()=>{this.failConnection(t,`Realtime connection failed`)}),this.lifecycle.finishStart(await n)}activate(){if(!(this.closed||!this.lifecycle.activate()))try{if(this.ctx.callbacks.onStatus?.(`listening`),this.assertActivationCurrent(),this.emitTalkEvent({type:`session.ready`}),this.assertActivationCurrent(),this.ctx.callbacks.onInputLevel&&this.input.stream&&this.inputContext){let e=new Rd(this.ctx.callbacks.onInputLevel);this.inputMeter=e,e.start(this.input.stream,this.inputContext),this.assertActivationCurrent()}this.startMicrophonePump(),this.camera.stream&&!this.cameraPublished&&(this.cameraPublished=!0,this.ctx.callbacks.onVideoStream?.(this.camera.stream)),this.assertActivationCurrent(),this.startVideoFrames()}catch(e){try{this.stop({emitClosed:!1})}catch{}throw e}}assertActivationCurrent(){if(this.closed||!this.lifecycle.isActive)throw Error(`Google Live transport activation cancelled`)}async setVideoEnabled(e){await this.camera.setEnabled(e)}async switchCamera(e){await this.camera.switchDevice(e)}stop(e){let t=!this.closed&&this.lifecycle.isActive&&e?.emitClosed!==!1;this.closed=!0,this.lifecycle.cancel(),vf([()=>{t&&this.emitTalkEvent({type:`session.closed`,final:!0})},()=>this.releaseResources()])}releaseResources(){this.clearSetupTimeout(),this.pendingTranscripts.user={text:``,byteCount:0},this.pendingTranscripts.assistant={text:``,byteCount:0};let e=this.inputMeter;this.inputMeter=null;let t=this.inputContext;this.inputContext=null;let n=this.outputContext;this.outputContext=null;let r=this.ws;this.ws=null,vf([()=>this.input.stop(),()=>this.toolOwner.release(),()=>this.inputPump.stop(),()=>e?.stop(),()=>this.camera.release(),()=>this.stopOutput(),()=>{t?.close()},()=>{n?.close()},()=>r?.close()])}clearSetupTimeout(){this.setupTimeout!==null&&(globalThis.clearTimeout(this.setupTimeout),this.setupTimeout=null)}failConnection(e,t){if(!(this.closed||this.ws!==e)){if(this.lifecycle.failStartup(e,Error(t))){try{this.stop({emitClosed:!1})}catch{}return}try{this.ctx.callbacks.onStatus?.(`error`,t)}finally{this.stop()}}}startMicrophonePump(){this.closed||!this.input.stream||!this.inputContext||this.inputPump.start(this.input.stream,this.inputContext,e=>{if(this.ws?.readyState!==WebSocket.OPEN)return;let t=jd(e);this.send({realtimeInput:{audio:{data:kd(t),mimeType:`audio/pcm;rate=${this.inputContext?.sampleRate??16e3}`}}})})}send(e){return!this.closed&&this.ws?.readyState===WebSocket.OPEN&&(this.ws.send(JSON.stringify(e)),!0)}async handleMessage(e,t){if(this.closed||this.ws!==e)return;let n;try{n=JSON.parse(await Pf(t))}catch{return}if(this.closed||this.ws!==e||(n.setupComplete&&this.lifecycle.markReady(e)&&this.clearSetupTimeout(),!this.lifecycle.isActive))return;let r=n.serverContent;if(r?.interrupted&&this.stopOutput(),!(r?.inputTranscription&&!this.appendTranscript(`user`,r.inputTranscription))&&!(r?.outputTranscription&&!this.appendTranscript(`assistant`,r.outputTranscription))){for(let e of r?.modelTurn?.parts??[])if(e.inlineData?.data&&(this.emitTalkEvent({type:`output.audio.delta`,payload:{byteLength:Fd(e.inlineData.data),mimeType:e.inlineData.mimeType}}),this.closed||(this.playPcm16(e.inlineData.data),this.closed)))return;if(!((r?.generationComplete||r?.interrupted||r?.turnComplete)&&!this.flushTranscript(`assistant`))&&(r?.interrupted?this.emitTalkEvent({type:`turn.cancelled`,final:!0,payload:{reason:`provider-interrupted`}}):r?.turnComplete&&this.emitTalkEvent({type:`turn.ended`,final:!0}),!this.closed)){for(let e of n.toolCall?.functionCalls??[])this.toolOwner.handleCall(e).catch(e=>{this.reportToolResultSubmissionError(e)});this.toolOwner.cancel(n.toolCallCancellation?.ids)}}}appendTranscript(e,t){let n=this.pendingTranscripts[e],r=e===`user`&&Nf(this.session.model);if(t.text){if(n.byteCount+=zf.encode(t.text).byteLength,n.byteCount>Rf)return this.ws&&this.failConnection(this.ws,`Google Live transcript exceeded the 256 KiB UTF-8 pending buffer limit`),!1;if(n.text+=t.text,!r&&!this.emitTranscript(e,t.text,!1))return!1}return t.finished||r?this.flushTranscript(e):!this.closed}flushTranscript(e){let t=this.pendingTranscripts[e].text.trim();return this.pendingTranscripts[e]={text:``,byteCount:0},t?this.emitTranscript(e,t,!0):!this.closed}emitTranscript(e,t,n){return this.ctx.callbacks.onTranscript?.({role:e,text:t,final:n}),!this.closed&&(this.emitTalkEvent({type:e===`user`?n?`transcript.done`:`transcript.delta`:n?`output.text.done`:`output.text.delta`,final:n,payload:e===`user`?{role:e,text:t}:{text:t}}),!this.closed&&e===`user`&&n&&this.toolOwner.hasPendingConsult()&&nr(t)&&Xd({ctx:this.ctx,text:t,emitTalkEvent:this.emitTalkEvent,onControlResult:e=>this.stopOutputForSuppressedControl(e),speakControlResult:e=>this.sendControlSpeechMessage(e),suppressSpeechForModes:[`cancel`]}),!this.closed)}playPcm16(e){this.closed||this.outputQueue.play(e,this.outputContext,this.session.audio.outputSampleRateHz)===`overflow`&&(this.stopOutput(),this.emitTalkEvent({type:`turn.cancelled`,final:!0,payload:{reason:`playback-overflow`}}),this.ctx.callbacks.onStatus?.(`error`,`Realtime Talk playback exceeded the browser audio buffer limit`),this.stop())}stopOutput(){this.outputQueue.stop(this.outputContext)}sendToolResult(e,t,n){if(!this.send({toolResponse:{functionResponses:[{id:e,name:t,...Nf(this.session.model)?{}:{scheduling:`WHEN_IDLE`},response:n&&typeof n==`object`&&!Array.isArray(n)?n:{output:n}}]}}))throw Error(`Google Live socket is not open`)}reportToolResultSubmissionError(e){if(this.closed)return;let t=C(e);this.ctx.callbacks.onStatus?.(`error`,t)}startVideoFrames(){!this.camera.video||this.videoFramesActive||this.closed||(this.videoFramesActive=!0,this.scheduleVideoFrame(0))}scheduleVideoFrame(e){!this.videoFramesActive||this.closed||(this.videoFrameTimer=globalThis.setTimeout(()=>{this.videoFrameTimer=null,this.sendVideoFrame()},e))}async sendVideoFrame(){if(!this.camera.hasLiveTrack()){this.stopVideoFrames();return}if(!this.camera.hasUsableTrack()){this.scheduleVideoFrame(If);return}try{let e=await Of(this.camera.video,Lf,Mf);if(!this.videoFramesActive||this.closed)return;if(!this.send(Mf(e)))throw Error(`Google Live socket is not open`);this.hasSentVideoFrame=!0}catch(e){this.closed||(this.videoFramesActive=!1,this.reportToolResultSubmissionError(e));return}this.scheduleVideoFrame(If)}stopVideoFrames(){this.videoFramesActive=!1,this.hasSentVideoFrame=!1,this.videoFrameTimer!==null&&(globalThis.clearTimeout(this.videoFrameTimer),this.videoFrameTimer=null)}sendControlSpeechMessage(e){if(this.stopOutput(),!Nf(this.session.model)){this.send({clientContent:{turns:[{role:`user`,parts:[{text:e}]}],turnComplete:!0}});return}this.send({realtimeInput:{text:e}})}stopOutputForSuppressedControl(e){if(!e||typeof e!=`object`)return;let t=e;t.ok===!0&&(t.mode===`cancel`||t.suppress===!0&&t.mode!==`steer`)&&this.stopOutput()}}})))()}function Hf(e,t){let n=Zf.get(e);n||(n=new Map,Zf.set(e,n));let r=n.get(t)??0,i=[...n.values()].reduce((e,t)=>e+t,0);if(r>=qf||i>=Jf)throw Error(`Too many active or closing realtime Talk voice sessions`);n.set(t,r+1);let a=n,o=new AbortController,s=new AbortController,c=!1,l,u,d=()=>{if(c)return;c=!0,l!==void 0&&(clearTimeout(l),l=void 0),u!==void 0&&(clearTimeout(u),u=void 0);let e=(a.get(t)??1)-1;e>0?a.set(t,e):a.delete(t)};return{signal:o.signal,closeSignal:s.signal,beginDrain:()=>{c||l!==void 0||u!==void 0||(l=setTimeout(()=>{o.abort()},Yf),u=setTimeout(()=>{o.abort(),s.abort(),d()},Xf))},release:d}}function Uf(e){if(e.nextTransport?.stop({emitClosed:!1}),!e.reusesExistingOwner){if(e.transport===`gateway-relay`&&e.nextTransport){e.owner.release();return}e.closeVoiceSession()}}function Wf(){let e=Error(`voice transcript persistence aborted`);return e.name=`AbortError`,e}async function Gf(e,t){if(t.aborted)throw Wf();e<=0||await new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(Wf())};t.addEventListener(`abort`,a,{once:!0})})}async function Kf(e,t,n){let r;for(let n of[0,500,2e3]){if(n>0)await Gf(n,e);else if(e.aborted)throw Wf();try{await t();return}catch(t){if(e.aborted)throw Wf();r=t}}throw r instanceof Error?r:Error(n,{cause:r})}var qf,Jf,Yf,Xf,Zf;function Qf(){return(Qf=e((()=>{ee(),qf=2,Jf=16,Yf=h,Xf=Yf+h,Zf=new WeakMap})))()}function $f(e,t){let n=e??ip;try{return new URL(n).toString()}catch{}let r=new URL(t,window.location.href);return r.protocol===`ws:`?r.protocol=`http:`:r.protocol===`wss:`&&(r.protocol=`https:`),r.pathname=`/`,r.search=``,r.hash=``,new URL(n,r).toString()}function ep(e){let t=e?.sctp?.maxMessageSize;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:rp}function tp(e){return{type:`conversation.item.create`,item:{type:`message`,role:`user`,content:[{type:`input_image`,image_url:`data:${e.mimeType};base64,${e.data}`}]}}}var np,rp,ip,ap,op;function sp(){return(sp=e((()=>{ir(),np=3e4,rp=65536,ip=`https://api.openai.com/v1/realtime/calls`,ap=class{constructor(e){this.maxSettledResponses=e,this.unkeyedSettled=!1,this.settledResponseIds=new Set}start(e){this.activeResponseId=e,this.unkeyedSettled=!1}finish(e){let t=e.type===`response.cancelled`?{status:`cancelled`,...e.response?.id?{responseId:e.response.id}:{}}:ar({providerLabel:`OpenAI realtime voice`,response:e.response});if(t.responseId&&this.settledResponseIds.has(t.responseId)||!t.responseId&&this.unkeyedSettled||t.responseId&&this.activeResponseId!==void 0&&t.responseId!==this.activeResponseId)return;let n=t.responseId!==void 0&&this.settledResponseIds.size>=this.maxSettledResponses;return t.responseId&&!n?this.settledResponseIds.add(t.responseId):t.responseId||(this.unkeyedSettled=!0),this.activeResponseId=void 0,{outcome:t,overflow:n}}reset(){this.activeResponseId=void 0,this.unkeyedSettled=!1,this.settledResponseIds.clear()}},op=class{constructor(){this.pendingRequest=null}async readAnswer(e){let t=this.beginRequest();try{let n;try{n=await fetch($f(e.session.offerUrl,e.gatewayUrl),{method:`POST`,body:e.offer.sdp,headers:{...e.session.offerHeaders,Authorization:`Bearer ${e.session.clientSecret}`,"Content-Type":`application/sdp`},signal:t.controller.signal})}catch(t){if(!e.isCurrent())return;throw t}if(!e.isCurrent()){n.body?.cancel().catch(()=>void 0);return}if(!n.ok)throw n.body?.cancel().catch(()=>void 0),Error(`Realtime WebRTC setup failed (${n.status})`);let r;try{let t=e.session.offerResponseMaxBytes;r=t===void 0?await n.text():await Kt(n,{maxBytes:t,tooLargeMessage:`Realtime WebRTC SDP answer: text response exceeds ${t} bytes`})}catch(t){if(!e.isCurrent())return;throw t}return e.isCurrent()?r:void 0}finally{this.finishRequest(t)}}abort(){let e=this.pendingRequest;e&&(this.pendingRequest=null,globalThis.clearTimeout(e.timeout),e.controller.abort())}beginRequest(){this.abort();let e=new AbortController,t={controller:e,timeout:globalThis.setTimeout(()=>{e.abort(Error(`Realtime WebRTC offer request timed out after ${np}ms`))},np)};return this.pendingRequest=t,t}finishRequest(e){globalThis.clearTimeout(e.timeout),this.pendingRequest===e&&(this.pendingRequest=null)}}})))()}var cp,lp,up,dp,fp;function pp(){return(pp=e((()=>{cr(),T(),Hd(),gf(),Ed(),nf(),jf(),sp(),cp=256e3,lp=1024,up=new TextEncoder,dp=Symbol(`cancelledSetup`),fp=class{constructor(e,t){this.session=e,this.ctx=t,this.peer=null,this.channel=null,this.input=new Td(e=>this.failConnection(e)),this.audio=null,this.inputMeter=null,this.closed=!1,this.responseActive=!1,this.responseCreateInFlight=!1,this.responseCreatePending=!1,this.responseOutcomes=new ap(lp),this.completedToolCallIds=new Set,this.offerExchange=new op,this.consultAbortControllers=new Set,this.starting=!1,this.startupError=null,this.emitTalkEvent=Ud(t,e),this.camera=new hf({acquire:(e,t)=>Sd(e,{signal:t}),getDeviceId:()=>this.ctx.videoDeviceId,setDeviceId:e=>this.ctx.videoDeviceId=e,isClosed:()=>this.closed,onStream:e=>this.ctx.callbacks.onVideoStream?.(e)})}async start(){if(!navigator.mediaDevices?.getUserMedia||typeof RTCPeerConnection>`u`)throw Error(`Realtime Talk requires browser WebRTC and microphone access`);this.closed=!1,this.starting=!0,this.startupError=null;let e=new RTCPeerConnection;this.peer=e,this.audio=document.createElement(`audio`),this.audio.autoplay=!0,this.audio.muted=!1,this.audio.setAttribute(`playsinline`,``),this.audio.style.display=`none`,document.body.append(this.audio),e.addEventListener(`track`,e=>{let t=e.streams[0];if(this.audio&&t){this.audio.srcObject=t;let n=this.audio,r=e=>{this.audio!==n||this.closed||n.play().catch(t=>{e&&this.audio===n&&!this.closed&&this.ctx.callbacks.onStatus?.(`error`,`Realtime audio playback failed: ${C(t)}`)})};r(!e.track.muted),e.track.addEventListener(`unmute`,()=>r(!0),{once:!0})}});let t=await this.awaitSetupStep(e,this.input.open(this.ctx.inputDeviceId));if(t===dp||!this.isCurrentPeer(e))return this.cancelledStart();this.ctx.callbacks.onInputLevel&&(this.inputMeter=new Rd(this.ctx.callbacks.onInputLevel),this.inputMeter.start(t));for(let n of t.getAudioTracks())e.addTrack(n,t);let n=e.createDataChannel(`oai-events`);if(!this.isCurrentPeer(e))return n.close(),this.cancelledStart();this.channel=n,n.addEventListener(`open`,()=>{this.ctx.callbacks.onStatus?.(`listening`),this.emitTalkEvent({type:`session.ready`})}),n.addEventListener(`message`,e=>this.handleRealtimeEvent(e.data)),e.addEventListener(`connectionstatechange`,()=>{this.closed||(this.peer?.connectionState===`failed`||this.peer?.connectionState===`closed`)&&this.failConnection(`Realtime connection closed`)});let r=await this.awaitSetupStep(e,e.createOffer());if(r===dp||!this.isCurrentPeer(e)||await this.awaitSetupStep(e,e.setLocalDescription(r))===dp||!this.isCurrentPeer(e))return this.cancelledStart();let i=await this.offerExchange.readAnswer({session:this.session,offer:r,gatewayUrl:this.ctx.client.gatewayUrl,isCurrent:()=>this.isCurrentPeer(e)});return i===void 0||!this.isCurrentPeer(e)||await this.awaitSetupStep(e,e.setRemoteDescription({type:`answer`,sdp:i}))===dp||!this.isCurrentPeer(e)?this.cancelledStart():(this.starting=!1,`ready`)}async setVideoEnabled(e){await this.camera.setEnabled(e)}async switchCamera(e){await this.camera.switchDevice(e)}isCurrentPeer(e){return!this.closed&&this.peer===e}cancelledStart(){let e=this.currentStartupError();if(e)throw e;return`cancelled`}currentStartupError(){return this.startupError}async awaitSetupStep(e,t){try{return await t}catch(t){if(!this.isCurrentPeer(e))return dp;throw t}}stop(e){let t=!this.closed&&e?.emitClosed!==!1;this.closed=!0;try{t&&this.emitTalkEvent({type:`session.closed`,final:!0})}finally{this.releaseResources()}}releaseResources(){this.starting=!1,this.input.stop(),this.offerExchange.abort(),this.channel?.close(),this.channel=null,this.peer?.close(),this.peer=null,this.camera.release(),this.inputMeter?.stop(),this.inputMeter=null,this.audio?.remove(),this.audio=null;for(let e of this.consultAbortControllers)e.abort();this.consultAbortControllers.clear(),this.completedToolCallIds.clear(),this.responseOutcomes.reset(),this.responseActive=!1,this.responseCreateInFlight=!1,this.responseCreatePending=!1}failConnection(e){if(this.closed)return;let t=this.starting;try{t?this.startupError=Error(e):this.ctx.callbacks.onStatus?.(`error`,e)}finally{this.stop({emitClosed:!t})}}send(e){this.channel?.readyState===`open`&&this.channel.send(JSON.stringify(e))}handleRealtimeEvent(e){if(this.closed)return;let t;try{t=JSON.parse(String(e))}catch{return}switch(t.type){case`input_transcript.added`:this.emitFramelessTranscript(`user`,t.item?.text,!1,t.item?.id);return;case`output_transcript.added`:this.emitFramelessTranscript(`assistant`,t.item?.text,!1,t.item?.id);return;case`turn.done`:{let e=t.turn?.role;if(e===`user`||e===`assistant`){if(this.emitFramelessTranscript(e,t.turn?.transcript,!0,t.turn?.id),this.closed)return;e===`assistant`&&(this.ctx.callbacks.onStatus?.(`listening`),this.emitTalkEvent({type:`turn.ended`,final:!0,payload:{status:`completed`}}))}return}case`conversation.item.input_audio_transcription.completed`:if(t.transcript){if(this.ctx.callbacks.onTranscript?.({role:`user`,text:t.transcript,final:!0}),this.closed)return;this.emitTalkEvent({type:`transcript.done`,final:!0,itemId:t.item_id,payload:{role:`user`,text:t.transcript}}),this.consultAbortControllers.size>0&&nr(t.transcript)&&Xd({ctx:this.ctx,text:t.transcript,emitTalkEvent:this.emitTalkEvent,onControlResult:e=>this.interruptSuppressedControlResponse(e),speakControlResult:e=>this.sendControlSpeechMessage(e),suppressSpeechForModes:[`cancel`]})}return;case`conversation.output_transcript.delta`:case`response.output_text.delta`:case`response.audio_transcript.delta`:case`response.output_audio_transcript.delta`:this.emitAssistantTranscript(t,!1);return;case`response.output_text.done`:case`response.audio_transcript.done`:case`response.output_audio_transcript.done`:this.emitAssistantTranscript(t,!0);break;case`response.function_call_arguments.delta`:case`response.function_call_arguments.done`:break;case`input_audio_buffer.speech_started`:this.ctx.callbacks.onStatus?.(`listening`,`Speech detected`),this.emitTalkEvent({type:`turn.started`,payload:{source:t.type}});return;case`input_audio_buffer.speech_stopped`:this.ctx.callbacks.onStatus?.(`thinking`,`Processing speech`),this.emitTalkEvent({type:`input.audio.committed`,final:!0});return;case`response.created`:this.responseActive=!0,this.responseCreateInFlight=!1,this.responseOutcomes.start(t.response?.id),this.ctx.callbacks.onStatus?.(`thinking`,`Generating response`);return;case`response.cancelled`:case`response.done`:{let e=this.responseOutcomes.finish(t);if(!e)return;let{outcome:n}=e;try{if(n.status===`completed`&&(this.handleCompletedResponse(t),this.closed))return;n.status===`failed`||n.status===`incomplete`?(this.ctx.callbacks.onStatus?.(`error`,n.message),this.emitTalkEvent({type:`session.error`,final:!0,payload:n})):this.ctx.callbacks.onStatus?.(`listening`,n.status===`cancelled`?`Response cancelled`:void 0),this.emitTalkEvent({type:n.status===`cancelled`?`turn.cancelled`:`turn.ended`,final:!0,payload:n})}finally{e.overflow&&this.failConnection(`Realtime response session limit exceeded`),this.responseActive=!1,this.responseCreateInFlight=!1,this.flushPendingResponseCreate()}return}case`error`:this.responseCreateInFlight=!1,this.ctx.callbacks.onStatus?.(`error`,this.extractErrorDetail(t.error)),this.emitTalkEvent({type:`session.error`,final:!0,payload:{message:this.extractErrorDetail(t.error)}})}}emitAssistantTranscript(e,t){let n=t?e.transcript??e.text:e.delta;n&&(this.ctx.callbacks.onTranscript?.({role:`assistant`,text:n,final:t}),!this.closed&&this.emitTalkEvent({type:t?`output.text.done`:`output.text.delta`,final:t,itemId:e.item_id,payload:{text:n}}))}emitFramelessTranscript(e,t,n,r){if(!t||(this.ctx.callbacks.onTranscript?.({role:e,text:t,final:n}),this.closed))return;let i=e===`user`?n?`transcript.done`:`transcript.delta`:n?`output.text.done`:`output.text.delta`;this.emitTalkEvent({type:i,final:n,itemId:r,payload:{role:e,text:t}})}extractErrorDetail(e){if(!e||typeof e!=`object`)return`Realtime provider error`;let t=e,n=typeof t.message==`string`?t.message.trim():``,r=typeof t.code==`string`?t.code.trim():``,i=typeof t.type==`string`?t.type.trim():``;return n||r||i||`Realtime provider error`}handleCompletedResponse(e){let t=e.response;if(!(!ae(t)||t.status!==`completed`||!Array.isArray(t.output)))for(let e of t.output){if(!ae(e)||e.type!==`function_call`||e.status!==void 0&&e.status!==`completed`)continue;let t=typeof e.id==`string`&&e.id.trim()||void 0,n=typeof e.call_id==`string`?e.call_id.trim():``,r=typeof e.name==`string`?e.name.trim():``,i=typeof e.arguments==`string`?e.arguments:``;if(!(!n||!r||!i.trim())&&(r===`openclaw_agent_control`||r===`describe_view`||r===`openclaw_agent_consult`)&&!this.completedToolCallIds.has(n)){if(this.completedToolCallIds.size>=lp){this.failConnection(`Realtime tool-call session limit exceeded`);return}if(this.completedToolCallIds.add(n),up.encode(i).byteLength>cp){let e=`Realtime tool arguments exceed the 256000-byte UTF-8 limit`;this.submitToolResult(n,{error:e}),this.emitTalkEvent({type:`tool.error`,callId:n,itemId:t,final:!0,payload:{name:r,message:e}});continue}this.handleToolCall({itemId:t,callId:n,name:r,args:i}).catch(e=>{this.reportToolResultSubmissionError(e)})}}}async handleToolCall(e){let{itemId:t,callId:n,name:r,args:i}=e;if(r===`openclaw_agent_control`){await Zd({ctx:this.ctx,callId:n,args:i,emitTalkEvent:this.emitTalkEvent,submit:(e,t)=>this.submitToolResult(e,t)});return}if(r===`describe_view`){await this.handleDescribeViewToolCall(n,t);return}if(r!==`openclaw_agent_consult`)return;this.emitTalkEvent({type:`tool.call`,callId:n,itemId:t,payload:{name:r,args:i}});let a=new AbortController;this.consultAbortControllers.add(a);try{await $d({ctx:this.ctx,callId:n,args:i,signal:a.signal,emitTalkEvent:this.emitTalkEvent,submit:(e,t)=>this.submitToolResult(e,t)})}finally{this.consultAbortControllers.delete(a)}}async handleDescribeViewToolCall(e,t){if(this.emitTalkEvent({type:`tool.call`,callId:e,itemId:t,payload:{name:lr}}),!this.camera.hasLiveTrack()){this.submitToolResult(e,{ok:!1,error:`camera is off`}),this.emitTalkEvent({type:`tool.error`,callId:e,itemId:t,final:!0,payload:{name:lr,message:`camera is off`}});return}try{let n=await Of(this.camera.video,ep(this.peer),tp);this.send(tp(n)),this.submitToolResult(e,{ok:!0,frameAttached:!0}),this.emitTalkEvent({type:`tool.result`,callId:e,itemId:t,final:!0,payload:{name:lr,frameAttached:!0}})}catch(n){let r=C(n);this.submitToolResult(e,{ok:!1,error:r}),this.emitTalkEvent({type:`tool.error`,callId:e,itemId:t,final:!0,payload:{name:lr,message:r}})}}submitToolResult(e,t){this.closed||(this.send({type:`conversation.item.create`,item:{type:`function_call_output`,call_id:e,output:JSON.stringify(t)}}),this.requestResponseCreate())}reportToolResultSubmissionError(e){if(this.closed)return;let t=C(e);this.ctx.callbacks.onStatus?.(`error`,t)}sendControlSpeechMessage(e){this.responseActive&&this.send({type:`response.cancel`}),this.send({type:`conversation.item.create`,item:{type:`message`,role:`user`,content:[{type:`input_text`,text:e}]}}),this.requestResponseCreate()}interruptSuppressedControlResponse(e){if(!this.responseActive||!e||typeof e!=`object`)return;let t=e;t.ok===!0&&(t.mode===`cancel`||t.suppress===!0&&t.mode!==`steer`)&&this.send({type:`response.cancel`})}requestResponseCreate(){if(this.responseActive||this.responseCreateInFlight){this.responseCreatePending=!0;return}this.responseCreatePending=!1,this.responseCreateInFlight=!0,this.send({type:`response.create`})}flushPendingResponseCreate(){this.responseCreatePending&&(this.responseCreatePending=!1,this.requestResponseCreate())}}})))()}async function mp(e){let t=!1,n;if(await Promise.all([...Y].map(async r=>{try{await r.switchCameraIfEnabled(e)}catch(e){t=!0,n??=e}})),t)throw n}function hp(e){if(typeof e!=`string`)return;let t=Yn(e);if(t===`webrtc`||t===`provider-websocket`||t===`gateway-relay`||t===`managed-room`)return t}function gp(e,t){let n=_p(e);if(n===`webrtc`)return new fp(e,t);if(n===`provider-websocket`)return new Bf(e,t);if(n===`gateway-relay`)return new pf(e,t);let r=e.transport??`unknown`;throw Error(`Unsupported realtime Talk transport: ${r}`)}function _p(e){return Yn(e.transport)??`webrtc`}function vp(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}var Y,yp;function bp(){return(bp=e((()=>{ee(),Xn(),fr(),T(),mf(),Vf(),Qf(),pp(),Y=new Set,yp=class{constructor(e,t,n={},r={},i={}){this.client=e,this.sessionKey=t,this.callbacks=n,this.options=r,this.localOptions=i,this.transport=null,this.pendingTransport=null,this.closed=!1,this.lifecycleGeneration=0,this.videoEnabled=!1,this.videoOperation=0,this.transportGeneration=0,this.transcriptSeqByVoiceSessionId=new Map,this.acceptingTranscripts=!1,this.serverOwnedVoiceSession=!1,this.transcriptQueue=Jn.createQueue()}async start(){let e=Hf(this.client,this.sessionKey),t=!1;try{let n=++this.lifecycleGeneration;this.stopPendingTransport(),this.closed=!1,this.callbacks.onStatus?.(`connecting`);let r=this.transport,i=this.voiceSessionId,a=this.clientVoiceSessionOwner,o=this.acceptingTranscripts,s=this.serverOwnedVoiceSession,c=this.transportGeneration,l=await this.resolveVideoCapability();if(this.closed||n!==this.lifecycleGeneration)return;let u=[`voice-transcript`];l&&u.push(`camera-frame`);let d=await this.createSession({...this.options,capabilities:u}),f=_p(d);if(f===`managed-room`)throw Error(`Managed-room realtime Talk sessions are not available in this UI yet`);let p=d.voiceSessionId??(f===`gateway-relay`?d.relaySessionId:void 0);if(!p)throw Error(`Realtime Talk session did not return a voice session id`);if(this.closed||n!==this.lifecycleGeneration){this.closeUnadoptedVoiceSession(p,f,e),t=!0;return}if(a&&(f===`gateway-relay`||p!==i))throw this.closeUnadoptedVoiceSession(p,f,e),t=!0,Error(`Realtime Talk replacement changed the active voice session`);let m=a&&p===i?a:e;m!==e&&e.release();let h=n,g=f===`gateway-relay`?this.callbacks:this.clientOwnedTranscriptCallbacks(p,h,m.signal),_=this.transcriptQueue,v=null,y;try{v=gp(d,{client:this.client,sessionKey:this.sessionKey,voiceSessionId:p,flushTranscriptWrites:async()=>await _.flush(),callbacks:g,inputDeviceId:this.localOptions.inputDeviceId,videoDeviceId:this.localOptions.videoDeviceId,consultThinkingLevel:d.consultThinkingLevel,consultFastMode:d.consultFastMode}),this.pendingTransport=v,this.callbacks.onVideoCapability?.(l&&typeof v.setVideoEnabled==`function`),y=await v.start()}catch(e){throw this.pendingTransport===v&&(this.pendingTransport=null),Uf({nextTransport:v,transport:f,owner:m,reusesExistingOwner:!!(a&&m===a),closeVoiceSession:()=>this.closeUnadoptedVoiceSession(p,f,m)}),t=!0,e}if(this.pendingTransport===v&&(this.pendingTransport=null),y===`cancelled`||this.closed||n!==this.lifecycleGeneration){Uf({nextTransport:v,transport:f,owner:m,reusesExistingOwner:!!(a&&m===a),closeVoiceSession:()=>this.closeUnadoptedVoiceSession(p,f,m)}),t=!0;return}this.voiceSessionId=p,this.acceptingTranscripts=!0,this.serverOwnedVoiceSession=f===`gateway-relay`,this.transportGeneration=h,this.transport=v,this.serverOwnedVoiceSession?(e.release(),this.clientVoiceSessionOwner=void 0):this.clientVoiceSessionOwner=m;try{v.activate?.()}catch(e){throw!this.closed&&n===this.lifecycleGeneration&&this.transport===v?(this.voiceSessionId=i,this.acceptingTranscripts=o,this.serverOwnedVoiceSession=s,this.transportGeneration=c,this.transport=r,this.clientVoiceSessionOwner=a,Uf({nextTransport:v,transport:f,owner:m,reusesExistingOwner:!!(a&&m===a),closeVoiceSession:()=>this.closeUnadoptedVoiceSession(p,f,m)})):(this.transport===v&&v.stop({emitClosed:!1}),r?.stop({emitClosed:!1})),t=!0,e}t=!0,r?.stop({emitClosed:!1})}finally{t||e.release()}}async resolveVideoCapability(){if(!this.callbacks.onVideoCapability)return!1;try{let e=await this.client.request(`talk.catalog`,{},{timeoutMs:h}),t=this.options.provider??e.realtime.activeProvider;return t?e.realtime.providers.find(e=>e.id===t||e.aliases?.includes(t))?.supportsVideoFrames===!0:!1}catch{return!1}}async createSession(e){let t={...e};try{return await this.client.request(`talk.client.create`,vp({sessionKey:this.sessionKey,voiceSessionId:this.voiceSessionId,...t}),{timeoutMs:h})}catch(e){let n=t.transport;if(!n){let t;try{t=await this.client.request(`talk.config`,{},{timeoutMs:h})}catch{throw e}if(!t.config||typeof t.config!=`object`)throw e;let r=t.config?.talk?.realtime?.transport;if(r!==void 0&&(n=hp(r),!n))throw e}if(n&&n!==`gateway-relay`)throw e;let r={...t};delete r.capabilities;try{let e=await this.client.request(`talk.session.create`,vp({sessionKey:this.sessionKey,...r,mode:`realtime`,transport:n??`gateway-relay`,brain:`agent-consult`}),{timeoutMs:h});return _p(e)===`gateway-relay`?{...e,voiceSessionId:e.relaySessionId}:e}catch{throw e}}}stop(){try{this.retireTransport()}finally{this.callbacks.onStatus?.(`idle`)}}retireTransport(){this.lifecycleGeneration+=1,this.closed=!0,this.videoOperation+=1,this.videoEnabled=!1,Y.delete(this);let e=this.detachVoiceSession(),t=this.transport;this.transport=null;try{this.stopPendingTransport()}finally{try{t?.stop()}finally{e&&this.closeLogicalVoiceSession(e)}}}stopPendingTransport(){let e=this.pendingTransport;this.pendingTransport=null,e?.stop({emitClosed:!1})}closeUnadoptedVoiceSession(e,t,n){if(t===`gateway-relay`){this.client.request(`talk.session.close`,{sessionId:e},{timeoutMs:h}).catch(()=>void 0).finally(n.release);return}let r=Jn.createQueue();r.seal(),this.closeLogicalVoiceSession({voiceSessionId:e,serverOwned:!1,transcriptQueue:r,owner:n})}clientOwnedTranscriptCallbacks(e,t,n){return{...this.callbacks,onTalkEvent:n=>{try{n.type===`session.closed`&&this.transportGeneration===t&&this.voiceSessionId===e&&this.acceptingTranscripts&&this.retireTransport()}finally{this.callbacks.onTalkEvent?.(n)}},onTranscript:r=>{if(!(this.transportGeneration!==t||this.voiceSessionId!==e||!this.acceptingTranscripts)){if(r.final){let i=(this.transcriptSeqByVoiceSessionId.get(e)??0)+1,a=String(i),o=r.role,s=Qn(r.text);if(s){let r=this.transcriptQueue.enqueue(async()=>await this.writeTranscriptWithRetry({voiceSessionId:e,entryId:a,role:o,text:s,signal:n}),{weight:s.length});if(!r.accepted){r.reason===`overflow`&&this.failTranscriptPersistence(t);return}this.transcriptSeqByVoiceSessionId.set(e,i),r.completion.catch(e=>{if(n.aborted)return;let r=`Voice transcript could not be saved: ${C(e)}`;console.warn(r,e),this.transportGeneration===t&&this.callbacks.onStatus?.(`error`,r)})}}this.callbacks.onTranscript?.(r)}}}}failTranscriptPersistence(e){this.transportGeneration!==e||!this.acceptingTranscripts||!this.voiceSessionId||(this.retireTransport(),this.transportGeneration+=1,console.warn(Jn.overflowMessage),this.callbacks.onStatus?.(`error`,Jn.overflowMessage))}async writeTranscriptWithRetry(e){await Kf(e.signal,()=>this.client.request(`talk.client.transcript`,{sessionKey:this.sessionKey,voiceSessionId:e.voiceSessionId,entryId:e.entryId,role:e.role,text:e.text,timestamp:Date.now()},{signal:e.signal,timeoutMs:h}),`voice transcript save failed`)}detachVoiceSession(){let e=this.voiceSessionId;if(!e)return;let t={voiceSessionId:e,serverOwned:this.serverOwnedVoiceSession,generation:this.transportGeneration,transcriptQueue:this.transcriptQueue,owner:this.clientVoiceSessionOwner};return t.transcriptQueue.seal(),this.transcriptSeqByVoiceSessionId.delete(e),this.voiceSessionId=void 0,this.acceptingTranscripts=!1,this.serverOwnedVoiceSession=!1,this.transcriptQueue=Jn.createQueue(),this.clientVoiceSessionOwner=void 0,t}closeLogicalVoiceSession(e){if(e.serverOwned){e.owner?.release();return}let t=e.owner;t.beginDrain(),e.transcriptQueue.flush().then(()=>Kf(t.closeSignal,()=>this.client.request(`talk.client.close`,{sessionKey:this.sessionKey,voiceSessionId:e.voiceSessionId},{signal:t.closeSignal,timeoutMs:h}),`Realtime Talk voice session close failed`)).catch(n=>{t.closeSignal.aborted||(console.warn(`Realtime Talk voice session close failed`,n),this.transportGeneration===e.generation&&this.callbacks.onStatus?.(`error`,`Realtime Talk voice session close failed`))}).finally(t.release)}async setVideoEnabled(e){let t=this.transport;if(this.closed||!t?.setVideoEnabled)throw Error(`Camera is unavailable for this realtime session`);let n=++this.videoOperation,r=this.videoEnabled;this.videoEnabled=e,e?Y.add(this):Y.delete(this);try{await t.setVideoEnabled(e)}catch(e){throw n===this.videoOperation&&!this.closed&&this.transport===t&&(this.videoEnabled=r,r?Y.add(this):Y.delete(this)),e}n===this.videoOperation&&(this.closed||this.transport!==t)&&(this.videoEnabled=!1,Y.delete(this))}async switchCamera(e){let t=e?.trim()||void 0;if(this.localOptions.videoDeviceId=t,this.closed||!this.transport?.switchCamera)throw Error(`Camera switching is unavailable for this realtime session`);await this.transport.switchCamera(t)}async switchCameraIfEnabled(e){if(this.videoEnabled)try{await this.switchCamera(e)}catch(e){throw this.callbacks.onVideoError?.(e),e}}}})))()}function xp(e){if(Ln(e))return null;let t=f(e),n=tr(e),r=typeof t?.stopReason==`string`?t.stopReason.trim().toLowerCase():``,i=f(t?.__openclaw);if(n===`commentary`||(!r||r===`tooluse`)&&i?.runTerminal!==!0)return null;let a=j(e);if(typeof a==`string`&&Vn(a))return null;let o=(Wn(e)?.content??[]).filter(e=>e.type===`text`?typeof e.text==`string`&&e.text.trim().length>0:!mn(e.type)&&!_n(e.type));if(o.length===0)return null;try{return JSON.stringify(o)??null}catch{return null}}function Sp(e,t){let n=Tn(e),r=wn(e,e.chatMessages,n),i=r.runs[t],a=i?.message===void 0?[]:[i.message];for(let e of r.messages)A(e)?.role===`assistant`&&kn(e)===t&&a.push(e);let o=new Set;for(let e of a){let t=xp(e);t&&o.add(t)}return{acceptedFinal:(i?.acceptedFinalMessageIdentities?.length??0)>0,terminalReplySignatures:o}}function Cp(){return(Cp=e((()=>{k(),gn(),sr(),It(),In(),On(),Fn(),xn()})))()}function wp(e,t){try{let n=e.getItem(t);if(!n)return!1;let r=JSON.parse(n);return ae(r)&&r.open===!0}catch{return!1}}function Tp(e){try{e.setItem(kp,`1`)}catch{}}function Ep(e){try{return e.getItem(kp)===`1`}catch{return!1}}function Dp(){try{return globalThis.localStorage??null}catch{return null}}function Op(e){let t=e.sessionKey.trim(),n=e.storage===void 0?Dp():e.storage;if(!t||!n||Ep(n))return e.settings;if(e.settings.sidebarSessionLayouts?.[t]!==void 0)return Tp(n),e.settings;let r=new Set([...e.browserAvailable?[`browser`]:[],...e.desktopAvailable?[`desktop`]:[]]),i={columns:[]};for(let e of Ap)r.has(e.slot)&&wp(n,e.storageKey)&&(i=Jl(i,e.slot));let a=i.columns.length>0?nt({sidebarSessionLayouts:Ue(e.settings.sidebarSessionLayouts,t,i)}):e.settings;return Tp(n),a}var kp,Ap;function jp(){return(jp=e((()=>{i(),Qe(),He(),du(),kp=`openclaw.chat.sidePanel.legacyDockVisibility.v1`,Ap=[{storageKey:`openclaw.browser.panel.v1`,slot:`browser`},{storageKey:`openclaw.desktopPanel`,slot:`desktop`}]})))()}function Mp(e,t){return X?X.expiresAt<=Date.now()?(X=void 0,!1):X.sourceData!==t&&w(X.sessionKey,e):!1}var Np,Pp,Fp,Ip,X,Lp;function Rp(){return(Rp=e((()=>{S(),Np=3e4,Pp=15e3,Fp=250,Ip=`.agent-chat__composer-combobox textarea`,Lp=class{constructor(e){this.host=e}rendered(e,t,n){let r=!!(e&&(t===void 0||t!==null&&w(t,e.sessionKey)));return e&&!e.draft&&r&&Mp(e.sessionKey,e)&&(X=void 0,this.maintain(e.sessionKey)),!!(e&&n!==e&&r&&(e.draft!==void 0||e.focusComposer))}shouldFocusPane(e,t,n,r){return!!(e&&r&&(t&&r.focusComposer||!t&&Mp(n,r)))}beforeDraftCleanup(e){e.focusComposer&&(X={expiresAt:Date.now()+Np,sessionKey:e.sessionKey,sourceData:e})}maintain(e){this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0);let t=Date.now()+Pp,n,r=()=>{if(!this.host.isConnected){this.timer=void 0;return}let i=[...this.host.querySelectorAll(`openclaw-chat-pane`)].find(t=>t.active&&t.sessionKey!==void 0&&w(t.sessionKey,e))?.querySelector(Ip),a=document.activeElement,o=a===n||a===document.body||a instanceof HTMLElement&&!a.isConnected;if(i&&(!n||o))i.focus({preventScroll:!0}),n=i;else if(n&&!o){this.timer=void 0;return}this.timer=Date.now()e===t[n])}function Hp(e,t,n,r){return new Jp(e,t,n,r)}var Up,Wp,Gp,Kp,qp,Jp;function Yp(){return(Yp=e((()=>{In(),yr(),ai(),Fr(),Up=5,Wp=250,Gp=3e4,Kp=`openclaw-chat-prefetch`,qp=class{constructor(e,t){this.cache=e,this.snapshotStore=t,this.connected=!1,this.snapshot=null,this.lastAttemptAt=new Map,this.delayTimer=null,this.idleTimer=null,this.idleCallback=null,this.running=!1,this.rescheduleDelayMs=null,this.handleVisibilityChange=()=>{document.visibilityState===`visible`&&this.schedule()}}connect(){this.connected||(this.connected=!0,document.addEventListener(`visibilitychange`,this.handleVisibilityChange),this.schedule())}disconnect(){this.connected=!1,this.rescheduleDelayMs=null,document.removeEventListener(`visibilitychange`,this.handleVisibilityChange),this.cancelScheduledWork()}update(e){let t=this.snapshot;this.snapshot=e,(!t||t.client!==e.client||t.listRevision!==e.listRevision||!Vp(t.openSessionKeys,e.openSessionKeys))&&this.schedule()}schedule(e=Wp){if(this.connected){if(this.running){this.rescheduleDelayMs=this.rescheduleDelayMs===null?e:Math.min(this.rescheduleDelayMs,e);return}this.delayTimer===null&&this.idleTimer===null&&this.idleCallback===null&&(this.delayTimer=globalThis.setTimeout(()=>{this.delayTimer=null,this.scheduleIdleCycle()},e))}}scheduleIdleCycle(){if(this.connected){if(typeof window.requestIdleCallback==`function`){this.idleCallback=window.requestIdleCallback(()=>{this.idleCallback=null,this.runCycle()});return}this.idleTimer=globalThis.setTimeout(()=>{this.idleTimer=null,this.runCycle()},0)}}async runCycle(){if(!(!this.connected||this.running||document.visibilityState===`hidden`)){this.running=!0;try{let e=typeof navigator>`u`?void 0:navigator.locks;e?await e.request(Kp,{ifAvailable:!0},async e=>{e&&await this.prefetchEligibleSessions()}):await this.prefetchEligibleSessions()}catch(e){Bp(`cycle failed`,e)}finally{if(this.running=!1,this.rescheduleDelayMs!==null){let e=this.rescheduleDelayMs;this.rescheduleDelayMs=null,this.schedule(e)}}}}async prefetchEligibleSessions(){let e=this.snapshot;if(!e?.client||!e.rows||document.visibilityState===`hidden`||!this.connected)return;let{client:t}=e;if(await this.snapshotStore.loadSavedAtIndex(),!this.isCurrent(e))return;for(let t of e.openSessionKeys){let n=Wr(this.cache,e.snapshotHost,{sessionKey:t});n&&this.cache.size===20&&this.snapshotStore.write(L(e.snapshotHost,{sessionKey:t}),n)}let n=this.selectCandidates(e);n.deferMs!==null&&this.schedule(n.deferMs),await Promise.all(n.candidates.map(async n=>{if(!(!this.isCurrent(e,n.snapshotKey)||this.isOpen(n.snapshotKey,this.snapshot))){this.lastAttemptAt.set(n.snapshotKey,Date.now());try{let r=Wr(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey});if(!r&&this.snapshotStore.readSavedAt(n.snapshotKey)!==null){if(r=await this.snapshotStore.read(n.snapshotKey),!this.isCurrent(e,n.snapshotKey))return;r&&Ur(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey},r)}let i=await zn(t,n.snapshotKey,this,()=>this.isCurrent(e,n.snapshotKey),r?.deltaCursor);if(!this.isCurrent(e,n.snapshotKey))return;if(i.kind===`reset`){if(r?.deltaCursor!==void 0){let{deltaCursor:t,...i}=r;Ur(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey},i),r=i}if(i=await zn(t,n.snapshotKey,this,()=>this.isCurrent(e,n.snapshotKey)),!this.isCurrent(e,n.snapshotKey))return}if(this.isOpen(n.snapshotKey,this.snapshot)||this.currentActivityAt(n.snapshotKey)>n.activityAt)return;let a;if(i.kind===`delta`){for(let t of i.messages){let r=s(t);!r||!Object.hasOwn(r,`message`)||Br(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey},r.message,r)}let t=Wr(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey});if(!t)return;a={...t,...i.inFlightRun?{}:{deltaCursor:i.deltaCursor},...Object.hasOwn(i.sessionInfo,`activeLeafEntryId`)?{displayedLeafEntryId:i.sessionInfo.activeLeafEntryId?.trim()||null}:{},sessionId:i.sessionInfo.sessionId?.trim()||t.sessionId}}else if(i.kind===`snapshot`)a=i.snapshot;else throw Error(`chat history page request returned a cursor reset`);Ur(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey},a)}catch(e){Bp(`history fetch failed for ${n.snapshotKey}`,e)}}}))}selectCandidates(e){let t=new Set(e.openSessionKeys.map(t=>L(e.snapshotHost,{sessionKey:t}))),n=Math.max(0,20-t.size),r=(e.rows??[]).toSorted((e,t)=>zp(t)-zp(e)),i=[],a=new Set,o=null;for(let s of r){if(we(s))continue;let r=L(e.snapshotHost,{sessionKey:s.key,agentId:s.agentId});if(t.has(r)||a.has(r))continue;if(a.add(r),a.size>n)break;let c=zp(s),l=this.snapshotStore.readSavedAt(r);if(l!==null&&l>=c)continue;let u=Date.now()-(this.lastAttemptAt.get(r)??0);if(uL(this.snapshot.snapshotHost,{sessionKey:e.key,agentId:e.agentId})===t)===!0)}isOpen(e,t){return!!t?.openSessionKeys.some(n=>L(t.snapshotHost,{sessionKey:n})===e)}currentActivityAt(e){let t=this.snapshot;if(!t?.rows)return 0;let n=0;for(let r of t.rows)L(t.snapshotHost,{sessionKey:r.key,agentId:r.agentId})===e&&(n=Math.max(n,zp(r)));return n}cancelScheduledWork(){this.delayTimer!==null&&(globalThis.clearTimeout(this.delayTimer),this.delayTimer=null),this.idleTimer!==null&&(globalThis.clearTimeout(this.idleTimer),this.idleTimer=null),this.idleCallback!==null&&(window.cancelIdleCallback(this.idleCallback),this.idleCallback=null)}},Jp=class{constructor(e,t,n,r){this.host=e,this.readContext=r,this.subscriptions=[],this.sync=()=>{let e=this.readContext();if(e!==this.context&&(this.clearSubscriptions(),this.context=e,e&&(this.subscriptions=[e.gateway.subscribe(this.sync),e.sessions.subscribe(this.sync)])),!e)return;let t=[...this.host.querySelectorAll(`openclaw-chat-pane`)].flatMap(e=>e.sessionKey?[e.sessionKey]:[]);this.prefetcher.update({client:e.gateway.snapshot.phase===`connected`?e.gateway.snapshot.client:null,listRevision:e.sessions.canonicalListRevision,openSessionKeys:t,rows:e.sessions.state.result?.sessions??null,snapshotHost:{assistantAgentId:e.gateway.snapshot.assistantAgentId,agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello}})},this.prefetcher=new qp(t,n),e.addController(this)}hostConnected(){this.prefetcher.connect(),this.sync()}hostUpdated(){this.sync()}hostDisconnected(){this.clearSubscriptions(),this.prefetcher.disconnect()}clearSubscriptions(){for(let e of this.subscriptions)e();this.subscriptions=[],this.context=void 0}}})))()}function Xp(e,t){t===void 0?console.debug(`[chat-snapshot-cache] ${e}`):console.debug(`[chat-snapshot-cache] ${e}`,t)}function Zp(e){return new Promise((t,n)=>{e.addEventListener(`complete`,()=>t()),e.addEventListener(`error`,()=>n(e.error??Error(`IndexedDB failed`))),e.addEventListener(`abort`,()=>n(e.error??Error(`IndexedDB aborted`)))})}function Qp(e){return new Promise((t,n)=>{e.addEventListener(`success`,()=>t(e.result)),e.addEventListener(`error`,()=>n(e.error??Error(`IndexedDB request failed`)))})}function $p(e){try{let t=JSON.stringify(e);return t?JSON.parse(t):null}catch{return null}}function em(e,t){let n=um.safeParse(e);return n.success&&(!t||n.data.sessionKey===t)?n.data:null}function tm(e,t){let n=$p(t.snapshot);if(!n)return null;let r=um.safeParse({savedAt:t.savedAt,sessionId:t.snapshot.sessionId,sessionKey:e,snapshot:n});return r.success?r.data:null}async function nm(e){let t=await wr();if(!t)return null;try{let n=t.transaction(I,`readonly`),r=await Qp(n.objectStore(I).get(e));return await Zp(n),r===void 0?null:em(r,e)||(Xp(`resetting cache after record shape mismatch`),await Tr(t),null)}catch(e){return Xp(`IndexedDB read failed`,e),await Tr(t),null}finally{t.close()}}async function rm(){let e=await wr();if(!e)return[];try{let t=e.transaction(I,`readonly`),n=await Qp(t.objectStore(I).getAll());await Zp(t);let r=[];for(let t of n){let n=em(t);if(!n)return Xp(`resetting cache after record shape mismatch`),await Tr(e),null;r.push(n)}return r}catch(t){return Xp(`IndexedDB read failed`,t),await Tr(e),null}finally{e.close()}}function im(e){let t=Gr(e.snapshot)??0;try{return t+JSON.stringify({savedAt:e.savedAt,sessionId:e.sessionId,sessionKey:e.sessionKey}).length}catch{return t}}async function am(e,t){if(e.length===0||t!==Z)return[];let n=await wr();if(!n)return[];try{let t=n.transaction([I,Or],`readwrite`),r=t.objectStore(I),i=t.objectStore(Or),a=await Qp(i.getAll()),o=new Map;for(let e of a){let n=dm.safeParse(e);if(!n.success)throw t.abort(),Error(`IndexedDB metadata shape mismatch`);o.set(n.data.sessionKey,n.data)}for(let t of e){let e={savedAt:t.savedAt,sessionKey:t.sessionKey,weight:im(t)};o.set(t.sessionKey,e),r.put(t),i.put(e)}let s=[...o.values()].toSorted((e,t)=>e.savedAt-t.savedAt),c=s.reduce((e,t)=>e+t.weight,0),l=[];for(;s.length>20||c>25165824;){let e=s.shift();if(!e)break;c-=e.weight,r.delete(e.sessionKey),i.delete(e.sessionKey),l.push(e.sessionKey)}return await Zp(t),l}catch(e){return Xp(`resetting cache after IndexedDB write failure`,e),await Tr(n),null}finally{n.close()}}function om(){for(let e of fm)e.flush()}var sm,cm,lm,um,dm,fm,Z,pm;function mm(){return(mm=e((()=>{dn(),yr(),ai(),Ar(),Pe(),Fr(),sm=500,cm=fn(`hasMore`,[pn({completeSnapshot:cn(!0).optional(),hasMore:cn(!1),totalMessages:ln().finite().nonnegative().optional()}).strict(),pn({hasMore:cn(!0),nextOffset:ln().finite().nonnegative(),totalMessages:ln().finite().nonnegative().optional()}).strict()]),lm=pn({deltaCursor:M().optional(),displayedLeafEntryId:M().nullable().optional(),messages:un(sn()),pagination:cm,sessionId:M().nullable()}).strict(),um=pn({savedAt:ln().finite().nonnegative(),sessionId:M().nullable(),sessionKey:M().min(1),snapshot:lm}).strict().refine(e=>e.sessionId===e.snapshot.sessionId),dm=pn({savedAt:ln().finite().nonnegative(),sessionKey:M().min(1),weight:ln().finite().nonnegative()}).strict(),fm=new Set,Z=0,pm=class{constructor(e){this.memoryCache=e,this.connected=!1,this.pending=new Map,this.hydratedSnapshots=new Map,this.revisions=new Map,this.savedAtBySession=new Map,this.savedAtSeed=null,this.writeTimer=null,this.writeChain=Promise.resolve()}connect(){this.connected=!0,fm.add(this)}disconnect(){this.connected=!1,this.flush().finally(()=>{this.connected||fm.delete(this)})}async read(e){let t=Z,n=this.revisions.get(e)??0,r=await nm(e);return!r||t!==Z||n!==(this.revisions.get(e)??0)?null:(F(this.hydratedSnapshots,e,r.snapshot),r.snapshot)}async loadSavedAtIndex(){this.savedAtSeed??=this.seedSavedAtIndex(),await this.savedAtSeed}readSavedAt(e){return this.pending.get(e)?.savedAt??this.savedAtBySession.get(e)??null}write(e,t){this.revisions.set(e,(this.revisions.get(e)??0)+1),P(this.hydratedSnapshots,e)!==t&&(this.hydratedSnapshots.delete(e),this.schedule(e,t))}async delete(e){this.forget(e),await Mr(e)}forget(e){this.revisions.set(e,(this.revisions.get(e)??0)+1),this.pending.delete(e),this.hydratedSnapshots.delete(e),this.savedAtBySession.delete(e),this.memoryCache?.delete(e)}async flush(){this.writeTimer!==null&&(globalThis.clearTimeout(this.writeTimer),this.writeTimer=null);let e=[...this.pending.entries()],t=new Map(e.map(([e])=>[e,this.revisions.get(e)??0]));this.pending.clear();let n=[];for(let[t,r]of e){let e=tm(t,r);e?n.push(e):await this.delete(t)}let r=Z;this.writeChain=this.writeChain.then(async()=>{let e=await am(n.filter(({sessionKey:e})=>t.get(e)===(this.revisions.get(e)??0)),r);if(e===null){this.resetSavedAtIndex();return}for(let t of e)this.pending.has(t)||this.savedAtBySession.delete(t)}),await this.writeChain}clearMemory(){this.writeTimer!==null&&(globalThis.clearTimeout(this.writeTimer),this.writeTimer=null),this.pending.clear(),this.hydratedSnapshots.clear(),this.revisions.clear(),this.savedAtBySession.clear(),this.memoryCache?.clear()}async whenIdle(){await this.writeChain}schedule(e,t){let n={savedAt:Date.now(),snapshot:t};this.pending.set(e,n),this.savedAtBySession.set(e,n.savedAt),this.writeTimer!==null&&globalThis.clearTimeout(this.writeTimer),this.writeTimer=globalThis.setTimeout(()=>{this.writeTimer=null,this.flush()},sm)}async seedSavedAtIndex(){let e=Z,t=new Map(this.revisions),n=await rm();if(e===Z){if(!n){this.resetSavedAtIndex();return}for(let e of n){if((t.get(e.sessionKey)??0)!==(this.revisions.get(e.sessionKey)??0))continue;let n=this.savedAtBySession.get(e.sessionKey)??0;this.savedAtBySession.set(e.sessionKey,Math.max(n,e.savedAt))}}}resetSavedAtIndex(){this.savedAtBySession.clear();for(let[e,t]of this.pending)this.savedAtBySession.set(e,t.savedAt)}},qe(async({sessionKey:e})=>{e||(Z+=1);for(let t of fm)e?t.forget(e):t.clearMemory();await Promise.all([...fm].map(e=>e.whenIdle()))}),typeof window<`u`&&(window.addEventListener(`pagehide`,om),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&om()}))})))()}function hm(e,t,n){let r=(t-e.left)/e.width,i=(n-e.top)/e.height,a=r<=_m?{edge:`left`,distance:r}:1-r<=_m?{edge:`right`,distance:1-r}:null,o=i<=_m?{edge:`up`,distance:i}:1-i<=_m?{edge:`down`,distance:1-i}:null,s=a&&o?a.distance<=o.distance?a:o:a??o;return s?{kind:`edge`,edge:s.edge}:{kind:`center`}}function gm(e,t){let n={left:e.left,top:e.top,width:e.width,height:e.height};return t.kind===`center`?n:t.edge===`left`?{...n,width:e.width/2}:t.edge===`right`?{...n,left:e.left+e.width/2,width:e.width/2}:t.edge===`up`?{...n,height:e.height/2}:{...n,top:e.top+e.height/2,height:e.height/2}}var _m;function vm(){return(vm=e((()=>{_m=.3})))()}function ym(e,t,n){let r=Le({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello}),i=Fe({agentId:n,mainKey:r});return{kind:`missing-session`,face:t,currentSessionHref:Ie({context:e,face:t,sessionKey:i,agentId:n}).href,sessionsHref:at(`sessions`,e.basePath)}}function bm(e,t,n){let r=e.toLowerCase().replaceAll(`-`,``);if(!m.test(r))return null;if(n)return r;let i=t.map(e=>e.toLowerCase().replaceAll(`-`,``));for(let e=8;e<=r.length;e+=1){let t=r.slice(0,e);if(i.filter(e=>e.startsWith(t)).length===1)return t}return r}function xm(e,t){if(t.kind!==`exact`)return null;let n={agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello},r=Ce(n,t.value);return x(t.value)?.rest.toLowerCase()===`global`||Ee(n)?r:null}function Sm(e,n){return n.kind===`exact`?xm(e,n)===t(n.agentId)?`global`:n.value:n.value.split(`-`).reduce((e,t)=>t.length>e.length?t:e,``)}function Cm(e,n,r){if(r.kind===`exact`){let i=xm(e,r);return n.sessions.filter(e=>w(e.key,r.value)||de(e.key)&&i===t(r.agentId))}return n.sessions.filter(e=>To(e.key)!==null&&y(e.displayName)===r.value)}async function wm(e,n,r){let i=await At(e.gateway,r);r.throwIfAborted();let a=Om.get(i)??new Map;Om.set(i,a);let o=`${t(n.agentId)}:${n.kind}:${n.value}`,s=a.get(o);if(!s||s.controller.signal.aborted){let t=new AbortController;s={controller:t,promise:Promise.resolve().then(()=>Em(e,n,t.signal)),subscribers:new Set},a.set(o,s)}s.subscribers.add(r);let c=s,l=()=>void 0,u=new Promise((e,t)=>{l=t}),d=()=>{c.subscribers.delete(r),c.subscribers.size===0&&c.controller.abort(r.reason),l(r.reason)};r.addEventListener(`abort`,d,{once:!0}),r.aborted&&d();try{return await Promise.race([c.promise,u])}finally{r.removeEventListener(`abort`,d),c.subscribers.delete(r),c.subscribers.size===0&&a.get(o)===c&&a.delete(o)}}function Tm(e){return{kind:`ambiguous`,sessions:e,truncated:!0}}async function Em(e,t,n){let r=new Map,i=0;for(let a=0;;a+=1){n.throwIfAborted();let o=await e.sessions.list({agentId:t.agentId,archivedFilter:`all`,includeDerivedTitles:!0,limit:Dm,search:Sm(e,t),...i>0?{offset:i}:{}});if(n.throwIfAborted(),!o)return null;for(let n of Cm(e,o,t))r.set(n.key,n);let s=[...r.values()];if(t.kind===`exact`&&s[0])return{kind:`unique`,session:s[0]};if(s.length>1)return{kind:`ambiguous`,sessions:s,truncated:o.hasMore===!0};if(o.hasMore!==!0){let e=s[0];return e?{kind:`unique`,session:e}:{kind:`not-found`}}if(a===4)return Tm(s);let c=o.nextOffset??i+o.sessions.length;if(c<=i)return Tm(s);i=c}}var Dm,Om;function km(){return(km=e((()=>{v(),st(),fe(),S(),Oo(),Dm=20,Om=new WeakMap})))()}async function Am(e,t,n){let r=await At(e.gateway,n);n.throwIfAborted();let i=await r.request(`sessions.resolve`,{shortId:t.shortId,...t.slugHint?{slugHint:t.slugHint}:{},agentId:t.agentId,allowMissing:!0});return n.throwIfAborted(),i.ok?{kind:`unique`,session:i}:i.candidates?.length?{kind:`ambiguous`,sessions:i.candidates,truncated:i.candidates.length===10}:{kind:`not-found`}}function jm(){return(jm=e((()=>{})))()}function Mm(e){return new URLSearchParams(e.search).get(ue)===`1`}function Nm(e,t){let n=new URLSearchParams(e.search);n.delete(t);let r=n.toString();return{...e,search:r?`?${r}`:``}}function Q(e){return Nm(Nm(e,ue),Ye)}function Pm(e){return e.boardFace===`dashboard`?`dashboard`:`chat`}function $(e){return Le({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})}function Fm(e){return!!(e.agents.state.agentsList?.mainKey?.trim()||e.gateway.snapshot.phase===`connected`&&e.gateway.snapshot.hello)}function Im(e,t,n,r){let i=x(r);if(!i)return null;let a=$(e).toLowerCase();if(i.rest.toLowerCase()!==a)return null;let o=rt(n,i.agentId,r,e.basePath,{mainKey:a});return o&&o!==t.pathname?{...Q(t),pathname:o}:null}function Lm(e){let t=e.face,n=se(e.row.key),r=rt(t,n,e.row.key,e.context.basePath,{displayName:e.row.displayName,mainKey:$(e.context),shortIdLength:e.shortIdLength});if(!r)return;let i=Q(e.location);return r!==e.location.pathname||i.search!==e.location.search?{...i,pathname:r}:null}function Rm(e,t){let n=$(e),r=it(t.pathname,e.basePath,n);if(r)return{target:r,location:t};let i=new URLSearchParams(t.search).get($e);if(!i)return null;let a=it(i,e.basePath,n);return a?{target:a,location:{...Nm(t,$e),pathname:i}}:null}function zm(e,t){return Fe({agentId:t.agentId,mainKey:$(e)})}function Bm(e,t,n,r,i){let a=n.sessions.flatMap(e=>{let t=To(e.key);return t?[{row:e,uuid:t}]:[]}),o=a.map(({uuid:e})=>e);return a.flatMap(({row:a,uuid:s})=>{let c=bm(s,o,n.truncated);if(!c)return[];let l=se(a.key),u=i?Pm(a):t,d=rt(u,l,a.key,e.basePath,{displayName:a.displayName,mainKey:$(e),shortIdLength:c.length});return d?[{agentId:l,displayName:a.displayName?.trim()||a.key,href:`${d}${Io(r)}`,idPrefix:c}]:[]})}function Vm(e){let t=e.preferenceDerived?Pm(e.row):e.face,n=Lm({context:e.context,location:e.location,face:t,row:e.row,...e.shortId?{shortIdLength:e.shortId.length}:{}});return n===void 0?null:{kind:`session`,sessionKey:e.row.key,...Fo(e.location),face:t,...e.shortId&&e.shortId.length>8?{shortId:e.shortId}:{},...n?{canonicalLocation:n,canonicalLocationSource:e.location}:{}}}function Hm(e){if(!de(e.row.key))return Vm(e);let t=e.preferenceDerived?Pm(e.row):e.face,n=rt(t,e.target.agentId,zm(e.context,e.target),e.context.basePath,{mainKey:$(e.context)});if(!n)return null;let r=Q(e.location),i=n!==e.location.pathname||r.search!==e.location.search?{...r,pathname:n}:void 0;return{kind:`session`,sessionKey:e.row.key,agentId:e.target.agentId,...Fo(e.location),face:t,...i?{canonicalLocation:i,canonicalLocationSource:e.location}:{}}}async function Um(e,t,n,r){let i=Rm(e,t);if(!i||i.target.namespace!==n)return p({routeId:n});let{target:a}=i,o=i.location,s=Mm(o),c=Ae(o.search);if(a.kind===`main`&&c){let t=Ne(c),i=s?Q(o):null,l=n;if(s){let n=await wm(e,{kind:`exact`,value:t,agentId:a.agentId},r);if(n?.kind===`unique`){l=Pm(n.session);let t=rt(l,a.agentId,zm(e,a),e.basePath,{mainKey:$(e)});t&&(i={...Q(o),pathname:t})}}return{kind:`session`,sessionKey:Ne(c,a.agentId),agentId:a.agentId,...Fo(o),face:l,...i?{canonicalLocation:i,canonicalLocationSource:o}:{}}}if(a.kind===`main`){await At(e.gateway,r);let t=zm(e,a);if(s){let i=await wm(e,{kind:`exact`,value:t,agentId:a.agentId},r);if(i?.kind===`unique`)return Hm({context:e,location:o,face:n,row:i.session,target:a,preferenceDerived:s})??p({routeId:n})}let i=s?Q(o):null;return{kind:`session`,sessionKey:t,...Fo(o),face:n,...i&&i.search!==o.search?{canonicalLocation:i,canonicalLocationSource:o}:{}}}if(a.kind===`literal`){let t=Fm(e),i=s||!!a.slugCandidate;if(!t&&i&&(await At(e.gateway,r),t=Fm(e),t))return await Um(e,o,n,r);if(i){let i=t?me(e,a.sessionKey,a.agentId):void 0,c=i?{kind:`unique`,session:i}:await wm(e,{kind:`exact`,value:a.sessionKey,agentId:a.agentId},r);if(c?.kind===`unique`)return Vm({context:e,location:o,face:n,row:c.session,preferenceDerived:s})??p({routeId:n});if(a.slugCandidate&&c?.kind===`not-found`){let t=await wm(e,{kind:`slug`,value:a.slugCandidate,agentId:a.agentId},r);if(t?.kind===`not-found`)return ym(e,n,a.agentId);if(t?.kind===`ambiguous`)return{kind:`ambiguous`,shortId:a.slugCandidate,candidates:Bm(e,n,t,o,s),truncated:t.truncated,face:n};if(t?.kind===`unique`)return Vm({context:e,location:o,face:n,row:t.session,preferenceDerived:s})??p({routeId:n})}}let c=t?Im(e,o,n,a.sessionKey):null,l=x(a.sessionKey),u=!t&&l?At(e.gateway,r).then(()=>Im(e,o,n,a.sessionKey)).catch(()=>null):void 0,d=s?Q(o):null;return{kind:`session`,sessionKey:a.sessionKey,...Fo(o),face:n,...c?{canonicalLocation:c,canonicalLocationSource:o}:d&&d.search!==o.search?{canonicalLocation:d,canonicalLocationSource:o}:{},...u?{canonicalLocationReady:u,canonicalLocationSource:o}:{}}}let l=Do(e,o,a);if(l&&!l.row){let e=Q(o),t=e.search!==o.search;return{kind:`session`,sessionKey:l.sessionKey,...Fo(o),face:n,...a.shortId.length>8?{shortId:a.shortId}:{},...t?{canonicalLocation:e,canonicalLocationSource:o}:{}}}let u=l?.row?{kind:`unique`,session:l.row}:await Am(e,a,r);if(u.kind===`not-found`){let t=await wm(e,{kind:`exact`,value:a.literalSessionKey,agentId:a.agentId},r);return t?.kind===`unique`?Vm({context:e,location:o,face:n,row:t.session,preferenceDerived:s})??p({routeId:n}):t?.kind===`not-found`?ym(e,n,a.agentId):p({routeId:n})}return u.kind===`ambiguous`?{kind:`ambiguous`,shortId:a.shortId,candidates:Bm(e,n,u,o,s),truncated:u.truncated,face:n}:Vm({context:e,location:o,face:n,row:u.session,preferenceDerived:s,shortId:a.shortId})??p({routeId:n})}function Wm(){return(Wm=e((()=>{u(),st(),tt(),Ze(),Ke(),fe(),S(),Ro(),km(),Oo(),jm()})))()}function Gm(e){window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`))}function Km(e){return D`

${O(`chat.sessionRoute.chooseTitle`)}

${e.candidates.length>1?O(`chat.sessionRoute.multipleMatches`,{shortId:e.shortId}):O(`chat.sessionRoute.additionalMatches`)}

${e.candidates.map(e=>D`

${e.displayName}
${e.agentId} · ${e.idPrefix}

`)} ${e.truncated&&e.candidates.length>1?D`

${O(`chat.sessionRoute.additionalMatches`)}

`:null}
`}function qm(e){return ct({className:`session-route-not-found`,role:`status`,title:O(`chat.sessionRoute.notFoundTitle`),subtitle:O(`chat.sessionRoute.notFoundExplanation`),actions:D` `})}function Jm(e){let t=e;return t?t.kind===`ambiguous`?Km(t):t.kind===`missing-session`?qm(t):D``:E}function Ym(e,t){return(e.data??t?.data)?.kind===`session`?Xm:void 0}var Xm;function Zm(){return(Zm=e((()=>{Xe(),ft(),lt(),Xm=`chat-page`})))()}export{Gl as $,ka as $n,cc as $t,hd as A,Vo as An,si as Ar,Yc as At,Bu as B,To as Bn,Nr as Br,hc as Bt,Id as C,qo as Cn,yi as Cr,xl as Ct,Dd as D,Xo as Dn,hi as Dr,Gc as Dt,Hd as E,es as En,di as Er,al as Et,pd as F,Lo as Fn,Hr as Fr,Jc as Ft,Su as G,yo as Gn,vr as Gr,Fc as Gt,zu as H,Co as Hn,Mr as Hr,zc as Ht,Uu as I,Ao as In,ai as Ir,qc as It,Xl as J,_o as Jn,F as Jr,jc as Jt,Ru as K,vo as Kn,P as Kr,Pc as Kt,cd as L,jo as Ln,Ir as Lr,Lc as Lt,_d as M,Ko as Mn,Br as Mr,tl as Mt,Ed as N,Ro as Nn,Rr as Nr,Qc as Nt,Od as O,Yo as On,mi as Or,Uc as Ot,md as P,Po as Pn,Ur as Pr,Hc as Pt,ru as Q,ro as Qn,Us as Qt,Wu as R,ko as Rn,Vr as Rr,fc as Rt,Rd as S,ns as Sn,gi as Sr,El as St,Md as T,$o as Tn,pi as Tr,il as Tt,Cu as U,xo as Un,Fr as Ur,dc as Ut,Hu as V,wo as Vn,Pr as Vr,mc as Vt,wu as W,bo as Wn,L as Wr,gc as Wt,nu as X,Oa as Xn,pc as Xt,Yl as Y,Aa as Yn,xc as Yt,du as Z,ua as Zn,tc as Zt,Cp as _,ps as _n,Ki as _r,Tl as _t,Um as a,hs as an,Qi as ar,Ql as at,bp as b,Jo as bn,Oi as br,kl as bt,gm as c,vs as cn,Xi as cr,Bl as ct,Yp as d,fs as dn,qi as dr,Fl as dt,zs as en,la as er,Jl as et,Hp as f,ys as fn,Pi as fr,Il as ft,Op as g,ls as gn,zi as gr,cl as gt,jp as h,cs as hn,Wi as hr,fl as ht,Wm as i,ms as in,aa as ir,$l as it,vd as j,Bo as jn,ci as jr,Xc as jt,Td as k,zo as kn,li as kr,Vc as kt,pm as l,as as ln,Ji as lr,Ml as lt,Rp as m,ss as mn,Ai as mr,gl as mt,Jm as n,Ls as nn,ra as nr,tu as nt,vm as o,gs as on,ea as or,Wl as ot,Lp as p,os as pn,Fi as pr,Nl as pt,ou as q,co as qn,yr as qr,Ic as qt,Ym as r,Rs as rn,na as rr,eu as rt,hm as s,_s as sn,ta as sr,zl as st,Zm as t,Ms as tn,ca as tr,Zl as tt,mm as u,us as un,Ni as ur,Ll as ut,Sp as v,ds as vn,bi as vr,wl as vt,kd as w,Go as wn,ui as wr,ol as wt,mp as x,Wo as xn,Ei as xr,ul as xt,yp as y,Zo as yn,Ci as yr,Al as yt,Vu as z,Oo as zn,Wr as zr,Sc as zt}; //# sourceMappingURL=control-ui-boot-D1DWJlBr.js.map