@idl3/claude-control 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,7 +41,7 @@ Error generating stack: `+i.message+`
41
41
 
42
42
  ${s.system}`:r.system=s.system),s.tools)for(const[o,a]of Object.entries(s.tools)){const l=r.tools?.[o];if(l&&l!==a){const u=n[o];if(u===i)throw new Error(`You tried to define a tool with the name ${o}, but it already exists.`);const c=u>i?l:a,f=u>i?a:l;r.tools[o]={...f,...c},n[o]=Math.max(u,i);continue}r.tools||(r.tools={}),r.tools[o]=a,n[o]??(n[o]=i)}return s.config&&(r.config={...r.config,...s.config}),s.callSettings&&(r.callSettings={...r.callSettings,...s.callSettings}),r},{})};var dp=class{constructor(){A(this,"_providers",new Set);A(this,"_subscribers",new Set)}getModelContext(){return dI(this._providers)}registerModelContextProvider(e){this._providers.add(e);const t=e.subscribe?.(()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t?.(),this.notifySubscribers()}}notifySubscribers(){for(const e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}};const Ef=[],fI={modelName:void 0,toolNames:Ef},hI=(e,t)=>e===t||e.length===t.length&&e.every((n,r)=>n===t[r]),ul=(e,t)=>{const n=e.getModelContext(),r=n.config?.modelName,s=n.tools?Object.keys(n.tools).sort():Ef,i=s.length?s:Ef;return r===t.modelName&&hI(i,t.toolNames)?t:{modelName:r,toolNames:i}},sb=ve(()=>{const e=ce(()=>new dp,[]),[t,n]=dn(()=>ul(e,fI));return tt(()=>(n(r=>ul(e,r)),e.subscribe(()=>{n(r=>ul(e,r))})),[e]),{getState:()=>ul(e,t),getModelContext:()=>e.getModelContext(),subscribe:r=>e.subscribe(r),register:r=>e.registerModelContextProvider(r)}}),pI=e=>e.display!==void 0?e.display==="standalone":e.type==="human",mI=(e,t)=>{if(!(t.status?.type==="running"||t.status?.type==="requires-action")){const r=e.complete;return typeof r!="function"?r??null:r({args:t.args,result:t.result})}const n=e.running;return typeof n!="function"?n??null:n({args:t.args})},gI=e=>function(n){return mI(e,n)},Tf=Symbol("assistant-ui.store.clientIndex"),yI=e=>e[Tf],ib=tb([]),fp=()=>rb(ib),vI=(e,t)=>{const n=fp();return nb(ib,ce(()=>[...n,e],[n,e]),t)},xI=new Set(["$$typeof","nodeType","then"]),oc=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!="symbol"){if(e==="toJSON")return()=>t;if(!xI.has(e))return!1}};var hp=class{getOwnPropertyDescriptor(e,t){const n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!0,configurable:!1}}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}};const ob=e=>{const t=ve(e);return n=>{const r=t(n);return n.key===void 0?r:lr(n.key,r)}},gu=Symbol("assistant-ui.store.getValue"),wI=e=>{const t=e[gu];if(!t)throw new Error("Client scope contains a non-client resource. Ensure your Derived get() returns a client created with tapClientResource(), not a plain resource.");return t.getState?.()},Gg=new Map;function _I(e){let t=Gg.get(e);return t||(t=function(...n){if(!this||typeof this!="object")throw new Error(`Method "${String(e)}" called without proper context. This may indicate the function was called incorrectly.`);const r=this[gu];if(!r)throw new Error(`Method "${String(e)}" called on invalid client proxy. Ensure you are calling this method on a valid client instance.`);const s=r[e];if(!s)throw new Error(`Method "${String(e)}" is not implemented.`);if(typeof s!="function")throw new Error(`"${String(e)}" is not a function.`);return s(...n)},Gg.set(e,t)),t}var bI=class extends hp{constructor(t,n){super();A(this,"outputRef");A(this,"index");A(this,"boundFns");A(this,"cachedReceiver");this.outputRef=t,this.index=n}get(t,n,r){if(n===gu)return this.outputRef.current;if(n===Tf)return this.index;const s=oc(n,"ClientProxy");if(s!==!1)return s;const i=this.outputRef.current[n];if(typeof i=="function"){this.cachedReceiver!==r&&(this.boundFns=new Map,this.cachedReceiver=r);let o=this.boundFns.get(n);return o||(o=_I(n).bind(r),this.boundFns.set(n,o)),o}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(t,n){return n===gu||n===Tf?!0:n in this.outputRef.current}};const ab=ob(e=>{const t=ir(null),n=fp().length,r=ce(()=>new Proxy({},new bI(t,n)),[n]),s=vI(r,()=>pt(e));return t.current||(t.current=s),tt(()=>{t.current=s}),{methods:r,state:s.getState?.(),key:e.key}}),ac=e=>pt(ab(e)),$o=Symbol("assistant-ui.store.proxiedAssistantState"),Jc=e=>e==="on"||e==="subscribe"||typeof e=="symbol",lb=e=>{class t extends hp{get(r,s){const i=oc(s,"AssistantState");if(i!==!1)return i;const o=s;if(!Jc(o))return wI(e[o]())}ownKeys(){return Object.keys(e).filter(r=>!Jc(r))}has(r,s){return!Jc(s)&&s in e}}return new Proxy({},new t)},kI=e=>e[$o],Yg=()=>()=>{},ub=e=>{const t=()=>{throw new Error(e)};return t.source=null,t.query=null,t};var SI=class extends hp{get(e,t){if(t==="subscribe"||t==="on")return Yg;if(t===$o)return CI;const n=oc(t,"DefaultAssistantClient");return n!==!1?n:ub("You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.")}ownKeys(){return["subscribe","on",$o]}has(e,t){return t==="subscribe"||t==="on"||t===$o}};const lc=new Proxy({},new SI),CI=lb(lc),EI=()=>new Proxy({},{get(e,t){const n=oc(t,"AssistantClient");return n!==!1?n:ub(`The current scope does not have a "${String(t)}" property.`)}}),cb=m.createContext(lc),TI=()=>m.useContext(cb),Rr=({value:e,children:t})=>d.jsx(cb.Provider,{value:e,children:t}),En=ve(e=>null),If=Symbol("assistant-ui.transform-scopes");function db(e,t){const n=e;if(n[If])throw new Error("transformScopes is already attached to this resource");n[If]=t}function II(e){return e[If]}const fb=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},hb=tb(null),RI=(e,t)=>nb(hb,e,t),pb=()=>{const e=rb(hb);if(!e)throw new Error("AssistantTapContext is not available");return e},mb=()=>pb().clientRef,pp=()=>{const{emit:e}=pb(),t=fp();return or((n,r)=>{e(n,r,t)})};function PI(e,t){const n={...e},r=new Set;let s=!0;for(;s;){s=!1;for(const a of Object.values(n)){if(a.type===En||r.has(a.type))continue;r.add(a.type);const l=II(a.type);if(l){l(n,t),s=!0;break}}}const i={},o={};for(const[a,l]of Object.entries(n))l.type===En?o[a]=l:i[a]=l;return{rootClients:i,derivedClients:o}}const Qg=e=>ce(()=>e,[...Object.entries(e).flat()]),jI=(e,t)=>{const{rootClients:n,derivedClients:r}=PI(e,t);return{rootClients:Qg(n),derivedClients:Qg(r)}},AI=ve(()=>Ps(()=>{const e=new Map,t=new Set,n=new Set;return{on(r,s){const i=s;if(r==="*")return t.add(i),()=>t.delete(i);let o=e.get(r);return o||(o=new Set,e.set(r,o)),o.add(i),()=>{o.delete(i),o.size===0&&e.delete(r)}},emit(r,s,i){const o=e.get(r);!o&&t.size===0||queueMicrotask(()=>{const a=[];if(o)for(const l of o)try{l(s,i)}catch(u){a.push(u)}if(t.size>0){const l={event:r,payload:s};for(const u of t)try{u(l,i)}catch(c){a.push(c)}}if(a.length>0){if(a.length===1)throw a[0];for(const l of a)console.error(l);throw new AggregateError(a,"Errors occurred during event emission")}})},subscribe(r){return n.add(r),()=>n.delete(r)},notifySubscribers(){for(const r of n)try{r()}catch(s){console.error("NotificationManager: subscriber callback error",s)}}}})),NI=()=>null;function gb(e){const t=m.useMemo(()=>X_(a=>r(a)),[]),[n,r]=m.useReducer((a,l)=>(Fo(t,a),a+(l()?1:0)),0);Fo(t,n);const s=NI(),i=m.useMemo(()=>(e.key,pa(e.type,t,void 0,s)),[e.type,e.key,t,s]),o=Zr(i,e.props);return m.useLayoutEffect(()=>()=>Pi(i),[i]),m.useLayoutEffect(()=>{mu(t),Ui(i,o)}),o.output}const yb=e=>ce(()=>e,e),MI=ve(({element:e,emit:t,clientRef:n})=>{const{methods:r,state:s}=RI({clientRef:n,emit:t},()=>ac(e));return ce(()=>({state:s,methods:r}),[r,s])}),DI=ve(({element:e,notifications:t,clientRef:n,name:r})=>{const s=uI(MI({element:e,emit:t.emit,clientRef:n}));return tt(()=>s.subscribe(t.notifySubscribers),[s,t]),ce(()=>{const i=()=>s.getValue().methods;return Object.defineProperties(i,{source:{value:"root",writable:!1},query:{value:{},writable:!1},name:{value:r,configurable:!0}}),i},[s,r])}),OI=ve(()=>ce(()=>({clients:[],subscribe:void 0,on:void 0}),[])),LI=ve(({clients:e,clientRef:t})=>{const n=pt(AI());tt(()=>t.parent.subscribe(n.notifySubscribers),[t,n]);const r=yb(ic(()=>Object.keys(e).map(s=>lr(s,DI({element:e[s],notifications:n,clientRef:t,name:s}))),[e,n,t]));return ce(()=>({clients:r,subscribe:n.subscribe,on:function(s,i){if(!this)throw new Error("const { on } = useAui() is not supported. Use aui.on() instead.");const{scope:o,event:a}=fb(s);if(o!=="*"&&this[o].source===null)throw new Error(`Scope "${o}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);const l=n.on(a,(c,f)=>{if(o==="*"){i(c);return}const h=this[o]();h===f[yI(h)]&&i(c)});if(o!=="*"&&t.parent[o].source===null)return l;const u=t.parent.on(s,i);return()=>{l(),u()}}}),[r,n,t])}),zI=ve(({element:e,clientRef:t,name:n})=>{const r=ir(e.props);return r.current=e.props,ce(()=>{const s=()=>r.current.get(t.current);return Object.defineProperties(s,{source:{value:r.current.source},query:{value:r.current.query},name:{value:n,configurable:!0}}),s},[t,n])}),FI=(e,t)=>{let n;try{const r={};for(const s of Object.keys(t.query).sort())r[s]=t.query[s];n=JSON.stringify(r)}catch{n=String(t.query)}return`${e}::${t.source}::${n}`},BI=ve(({clients:e,clientRef:t})=>yb(ic(()=>Object.keys(e).map(n=>{const r=n,s=e[r];return lr(FI(r,s.props),zI({element:s,clientRef:t,name:r}))}),[e,t]))),$I=ve(({parent:e,clients:t})=>{const{rootClients:n,derivedClients:r}=jI(t,e),s=ir({parent:e,current:null}).current;tt(()=>{s.current=a});const i=pt(Object.keys(n).length>0?LI({clients:n,clientRef:s}):OI()),o=pt(BI({clients:r,clientRef:s})),a=ce(()=>{const l=e===lc?EI():e,u=Object.create(l);Object.assign(u,{subscribe:i.subscribe??e.subscribe,on:i.on??e.on,[$o]:lb(u)});for(const c of i.clients)u[c.name]=c;for(const c of o)u[c.name]=c;return u},[e,i,o]);return s.current===null&&(s.current=a),a});function ue(e,{parent:t}={parent:TI()}){if(e)return gb($I({parent:t??lc,clients:e}));if(t===null)throw new Error("received null parent, this usage is not allowed");return t}const G=e=>{const t=ue(),n=kI(t),r=m.useSyncExternalStore(t.subscribe,()=>e(n),()=>e(n));if(r===n)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return m.useDebugValue(r),r},UI=e=>{const t=ue(),n=m.useRef(!1),r=n.current?null:e(t);return G(()=>n.current?e(t):r),()=>(n.current=!0,e(t))},VI=Object.freeze({});function to({getItemState:e,children:t}){return HI(t(UI(e)))}const HI=e=>{const t=typeof e=="object"&&e!=null&&"type"in e?e:null,n=t?.type,r=t?.key;return m.useMemo(()=>t,[n,r,typeof t?.props=="object"&&t.props!=null&&Object.entries(t.props).length===0?VI:t?.props])??e},WI=Bt.createContext(!0);function Xg(){throw new Error("A function wrapped in useEffectEvent can't be called during rendering.")}const KI="use"in Bt?()=>{try{return Bt.use(WI)}catch{return!1}}:()=>!1;function qI(e){const t=Bt.useRef(Xg);return Bt.useInsertionEffect(()=>{t.current=e},[e]),(...n)=>{KI()&&Xg();const r=t.current;return r(...n)}}const yu=(e,t)=>{const n=ue(),r=qI(t),{scope:s,event:i}=fb(e);m.useEffect(()=>n.on({scope:s,event:i},r),[n,s,i])},GI=ob(e=>{if(e.key===void 0)throw new Error("tapClientResource: Element has no key");return pt(ab(e))});function Vi(e,t){const n=ic(()=>e().map(i=>GI(i)),t),r=ce(()=>Object.keys(n),[n]),s=ce(()=>n.reduce((i,o,a)=>(i[o.key]=a,i),{}),[n]);return{state:ce(()=>n.map(i=>i.state),[n]),get:i=>{if("index"in i){if(i.index<0||i.index>=r.length)throw new Error(`tapClientLookup: Index ${i.index} out of bounds (length: ${r.length})`);return n[i.index].methods}const o=s[i.key];if(o===void 0)throw new Error(`tapClientLookup: Key "${i.key}" not found`);return n[o].methods}}}const vb=ve(({toolkit:e,mcpApp:t})=>{const n=ic(()=>t?[lr("mcpApp",t)]:[],[t])[0],[r,s]=dn(()=>({})),i=ce(()=>({toolUIs:r,mcpApp:n,tools:Object.fromEntries(Object.entries(r).map(([l,u])=>[l,u.map(c=>c.render)]))}),[r,n]),o=mb(),a=ha((l,u,c)=>{const f={render:u,standalone:c?.standalone??!1};return s(h=>({...h,[l]:[...h[l]??[],f]})),()=>{s(h=>{const p=h[l]?.filter(_=>_!==f)??[];if(p.length>0)return{...h,[l]:p};const{[l]:g,...y}=h;return y})}},[]);return tt(()=>{if(!e)return;const l=[];for(const[c,f]of Object.entries(e)){const h="render"in f?f.render:void 0,p="renderText"in f?f.renderText:void 0,g=h??(p?gI(p):void 0);g&&l.push(a(c,g,{standalone:pI(f)}))}const u=Object.entries(e).reduce((c,[f,h])=>{if(h.type==="mcp")return c;const{display:p,render:g,renderText:y,..._}=h;return c[f]=_,c},{});return l.push(o.current.modelContext().register({getModelContext:()=>({tools:u})})),()=>{l.forEach(c=>c())}},[e,a,o]),{getState:()=>i,setToolUI:a}});db(vb,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=sb())});const Ks=e=>{const[,t]=dn(e.getState);return tt(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},xb=ve(({runtime:e})=>{const t=Ks(e);return{getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e}}),YI=ve(({runtime:e,index:t})=>pt(xb({runtime:ce(()=>e.getAttachmentByIndex(t),[e,t])}))),wb=ve(({threadIdRef:e,messageIdRef:t,runtime:n})=>{const r=Ks(n),s=pp();tt(()=>{const a=[];for(const l of["send","attachmentAdd"]){const u=n.unstable_on(l,()=>{s(`composer.${l}`,{threadId:e.current,...t&&{messageId:t.current}})});a.push(u)}return a.push(n.unstable_on("attachmentAddError",l=>{s("composer.attachmentAddError",{threadId:e.current,...t&&{messageId:t.current},...l.attachmentId&&{attachmentId:l.attachmentId},reason:l.reason,message:l.message})})),()=>{for(const l of a)l()}},[n,s,e,t]);const i=Vi(()=>r.attachments.map((a,l)=>lr(a.id,YI({runtime:n,index:l}))),[r.attachments,n]),o=ce(()=>({text:r.text,role:r.role,attachments:i.state,runConfig:r.runConfig,isEditing:r.isEditing,canCancel:r.canCancel,canSend:r.canSend,attachmentAccept:r.attachmentAccept,isEmpty:r.isEmpty,type:r.type??"thread",dictation:r.dictation,quote:r.quote,queue:[]}),[r,i.state]);return{getState:()=>o,setText:n.setText,setRole:n.setRole,setRunConfig:n.setRunConfig,addAttachment:n.addAttachment,reset:n.reset,clearAttachments:n.clearAttachments,send:n.send,cancel:n.cancel,beginEdit:n.beginEdit??(()=>{throw new Error("beginEdit is not supported in this runtime")}),startDictation:n.startDictation,stopDictation:n.stopDictation,setQuote:n.setQuote,attachment:a=>"id"in a?i.get({key:a.id}):i.get(a),queueItem:()=>{throw new Error("Queue is not supported in this runtime")},__internal_getRuntime:()=>n}}),QI=ve(({runtime:e})=>{const t=Ks(e);return{getState:()=>t,addToolResult:n=>e.addToolResult(n),resumeToolCall:n=>e.resumeToolCall(n),respondToToolApproval:n=>e.respondToToolApproval(n),__internal_getRuntime:()=>e}}),XI=ve(({runtime:e,index:t})=>pt(xb({runtime:ce(()=>e.getAttachmentByIndex(t),[e,t])}))),JI=ve(({runtime:e,index:t})=>pt(QI({runtime:ce(()=>e.getMessagePartByIndex(t),[e,t])}))),ZI=ve(({runtime:e,threadIdRef:t})=>{const n=Ks(e),[r,s]=dn(!1),[i,o]=dn(!1),a=ce(()=>({get current(){return e.getState().id}}),[e]),l=ac(wb({runtime:e.composer,threadIdRef:t,messageIdRef:a})),u=Vi(()=>n.content.map((h,p)=>lr("toolCallId"in h&&h.toolCallId!=null?`toolCallId-${h.toolCallId}`:`index-${p}`,JI({runtime:e,index:p}))),[n.content,e]),c=Vi(()=>(n.attachments??[]).map((h,p)=>lr(h.id,XI({runtime:e,index:p}))),[n.attachments,e]),f=ce(()=>({...n,parts:u.state,composer:l.state,isCopied:r,isHovering:i}),[n,u.state,l.state,r,i]);return{getState:()=>f,composer:()=>l.methods,reload:h=>e.reload(h),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:h=>e.submitFeedback(h),switchToBranch:h=>e.switchToBranch(h),getCopyText:()=>e.unstable_getCopyText(),part:h=>"index"in h?u.get({index:h.index}):u.get({key:`toolCallId-${h.toolCallId}`}),attachment:h=>"id"in h?c.get({key:h.id}):c.get(h),setIsCopied:s,setIsHovering:o,__internal_getRuntime:()=>e}}),eR=ve(({runtime:e,id:t,threadIdRef:n})=>pt(ZI({runtime:ce(()=>e.getMessageById(t),[e,t]),threadIdRef:n}))),tR=ve(({runtime:e})=>{const t=Ks(e),n=pp();tt(()=>{const a=[];for(const l of["runStart","runEnd","initialize","modelContextUpdate"]){const u=e.unstable_on(l,()=>{const c=e.getState()?.threadId||"unknown";n(`thread.${l}`,{threadId:c})});a.push(u)}return()=>{for(const l of a)l()}},[e,n]);const r=ce(()=>({get current(){return e.getState().threadId}}),[e]),s=ac(wb({runtime:e.composer,threadIdRef:r})),i=Vi(()=>t.messages.map(a=>lr(a.id,eR({runtime:e,id:a.id,threadIdRef:r}))),[t.messages,e,r]),o=ce(()=>({isEmpty:i.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,voice:t.voice,composer:s.state,messages:i.state}),[t,i,s.state]);return{getState:()=>o,composer:()=>s.methods,append:e.append,startRun:e.startRun,resumeRun:e.resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,connectVoice:e.connectVoice,disconnectVoice:e.disconnectVoice,getVoiceVolume:e.getVoiceVolume,subscribeVoiceVolume:e.subscribeVoiceVolume,muteVoice:e.muteVoice,unmuteVoice:e.unmuteVoice,message:a=>"id"in a?i.get({key:a.id}):i.get(a),__internal_getRuntime:()=>e}}),nR=ve(({runtime:e})=>{const t=Ks(e),n=pp();return tt(()=>{const r=[];for(const s of["switchedTo","switchedAway"]){const i=e.unstable_on(s,()=>{n(`threadListItem.${s}`,{threadId:e.getState().id})});r.push(i)}return()=>{for(const s of r)s()}},[e,n]),{getState:()=>t,switchTo:e.switchTo,rename:e.rename,updateCustom:e.updateCustom,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e}}),rR=ve(({runtime:e,id:t})=>pt(nR({runtime:ce(()=>e.getItemById(t),[e,t])}))),sR=ve(({runtime:e,__internal_assistantRuntime:t})=>{const n=Ks(e),r=ac(tR({runtime:e.main})),s=Vi(()=>Object.keys(n.threadItems).map(o=>lr(o,rR({runtime:e,id:o}))),[n.threadItems,e]),i=ce(()=>({mainThreadId:n.mainThreadId,newThreadId:n.newThreadId??null,isLoading:n.isLoading,isLoadingMore:n.isLoadingMore,hasMore:n.hasMore,threadIds:n.threadIds,archivedThreadIds:n.archivedThreadIds,threadItems:s.state,main:r.state}),[n,s.state,r.state]);return{getState:()=>i,thread:()=>r.methods,item:o=>{if(o==="main")return s.get({key:i.mainThreadId});if("id"in o)return s.get({key:o.id});const{index:a,archived:l=!1}=o,u=l?i.archivedThreadIds[a]:i.threadIds[a];return s.get({key:u})},switchToThread:async(o,a)=>{await e.switchToThread(o,a)},switchToNewThread:async()=>{await e.switchToNewThread()},getLoadThreadsPromise:()=>e.getLoadThreadsPromise(),reload:()=>e.reload(),loadMore:()=>e.loadMore(),__internal_getAssistantRuntime:()=>t}}),iR=ve(e=>({getState:()=>e})),oR=ve(e=>{const[t]=dn(()=>({suggestions:(e??[]).map(r=>typeof r=="string"?{title:r,label:"",prompt:r}:{title:r.title,label:r.label,prompt:r.prompt})})),n=Vi(()=>t.suggestions.map((r,s)=>lr(s,iR(r))),[t.suggestions]);return{getState:()=>t,suggestion:({index:r})=>n.get({index:r})}}),aR=ve(e=>{const t=mb();return tt(()=>e.registerModelContextProvider(t.current.modelContext()),[e,t]),pt(sR({runtime:e.threads,__internal_assistantRuntime:e}))}),lR=(e,t)=>{e.thread??(e.thread=En({source:"threads",query:{type:"main"},get:n=>n.threads().thread("main")})),e.threadListItem??(e.threadListItem=En({source:"threads",query:{type:"main"},get:n=>n.threads().item("main")})),e.composer??(e.composer=En({source:"thread",query:{},get:n=>n.threads().thread("main").composer()})),!e.modelContext&&t.modelContext.source===null&&(e.modelContext=sb()),!e.suggestions&&t.suggestions.source===null&&(e.suggestions=oR())},_b=ve(e=>pt(aR(e)));db(_b,(e,t)=>{lR(e,t),!e.tools&&t.tools.source===null&&(e.tools=vb({})),!e.dataRenderers&&t.dataRenderers.source===null&&(e.dataRenderers=cI())});const uR=e=>e._core?.RenderComponent,cR=m.memo(({runtime:e,aui:t=null,children:n})=>{const r=ue({threads:_b(e)},{parent:t}),s=uR(e);return d.jsxs(Rr,{value:r,children:[s&&d.jsx(s,{}),n]})}),Jg=e=>{let t;const n=new Set,r=(u,c)=>{const f=typeof u=="function"?u(t):u;if(!Object.is(f,t)){const h=t;t=c??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(p=>p(t,h))}},s=()=>t,a={setState:r,getState:s,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u))},l=t=e(r,s,a);return a},dR=e=>e?Jg(e):Jg,fR=e=>e;function hR(e,t=fR){const n=Bt.useSyncExternalStore(e.subscribe,Bt.useCallback(()=>t(e.getState()),[e,t]),Bt.useCallback(()=>t(e.getInitialState()),[e,t]));return Bt.useDebugValue(n),n}const Zg=e=>{const t=dR(e),n=r=>hR(t,r);return Object.assign(n,t),n},bb=e=>e?Zg(e):Zg,mp=()=>{let e,t;const n=new Promise((r,s)=>{e=r,t=s});if(!e||!t)throw new Error("Failed to create promise");return{promise:n,resolve:e,reject:t}},pR=()=>{const e=[];let t=!1,n,r;const s=i=>{i.promise||(i.promise=i.reader.read().then(({done:o,value:a})=>{i.promise=void 0,o?(e.splice(e.indexOf(i),1),t&&e.length===0&&n.close()):n.enqueue(a),r?.resolve(),r=void 0}).catch(o=>{console.error(o),e.forEach(a=>{a.reader.cancel()}),e.length=0,n.error(o),r?.reject(o),r=void 0}))};return{readable:new ReadableStream({start(i){n=i},pull(){return r=mp(),e.forEach(i=>{s(i)}),r.promise},cancel(){e.forEach(i=>{i.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&n.close()},addStream(i){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:i.getReader()};e.push(o),s(o)},enqueue(i){this.addStream(new ReadableStream({start(o){o.enqueue(i),o.close()}}))}}};var ey=class{constructor(e){A(this,"_controller");A(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}};const kb=e=>new ReadableStream({start(t){return e.start?.(new ey(t))},pull(t){return e.pull?.(new ey(t))},cancel(t){return e.cancel?.(t)}}),ty=()=>{let e;return[kb({start(t){e=t}}),e]};var ny=class{constructor(e){A(this,"_controller");A(this,"_isClosed",!1);A(this,"_mergeTask");A(this,"_argsTextController");this._controller=e;const t=kb({start:r=>{this._argsTextController=r}});let n=!1;this._mergeTask=t.pipeTo(new WritableStream({write:r=>{switch(r.type){case"text-delta":n=!0,this._controller.enqueue(r);break;case"part-finish":n||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${r.type}`)}}}))}get argsText(){return this._argsTextController}async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...e.artifact!==void 0?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1,...e.modelContent!==void 0?{modelContent:e.modelContent}:{},...e.messages!==void 0?{messages:e.messages}:{}})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}};const mR=e=>new ReadableStream({start(t){return e.start?.(new ny(t))},pull(t){return e.pull?.(new ny(t))},cancel(t){return e.cancel?.(t)}}),gR=()=>{let e;return[mR({start(t){e=t}}),e]};var Sb=class{constructor(){A(this,"value",-1)}up(){return++this.value}},yR=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue({...t,path:[e,...t.path]})}})}};(class extends TransformStream{constructor(e){super({transform(t,n){const{path:[r,...s]}=t;if(e!==r)throw new Error(`Path mismatch: expected ${e}, got ${r}`);n.enqueue({...t,path:s})}})}});var vR=class extends TransformStream{constructor(e){const t=new Sb,n=new Map;super({transform(r,s){r.type==="part-start"&&r.path.length===0&&n.set(t.up(),e.up());const[i,...o]=r.path;if(i===void 0){s.enqueue(r);return}const a=n.get(i);if(a===void 0)throw new Error("Path not found");s.enqueue({...r,path:[a,...o]})}})}},xR=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},Cb=class extends TransformStream{constructor(){const e=[];super({transform(t,n){if(t.type==="part-start"){if(t.path.length!==0){n.error(new Error("Nested parts are not supported"));return}e.push(t.part),n.enqueue(t);return}if(t.type==="text-delta"||t.type==="result"||t.type==="part-finish"||t.type==="tool-call-args-text-finish"){if(t.path.length!==1){n.error(new Error(`${t.type} chunks must have a path of length 1`));return}const r=t.path[0];if(r<0||r>=e.length){n.error(new Error(`Invalid path index: ${r}`));return}const s=e[r];n.enqueue({...t,meta:s});return}n.enqueue(t)}})}};let Eb=(e,t=21)=>(n=t)=>{let r="",s=n|0;for(;s--;)r+=e[Math.random()*e.length|0];return r};const wR=Eb("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);var _R=class Tb{constructor(t){A(this,"_state");A(this,"_parentId");this._state=t||{merger:pR(),contentCounter:new Sb}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,n){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(n.pipeThrough(new yR(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new vR(this._state.contentCounter)))}appendText(t){(this._state.append?.kind!=="text"||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:"text",parentId:this._parentId,controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){(this._state.append?.kind!=="reasoning"||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:"reasoning",parentId:this._parentId,controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,n]=ty();return this._addPart(this._withParentIdOption({type:"text"}),t),n}addReasoningPart(){const[t,n]=ty();return this._addPart(this._withParentIdOption({type:"reasoning"}),t),n}addToolCallPart(t){const n=typeof t=="string"?{toolName:t}:t,r=n.toolName,s=n.toolCallId??wR(),[i,o]=gR();return this._addPart({type:"tool-call",toolName:r,toolCallId:s,...this._parentId&&{parentId:this._parentId}},i),n.argsText!==void 0&&(o.argsText.append(n.argsText),o.argsText.close()),n.args!==void 0&&(o.argsText.append(JSON.stringify(n.args)),o.argsText.close()),n.response!==void 0&&o.setResponse(n.response),o}_finishedPartStream(){return new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}})}_withParentIdOption(t){return this._parentId?{...t,parentId:this._parentId}:t}appendSource(t){this._addPart(this._withParentIdOption(t),this._finishedPartStream())}appendFile(t){this._addPart(this._withParentIdOption(t),this._finishedPartStream())}appendData(t){this._addPart(this._withParentIdOption(t),this._finishedPartStream())}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const n=new Tb(this._state);return n._parentId=t,n}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function bR(e){const t=new _R;return(async()=>{try{await e(t)}catch(r){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(r)}),r}finally{t.__internal_isClosed||t.close()}})(),t.__internal_getReadable()}function kR(){const{resolve:e,promise:t}=mp();let n;return[bR(r=>(n=r,n.__internal_subscribeToClose(e),t)),n]}function SR(e){const t=["ROOT"];let n=-1,r=null;const s=[];let i;function o(){i!==void 0&&(s.push(JSON.parse(`"${i}"`)),i=void 0)}function a(f,h,p){switch(f){case'"':n=h,t.pop(),t.push(p),t.push("INSIDE_STRING"),o();break;case"f":case"t":case"n":n=h,r=h,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(p),t.push("INSIDE_NUMBER"),o();break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=h,t.pop(),t.push(p),t.push("INSIDE_NUMBER"),o();break;case"{":n=h,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START"),o();break;case"[":n=h,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START"),o();break}}function l(f,h){switch(f){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=h,t.pop(),i=s.pop();break}}function u(f,h){switch(f){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break;case"]":n=h,t.pop(),i=s.pop();break}}for(let f=0;f<e.length;f++){const h=e[f];switch(t[t.length-1]){case"ROOT":a(h,f,"FINISH");break;case"INSIDE_OBJECT_START":switch(h){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break;case"}":n=f,t.pop(),i=s.pop();break}break;case"INSIDE_OBJECT_AFTER_COMMA":switch(h){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}break;case"INSIDE_OBJECT_KEY":switch(h){case'"':t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"\\":t.push("INSIDE_STRING_ESCAPE"),i+=h;break;default:i+=h;break}break;case"INSIDE_OBJECT_AFTER_KEY":switch(h){case":":t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}break;case"INSIDE_OBJECT_BEFORE_VALUE":a(h,f,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":l(h,f);break;case"INSIDE_STRING":switch(h){case'"':t.pop(),n=f,i=s.pop();break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=f}break;case"INSIDE_ARRAY_START":switch(h){case"]":n=f,t.pop(),i=s.pop();break;default:n=f,i="0",a(h,f,"INSIDE_ARRAY_AFTER_VALUE");break}break;case"INSIDE_ARRAY_AFTER_VALUE":switch(h){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break;case"]":n=f,t.pop(),i=s.pop();break;default:n=f;break}break;case"INSIDE_ARRAY_AFTER_COMMA":a(h,f,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),t[t.length-1]==="INSIDE_STRING"?n=f:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(i+=h);break;case"INSIDE_NUMBER":switch(h){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=f;break;case"e":case"E":case"-":case".":break;case",":t.pop(),i=s.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,f),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,f);break;case"}":t.pop(),i=s.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,f);break;case"]":t.pop(),i=s.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,f);break;default:t.pop(),i=s.pop();break}break;case"INSIDE_LITERAL":{const p=e.substring(r,f+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(h,f):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,f)):n=f;break}}}let c=e.slice(0,n+1);for(let f=t.length-1;f>=0;f--)switch(t[f]){case"INSIDE_STRING":c+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":c+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":c+="]";break;case"INSIDE_LITERAL":{const h=e.substring(r,e.length);"true".startsWith(h)?c+="true".slice(h.length):"false".startsWith(h)?c+="false".slice(h.length):"null".startsWith(h)&&(c+="null".slice(h.length))}}return[c,s]}var no={exports:{}};const CR=typeof Buffer<"u",ry=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,sy=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Ib(e,t,n){n==null&&t!==null&&typeof t=="object"&&(n=t,t=void 0),CR&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));const r=JSON.parse(e,t);if(r===null||typeof r!="object")return r;const s=n&&n.protoAction||"error",i=n&&n.constructorAction||"error";if(s==="ignore"&&i==="ignore")return r;if(s!=="ignore"&&i!=="ignore"){if(ry.test(e)===!1&&sy.test(e)===!1)return r}else if(s!=="ignore"&&i==="ignore"){if(ry.test(e)===!1)return r}else if(sy.test(e)===!1)return r;return Rb(r,{protoAction:s,constructorAction:i,safe:n&&n.safe})}function Rb(e,{protoAction:t="error",constructorAction:n="error",safe:r}={}){let s=[e];for(;s.length;){const i=s;s=[];for(const o of i){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(o,"__proto__")){if(r===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete o.__proto__}if(n!=="ignore"&&Object.prototype.hasOwnProperty.call(o,"constructor")&&o.constructor!==null&&typeof o.constructor=="object"&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype")){if(r===!0)return null;if(n==="error")throw new SyntaxError("Object contains forbidden prototype property");delete o.constructor}for(const a in o){const l=o[a];l&&typeof l=="object"&&s.push(l)}}}return e}function gp(e,t,n){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return Ib(e,t,n)}finally{Error.stackTraceLimit=r}}function ER(e,t){const{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return Ib(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}no.exports=gp;no.exports.default=gp;no.exports.parse=gp;no.exports.safeParse=ER;no.exports.scan=Rb;var TR=no.exports;const Rf=Ia(TR),Ol=Symbol("aui.parse-partial-json-object.meta"),IR=e=>e?.[Ol],Pf=e=>{if(e.length===0)return{[Ol]:{state:"partial",partialPath:[]}};try{const t=Rf.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Ol]={state:"complete",partialPath:[]},t}catch{try{const[t,n]=SR(e),r=Rf.parse(t);if(typeof r!="object"||r===null)throw new Error("argsText is expected to be an object");return r[Ol]={state:"partial",partialPath:n},r}catch{return}}},Pb=(e,t,n)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(n.length===0)return t.state;const[r,...s]=n;if(!Object.hasOwn(e,r))return"partial";const[i,...o]=t.partialPath;if(r!==i)return"complete";const a=e[r];return Pb(a,{state:"partial",partialPath:o},s)},Hi=(e,t)=>{const n=IR(e);if(!n)throw new Error("unable to determine object state");return Pb(e,n,t.map(String))};async function*RR(){const e=this.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{e.releaseLock()}}function Zc(e){var t;return e[t=Symbol.asyncIterator]??(e[t]=RR),e}const iy=Symbol.for("aui.tool-response");var wr=class jf{constructor(t){A(this,"artifact");A(this,"result");A(this,"isError");A(this,"modelContent");A(this,"messages");t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=t.isError??!1,t.modelContent!==void 0&&(this.modelContent=t.modelContent),t.messages!==void 0&&(this.messages=t.messages)}get[iy](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&iy in t}static toResponse(t){return t instanceof jf?t:new jf({result:t===void 0?"<no result>":t})}};function PR(e,t,n){try{const r=e();if(typeof r=="object"&&r!==null&&"then"in r)return r.then(t,n);t(r)}catch(r){n(r)}}function Wi(e,t){let n=e;for(const r of t){if(n==null)return;n=n[r]}return n}var jR=class{constructor(e,t,n){A(this,"resolve");A(this,"reject");A(this,"disposed",!1);A(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=n}update(e){if(!this.disposed)try{if(Hi(e,this.fieldPath)==="complete"){const t=Wi(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}end(e){if(!this.disposed)try{const t=Wi(e,this.fieldPath);this.resolve(t)}catch(t){this.reject(t)}finally{this.dispose()}}dispose(){this.disposed=!0}},AR=class{constructor(e,t){A(this,"controller");A(this,"disposed",!1);A(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=Wi(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),Hi(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},NR=class{constructor(e,t){A(this,"controller");A(this,"disposed",!1);A(this,"fieldPath");A(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=Wi(e,this.fieldPath);if(t!==void 0&&typeof t=="string"){const n=t.substring(this.lastValue?.length||0);this.lastValue=t,this.controller.enqueue(n)}Hi(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},MR=class{constructor(e,t){A(this,"controller");A(this,"disposed",!1);A(this,"fieldPath");A(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=Wi(e,this.fieldPath);if(!Array.isArray(t))return;for(let n=0;n<t.length;n++)this.processedIndexes.has(n)||Hi(e,[...this.fieldPath,n])==="complete"&&(this.controller.enqueue(t[n]),this.processedIndexes.add(n));Hi(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},DR=class{constructor(e){A(this,"argTextDeltas");A(this,"handles",new Set);A(this,"args",Pf(""));A(this,"finished",!1);this.argTextDeltas=e,this.processStream()}async processStream(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:n,done:r}=await t.read();if(r)break;e+=n;const s=Pf(e);if(s!==void 0){this.args=s;for(const i of this.handles)i.update(s)}}}catch(e){console.error("Error processing argument stream:",e)}finally{this.finished=!0;for(const e of this.handles)e.end(this.args);this.handles.clear()}}get(...e){return new Promise((t,n)=>{const r=new jR(t,n,e);if(this.args&&Hi(this.args,e)==="complete"){const s=Wi(this.args,e);if(s!==void 0){t(s);return}}if(this.finished){r.end(this.args);return}this.handles.add(r),r.update(this.args)})}streamValues(...e){const t=e;let n;return Zc(new ReadableStream({start:r=>{n=new AR(r,t),this.finished||this.handles.add(n),n.update(this.args),this.finished&&n.end()},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}streamText(...e){const t=e;let n;return Zc(new ReadableStream({start:r=>{n=new NR(r,t),this.finished||this.handles.add(n),n.update(this.args),this.finished&&n.end()},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}forEach(...e){const t=e;let n;return Zc(new ReadableStream({start:r=>{n=new MR(r,t),this.finished||this.handles.add(n),n.update(this.args),this.finished&&n.end()},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}},OR=class{constructor(e){A(this,"promise");this.promise=e}get(){return this.promise}},LR=class{constructor(){A(this,"args");A(this,"response");A(this,"writable");A(this,"resolve");A(this,"argsText","");A(this,"result",{get:async()=>(await this.response.get()).result});const e=new TransformStream;this.writable=e.writable,this.args=new DR(e.readable);const{promise:t,resolve:n}=mp();this.resolve=n,this.response=new OR(t)}async appendArgsTextDelta(e){const t=this.writable.getWriter();try{await t.write(e)}catch(n){console.warn(n)}finally{t.releaseLock()}this.argsText+=e}async finishArgsText(){const e=this.writable.getWriter();try{await e.close()}catch(t){console.warn(t)}finally{e.releaseLock()}}setResponse(e){this.resolve(e)}},zR=class extends xR{constructor(e){const t=new Map,n=new Map;super(r=>{const s=new TransformStream({async transform(i,o){switch((i.type!=="part-finish"||i.meta.type!=="tool-call")&&o.enqueue(i),i.type){case"part-start":if(i.part.type==="tool-call"){const a=new LR;n.set(i.part.toolCallId,a),e.streamCall({reader:a,toolCallId:i.part.toolCallId,toolName:i.part.toolName})}break;case"text-delta":if(i.meta.type==="tool-call"){const a=i.meta.toolCallId,l=n.get(a);if(!l)throw new Error("No controller found for tool call");await l.appendArgsTextDelta(i.textDelta)}break;case"result":{if(i.meta.type!=="tool-call")break;const{toolCallId:a}=i.meta,l=n.get(a);if(!l)throw new Error("No controller found for tool call");l.setResponse(new wr({result:i.result,artifact:i.artifact,isError:i.isError,modelContent:i.modelContent}));break}case"tool-call-args-text-finish":{if(i.meta.type!=="tool-call")break;const{toolCallId:a,toolName:l}=i.meta,u=n.get(a);if(!u)throw new Error("No controller found for tool call");await u.finishArgsText();let c=!1;const f=PR(()=>{let h;try{h=Rf.parse(u.argsText)}catch(g){throw new Error(`Function parameter parsing failed. ${JSON.stringify(g.message)}`)}const p=e.execute({toolCallId:a,toolName:l,args:h});return p!==void 0&&(c=!0,e.onExecutionStart?.(a,l)),p},h=>{if(c&&e.onExecutionEnd?.(a,l),h===void 0)return;const p=new wr({artifact:h.artifact,result:h.result,isError:h.isError,messages:h.messages,modelContent:h.modelContent});u.setResponse(p),o.enqueue({type:"result",path:i.path,...p})},h=>{c&&e.onExecutionEnd?.(a,l);const p=new wr({result:String(h),isError:!0});u.setResponse(p),o.enqueue({type:"result",path:i.path,...p})});f&&t.set(a,f);break}case"part-finish":{if(i.meta.type!=="tool-call")break;const{toolCallId:a}=i.meta,l=t.get(a);l?l.then(()=>{t.delete(a),n.delete(a),o.enqueue(i)}):o.enqueue(i)}}},async flush(){await Promise.all(t.values())}});return r.pipeThrough(new Cb).pipeThrough(s)})}};const FR=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function BR(e,t,n,r){const s=e?.[n.toolName];return s?.execute?(async o=>{if(t.aborted)return new wr({result:"Tool execution was cancelled.",isError:!0});let a=o;if(FR(s.parameters)){let c=s.parameters["~standard"].validate(n.args);c instanceof Promise&&(c=await c),c.issues&&(a=s.experimental_onSchemaValidationError??(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const f=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new wr({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?f():t.addEventListener("abort",f,{once:!0})}),u=(async()=>{const c=await a(n.args,{toolCallId:n.toolCallId,abortSignal:t,human:h=>r(n.toolCallId,h)}),f=wr.toResponse(c);if(s.toModelOutput&&!f.isError&&f.modelContent===void 0)try{const h=await s.toModelOutput({toolCallId:n.toolCallId,input:n.args,output:f.result});return new wr({result:f.result,artifact:f.artifact,isError:f.isError,messages:f.messages,modelContent:h})}catch(h){console.warn(`[assistant-stream] tool "${n.toolName}" toModelOutput threw; falling back to default projection.`,h)}return f})();return Promise.race([u,l])})(s.execute):void 0}function $R(e,t,n,r,s){e?.[r.toolName]?.streamCall?.(n,{toolCallId:r.toolCallId,abortSignal:t,human:i=>s(r.toolCallId,i)})}function UR(e,t,n,r){const s=typeof e=="function"?e:()=>e,i=typeof t=="function"?t:()=>t;return new zR({execute:o=>BR(s(),i(),o,n),streamCall:({reader:o,...a})=>$R(s(),i(),o,a,n),onExecutionStart:r?.onExecutionStart,onExecutionEnd:r?.onExecutionEnd})}const jb=({index:e,children:t})=>d.jsx(Rr,{value:ue({attachment:En({source:"message",query:{type:"index",index:e},get:n=>n.message().attachment({index:e})})}),children:t}),Ab=({index:e,children:t})=>d.jsx(Rr,{value:ue({attachment:En({source:"composer",query:{type:"index",index:e},get:n=>n.composer().attachment({index:e})})}),children:t}),Nb=({index:e,children:t})=>d.jsx(Rr,{value:ue({message:En({source:"thread",query:{type:"index",index:e},get:n=>n.thread().message({index:e})}),composer:En({source:"message",query:{},get:n=>n.thread().message({index:e}).composer()})}),children:t}),yp=({index:e,children:t})=>d.jsx(Rr,{value:ue({part:En({source:"message",query:{type:"index",index:e},get:n=>n.message().part({index:e})})}),children:t}),VR=ve(({text:e,isRunning:t})=>{const n=ce(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return{getState:()=>n,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")},respondToToolApproval:()=>{throw new Error("Not supported")}}}),vp=({text:e,isRunning:t=!1,children:n})=>d.jsx(Rr,{value:ue({part:VR({text:e,isRunning:t})}),children:n}),HR=Object.freeze({type:"complete"}),WR=ve(({parts:e,getMessagePart:t})=>{const[n,r]=dn(!0),s=ce(()=>e[e.length-1]?.status??HR,[e]),i=ce(()=>({parts:e,collapsed:n,status:s}),[e,n,s]);return{getState:()=>i,setCollapsed:r,part:t}}),KR=({startIndex:e,endIndex:t,children:n})=>{const r=G(i=>i.message.parts).slice(e,t+1),s=ue();return d.jsx(Rr,{value:ue({chainOfThought:WR({parts:r,getMessagePart:({index:i})=>{if(i<0||i>=r.length)throw new Error(`ChainOfThought part index ${i} is out of bounds (0..${r.length-1})`);return s.message().part({index:e+i})}})}),children:n})},Mb=({index:e,children:t})=>d.jsx(Rr,{value:ue({suggestion:En({source:"suggestions",query:{index:e},get:n=>n.suggestions().suggestion({index:e})})}),children:t}),qR=({index:e,children:t})=>d.jsx(Rr,{value:ue({queueItem:En({source:"composer",query:{index:e},get:n=>n.composer().queueItem({index:e})})}),children:t}),$s=Symbol("innerMessage"),ed=Symbol("innerMessages"),GR=[],YR=(e,t)=>{$s in e||(e[$s]=t)},QR=e=>{const t="messages"in e?e.messages:e,n=t[ed]||t[$s];return n?Array.isArray(n)?n:(t[ed]=[n],t[ed]):GR},Hn=Symbol("skip-update");function XR(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const n of Object.keys(e)){const r=e[n],s=t[n];if(!Object.is(r,s))return!1}return!0}var JR=class{constructor(){A(this,"_subscribers",new Set)}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{const t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){const e=[];for(const t of this._subscribers)try{t()}catch(n){e.push(n)}if(e.length>0){if(e.length===1)throw e[0];for(const t of e)console.error(t);throw new AggregateError(e)}}},uc=class{constructor(){A(this,"_subscriptions",new Set);A(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(e){for(const t of this._subscriptions)t(e)}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else this._connection?.(),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},Fn=class extends uc{constructor(t){super();A(this,"binding");A(this,"_previousState");A(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const n=t.getState();if(n===Hn)throw new Error("Entry not available in the store");this._previousState=n}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===Hn||XR(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},xp=class extends uc{constructor(t){super();A(this,"binding");A(this,"_previousStateDirty",!0);A(this,"_previousState");A(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Hn&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=t}get path(){return this.binding.path}_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}},vu=class extends uc{constructor(t){super();A(this,"binding");this.binding=t}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let n=this.binding.getState(),r=n?.subscribe(t);const s=()=>{const o=this.binding.getState();o!==n&&(n=o,r?.(),r=o?.subscribe(t),t())},i=this.outerSubscribe(s);return()=>{i?.(),r?.()}}},Db=class extends uc{constructor(t){super();A(this,"config");this.config=t}getState(){return this.config.binding.getState()}outerSubscribe(t){return this.config.binding.subscribe(t)}_connect(){const t=o=>{this.notifySubscribers(o)};let n=this.config.binding.getState(),r=n?.unstable_on(this.config.event,t);const s=()=>{const o=this.config.binding.getState();o!==n&&(n=o,r?.(),r=o?.unstable_on(this.config.event,t))},i=this.outerSubscribe(s);return()=>{i?.(),r?.()}}},Ob=class{constructor(e){A(this,"_core");this._core=e,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},Lb=class extends Ob{constructor(t,n){super(t);A(this,"_composerApi");this._composerApi=n}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}},ZR=class extends Lb{get source(){return"thread-composer"}},eP=class extends Lb{get source(){return"edit-composer"}},tP=class extends Ob{get source(){return"message"}remove(){throw new Error("Message attachments cannot be removed")}};const zb=Object.freeze([]),Fb=Object.freeze({}),nP=e=>Object.freeze({type:"thread",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??zb,text:e?.text??"",role:e?.role??"user",runConfig:e?.runConfig??Fb,attachmentAccept:e?.attachmentAccept??"",dictation:e?.dictation,quote:e?.quote,value:e?.text??""}),rP=e=>Object.freeze({type:"edit",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,text:e?.text??"",role:e?.role??"user",attachments:e?.attachments??zb,runConfig:e?.runConfig??Fb,attachmentAccept:e?.attachmentAccept??"",dictation:e?.dictation,quote:e?.quote,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??""});var Bb=class{constructor(e){A(this,"_core");A(this,"_eventSubscriptionSubjects",new Map);this._core=e}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.startDictation=this.startDictation.bind(this),this.stopDictation=this.stopDictation.bind(this),this.setQuote=this.setQuote.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setText(e)}setRunConfig(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.addAttachment(e)}reset(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.reset()}clearAttachments(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.clearAttachments()}send(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.send(e)}cancel(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.cancel()}setRole(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRole(e)}startDictation(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.startDictation()}stopDictation(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.stopDictation()}setQuote(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setQuote(e)}subscribe(e){return this._core.subscribe(e)}unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new Db({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},sP=class extends Bb{constructor(t){const n=new xp({path:t.path,getState:()=>nP(t.getState()),subscribe:r=>t.subscribe(r)});super({path:t.path,getState:()=>t.getState(),subscribe:r=>n.subscribe(r)});A(this,"_getState");this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new ZR(new Fn({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}.attachments[${t}]`},getState:()=>{const n=this.getState().attachments[t];return n?{...n,source:"thread-composer"}:Hn},subscribe:n=>this._core.subscribe(n)}),this._core)}},iP=class extends Bb{constructor(t,n){const r=new xp({path:t.path,getState:()=>rP(t.getState()),subscribe:s=>t.subscribe(s)});super({path:t.path,getState:()=>t.getState(),subscribe:s=>r.subscribe(s)});A(this,"_beginEdit");A(this,"_getState");this._beginEdit=n,this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new eP(new Fn({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}.attachments[${t}]`},getState:()=>{const n=this.getState().attachments[t];return n?{...n,source:"edit-composer"}:Hn},subscribe:n=>this._core.subscribe(n)}),this._core)}};const ma=e=>e.content.filter(t=>t.type==="text").map(t=>t.text).join(`
43
43
 
44
- `);var oy=class{constructor(e,t,n){A(this,"contentBinding");A(this,"messageApi");A(this,"threadApi");this.contentBinding=e,this.messageApi=t,this.threadApi=n,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.respondToToolApproval=this.respondToToolApproval.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const n=this.messageApi.getState();if(!n)throw new Error("Message is not available");const r=t.toolName,s=t.toolCallId,i=wr.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:s,result:i.result,artifact:i.artifact,isError:i.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e})}respondToToolApproval(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to respond to tool approval on non-tool message part");if(!t.approval||t.approval.approved!==void 0)throw new Error("Tool call has no pending approval");if(!this.threadApi)throw new Error("Thread API is not available");this.threadApi.getState().respondToToolApproval({approvalId:t.approval.id,approved:e.approved,...e.reason!=null&&{reason:e.reason}})}subscribe(e){return this.contentBinding.subscribe(e)}};const cl=Object.freeze({type:"complete"}),oP=(e,t,n)=>{if(e.role!=="assistant")return cl;if(n.type==="tool-call")return n.result?cl:e.status;const r=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?cl:r?e.status:cl},ay=(e,t)=>{const n=e.content[t];if(!n)return Hn;const r=oP(e,t,n);return Object.freeze({...n,[$s]:n[$s],status:r})};var aP=class{constructor(e,t){A(this,"_core");A(this,"_threadBinding");A(this,"composer");A(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new iP(new vu({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:n=>this._threadBinding.subscribe(n)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(e={}){const t=this._getEditComposerRuntimeCore(),n=t??this._threadBinding.getState().composer,r=t??n,{runConfig:s=r.runConfig}=e,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:s})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){const e=this._core.getState();if(this._threadBinding.getState().speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const n=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");if(!t&&!e)throw new Error("Must specify either branchId or position");const r=this._threadBinding.getState().getBranches(n.id);let s=t;if(e==="previous"?s=r[n.branchNumber-2]:e==="next"&&(s=r[n.branchNumber]),!s)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(s)}unstable_getCopyText(){return ma(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new oy(new Fn({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}},getState:()=>ay(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new oy(new Fn({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}},getState:()=>{const t=this._core.getState(),n=t.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===e);return n===-1?Hn:ay(t,n)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new tP(new Fn({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}},getState:()=>{const t=this.getState().attachments?.[e];return t?{...t,source:"message"}:Hn},subscribe:t=>this._core.subscribe(t)}))}};const lP=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),uP=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),cP=(e,t)=>typeof t=="string"?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId??e.at(-1)?.id??null,sourceId:t.sourceId??null,role:t.role??"user",content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},dP=(e,t)=>{const n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:e.isRunning??(n?.role!=="assistant"?!1:n.status.type==="running"),messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech,voice:e.voice})};var $b=class{constructor(e,t){A(this,"_threadBinding");A(this,"composer");A(this,"_eventSubscriptionSubjects",new Map);const n=new Fn({path:e.path,getState:()=>dP(e.getState(),t.getState()),subscribe:r=>{const s=e.subscribe(r),i=t.subscribe(r);return()=>{s(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:r=>e.outerSubscribe(r),subscribe:r=>e.subscribe(r)},this.composer=new sP(new vu({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.resumeRun=this.resumeRun.bind(this),this.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.connectVoice=this.connectVoice.bind(this),this.disconnectVoice=this.disconnectVoice.bind(this),this.muteVoice=this.muteVoice.bind(this),this.unmuteVoice=this.unmuteVoice.bind(this),this.getVoiceVolume=this.getVoiceVolume.bind(this),this.subscribeVoiceVolume=this.subscribeVoiceVolume.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(cP(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}startRun(e){return this._threadBinding.getState().startRun(uP(e))}resumeRun(e){return this._threadBinding.getState().resumeRun(lP(e))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}connectVoice(){this._threadBinding.getState().connectVoice()}disconnectVoice(){this._threadBinding.getState().disconnectVoice()}getVoiceVolume(){return this._threadBinding.getState().getVoiceVolume()}subscribeVoiceVolume(e){return this._threadBinding.getState().subscribeVoiceVolume(e)}muteVoice(){this._threadBinding.getState().muteVoice()}unmuteVoice(){this._threadBinding.getState().unmuteVoice()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}},()=>{const t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:t[e-1]?.id??null,index:e}})}getMessageById(e){return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}},()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new aP(new Fn({path:e,getState:()=>{const{message:n,parentId:r,index:s}=t()??{},{messages:i,speech:o}=this._threadBinding.getState();if(!n||r===void 0||s===void 0)return Hn;const a=this._threadBinding.getState().getBranches(n.id);return{...n,[$s]:n[$s],index:s,isLast:i.at(-1)?.id===n.id,parentId:r,branchNumber:a.indexOf(n.id)+1,branchCount:a.length,speech:o?.messageId===n.id?o:void 0}},subscribe:n=>this._threadBinding.subscribe(n)}),this._threadBinding)}unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new Db({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}};const fP=m.createContext(null),hP=()=>m.useContext(fP);var dl=class{constructor(e,t){A(this,"_core");A(this,"_threadListBinding");this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.updateCustom=this.updateCustom.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(e){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id,e)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}updateCustom(e){const t=this._core.getState();if(!this._threadListBinding.updateCustom)throw new Error("Thread list runtime does not support updating custom metadata");return this._threadListBinding.updateCustom(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{const s=this._core.getState(),i=s.isMain,o=s.id;n===i&&r===o||(n=i,r=o,!(e==="switchedTo"&&!i)&&(e==="switchedAway"&&i||t({})))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};const ly=Promise.resolve(),pP=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,isLoadingMore:e.isLoadingMore??!1,hasMore:e.hasMore??!1,threadItems:e.threadItems}),fl=(e,t)=>{if(t===void 0)return Hn;const n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,custom:n.custom,isMain:n.id===e.mainThreadId}:Hn};var mP=class{constructor(e,t=$b){A(this,"_core");A(this,"_runtimeFactory");A(this,"_getState");A(this,"_mainThreadListItemRuntime");A(this,"main");this._core=e,this._runtimeFactory=t;const n=new xp({path:{},getState:()=>pP(e),subscribe:r=>e.subscribe(r)});this._getState=n.getState.bind(n),this._mainThreadListItemRuntime=new dl(new Fn({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>fl(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new t(new vu({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:r=>e.subscribe(r)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getLoadThreadsPromise=this.getLoadThreadsPromise.bind(this),this.reload=this.reload.bind(this),this.loadMore=this.loadMore.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e,t){return this._core.switchToThread(e,t)}switchToNewThread(){return this._core.switchToNewThread()}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}reload(){return this._core.reload?.()??ly}loadMore(){return this._core.loadMore?.()??ly}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new vu({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new dl(new Fn({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>fl(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new dl(new Fn({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>fl(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new dl(new Fn({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>fl(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},Ub=class{constructor(e){A(this,"_core");A(this,"threads");A(this,"_thread");this._core=e,this.threads=new mP(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.registerModelContextProvider=this.registerModelContextProvider.bind(this)}get thread(){return this._thread}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}},Vb=class{constructor(){A(this,"_contextProvider",new dp)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}};const gs=Object.freeze([]),ji="DEFAULT_THREAD_ID",gP=Object.freeze([ji]),yP=Object.freeze({id:ji,remoteId:void 0,externalId:void 0,status:"regular"}),vP=Promise.resolve(),uy=Object.freeze({[ji]:yP});var xP=class{constructor(e={},t){A(this,"threadFactory");A(this,"_mainThreadId",ji);A(this,"_threads",gP);A(this,"_archivedThreads",gs);A(this,"_threadData",uy);A(this,"adapter",{});A(this,"_mainThread");A(this,"_subscriptions",new Set);this.threadFactory=t,this.__internal_setAdapter(e,!0)}get isLoading(){return this.adapter.isLoading??!1}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}get threadItems(){return this._threadData}getLoadThreadsPromise(){return vP}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(e){return this._threadData[e]}__internal_setAdapter(e,t=!1){const n=this.adapter;this.adapter=e;const r=e.threadId??ji,s=e.threads??gs,i=e.archivedThreads??gs,o=n.threadId??ji,a=n.threads??gs,l=n.archivedThreads??gs;!t&&o===r&&a===s&&l===i||((a!==s||l!==i||o!==r)&&(this._threadData={...uy,...Object.fromEntries(e.threads?.map(u=>[u.id,{...u,remoteId:u.remoteId,externalId:u.externalId,status:"regular"}])??[]),...Object.fromEntries(e.archivedThreads?.map(u=>[u.id,{...u,remoteId:u.remoteId,externalId:u.externalId,status:"archived"}])??[])}),a!==s&&(this._threads=this.adapter.threads?.map(u=>u.id)??gs),l!==i&&(this._archivedThreads=this.adapter.archivedThreads?.map(u=>u.id)??gs),(t||o!==r)&&(this._mainThreadId=r,this._mainThread=this.threadFactory()),this._threadData[this._mainThreadId]||(this._threadData={...this._threadData,[this._mainThreadId]:{id:this._mainThreadId,remoteId:void 0,externalId:void 0,status:"regular"}}),this._notifySubscribers())}async switchToThread(e,t){if(this._mainThreadId===e)return;const n=this.adapter.onSwitchToThread;if(!n)throw new Error("External store adapter does not support switching to thread");await n(e)}async switchToNewThread(){const e=this.adapter.onSwitchToNewThread;if(!e)throw new Error("External store adapter does not support switching to new thread");await e()}async rename(e,t){const n=this.adapter.onRename;if(!n)throw new Error("External store adapter does not support renaming");await n(e,t)}async updateCustom(e,t){const n=this.adapter.onUpdateCustom;if(!n)throw new Error("External store adapter does not support updating custom metadata");await n(e,t)}async detach(){}async archive(e){const t=this.adapter.onArchive;if(!t)throw new Error("External store adapter does not support archiving");await t(e)}async unarchive(e){const t=this.adapter.onUnarchive;if(!t)throw new Error("External store adapter does not support unarchiving");await t(e)}async delete(e){const t=this.adapter.onDelete;if(!t)throw new Error("External store adapter does not support deleting");await t(e)}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}_notifySubscribers(){for(const e of this._subscriptions)e()}};const is=Eb("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),ro=Symbol("autoStatus"),wP=Object.freeze(Object.assign({type:"running"},{[ro]:!0})),_P=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[ro]:!0})),bP=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[ro]:!0})),kP=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[ro]:!0})),SP=e=>e[ro]===!0,xu=(e,t,n,r,s)=>e&&s?Object.assign({type:"incomplete",reason:"error",error:s},{[ro]:!0}):e&&t?wP:n?kP:r?bP:_P,td=(e,t)=>{if(e.startsWith("data-"))return{type:"data",name:e.substring(5),data:t}},ga=(e,t,n)=>{const{role:r,id:s,createdAt:i,attachments:o,status:a,metadata:l}=e,u={id:s??t,createdAt:i??new Date},c=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,f=({image:h,...p})=>h.match(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,(.*)$/)?{...p,image:h}:/^(https:\/\/|blob:)/.test(h)?{...p,image:h}:(console.warn("Invalid image data format detected"),null);if(r!=="user"&&o?.length)throw new Error("attachments are only supported for user messages");if(r!=="assistant"&&a)throw new Error("status is only supported for assistant messages");if(r!=="assistant"&&l?.steps)throw new Error("metadata.steps is only supported for assistant messages");switch(r){case"assistant":return{...u,role:r,content:c.map(h=>{const p=h.type;switch(p){case"text":case"reasoning":return h.text.trim().length===0?null:h;case"file":case"source":return h;case"image":return f(h);case"data":return h;case"generative-ui":return h;case"tool-call":{const{parentId:g,messages:y,..._}=h,x={..._,toolCallId:h.toolCallId??`tool-${is()}`,...g!==void 0&&{parentId:g},...y!==void 0&&{messages:y}};return h.args?{...x,args:h.args,argsText:h.argsText??JSON.stringify(h.args)}:{...x,args:Pf(h.argsText??"")??{},argsText:h.argsText??""}}default:{const g=td(p,h.data);if(g)return g;throw new Error(`Unsupported assistant message part type: ${p}`)}}}).filter(h=>!!h),status:a??n,metadata:{unstable_state:l?.unstable_state??null,unstable_annotations:l?.unstable_annotations??[],unstable_data:l?.unstable_data??[],custom:l?.custom??{},steps:l?.steps??[],...l?.timing&&{timing:l.timing},...l?.submittedFeedback&&{submittedFeedback:l.submittedFeedback},...l?.isOptimistic&&{isOptimistic:!0}}};case"user":return{...u,role:r,content:c.map(h=>{const p=h.type;switch(p){case"text":case"image":case"audio":case"file":case"data":return h;default:{const g=td(p,h.data);if(g)return g;throw new Error(`Unsupported user message part type: ${p}`)}}}),attachments:(o??[]).map(h=>({...h,content:h.content.map(p=>td(p.type,p.data)??p)})),metadata:{custom:l?.custom??{}}};case"system":if(c.length!==1||c[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return{...u,role:r,content:c,metadata:{custom:l?.custom??{}}};default:throw new Error(`Unknown message role: ${r}`)}},Hb={fromArray:e=>{const t=e.map(n=>ga(n,is(),xu(!1,!1,!1,!1,void 0)));return{messages:t.map((n,r)=>({parentId:r>0?t[r-1].id:null,message:n}))}},fromBranchableArray:(e,t)=>{const n=xu(!1,!1,!1,!1,void 0);return{...t?.headId!==void 0?{headId:t.headId}:void 0,messages:e.map(({message:r,parentId:s})=>{if(!r.id)throw new Error("ExportedMessageRepository.fromBranchableArray: Each message must have an 'id' field set.");return{parentId:s,message:ga(r,r.id,n)}})}}},Ll=e=>e.next?Ll(e.next):"current"in e?e:null;var CP=class{constructor(e){A(this,"func");A(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},wp=class{constructor(){A(this,"messages",new Map);A(this,"head",null);A(this,"root",{children:[],next:null});A(this,"_messages",new CP(()=>{const e=new Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e}))}updateLevels(e,t){e.level=t;for(const n of e.children){const r=this.messages.get(n);r&&this.updateLevels(r,t+1)}}performOp(e,t,n){const r=t.prev??this.root,s=e??this.root;if(!(n==="relink"&&r===s)){if(n!=="link"&&(r.children=r.children.filter(i=>i!==t.current.id),r.next===t)){const i=r.children.at(-1),o=i?this.messages.get(i):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=o}if(n!=="cut"){for(let o=e;o;o=o.prev)if(o.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");s.children=[...s.children,t.current.id],(Ll(t)===this.head||s.next===null)&&(s.next=t),t.prev=e;const i=e?e.level+1:0;this.updateLevels(t,i)}}}get headId(){return this.head?.current.id??null}getMessages(e){if(e===void 0||e===this.head?.current.id)return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const n=new Array(t.level+1);for(let r=t;r;r=r.prev)n[r.level]=r.current;return n}addOrUpdateMessage(e,t){const n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(n){n.current=t,this.performOp(r,n,"relink"),this._messages.dirty();return}const s={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,s),this.performOp(r,s,"link"),this.head===r&&(this.head=s),this._messages.dirty()}getMessage(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:t.prev?.current.id??null,message:t.current,index:t.level}}deleteMessage(e,t){const n=this.messages.get(e);if(!n)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const s of n.children){const i=this.messages.get(s);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,i,"relink")}this.performOp(null,n,"cut"),this.messages.delete(e),this.head===n&&(this.head=Ll(r??this.root)),this._messages.dirty()}getBranches(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:n}=t.prev??this.root;return n}evictOffBranchOptimisticMessages(e,t){if(!e)return;const n=new Set;for(let s=t;s;s=s.prev)n.add(s.current.id);const r=[];for(let s=e;s&&!n.has(s.current.id);s=s.prev)s.current.metadata?.isOptimistic&&r.push(s.current.id);for(const s of r)this.messages.has(s)&&this.deleteMessage(s)}switchToBranch(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const n=this.head,r=t.prev??this.root;r.next=t,this.head=Ll(t),this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");const n=this.head;if(t.children.length>0){const r=s=>{for(const i of s.children){const o=this.messages.get(i);o&&(r(o),this.messages.delete(i))}};r(t),t.children=[],t.next=null}this.head=t;for(let r=t;r;r=r.prev)r.prev?r.prev.next=r:this.root.next=r;this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){const e=[];for(const[,n]of this.messages)n.current.metadata?.isOptimistic||e.push({message:n.current,parentId:n.prev?.current.id??null});let t=this.head;for(;t?.current.metadata?.isOptimistic;)t=t.prev;return{headId:t?.current.id??null,messages:e}}import({headId:e,messages:t}){for(const{message:n,parentId:r}of t)this.addOrUpdateMessage(r,n);this.resetHead(e??t.at(-1)?.message.id??null)}};function cy(e,t){if(t==="*")return!0;const n=t.split(",").map(i=>i.trim().toLowerCase()),r=`.${e.name.split(".").pop().toLowerCase()}`,s=e.type.toLowerCase();for(const i of n){if(i.startsWith(".")&&i===r||i.includes("/")&&i===s)return!0;if(i.endsWith("/*")){const o=i.split("/")[0];if(s.startsWith(`${o}/`))return!0}}return!1}function EP(e,t){return e.length!==t.length?!1:e.every((n,r)=>n.id===t[r].id)}function TP(e){const t=is();return e.type==="image"?{id:t,type:"image",name:e.filename??"image",content:[e],status:{type:"complete"}}:e.type==="file"?{id:t,type:"document",name:e.filename??"document",contentType:e.mimeType,content:[e],status:{type:"complete"}}:e.type==="audio"?{id:t,type:"audio",name:`audio.${e.audio.format}`,contentType:`audio/${e.audio.format}`,content:[e],status:{type:"complete"}}:{id:t,type:"data",name:e.name,content:[e],status:{type:"complete"}}}function IP(e){const t=[];for(const n of e)n.type!=="text"&&t.push(TP(n));return t}const nd=e=>e.status.type==="complete";var Wb=class extends JR{constructor(){super(...arguments);A(this,"isEditing",!0);A(this,"_attachments",[]);A(this,"_text","");A(this,"_role","user");A(this,"_runConfig",{});A(this,"_quote");A(this,"_dictation");A(this,"_dictationSession");A(this,"_dictationUnsubscribes",[]);A(this,"_dictationBaseText","");A(this,"_currentInterimText","");A(this,"_dictationSessionIdCounter",0);A(this,"_activeDictationSessionId");A(this,"_isCleaningDictation",!1);A(this,"_eventSubscribers",new Map)}get attachmentAccept(){return this.getAttachmentAdapter()?.accept??"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}get quote(){return this._quote}setQuote(t){this._quote!==t&&(this._quote=t,this._notifySubscribers())}setText(t){if(this._text!==t){if(this._text=t,this._dictation){this._dictationBaseText=t,this._currentInterimText="";const{status:n,inputDisabled:r}=this._dictation;this._dictation=r?{status:n,inputDisabled:r}:{status:n}}this._notifySubscribers()}}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){const t=this.getAttachmentAdapter();if(t){const n=this._attachments.filter(r=>!nd(r));await Promise.all(n.map(r=>t.remove(r)))}}async reset(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0&&this._quote===void 0)return;this._role="user",this._runConfig={},this._quote=void 0;const t=this._onClearAttachments();this._emptyTextAndAttachments(),await t}async clearAttachments(){const t=this._onClearAttachments();this.setAttachments([]),await t}async send(t){if(!this.canSend)return;this._dictationSession&&(this._dictationSession.cancel(),this._cleanupDictation());const n=this.getAttachmentAdapter(),r=this.attachments.length>0?Promise.all(this.attachments.map(async a=>{if(nd(a))return a;if(!n)throw new Error("Attachments are not supported");return await n.send(a)})):[],s=this.text,i=this._quote;this._quote=void 0,this._emptyTextAndAttachments();const o={createdAt:new Date,role:this.role,content:s?[{type:"text",text:s}]:[],attachments:await r,runConfig:this.runConfig,metadata:{custom:{...i?{quote:i}:{}}}};this.handleSend(o,t),this._notifyEventSubscribers("send",{})}cancel(){this.handleCancel()}async addAttachment(t){if(!(t instanceof File)){const i=this.getAttachmentAdapter();if(i&&!cy({name:t.name,type:t.contentType??""},i.accept)){const a=`File type ${t.contentType||"unknown"} is not accepted. Accepted types: ${i.accept}`,l=new Error(a);throw this._safeEmitAttachmentAddError("not-accepted",a,void 0,l),l}const o={id:t.id??is(),type:t.type??"document",name:t.name,contentType:t.contentType,content:t.content,status:{type:"complete"}};this._attachments=[...this._attachments,o],this._notifySubscribers(),this._notifyEventSubscribers("attachmentAdd",{});return}const n=i=>{const o=this._attachments.findIndex(a=>a.id===i.id);o!==-1?this._attachments=[...this._attachments.slice(0,o),i,...this._attachments.slice(o+1)]:this._attachments=[...this._attachments,i],this._notifySubscribers()},r=this.getAttachmentAdapter();if(!r){const i="Attachments are not supported",o=new Error(i);throw this._safeEmitAttachmentAddError("no-adapter",i,void 0,o),o}if(!cy({name:t.name,type:t.type},r.accept)){const i=`File type ${t.type||"unknown"} is not accepted. Accepted types: ${r.accept}`,o=new Error(i);throw this._safeEmitAttachmentAddError("not-accepted",i,void 0,o),o}let s;try{const i=r.add({file:t});if(Symbol.asyncIterator in i)for await(const o of i)s=o,n(o);else s=await i,n(s)}catch(i){throw s&&n({...s,status:{type:"incomplete",reason:"error"}}),this._safeEmitAttachmentAddError("adapter-error",i instanceof Error?i.message:String(i),s?.id,i instanceof Error?i:void 0),i}s?.status.type==="incomplete"&&s.status.reason==="error"?this._safeEmitAttachmentAddError("adapter-error","Attachment upload did not complete successfully.",s?.id):this._notifyEventSubscribers("attachmentAdd",{})}_safeEmitAttachmentAddError(t,n,r,s){try{this._notifyEventSubscribers("attachmentAddError",{reason:t,message:n,...r!==void 0&&{attachmentId:r},...s!==void 0&&{error:s}})}catch(i){console.error("[assistant-ui] attachmentAddError subscriber threw:",i)}}async removeAttachment(t){const n=this._attachments.findIndex(s=>s.id===t);if(n===-1)throw new Error("Attachment not found");const r=this._attachments[n];if(!nd(r)){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");await s.remove(r)}this._attachments=this._attachments.filter(s=>s.id!==t),this._notifySubscribers()}get dictation(){return this._dictation}_isActiveSession(t,n){return this._activeDictationSessionId===t&&this._dictationSession===n}startDictation(){const t=this.getDictationAdapter();if(!t)throw new Error("Dictation adapter not configured");if(this._dictationSession){for(const u of this._dictationUnsubscribes)u();this._dictationUnsubscribes=[],this._dictationSession.stop().catch(()=>{}),this._dictationSession=void 0}const n=t.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText="";const r=t.listen();this._dictationSession=r;const s=++this._dictationSessionIdCounter;this._activeDictationSessionId=s,this._dictation={status:r.status,inputDisabled:n},this._notifySubscribers();const i=r.onSpeech(u=>{if(!this._isActiveSession(s,r))return;const c=u.isFinal!==!1,f=this._dictationBaseText&&!this._dictationBaseText.endsWith(" ")&&u.transcript?" ":"";if(c){if(this._dictationBaseText=this._dictationBaseText+f+u.transcript,this._currentInterimText="",this._text=this._dictationBaseText,this._dictation){const{transcript:h,...p}=this._dictation;this._dictation=p}this._notifySubscribers()}else this._currentInterimText=f+u.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&(this._dictation={...this._dictation,transcript:u.transcript}),this._notifySubscribers()});this._dictationUnsubscribes.push(i);const o=r.onSpeechStart(()=>{this._isActiveSession(s,r)&&(this._dictation={status:{type:"running"},inputDisabled:n,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())});this._dictationUnsubscribes.push(o);const a=r.onSpeechEnd(()=>{this._cleanupDictation({sessionId:s})});this._dictationUnsubscribes.push(a);const l=setInterval(()=>{this._isActiveSession(s,r)&&r.status.type==="ended"&&this._cleanupDictation({sessionId:s})},100);this._dictationUnsubscribes.push(()=>clearInterval(l))}stopDictation(){if(!this._dictationSession)return;const t=this._dictationSession,n=this._activeDictationSessionId;t.stop().finally(()=>{this._cleanupDictation({sessionId:n})})}_cleanupDictation(t){if(!(t?.sessionId!==void 0&&t.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)){this._isCleaningDictation=!0;try{for(const n of this._dictationUnsubscribes)n();this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText="",this._currentInterimText="",this._notifySubscribers()}finally{this._isCleaningDictation=!1}}}_notifyEventSubscribers(t,n){const r=this._eventSubscribers.get(t);if(r)for(const s of r)s(n)}unstable_on(t,n){const r=n;let s=this._eventSubscribers.get(t);return s||(s=new Set,this._eventSubscribers.set(t,s)),s.add(r),()=>{this._eventSubscribers.get(t)?.delete(r)}}},Kb=class extends Wb{constructor(t){super();A(this,"runtime");A(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get canSend(){return!this.isEmpty&&!this.runtime.isSendDisabled}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}connect(){let t=this.runtime.isSendDisabled;return this.runtime.subscribe(()=>{let n=!1;this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,n=!0),t!==this.runtime.isSendDisabled&&(t=this.runtime.isSendDisabled,n=!0),n&&this._notifySubscribers()})}async handleSend(t,n){this.runtime.append({...t,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:n?.startRun})}async handleCancel(){this.runtime.cancelRun()}},RP=class extends Wb{constructor(t,n,{parentId:r,message:s}){super();A(this,"runtime");A(this,"endEditCallback");A(this,"_previousText");A(this,"_previousAttachments");A(this,"_nonTextPassthrough");A(this,"_parentId");A(this,"_sourceId");this.runtime=t,this.endEditCallback=n,this._parentId=r,this._sourceId=s.id,this._previousText=ma(s),this.setText(this._previousText),this.setRole(s.role),s.role==="user"?(this._previousAttachments=[...s.attachments??[],...IP(s.content)],this._nonTextPassthrough=[]):(this._previousAttachments=s.attachments??[],this._nonTextPassthrough=s.content.filter(i=>i.type!=="text")),this.setAttachments(this._previousAttachments),this.setRunConfig({...t.composer.runConfig})}get canCancel(){return!0}get canSend(){return!this.isEmpty}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}get parentId(){return this._parentId}get sourceId(){return this._sourceId}async handleSend(t,n){const r=ma(t),s=!EP(t.attachments??[],this._previousAttachments);if(r!==this._previousText||s||n?.startRun){const i=this._nonTextPassthrough.length>0?[...t.content,...this._nonTextPassthrough]:t.content;this.runtime.append({...t,content:i,parentId:this._parentId,sourceId:this._sourceId,startRun:n?.startRun})}this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},PP=class{constructor(e){A(this,"_contextProvider");A(this,"_subscriptions",new Set);A(this,"_isInitialized",!1);A(this,"repository",new wp);A(this,"_voiceMessages",[]);A(this,"_voiceGeneration",0);A(this,"_cachedMergedMessages",null);A(this,"_cachedVoiceGeneration",-1);A(this,"_cachedMergedBase",null);A(this,"composer",new Kb(this));A(this,"_editComposers",new Map);A(this,"_stopSpeaking");A(this,"speech");A(this,"_voiceSession");A(this,"_voiceUnsubs",[]);A(this,"voice");A(this,"_voiceVolume",0);A(this,"_voiceVolumeSubscribers",new Set);A(this,"getVoiceVolume",()=>this._voiceVolume);A(this,"subscribeVoiceVolume",e=>(this._voiceVolumeSubscribers.add(e),()=>this._voiceVolumeSubscribers.delete(e)));A(this,"_currentAssistantMsg",null);A(this,"_eventSubscribers",new Map);this._contextProvider=e}_markVoiceMessagesDirty(){this._voiceGeneration++,this._cachedMergedMessages=null}_getBaseMessages(){return this.repository.getMessages()}get messages(){if(this._voiceMessages.length===0)return this._getBaseMessages();const e=this._getBaseMessages();return(this._cachedVoiceGeneration!==this._voiceGeneration||this._cachedMergedBase!==e)&&(this._cachedMergedMessages=[...e,...this._voiceMessages],this._cachedVoiceGeneration=this._voiceGeneration,this._cachedMergedBase=e),this._cachedMergedMessages}get state(){let e;for(const t of this.messages)t.role==="assistant"&&(e=t);return e?.metadata.unstable_state??null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new RP(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{const t=this.repository.getMessages(),n=this._voiceMessages.findIndex(r=>r.id===e);return n!==-1?{parentId:n>0?this._voiceMessages[n-1].id:t.at(-1)?.id??null,message:this._voiceMessages[n],index:t.length+n}:void 0}}getBranches(e){return this._voiceMessages.some(t=>t.id===e)?[]:this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e,t){const n=this._eventSubscribers.get(e);if(n)for(const r of n)r(t)}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){const n=this.adapters?.feedback;if(!n)throw new Error("Feedback adapter not configured");const{message:r,parentId:s}=this.repository.getMessage(e);if(n.submit({message:r,type:t}),r.role==="assistant"){const i={...r,metadata:{...r.metadata,submittedFeedback:{type:t}}};this.repository.addOrUpdateMessage(s,i)}this._notifySubscribers()}speak(e){const t=this.adapters?.speech;if(!t)throw new Error("Speech adapter not configured");const{message:n}=this.repository.getMessage(e);this._stopSpeaking?.();const r=t.speak(ma(n)),s=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:r.status},this._notifySubscribers()});this.speech={messageId:e,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),s(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}connectVoice(){const e=this.adapters?.voice;if(!e)throw new Error("Voice adapter not configured");this.disconnectVoice();const t=e.connect({});this._voiceSession=t;const n=[];let r="listening";this.voice={status:t.status,isMuted:t.isMuted,mode:r},this._voiceVolume=0,this._notifySubscribers(),n.push(t.onStatusChange(s=>{s.type==="ended"?(this._finishVoiceAssistantMessage(),this._voiceSession=void 0,this.voice=void 0):this.voice={status:s,isMuted:t.isMuted,mode:r},this._notifySubscribers()})),n.push(t.onModeChange(s=>{r=s,this.voice&&(this.voice={...this.voice,mode:s},this._notifySubscribers())})),n.push(t.onVolumeChange(s=>{this._voiceVolume=s;for(const i of this._voiceVolumeSubscribers)i()})),n.push(t.onTranscript(s=>{this._handleVoiceTranscript(s)})),this._voiceUnsubs=n}_handleVoiceTranscript(e){if(this.ensureInitialized(),e.role==="user")this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null,e.isFinal&&(this._voiceMessages.push({id:is(),role:"user",content:[{type:"text",text:e.text}],metadata:{custom:{}},createdAt:new Date,status:{type:"complete",reason:"unknown"},attachments:[]}),this._markVoiceMessagesDirty(),this._notifySubscribers());else{if(!this._currentAssistantMsg)this._currentAssistantMsg={id:is(),role:"assistant",content:[{type:"text",text:e.text}],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},status:{type:"running"},createdAt:new Date},this._voiceMessages.push(this._currentAssistantMsg);else{const t=this._voiceMessages.indexOf(this._currentAssistantMsg);if(t===-1)return;const n={...this._currentAssistantMsg,content:[{type:"text",text:e.text}],...e.isFinal?{status:{type:"complete",reason:"stop"}}:{}};this._voiceMessages[t]=n,this._currentAssistantMsg=n}e.isFinal&&(this._currentAssistantMsg=null),this._markVoiceMessagesDirty(),this._notifySubscribers()}}_finishVoiceAssistantMessage(){const e=this._voiceMessages.at(-1);if(e?.role==="assistant"&&e.status.type==="running"){const t=this._voiceMessages.length-1;this._voiceMessages[t]={...e,status:{type:"complete",reason:"stop"}},this._markVoiceMessagesDirty(),this._notifySubscribers()}}disconnectVoice(){this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null;for(const e of this._voiceUnsubs)e();this._voiceUnsubs=[],this._voiceSession?.disconnect(),this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;for(const e of this._voiceVolumeSubscribers)e();this._voiceMessages=[],this._markVoiceMessagesDirty(),this._notifySubscribers()}muteVoice(){if(!this._voiceSession)throw new Error("No active voice session");this._voiceSession.mute(),this.voice={...this.voice,isMuted:!0},this._notifySubscribers()}unmuteVoice(){if(!this._voiceSession)throw new Error("No active voice session");this._voiceSession.unmute(),this.voice={...this.voice,isMuted:!1},this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize",{}))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(Hb.fromArray(e??[]))}unstable_on(e,t){const n=t;if(e==="modelContextUpdate")return this._contextProvider.subscribe?.(()=>n({}))??(()=>{});let r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),e==="initialize"&&this._isInitialized&&queueMicrotask(()=>{r.has(n)&&n({})}),()=>{this._eventSubscribers.get(e)?.delete(n)}}},dy=class{constructor(){A(this,"cache",new WeakMap)}convertMessages(e,t){return e.map((n,r)=>{const s=t(this.cache.get(n),n,r);return this.cache.set(n,s),s})}};function Af(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function wu(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(n=>wu(n,t+1)):Af(e)?Object.entries(e).every(([n,r])=>typeof n=="string"&&wu(r,t+1)):!1}const jP=100,Nf=(e,t,n)=>{if(e===t)return!0;if(n>jP||e==null||t==null)return!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((i,o)=>Nf(i,t[o],n+1));if(Array.isArray(t)||!Af(e)||!Af(t))return!1;const r=Object.keys(e),s=Object.keys(t);return r.length!==s.length?!1:r.every(i=>Object.hasOwn(t,i)&&Nf(e[i],t[i],n+1))},AP=(e,t)=>!wu(e)||!wu(t)?!1:Nf(e,t,0),hl=e=>{try{return JSON.parse(e),!0}catch{return!1}},fy=e=>{try{return JSON.parse(e)}catch{return}},hy=(e,t)=>{const n=fy(e),r=fy(t);return n===void 0||r===void 0?!1:AP(n,r)};var NP=class{constructor(e,t){A(this,"_getTools");A(this,"_callbacks");A(this,"_entries",new Map);A(this,"_skipExecuteStreamIds",new Set);A(this,"_humanInput",new Map);A(this,"_executing",new Set);A(this,"_settledResolvers",[]);A(this,"_statuses",new Map);A(this,"_ac",new AbortController);A(this,"_pendingRestore",!0);A(this,"_lastSnapshot",null);A(this,"_isRunning",!1);A(this,"_controller");A(this,"_pipelineDead",!1);A(this,"_pipelineRestartUsed",!1);this._getTools=e,this._callbacks=t,this._initPipeline()}_initPipeline(){const[e,t]=kR();this._controller=t;const n=UR(()=>this._getWrappedTools(),()=>this._ac.signal,(r,s)=>this._onHumanInput(r,s),{onExecutionStart:r=>this._onExecutionStart(r),onExecutionEnd:r=>this._onExecutionEnd(r)});e.pipeThrough(n).pipeThrough(new Cb).pipeTo(new WritableStream({write:r=>{try{if(r.type!=="result")return;this._handleResultChunk(r)}catch(s){console.error("[ToolInvocationTracker] result chunk handling failed",s)}}})).catch(r=>{console.error("[ToolInvocationTracker] stream pipeline failed; will attempt single restart on next setState",r),this._pipelineDead=!0})}setState(e){try{if(this._pipelineDead){if(this._pipelineRestartUsed)return;this._pipelineRestartUsed=!0,this._pipelineDead=!1,this._demoteEntriesToRestored(),this._executing.clear(),this._ac=new AbortController,this._initPipeline()}if(this._lastSnapshot&&this._lastSnapshot.messages===e.messages&&this._lastSnapshot.isRunning===e.isRunning&&this._lastSnapshot.isLoading===e.isLoading)return;e.isLoading===!0&&(this._pendingRestore=!0);const t=this._isRunning;this._isRunning=e.isRunning;try{this._processMessages(e.messages)}catch(n){throw this._isRunning=t,n}this._lastSnapshot=e,this._pendingRestore=!1}catch(t){console.error("[ToolInvocationTracker] setState failed; snapshot dropped",t)}}reset(){try{this._pendingRestore=!0,this._entries.clear(),this._lastSnapshot=null,this.abort().finally(()=>{this._executing.clear()})}catch(e){console.error("[ToolInvocationTracker] reset failed",e)}}abort(){try{return this._humanInput.forEach(({reject:e})=>{try{e(new Error("Tool execution aborted"))}catch{}}),this._humanInput.clear(),this._ac.abort(),this._ac=new AbortController,this._executing.size===0?Promise.resolve():new Promise(e=>{this._settledResolvers.push(e)})}catch(e){return console.error("[ToolInvocationTracker] abort failed",e),Promise.resolve()}}resume(e,t){try{const n=this._humanInput.get(e);return n?(this._humanInput.delete(e),this._setStatus(e,{type:"executing"}),n.resolve(t),!0):!1}catch(n){return console.error("[ToolInvocationTracker] resume failed",n),!1}}getStatuses(){return this._statuses}_getWrappedTools(){const e=this._getTools();if(e)return Object.fromEntries(Object.entries(e).map(([t,n])=>{const r=n.execute;return r===void 0?[t,n]:[t,{...n,execute:(...[s,i])=>this._skipExecuteStreamIds.has(i.toolCallId)?new Promise(()=>{}):r(s,i)}]}))}_onHumanInput(e,t){return new Promise((n,r)=>{const s=this._humanInput.get(e);if(s)try{s.reject(new Error("Human input request was superseded by a new request"))}catch{}this._humanInput.set(e,{resolve:n,reject:r}),this._setStatus(e,{type:"interrupt",payload:{type:"human",payload:t}})})}_onExecutionStart(e){this._skipExecuteStreamIds.has(e)||(this._executing.add(e),this._setStatus(e,{type:"executing"}))}_onExecutionEnd(e){this._executing.delete(e)&&(this._deleteStatus(e),this._executing.size===0&&this._settledResolvers.splice(0).forEach(t=>{try{t()}catch{}}))}_handleResultChunk(e){const t=e.meta.toolCallId,n=this._entries.get(t);!n&&this._skipExecuteStreamIds.has(t)||n?.hasResult||this._invokeOnResult({type:"add-tool-result",toolCallId:t,toolName:e.meta.toolName,result:e.result,isError:e.isError,...e.artifact!==void 0&&{artifact:e.artifact},...e.modelContent!==void 0&&{modelContent:e.modelContent}})}_invokeOnResult(e){try{this._callbacks.onResult(e)}catch(t){console.error("[ToolInvocationTracker] onResult callback threw; result dropped",t)}}_invokeOnStatusesChange(){try{this._callbacks.onStatusesChange(this._statuses)}catch(e){console.error("[ToolInvocationTracker] onStatusesChange callback threw; status change not propagated",e)}}_setStatus(e,t){const n=new Map(this._statuses);n.set(e,t),this._statuses=n,this._invokeOnStatusesChange()}_deleteStatus(e){if(!this._statuses.has(e))return;const t=new Map(this._statuses);t.delete(e),this._statuses=t,this._invokeOnStatusesChange()}_hasExecutableTool(e){const t=this._getTools()?.[e];return t?.execute!==void 0||t?.streamCall!==void 0}_shouldCloseArgsStream({toolName:e,argsText:t,hasResult:n}){return n?!0:(this._hasExecutableTool(e)||!this._isRunning)&&hl(t)}_startActiveEntry(e,t,n){const r=this._controller.addToolCallPart({toolName:t,toolCallId:e});n&&this._skipExecuteStreamIds.add(e);const s={toolName:t,controller:r,argsText:"",hasResult:!1,argsComplete:!1};return this._entries.set(e,s),s}_demoteEntriesToRestored(){for(const[e,t]of this._entries)t.controller&&this._entries.set(e,{toolName:t.toolName,argsText:t.argsText,hasResult:t.hasResult})}_processArgsText(e,t){if(!e.controller)return;const n=t.result!==void 0;if(t.argsText!==e.argsText){let r=!0;if(e.argsComplete)hy(e.argsText,t.argsText)&&(e.argsText=t.argsText),r=!1;else if(!t.argsText.startsWith(e.argsText))if(hl(e.argsText)&&hl(t.argsText)&&hy(e.argsText,t.argsText)){const s=this._shouldCloseArgsStream({toolName:t.toolName,argsText:t.argsText,hasResult:n});s&&e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=s,r=!1}else r=!1;if(r&&e.controller){const s=t.argsText.slice(e.argsText.length);e.controller.argsText.append(s);const i=this._shouldCloseArgsStream({toolName:t.toolName,argsText:t.argsText,hasResult:n});i&&e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=i}}!e.argsComplete&&e.controller&&this._shouldCloseArgsStream({toolName:t.toolName,argsText:t.argsText,hasResult:n})&&(e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=!0)}_processMessages(e){const t=this._pendingRestore;for(const n of e)if(!(!n||!Array.isArray(n.content)))for(const r of n.content){if(!r||r.type!=="tool-call")continue;const s=this._entries.get(r.toolCallId);if(t){s?.controller||this._entries.set(r.toolCallId,{toolName:r.toolName,argsText:r.argsText,hasResult:r.result!==void 0}),r.messages&&this._processMessages(r.messages);continue}let i=s;if(i&&!i.controller){if(!(r.argsText!==i.argsText||r.result!==void 0!==i.hasResult)){r.messages&&this._processMessages(r.messages);continue}this._entries.delete(r.toolCallId),i=void 0}if(i||(i=this._startActiveEntry(r.toolCallId,r.toolName,r.result!==void 0)),this._processArgsText(i,r),r.result!==void 0&&!i.hasResult){const{controller:o}=i;if(!o)continue;i.hasResult=!0,i.argsComplete=!0,o.setResponse(new wr({result:r.result,artifact:r.artifact,isError:r.isError,...r.modelContent!==void 0?{modelContent:r.modelContent}:{}})),o.close()}r.messages&&this._processMessages(r.messages)}}};const MP=Object.freeze([]),py=(e,t)=>{const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(e[r]!==t[r])return!1;return!0},DP=(e,t)=>e&&t[t.length-1]?.role!=="assistant";var OP=class extends PP{constructor(t,n){super(t);A(this,"_capabilities",{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1});A(this,"_messages");A(this,"isDisabled");A(this,"isSendDisabled");A(this,"suggestions",[]);A(this,"extras");A(this,"_converter",new dy);A(this,"_store");A(this,"_toolInvocations",null);A(this,"_toolCallToMessageId",new Map);A(this,"_messagesForToolCallIndex",null);A(this,"updateMessages",t=>{this._store.convertMessage!==void 0?this._store.setMessages?.(t.flatMap(QR)):this._store.setMessages?.(t)});this.__internal_setAdapter(n)}get capabilities(){return this._capabilities}get isLoading(){return this._store.isLoading??!1}get isRunning(){return this._store.isRunning}_getBaseMessages(){return this._messages}get state(){return this._store.state??super.state}get adapters(){return this._store.adapters}beginEdit(t){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(t)}__internal_setAdapter(t){if(this._store===t)return;const n=t.isRunning??!1;this.isDisabled=t.isDisabled??!1,this.isSendDisabled=t.isSendDisabled??!1;const r=this._store;this._store=t,this.extras!==t.extras&&(this.extras=t.extras);const s=t.suggestions??MP;py(this.suggestions,s)||(this.suggestions=s);const i={switchToBranch:this._store.setMessages!==void 0,switchBranchDuringRun:!1,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:this._store.adapters?.speech!==void 0,dictation:this._store.adapters?.dictation!==void 0,voice:this._store.adapters?.voice!==void 0,unstable_copy:this._store.unstable_capabilities?.copy!==!1,attachments:!!this._store.adapters?.attachments,feedback:!!this._store.adapters?.feedback,queue:!1};py(this._capabilities,i)||(this._capabilities=i);let o;if(t.messageRepository){if(r&&r.isRunning===t.isRunning&&r.messageRepository===t.messageRepository){this._notifySubscribers();return}this.repository.clear(),this.repository.import(t.messageRepository),o=this.repository.getMessages()}else if(t.messages){if(r){if(r.convertMessage!==t.convertMessage)this._converter=new dy;else if(r.isRunning===t.isRunning&&r.messages===t.messages){this._notifySubscribers();return}}o=t.convertMessage?this._converter.convertMessages(t.messages,(l,u,c)=>{if(!t.convertMessage)return u;const f=xu(c===(t.messages?.length??0)-1,n,!1,!1,void 0);if(l&&(l.role!=="assistant"||!SP(l.status)||l.status===f))return l;const h=ga(t.convertMessage(u,c),c.toString(),f);return YR(h,u),h}):t.messages;for(let l=0;l<o.length;l++){const u=o[l],c=o[l-1];this.repository.addOrUpdateMessage(c?.id??null,u)}}else throw new Error("ExternalStoreAdapter must provide either 'messages' or 'messageRepository'");o.length>0&&this.ensureInitialized(),(r?.isRunning??!1)!==(t.isRunning??!1)&&(t.isRunning?this._notifyEventSubscribers("runStart",{}):this._notifyEventSubscribers("runEnd",{}));let a=null;DP(n,o)&&(a=is(),this.repository.addOrUpdateMessage(o.at(-1)?.id??null,ga({role:"assistant",content:[],metadata:{isOptimistic:!0}},a,{type:"running"}))),this.repository.resetHead(a??o.at(-1)?.id??null),this._messages=this.repository.getMessages(),this._driveToolInvocations(),this._notifySubscribers()}_driveToolInvocations(){if(!this._store.unstable_enableToolInvocations){this._toolInvocations&&(this._toolInvocations.reset(),this._toolInvocations=null,this._store.setToolStatuses?.({}));return}this._toolInvocations||(this._toolInvocations=new NP(()=>this.getModelContext().tools,{onResult:t=>{try{const n=this._findMessageIdForToolCall(t.toolCallId);if(n===void 0)return;this._store.onAddToolResult?.({messageId:n,toolCallId:t.toolCallId,toolName:t.toolName,result:t.result,isError:t.isError,...t.artifact!==void 0&&{artifact:t.artifact},...t.modelContent!==void 0&&{modelContent:t.modelContent}})}catch(n){console.error("[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed",n)}},onStatusesChange:t=>{this._store.setToolStatuses?.(Object.fromEntries(t))}})),this._toolInvocations.setState({messages:this._messages,isRunning:this._store.isRunning??!1,...this._store.isLoading!==void 0&&{isLoading:this._store.isLoading}})}_findMessageIdForToolCall(t){if(this._messagesForToolCallIndex!==this._messages){this._toolCallToMessageId.clear();const n=r=>{for(const s of r)if(Array.isArray(s.content))for(const i of s.content)!i||i.type!=="tool-call"||(this._toolCallToMessageId.set(i.toolCallId,s.id),i.messages&&n(i.messages))};n(this._messages),this._messagesForToolCallIndex=this._messages}return this._toolCallToMessageId.get(t)}switchToBranch(t){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this._store.isRunning||(this.repository.switchToBranch(t),this.updateMessages(this.repository.getMessages()))}async append(t){if((t.startRun??t.role==="user")&&await this._toolInvocations?.abort(),t.parentId!==(this.messages.at(-1)?.id??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(t)}else await this._store.onNew(t)}async startRun(t){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._toolInvocations?.abort(),await this._store.onReload(t.parentId,t)}async resumeRun(t){if(!this._store.onResume)throw new Error("Runtime does not support resuming runs.");await this._store.onResume(t)}exportExternalState(){if(!this._store.onExportExternalState)throw new Error("Runtime does not support exporting external states.");return this._store.onExportExternalState()}importExternalState(t){if(!this._store.onLoadExternalState)throw new Error("Runtime does not support importing external states.");this._toolInvocations&&(this._toolInvocations.reset(),this._store.setToolStatuses?.({})),this._store.onLoadExternalState(t)}cancelRun(){if(!this._store.onCancel)throw new Error("Runtime does not support cancelling runs.");this._toolInvocations?.abort(),this._store.onCancel();const t=this.repository.getMessages().at(-1);t&&t.metadata.isOptimistic&&t.content.length===0&&this.repository.deleteMessage(t.id);let n=this.repository.getMessages();const r=n[n.length-1];r?.role==="user"&&r.id===n.at(-1)?.id?(this.repository.deleteMessage(r.id),this.composer.text.trim()||this.composer.setText(ma(r)),n=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(n)},0)}addToolResult(t){if(!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult?.(t)}resumeToolCall(t){if(!(this._toolInvocations?.resume(t.toolCallId,t.payload)??!1)){if(this._store.onResumeToolCall){this._store.onResumeToolCall(t);return}throw new Error(`Tool call ${t.toolCallId} is not waiting for resume.`)}}respondToToolApproval(t){if(!this._store.onRespondToToolApproval)throw new Error("Runtime does not support tool approvals.");this._store.onRespondToToolApproval(t)}reset(t){const n=new wp;n.import(Hb.fromArray(t??[])),this.updateMessages(n.getMessages())}import(t){super.import(t),this._store.onImport&&this._store.onImport(this.repository.getMessages())}};const my=e=>e.adapters?.threadList??{};var LP=class extends Vb{constructor(t){super();A(this,"threads");this.threads=new xP(my(t),()=>new OP(this._contextProvider,t))}setAdapter(t){this.threads.__internal_setAdapter(my(t)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(t)}};const Ma=e=>{const[t]=m.useState(()=>new LP(e));m.useEffect(()=>{t.setAdapter(e)});const{modelContext:n}=hP()??{};return m.useEffect(()=>{if(n)return t.registerModelContextProvider(n)},[n,t]),m.useMemo(()=>new Ub(t),[t])},qb=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,zP=()=>null,FP=(e,t,n)=>{switch(t){case"user":return n?e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message:e.UserMessage??e.Message;case"assistant":return n?e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message:e.AssistantMessage??e.Message;case"system":return n?e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message:e.SystemMessage??e.Message??zP;default:throw new Error(`Unknown message role: ${t}`)}},Gb=({components:e})=>d.jsx(FP(e,G(t=>t.message.role),G(t=>t.message.composer.isEditing)),{}),Yb=m.memo(({index:e,components:t})=>d.jsx(Nb,{index:e,children:d.jsx(Gb,{components:t})}),(e,t)=>e.index===t.index&&qb(e.components,t.components));Yb.displayName="ThreadPrimitive.MessageByIndex";const gy=({children:e})=>{const t=G(n=>n.thread.messages.length);return m.useMemo(()=>t===0?null:Array.from({length:t},(n,r)=>d.jsx(Nb,{index:r,children:d.jsx(to,{getItemState:s=>s.thread().message({index:r}).getState(),children:s=>e({get message(){return s()}})})},r)),[t,e])},Qb=({components:e,children:t})=>e?d.jsx(gy,{children:()=>d.jsx(Gb,{components:e})}):d.jsx(gy,{children:t});Qb.displayName="ThreadPrimitive.Messages";const BP=m.memo(Qb,(e,t)=>e.children||t.children?e.children===t.children:qb(e.components,t.components)),Xb=e=>{const t=e.message.metadata;if(!(!t||typeof t!="object"))return t.custom?.quote};var $P=class extends Error{constructor(t,n=`Component "${t}" is not in the generative-ui allowlist.`){super(n);A(this,"componentName");this.name="GenerativeUIRenderError",this.componentName=t}};const UP=e=>typeof e=="object"&&e!==null,Jb=(e,t,n,r)=>{if(e==null)return null;if(typeof e=="string")return e;if(!UP(e)||!("component"in e))return null;const{component:s,props:i,children:o,key:a}=e,l=t[s];if(!l){if(n)return d.jsx(n,{component:s,props:i},a??r);throw new $P(s)}const u=o?.length?o.map((c,f)=>Jb(c,t,n,`${r}/${f}`)):void 0;return m.createElement(l,{...i??{},key:a??r},...u??[])},VP=e=>{if(!e||e.root===void 0||e.root===null)return[];const t=e.root;return Array.isArray(t)?t:[t]},_p=({spec:e,components:t,Fallback:n})=>d.jsx(d.Fragment,{children:m.useMemo(()=>VP(e),[e]).map((r,s)=>Jb(r,t,n,`${s}`))});_p.displayName="GenerativeUIRender";const Zb=({components:e,spec:t,Fallback:n})=>{const r=G(i=>{const o=i.part;return o?.type==="generative-ui"?o.spec:void 0}),s=t??r;return s?d.jsx(_p,{spec:s,components:e,Fallback:n}):null};Zb.displayName="MessagePrimitive.GenerativeUI";const HP="ui://",WP=e=>!!e?.startsWith(HP),yy=e=>Symbol.iterator in e,vy=e=>"entries"in e,xy=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[s,i]of n)if(!r.has(s)||!Object.is(i,r.get(s)))return!1;return!0},KP=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=n.next(),i=r.next();for(;!s.done&&!i.done;){if(!Object.is(s.value,i.value))return!1;s=n.next(),i=r.next()}return!!s.done&&!!i.done};function qP(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:yy(e)&&yy(t)?vy(e)&&vy(t)?xy(e,t):KP(e,t):xy({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function e0(e){const t=Bt.useRef(void 0);return n=>{const r=e(n);return qP(t.current,r)?t.current:t.current=r}}const rd=e=>{let t=-1;return{startGroup:n=>{t===-1&&(t=n)},endGroup:(n,r)=>{t!==-1&&(r.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,r)=>{t!==-1&&r.push({type:e,startIndex:t,endIndex:n})}}},GP=(e,t)=>{const n=[];if(t){const r=rd("chainOfThoughtGroup");for(let s=0;s<e.length;s++){const i=e[s];i==="tool-call"||i==="reasoning"?r.startGroup(s):(r.endGroup(s-1,n),n.push({type:"single",index:s}))}r.finalize(e.length-1,n)}else{const r=rd("toolGroup"),s=rd("reasoningGroup");for(let i=0;i<e.length;i++){const o=e[i];o==="tool-call"?(s.endGroup(i-1,n),r.startGroup(i)):o==="reasoning"?(r.endGroup(i-1,n),s.startGroup(i)):(r.endGroup(i-1,n),s.endGroup(i-1,n),n.push({type:"single",index:i}))}r.finalize(e.length-1,n),s.finalize(e.length-1,n)}return n},YP=e=>{const t=G(e0(n=>n.message.parts.map(r=>r.type)));return m.useMemo(()=>t.length===0?[]:GP(t,e),[t,e])},QP=({Fallback:e,...t})=>{const n=G(r=>r.tools.toolUIs[t.toolName]?.[0]?.render??e);return n?d.jsx(n,{...t}):null},bp=(e,t,n)=>{const r=e.renderers[t]?.[0];return r||(e.fallbacks[0]??n)},XP=({Fallback:e,...t})=>{const n=G(r=>bp(r.dataRenderers,t.name,e));return n?d.jsx(n,{...t}):null},St={Text:()=>null,Reasoning:()=>null,Source:()=>null,Image:()=>null,File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},JP=({components:{Text:e=St.Text,Reasoning:t=St.Reasoning,Image:n=St.Image,Source:r=St.Source,File:s=St.File,Unstable_Audio:i=St.Unstable_Audio,tools:o={},data:a,generativeUI:l}={}})=>{const u=ue(),c=G(h=>h.part),f=c.type;if(f==="tool-call"){const h=u.part().addToolResult,p=u.part().resumeToolCall,g=u.part().respondToToolApproval;if("Override"in o)return d.jsx(o.Override,{...c,addResult:h,resume:p,respondToApproval:g});const y=o.by_name?.[c.toolName]??o.Fallback;return d.jsx(QP,{...c,Fallback:y,addResult:h,resume:p,respondToApproval:g})}if(c.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(f){case"text":return d.jsx(e,{...c});case"reasoning":return d.jsx(t,{...c});case"source":return d.jsx(r,{...c});case"image":return d.jsx(n,{...c});case"file":return d.jsx(s,{...c});case"audio":return d.jsx(i,{...c});case"data":{const h=a?.by_name?.[c.name]??a?.Fallback;return d.jsx(XP,{...c,Fallback:h})}case"generative-ui":return l?.components?d.jsx(_p,{spec:c.spec,components:l.components,Fallback:l.Fallback}):null;default:return console.warn(`Unknown message part type: ${f}`),null}},Uo=m.memo(({index:e,components:t})=>d.jsx(yp,{index:e,children:d.jsx(JP,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.generativeUI===t.components?.generativeUI&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);Uo.displayName="MessagePrimitive.PartByIndex";const ZP=({status:e,component:t})=>d.jsx(vp,{text:"",isRunning:e.type==="running",children:d.jsx(t,{type:"text",text:"",status:e})}),ej=Object.freeze({type:"complete"}),tj=Object.freeze({type:"running"}),nj=({components:e})=>{const t=G(n=>n.message.status??ej);return e?.Empty?d.jsx(e.Empty,{status:t}):t.type!=="running"?null:d.jsx(ZP,{status:t,component:e?.Text??St.Text})},t0=m.memo(nj,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),rj=({components:e,enabled:t})=>G(n=>{if(!t||n.message.parts.length===0)return!1;const r=n.message.parts[n.message.parts.length-1];return r?.type!=="text"&&r?.type!=="reasoning"})?d.jsx(t0,{components:e}):null,sj=m.memo(rj,(e,t)=>e.enabled===t.enabled&&e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),ij=({Quote:e})=>{const t=G(Xb);return t?d.jsx(e,{text:t.text,messageId:t.messageId}):null},oj=m.memo(ij);function n0(e,t){const n=e.toolUIs[t.toolName]?.[0]?.render??null;return n||(WP(t.mcp?.app?.resourceUri)&&e.mcpApp?e.mcpApp.render:null)}const r0=()=>{const e=ue(),t=G(r=>r.part),n=G(r=>r.part.type==="tool-call"?n0(r.tools,r.part):null);return!n||t.type!=="tool-call"?null:d.jsx(n,{...t,addResult:e.part().addToolResult,resume:e.part().resumeToolCall,respondToApproval:e.part().respondToToolApproval})},s0=()=>{const e=G(n=>n.part),t=G(n=>n.part.type==="data"?bp(n.dataRenderers,n.part.name,void 0)??null:null);return!t||e.type!=="data"?null:d.jsx(t,{...e})},aj=()=>{const e=G(t=>t.part.type);return e==="tool-call"?d.jsx(r0,{}):e==="data"?d.jsx(s0,{}):null},lj=Object.freeze({type:"text",text:"",status:tj}),i0=({index:e,children:t})=>{const n=ue(),r=G(s=>s.dataRenderers);return d.jsx(yp,{index:e,children:d.jsx(to,{getItemState:s=>s.message().part({index:e}).getState(),children:s=>t({get part(){const i=s();if(i.type==="tool-call"){const o=n0(n.tools().getState(),i)!==null,a=n.message().part({index:e});return{...i,toolUI:o?d.jsx(r0,{}):null,addResult:a.addToolResult,resume:a.resumeToolCall,respondToApproval:a.respondToToolApproval}}if(i.type==="data"){const o=bp(r,i.name,void 0)!==void 0;return{...i,dataRendererUI:o?d.jsx(s0,{}):null}}return i}})})})},uj=({children:e})=>{const t=G(s=>s.message.parts.length),n=G(s=>(s.message.status?.type??"complete")==="running"),r=t===0&&n;return t===0?r?d.jsx(vp,{text:"",isRunning:!0,children:e({part:lj})}):null:d.jsx(d.Fragment,{children:Array.from({length:t},(s,i)=>d.jsx(i0,{index:i,children:o=>e(o)??d.jsx(aj,{})},i))})},Mf=({components:e,unstable_showEmptyOnNonTextEnd:t=!0,children:n})=>n?d.jsx(uj,{children:n}):d.jsx(cj,{components:e,unstable_showEmptyOnNonTextEnd:t});Mf.displayName="MessagePrimitive.Parts";const cj=({components:e,unstable_showEmptyOnNonTextEnd:t})=>{const n=G(i=>i.message.parts.length),r=YP(!!e?.ChainOfThought),s=m.useMemo(()=>n===0?d.jsx(t0,{components:e}):r.map(i=>{if(i.type==="single")return d.jsx(Uo,{index:i.index,components:e},i.index);if(i.type==="chainOfThoughtGroup"){const o=e?.ChainOfThought;return o?d.jsx(KR,{startIndex:i.startIndex,endIndex:i.endIndex,children:d.jsx(o,{})},`chainOfThought-${i.startIndex}`):null}else return i.type==="toolGroup"?d.jsx(e?.ToolGroup??St.ToolGroup,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(o,a)=>{const l=i.startIndex+a;return d.jsx(Uo,{index:l,components:e},`part-${l}`)})},`tool-${i.startIndex}`):d.jsx(e?.ReasoningGroup??St.ReasoningGroup,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(o,a)=>{const l=i.startIndex+a;return d.jsx(Uo,{index:l,components:e},`part-${l}`)})},`reasoning-${i.startIndex}`)}),[r,e,n]);return d.jsxs(d.Fragment,{children:[e?.Quote&&d.jsx(oj,{Quote:e.Quote}),s,d.jsx(sj,{components:e,enabled:t})]})},dj=Symbol.for("@assistant-ui/groupBy.memoKey"),wy=e=>{const t=e.nextChildIdx++;return e.nodeKey===""?String(t):`${e.nodeKey}.${t}`},fj=e=>{const t={key:"",nodeKey:"",indices:[],children:[],nextChildIdx:0},n=[t],r=()=>{const s=n.pop();n[n.length-1].children.push({type:"group",key:s.key,nodeKey:s.nodeKey,indices:s.indices,children:s.children})};for(let s=0;s<e.length;s++){const i=e[s];let o=0;for(;o<n.length-1&&o<i.length&&n[o+1].key===i[o];)o++;for(;n.length-1>o;)r();for(;n.length-1<i.length;){const l=n[n.length-1];n.push({key:i[n.length-1],nodeKey:wy(l),indices:[],children:[],nextChildIdx:0})}const a=n[n.length-1];a.children.push({type:"part",index:s,nodeKey:wy(a)});for(let l=1;l<n.length;l++)n[l].indices.push(s)}for(;n.length>1;)r();return t.children},hj=Object.freeze({type:"complete"}),pj=(e,t,n)=>{if(!n)return!1;switch(e){case"never":return!1;case"always":return!0;case"empty":return t.length===0;case"no-text":{const r=t[t.length-1];return r!==void 0&&r.type!=="text"&&r.type!=="reasoning"}}},o0=()=>{throw new Error("MessagePrimitive.GroupedParts: rendered `children` under a leaf part. `children` is only meaningful for `group-…` cases — add a matching case for the part type or return `null` to skip it.")},a0=(e,t,n)=>{if(e.type==="part")return d.jsx(i0,{index:e.index,children:({part:s})=>n({part:s,children:d.jsx(o0,{})})},`part-${e.index}`);const r=t[e.indices.at(-1)]?.status??hj;return d.jsx(m.Fragment,{children:n({part:{type:e.key,status:r,indices:e.indices},children:d.jsx(d.Fragment,{children:e.children.map(s=>a0(s,t,n))})})},e.nodeKey)},l0=({groupBy:e,indicator:t="no-text",children:n})=>{const r=G(e0(o=>o.message.parts)),s=G(o=>o.tools.toolUIs),i=G(o=>t==="never"?!1:o.message.status?.type==="running");return d.jsxs(d.Fragment,{children:[m.useMemo(()=>{const o={toolUIs:s};return fj(r.map(a=>e(a,o)??[]))},[r,e[dj]??e,s]).map(o=>a0(o,r,n)),pj(t,r,i)&&n({part:{type:"indicator"},children:d.jsx(o0,{})})]})};l0.displayName="MessagePrimitive.GroupedParts";const mj=({children:e})=>{const t=G(Xb);return t?d.jsx(d.Fragment,{children:e(t)}):null},u0=m.memo(mj);u0.displayName="MessagePrimitive.Quote";const c0=(e,t)=>{switch(t.type){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:return e?.Attachment}},gj=({components:e})=>{const t=G(r=>r.attachment);if(!t)return null;const n=c0(e,t);return n?d.jsx(n,{}):null},d0=m.memo(({index:e,components:t})=>d.jsx(jb,{index:e,children:d.jsx(gj,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);d0.displayName="MessagePrimitive.AttachmentByIndex";const _y=({children:e})=>{const t=G(n=>n.message.role!=="user"?0:(n.message.attachments??[]).length);return m.useMemo(()=>Array.from({length:t},(n,r)=>d.jsx(jb,{index:r,children:d.jsx(to,{getItemState:s=>s.message().attachment({index:r}).getState(),children:s=>e({get attachment(){return s()}})})},r)),[t,e])},f0=({components:e,children:t})=>e?d.jsx(_y,{children:({attachment:n})=>{const r=c0(e,n);return r?d.jsx(r,{}):null}}):d.jsx(_y,{children:t});f0.displayName="MessagePrimitive.Attachments";const h0=(e,t)=>{switch(t.type){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:return e?.Attachment}},yj=({components:e})=>{const t=G(r=>r.attachment);if(!t)return null;const n=h0(e,t);return n?d.jsx(n,{}):null},p0=m.memo(({index:e,components:t})=>d.jsx(Ab,{index:e,children:d.jsx(yj,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);p0.displayName="ComposerPrimitive.AttachmentByIndex";const by=({children:e})=>{const t=G(n=>n.composer.attachments.length);return m.useMemo(()=>Array.from({length:t},(n,r)=>d.jsx(Ab,{index:r,children:d.jsx(to,{getItemState:s=>s.composer().attachment({index:r}).getState(),children:s=>e({get attachment(){return s()}})})},r)),[t,e])},m0=({components:e,children:t})=>e?d.jsx(by,{children:({attachment:n})=>{const r=h0(e,n);return r?d.jsx(r,{}):null}}):d.jsx(by,{children:t});m0.displayName="ComposerPrimitive.Attachments";const vj=({children:e})=>{const t=G(n=>n.composer.queue.length);return m.useMemo(()=>Array.from({length:t},(n,r)=>d.jsx(qR,{index:r,children:d.jsx(to,{getItemState:s=>s.composer().queueItem({index:r}).getState(),children:s=>e({get queueItem(){return s()}})})},r)),[t,e])},g0=m.memo(vj);g0.displayName="ComposerPrimitive.Queue";const kp=({children:e})=>G(t=>t.part.status.type==="running")?e:null;kp.displayName="MessagePartPrimitive.InProgress";const y0=({components:e})=>{const t=e.Suggestion;return d.jsx(t,{})},v0=m.memo(({index:e,components:t})=>d.jsx(Mb,{index:e,children:d.jsx(y0,{components:t})}),(e,t)=>e.index===t.index&&e.components.Suggestion===t.components.Suggestion);v0.displayName="ThreadPrimitive.SuggestionByIndex";const ky=({children:e})=>{const t=G(n=>n.suggestions.suggestions.length);return m.useMemo(()=>t===0?null:Array.from({length:t},(n,r)=>d.jsx(Mb,{index:r,children:d.jsx(to,{getItemState:s=>s.suggestions().suggestion({index:r}).getState(),children:s=>e({get suggestion(){return s()}})})},r)),[t,e])},x0=({components:e,children:t})=>e?d.jsx(ky,{children:()=>d.jsx(y0,{components:e})}):d.jsx(ky,{children:t});x0.displayName="ThreadPrimitive.Suggestions";const xj=m.memo(x0,(e,t)=>e.children||t.children?e.children===t.children:e.components.Suggestion===t.components.Suggestion),wj=e=>G(t=>{if(e.editing===!0&&!t.composer.isEditing||e.editing===!1&&t.composer.isEditing)return!1;const n=t.composer.dictation!=null;return!(e.dictation===!0&&!n||e.dictation===!1&&n)}),w0=({children:e,...t})=>wj(t)?e:null;w0.displayName="ComposerPrimitive.If";const _j=()=>{const e=ue(),t=G(n=>!n.composer.canSend||n.thread.isRunning&&!n.thread.capabilities.queue);return{send:m.useCallback(n=>{e.composer().send(n)},[e]),disabled:t}},bj=()=>{const e=ue(),t=G(n=>!n.composer.canCancel);return{cancel:m.useCallback(()=>{e.composer().cancel()},[e]),disabled:t}},kj=()=>{const e=ue(),t=G(n=>n.composer.dictation!=null||!n.thread.capabilities.dictation||!n.composer.isEditing);return{startDictation:m.useCallback(()=>{e.composer().startDictation()},[e]),disabled:t}},Sj=()=>{const e=ue(),t=G(n=>!n.composer.isEditing);return{addAttachment:m.useCallback(n=>e.composer().addAttachment(n),[e]),disabled:t}},Cj=({copiedDuration:e=3e3,copyToClipboard:t}={})=>{const n=ue(),r=G(a=>!((a.message.role!=="assistant"||a.message.status?.type!=="running")&&a.message.parts.some(l=>l.type==="text"&&l.text.length>0))),s=G(a=>a.message.isCopied),i=G(a=>a.composer.isEditing),o=G(a=>a.composer.text);return{copy:m.useCallback(()=>{const a=i?o:n.message().getCopyText();if(!a)return;const l=t??(()=>{});Promise.resolve(l(a)).then(()=>{n.message().setIsCopied(!0),setTimeout(()=>n.message().setIsCopied(!1),e)},()=>{})},[n,i,o,e,t]),disabled:r,isCopied:s}},Ej=()=>{const e=ue(),t=G(n=>n.composer.isEditing);return{edit:m.useCallback(()=>{e.composer().beginEdit()},[e]),disabled:t}},Tj=()=>{const e=ue(),t=G(n=>n.thread.isRunning||n.thread.isDisabled||n.message.role!=="assistant");return{reload:m.useCallback(()=>{e.message().reload()},[e]),disabled:t}},Ij=()=>{const e=ue(),t=G(n=>n.message.metadata.submittedFeedback?.type==="positive");return{submit:m.useCallback(()=>{e.message().submitFeedback({type:"positive"})},[e]),isSubmitted:t}},Rj=()=>{const e=ue(),t=G(n=>n.message.metadata.submittedFeedback?.type==="negative");return{submit:m.useCallback(()=>{e.message().submitFeedback({type:"negative"})},[e]),isSubmitted:t}},Pj=()=>{const e=ue(),t=G(n=>!((n.message.role!=="assistant"||n.message.status?.type!=="running")&&n.message.parts.some(r=>r.type==="text"&&r.text.length>0)));return{speak:m.useCallback(async()=>{e.message().speak()},[e]),disabled:t}},jj=()=>{const e=ue(),t=G(n=>n.message.speech==null);return{stopSpeaking:m.useCallback(()=>{e.message().stopSpeaking()},[e]),disabled:t}},Aj=({prompt:e,send:t,clearComposer:n=!0})=>{const r=ue(),s=G(o=>o.thread.isDisabled),i=t??!1;return{trigger:m.useCallback(()=>{const o=r.thread().getState().isRunning;if(i&&!o)r.thread().append({content:[{type:"text",text:e}],runConfig:r.composer().getState().runConfig}),n&&r.composer().setText("");else if(n)r.composer().setText(e);else{const a=r.composer().getState().text;r.composer().setText(a.trim()?`${a} ${e}`:e)}},[r,i,n,e]),disabled:s}},Nj=()=>G(e=>e.message.status?.type==="incomplete"&&e.message.status.reason==="error"?e.message.status.error??"An error occurred":void 0),Mj=e=>{const{cloud:t,initialMessages:n,maxSteps:r,adapters:s,unstable_humanToolNames:i,...o}=e;return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:r,adapters:s,unstable_humanToolNames:i},otherOptions:o}},Dj=/:([\w-]{1,64})\[([^\]\n]{1,1024})\](?:\{name=([^}\n]{1,1024})\})?/gu,_0={serialize(e){const t=e.id!==e.label?`{name=${e.id}}`:"";return`:${e.type}[${e.label}]${t}`},parse(e){const t=[];let n=0;for(const r of e.matchAll(Dj)){r.index>n&&t.push({kind:"text",text:e.slice(n,r.index)});const s=r[2];t.push({kind:"mention",type:r[1],label:s,id:r[3]??s}),n=r.index+r[0].length}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t}};function Oj(e,t){function n(r){const s=m.useContext(e);if(!r?.optional&&!s)throw new Error(`This component must be used within ${t}.`);return s}return n}function b0(e,t){function n(s){const i=e(s);return i?i[t]:null}function r(s){let i=!1,o;typeof s=="function"?o=s:s&&typeof s=="object"&&(i=!!s.optional,o=s.selector);const a=n({optional:i});return a?o?a(o):a():null}return{[t]:r,[`${t}Store`]:n}}const k0=m.createContext(null),{useThreadViewport:qs,useThreadViewportStore:Gs}=b0(Oj(k0,"ThreadPrimitive.Viewport"),"useThreadViewport"),Sy=e=>{const t=new Map,n=()=>{let r=0;for(const s of t.values())r+=s;e(r)};return{register:()=>{const r=Symbol();return t.set(r,0),{setHeight:s=>{t.get(r)!==s&&(t.set(r,s),n())},unregister:()=>{t.delete(r),n()}}}}},Lj=(e={})=>{const t=new Set,n=Sy(o=>{i.setState({height:{...i.getState().height,viewport:o}})}),r=Sy(o=>{i.setState({height:{...i.getState().height,inset:o}})}),s=(o,a)=>(i.setState({element:{...i.getState().element,[o]:a}}),()=>{i.getState().element[o]===a&&i.setState({element:{...i.getState().element,[o]:null}})}),i=bb(()=>({isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const a of t)a({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:e.turnAnchor??"bottom",topAnchorMessageClamp:{tallerThan:e.topAnchorMessageClamp?.tallerThan??"10em",visibleHeight:e.topAnchorMessageClamp?.visibleHeight??"6em"},height:{viewport:0,inset:0},element:{viewport:null,anchor:null,target:null},targetConfig:null,topAnchorTurn:null,registerViewport:n.register,registerContentInset:r.register,registerViewportElement:o=>s("viewport",o),registerAnchorElement:o=>s("anchor",o),registerAnchorTargetElement:(o,a)=>(i.setState({element:{...i.getState().element,target:o},targetConfig:o&&a?a:null}),()=>{i.getState().element.target===o&&i.setState({element:{...i.getState().element,target:null},targetConfig:null})}),setTopAnchorTurn:o=>{i.setState({topAnchorTurn:o})}}));return i},_u=e=>e,zj=e=>{const t=Gs({optional:!0}),[n]=m.useState(()=>Lj(e));return m.useEffect(()=>t?.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),m.useEffect(()=>{if(t)return n.subscribe(r=>{t.getState().isAtBottom!==r.isAtBottom&&_u(t).setState({isAtBottom:r.isAtBottom})})},[n,t]),n},Sp=({children:e,options:t={}})=>{const n=zj(t),[r]=m.useState(()=>({useThreadViewport:n}));return d.jsx(k0.Provider,{value:r,children:e})},Fj=()=>{const e=ue();return m.useEffect(()=>{},[e]),null},Bj=({children:e,aui:t,runtime:n})=>d.jsxs(cR,{runtime:n,aui:t??null,children:[d.jsx(Fj,{}),d.jsx(Sp,{children:e})]}),Da=m.memo(Bj),$j=e=>{const t=e;t.__isBound||(t.__internal_bindMethods?.(),t.__isBound=!0)};function Uj(e,t=Vj){$j(e);const n=m.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return m.useDebugValue(n),n}const Vj=e=>e;function Hj(e){function t(n){let r=!1,s;typeof n=="function"?s=n:n&&(r=!!n.optional,s=n.selector);const i=e({optional:r});return i?Uj(i,s):null}return t}function S0(e){const t=ue(),n=G(()=>t.composer.source?t.composer().__internal_getRuntime?.()??null:null);if(!n&&!e?.optional)throw new Error("ComposerRuntime is not available");return n}function Wj(e){const t=ue(),n=G(()=>t.message.source?t.message().__internal_getRuntime?.()??null:null);if(!n&&!e?.optional)throw new Error("MessageRuntime is not available");return n}const bu=Hj(Wj);function Cy(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Kj(...e){return t=>{let n=!1;const r=e.map(s=>{const i=Cy(s,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let s=0;s<r.length;s++){const i=r[s];typeof i=="function"?i():Cy(e[s],null)}}}}function Ys(...e){return m.useCallback(Kj(...e),e)}var Ey=Object.defineProperty,so=(e,t)=>{let n={};for(var r in e)Ey(n,r,{get:e[r],enumerable:!0});return Ey(n,Symbol.toStringTag,{value:"Module"}),n};function C0(e){const t=m.forwardRef((n,r)=>{let{children:s,...i}=n,o=null,a=!1;const l=[];Ty(s)&&typeof pl=="function"&&(s=pl(s._payload)),m.Children.forEach(s,h=>{if(Xj(h)){a=!0;const p=h;let g="child"in p.props?p.props.child:p.props.children;Ty(g)&&typeof pl=="function"&&(g=pl(g._payload)),o=Gj(p,g),l.push(o?.props?.children)}else l.push(h)}),o?o=m.cloneElement(o,void 0,l):!a&&m.Children.count(s)===1&&m.isValidElement(s)&&(o=s);const u=o?Qj(o):void 0,c=Ys(r,u);if(!o){if(s||s===0)throw new Error(a?tA(e):eA(e));return s}const f=Yj(i,o.props??{});return o.type!==m.Fragment&&(f.ref=r?c:u),m.cloneElement(o,f)});return t.displayName=`${e}.Slot`,t}var ku=C0("Slot"),qj=Symbol.for("radix.slottable"),Gj=(e,t)=>{if("child"in e.props){const n=e.props.child;return m.isValidElement(n)?m.cloneElement(n,void 0,e.props.children(n.props.children)):null}return m.isValidElement(t)?t:null};function Yj(e,t){const n={...t};for(const r in t){const s=e[r],i=t[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...a)=>{const l=i(...a);return s(...a),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...e,...n}}function Qj(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function Xj(e){return m.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===qj}var Jj=Symbol.for("react.lazy");function Ty(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Jj&&"_payload"in e&&Zj(e._payload)}function Zj(e){return typeof e=="object"&&e!==null&&"then"in e}var eA=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,tA=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,pl=DC[" use ".trim().toString()],nA=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rA=nA.reduce((e,t)=>{const n=C0(`Primitive.${t}`),r=m.forwardRef((s,i)=>{const{asChild:o,...a}=s,l=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});const sA=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"];function iA(e){const t=m.forwardRef(({render:n,asChild:r,children:s,...i},o)=>{const a=e;if(n&&m.isValidElement(n)){const l=s!==void 0?s:n.props.children;return d.jsx(a,{...i,asChild:!0,ref:o,children:m.cloneElement(n,void 0,l)})}return d.jsx(a,{...i,asChild:r,ref:o,children:s})});return t.displayName=typeof e=="string"?e:e.displayName??e.name??"Component",t}function oA(e){const t=rA[e],n=iA(t);return n.displayName=`Primitive.${e}`,n}const Ne=sA.reduce((e,t)=>(e[t]=oA(t),e),{}),aA=({hideWhenRunning:e,autohide:t,autohideFloat:n,forceVisible:r})=>G(s=>{if(e&&s.thread.isRunning)return"hidden";const i=t==="always"||t==="not-last"&&!s.message.isLast,o=r||s.message.isHovering;return i?o?n==="always"||n==="single-branch"&&s.message.branchCount<=1?"floating":"normal":"hidden":"normal"}),lA=m.createContext(null),E0=m.forwardRef(({hideWhenRunning:e,autohide:t,autohideFloat:n,...r},s)=>{const[i,o]=m.useState(0),a=m.useCallback(()=>{let c=!1;return o(f=>f+1),()=>{c||(c=!0,o(f=>Math.max(0,f-1)))}},[]),l=m.useMemo(()=>({acquireInteractionLock:a}),[a]),u=aA({hideWhenRunning:e,autohide:t,autohideFloat:n,forceVisible:i>0});return u==="hidden"?null:d.jsx(lA.Provider,{value:l,children:d.jsx(Ne.div,{...u==="floating"?{"data-floating":"true"}:null,...r,ref:s})})});E0.displayName="ActionBarPrimitive.Root";function Ke(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e?.(s),n===!1||!s.defaultPrevented)return t?.(s)}}const uA=({copiedDuration:e=3e3}={})=>{const{copy:t,disabled:n}=Cj({copiedDuration:e,copyToClipboard:r=>typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("Clipboard API is unavailable")):navigator.clipboard.writeText(r)});return n?null:t},T0=m.forwardRef(({copiedDuration:e,onClick:t,disabled:n,...r},s)=>{const i=G(a=>a.message.isCopied),o=uA({copiedDuration:e});return d.jsx(Ne.button,{type:"button",...i?{"data-copied":"true"}:{},...r,ref:s,disabled:n||!o,onClick:Ke(t,()=>{o?.()})})});T0.displayName="ActionBarPrimitive.Copy";const Wn=(e,t,n=[])=>{const r=m.forwardRef((s,i)=>{const o={},a={};Object.keys(s).forEach(u=>{n.includes(u)?o[u]=s[u]:a[u]=s[u]});const l=t(o)??void 0;return d.jsx(Ne.button,{...a,type:"button",ref:i,disabled:a.disabled||!l,onClick:Ke(a.onClick,l)})});return r.displayName=e,r},cA=()=>{const{disabled:e,reload:t}=Tj();return e?null:t},dA=Wn("ActionBarPrimitive.Reload",cA),fA=()=>{const{disabled:e,edit:t}=Ej();return e?null:t},hA=Wn("ActionBarPrimitive.Edit",fA),pA=()=>{const{disabled:e,speak:t}=Pj();return e?null:t},mA=Wn("ActionBarPrimitive.Speak",pA);function Us(e){const t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>(...n)=>t.current?.(...n),[])}function I0(e,t=globalThis?.document){const n=Us(e);m.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}const gA=()=>{const{disabled:e,stopSpeaking:t}=jj();return e?null:t},R0=m.forwardRef((e,t)=>{const n=gA();return I0(r=>{n&&(r.preventDefault(),n())}),d.jsx(Ne.button,{type:"button",disabled:!n,...e,ref:t,onClick:Ke(e.onClick,()=>{n?.()})})});R0.displayName="ActionBarPrimitive.StopSpeaking";const yA=()=>{const{submit:e}=Ij();return e},P0=m.forwardRef(({onClick:e,disabled:t,...n},r)=>{const s=G(o=>o.message.metadata.submittedFeedback?.type==="positive"),i=yA();return d.jsx(Ne.button,{type:"button",...s?{"data-submitted":"true"}:{},...n,ref:r,disabled:t||!i,onClick:Ke(e,()=>{i?.()})})});P0.displayName="ActionBarPrimitive.FeedbackPositive";const vA=()=>{const{submit:e}=Rj();return e},j0=m.forwardRef(({onClick:e,disabled:t,...n},r)=>{const s=G(o=>o.message.metadata.submittedFeedback?.type==="negative"),i=vA();return d.jsx(Ne.button,{type:"button",...s?{"data-submitted":"true"}:{},...n,ref:r,disabled:t||!i,onClick:Ke(e,()=>{i?.()})})});j0.displayName="ActionBarPrimitive.FeedbackNegative";const xA=({filename:e,onExport:t}={})=>{const n=ue(),r=G(i=>(i.message.role!=="assistant"||i.message.status?.type!=="running")&&i.message.parts.some(o=>o.type==="text"&&o.text.length>0)),s=m.useCallback(async()=>{const i=n.message().getCopyText();if(!i)return;if(t){await t(i);return}const o=new Blob([i],{type:"text/markdown"}),a=URL.createObjectURL(o),l=document.createElement("a");l.href=a,l.download=e??`message-${Date.now()}.md`,l.click(),URL.revokeObjectURL(a)},[n,e,t]);return r?s:null},A0=m.forwardRef(({filename:e,onExport:t,onClick:n,disabled:r,...s},i)=>{const o=xA({filename:e,onExport:t});return d.jsx(Ne.button,{type:"button",...s,ref:i,disabled:r||!o,onClick:Ke(n,()=>{o?.()})})});A0.displayName="ActionBarPrimitive.ExportMarkdown";var Iy=so({Copy:()=>T0,Edit:()=>hA,ExportMarkdown:()=>A0,FeedbackNegative:()=>j0,FeedbackPositive:()=>P0,Reload:()=>dA,Root:()=>E0,Speak:()=>mA,StopSpeaking:()=>R0});const N0=m.forwardRef((e,t)=>d.jsx(Ne.div,{...e,ref:t}));N0.displayName="AttachmentPrimitive.Root";const M0=m.forwardRef((e,t)=>{const n=G(r=>{const s=r.attachment.name.split(".");return s.length>1?s.pop():""});return d.jsxs(Ne.div,{...e,ref:t,children:[".",n]})});M0.displayName="AttachmentPrimitive.unstable_Thumb";const D0=()=>d.jsx(d.Fragment,{children:G(e=>e.attachment.name)});D0.displayName="AttachmentPrimitive.Name";const wA=()=>{const e=ue();return m.useCallback(()=>{e.attachment().remove()},[e])},_A=Wn("AttachmentPrimitive.Remove",wA);var Ry=so({Name:()=>D0,Remove:()=>_A,Root:()=>N0,unstable_Thumb:()=>M0});const bA=e=>G(t=>{const{role:n,attachments:r,parts:s,branchCount:i,isLast:o,speech:a,isCopied:l,isHovering:u}=t.message;return!(e.hasBranches===!0&&i<2||e.user&&n!=="user"||e.assistant&&n!=="assistant"||e.system&&n!=="system"||e.lastOrHover===!0&&!u&&!o||e.last!==void 0&&e.last!==o||e.copied===!0&&!l||e.copied===!1&&l||e.speaking===!0&&a==null||e.speaking===!1&&a!=null||e.hasAttachments===!0&&(n!=="user"||!r?.length)||e.hasAttachments===!1&&n==="user"&&r?.length||e.hasContent===!0&&s.length===0||e.hasContent===!1&&s.length>0||e.submittedFeedback!==void 0&&(t.message.metadata.submittedFeedback?.type??null)!==e.submittedFeedback)}),O0=({children:e,...t})=>bA(t)?e:null;O0.displayName="MessagePrimitive.If";const L0=m.createContext(null),cc=()=>m.useContext(L0),kA=({children:e})=>{const t=m.useRef(new Map),n=m.useRef([]),r=m.useCallback(()=>{const a=Array.from(t.current.entries());a.sort((l,u)=>u[1]-l[1]),n.current=a.map(([l])=>l)},[]),s=m.useCallback((a,l)=>{const u=l?.priority??0;return t.current.set(a,u),r(),()=>{t.current.delete(a),r()}},[r]),i=m.useCallback(()=>n.current,[]),o=m.useMemo(()=>({register:s,getPlugins:i}),[s,i]);return d.jsx(L0.Provider,{value:o,children:e})},Cp=m.createContext(null),z0=m.createContext(null),Ep=()=>{const e=m.useContext(Cp);if(!e)throw new Error("useTriggerPopoverRootContext must be used within ComposerPrimitive.TriggerPopoverRoot");return e},Tp=()=>m.useContext(Cp),SA=()=>{const e=m.useContext(z0);if(!e)throw new Error("useTriggerPopoverAriaPublish must be used within ComposerPrimitive.TriggerPopoverRoot");return e},CA=()=>{const e=Ep();return m.useSyncExternalStore(e.subscribe,e.getTriggers,e.getTriggers)},EA=new Map,F0=()=>()=>{},Py=()=>EA,TA=()=>{const e=Tp();return m.useSyncExternalStore(e?e.subscribe:F0,e?e.getTriggers:Py,e?e.getTriggers:Py)},jy=()=>null,IA=()=>{const e=Tp();return m.useSyncExternalStore(e?e.subscribeAria:F0,e?e.getActiveAria:jy,e?e.getActiveAria:jy)};function Ay(){const e=m.useRef(new Set);return{notify:m.useCallback(()=>{for(const t of e.current)t()},[]),subscribe:m.useCallback(t=>(e.current.add(t),()=>{e.current.delete(t)}),[])}}const Ny=({children:e})=>{const t=m.useRef(new Map),n=m.useRef(new Set),{notify:r,subscribe:s}=Ay(),i=m.useCallback(_=>{const{char:x}=_;if(t.current.has(x))return()=>{};const v=new Map(t.current);v.set(x,_),t.current=v,r();for(const w of n.current)w.added(_);return()=>{const w=new Map(t.current);w.delete(x),t.current=w,r();for(const C of n.current)C.removed(x)}},[r]),o=m.useCallback(()=>t.current,[]),a=m.useCallback(_=>(n.current.add(_),()=>{n.current.delete(_)}),[]),l=m.useRef(null),u=m.useRef(null),{notify:c,subscribe:f}=Ay(),h=m.useCallback((_,x)=>{if(x===null){if(u.current!==_)return;l.current=null,u.current=null,c();return}const v=l.current;u.current===_&&v!==null&&v.popoverId===x.popoverId&&v.highlightedItemId===x.highlightedItemId||(l.current=x,u.current=_,c())},[c]),p=m.useCallback(()=>l.current,[]),g=m.useMemo(()=>({register:i,getTriggers:o,subscribe:s,subscribeLifecycle:a,getActiveAria:p,subscribeAria:f}),[i,o,s,a,p,f]),y=m.useMemo(()=>({setActiveAria:h}),[h]);return d.jsx(Cp.Provider,{value:g,children:d.jsx(z0.Provider,{value:y,children:e})})},B0=({children:e})=>cc()?d.jsx(Ny,{children:e}):d.jsx(kA,{children:d.jsx(Ny,{children:e})});B0.displayName="ComposerPrimitive.TriggerPopoverRoot";const My=/\s/u;function RA(e,t,n){const r=e.slice(0,n);for(let s=r.length-1;s>=0;s--){const i=r[s];if(My.test(i))return null;if(r.startsWith(t,s)){if(s>0&&!My.test(r[s-1]))continue;return{query:r.slice(s+t.length),offset:s}}}return null}const PA=ve(({text:e,triggerChar:t})=>{const[n,r]=dn(e.length),s=ce(()=>RA(e,t,Math.min(n,e.length)),[n,e,t]);return{trigger:s,query:s?.query??"",setCursorPosition:r}});function jA(e){return"type"in e}const AA=ve(({navigableList:e,isSearchMode:t,activeCategoryId:n,query:r,popoverId:s,open:i,selectItem:o,selectCategory:a,goBack:l,close:u})=>{const[c,f]=dn(0);tt(()=>{f(0)},[e]),tt(()=>{f(0)},[t,n]);const h=or(y=>{y<0||y>=e.length||y!==c&&f(y)}),p=or(y=>{if(!i)return!1;switch(y.key){case"ArrowDown":return y.preventDefault(),f(_=>{const x=e.length;return x===0?0:_<x-1?_+1:0}),!0;case"ArrowUp":return y.preventDefault(),f(_=>{const x=e.length;return x===0?0:_>0?_-1:x-1}),!0;case"Enter":case"Tab":{if(y.shiftKey)return!1;y.preventDefault();const _=e[c];return _&&(jA(_)?o(_):a(_.id)),!0}case"Escape":return y.preventDefault(),u(),!0;case"Backspace":return n&&r===""?(y.preventDefault(),l(),!0):!1;default:return!1}}),g=e[c];return{highlightedIndex:c,highlightedItemId:i&&g?`${s}-option-${g.id}`:void 0,highlightIndex:h,handleKeyDown:p}});function Dy(e,t){return e.id.toLowerCase().includes(t)||e.label.toLowerCase().includes(t)||(e.description?.toLowerCase().includes(t)??!1)}const NA=ve(({adapter:e,query:t,open:n})=>{const[r,s]=dn(null);tt(()=>{n||s(null)},[n]);const i=ce(()=>!n||!e?[]:e.categories(),[n,e]),o=n?r:null,a=ce(()=>!o||!e?[]:e.categoryItems(o),[o,e]),l=ce(()=>{if(!n||!e||o||!t&&i.length>0)return null;if(e.search)return e.search(t);const h=[],p=t.toLowerCase();for(const g of i)for(const y of e.categoryItems(g.id))Dy(y,p)&&h.push(y);return h},[n,e,t,o,i]),u=l!==null,c=ce(()=>{if(u)return[];if(!t)return i;const h=t.toLowerCase();return i.filter(p=>p.label.toLowerCase().includes(h))},[i,t,u]),f=ce(()=>{if(u)return l??[];if(!t)return a;const h=t.toLowerCase();return a.filter(p=>Dy(p,h))},[a,t,u,l]);return{categories:c,items:f,isSearchMode:u,activeCategoryId:o,navigableList:ce(()=>u?l??[]:o?f:c,[u,l,o,f,c]),selectCategory:or(h=>{s(h)}),goBack:or(()=>{s(null)})}}),MA=ve(({behavior:e,trigger:t,aui:n,triggerChar:r,setCursorPosition:s,onSelected:i})=>{const o=ir(null),a=or(l=>(o.current=l,()=>{o.current===l&&(o.current=null)}));return{selectItem:or(l=>{if(!t||!e)return;if(o.current?.(l)){i();return}const u=n.composer().getState().text,c=u.slice(0,t.offset),f=u.slice(t.offset+r.length+t.query.length),h=()=>{const p=e.formatter.serialize(l);n.composer().setText(c+p+(f.startsWith(" ")?f:` ${f}`))};e.kind==="directive"?(h(),e.onInserted?.(l)):(e.removeOnExecute?n.composer().setText(c+(f.startsWith(" ")?f.slice(1):f)):h(),e.onExecute(l)),i()}),close:or(()=>{i(),t&&s(t.offset)}),registerSelectItemOverride:a}}),DA=ve(({adapter:e,text:t,triggerChar:n,behavior:r,aui:s,popoverId:i})=>{const o=pt(PA({text:t,triggerChar:n})),a=o.trigger!==null&&e!==void 0&&r!==void 0,l=pt(NA({adapter:e,query:o.query,open:a})),u=or(()=>{l.goBack()}),c=pt(MA({behavior:r,trigger:o.trigger,aui:s,triggerChar:n,setCursorPosition:o.setCursorPosition,onSelected:u})),f=pt(AA({navigableList:l.navigableList,isSearchMode:l.isSearchMode,activeCategoryId:l.activeCategoryId,query:o.query,popoverId:i,open:a,selectItem:c.selectItem,selectCategory:l.selectCategory,goBack:l.goBack,close:c.close}));return{open:a,query:o.query,activeCategoryId:l.activeCategoryId,categories:l.categories,items:l.items,highlightedIndex:f.highlightedIndex,isSearchMode:l.isSearchMode,popoverId:i,highlightedItemId:f.highlightedItemId,selectCategory:l.selectCategory,goBack:l.goBack,selectItem:c.selectItem,close:c.close,highlightIndex:f.highlightIndex,handleKeyDown:f.handleKeyDown,setCursorPosition:o.setCursorPosition,registerSelectItemOverride:c.registerSelectItemOverride}}),Ip=m.createContext(null),io=()=>{const e=m.useContext(Ip);if(!e)throw new Error("useTriggerPopoverScopeContext must be used within ComposerPrimitive.TriggerPopover");return e},OA=()=>m.useContext(Ip),$0=m.createContext(null),U0=()=>{const e=m.useContext($0);if(!e)throw new Error("TriggerPopover.Directive / TriggerPopover.Action must be rendered inside ComposerPrimitive.TriggerPopover");return e},V0=m.forwardRef(({char:e,adapter:t,"aria-label":n,children:r,...s},i)=>{const o=ue(),a=G(S=>S.composer.text),l=m.useId(),u=m.useRef(null),[c,f]=m.useState(null),h=m.useRef(0),p=m.useCallback(S=>(h.current+=1,u.current=S,f(S),()=>{h.current=Math.max(0,h.current-1),u.current===S&&(u.current=null,f(null))}),[e]),g=m.useMemo(()=>({register:p}),[p]),y=gb(DA({adapter:t,text:a,triggerChar:e,behavior:c??void 0,aui:o,popoverId:l})),_=m.useRef(y);_.current=y;const x=Ep();m.useEffect(()=>x.register({char:e,...c?{behavior:c}:{},resource:_.current}),[x,e,c]);const v=cc();m.useEffect(()=>{if(v)return v.register(_.current)},[v]);const w=c!==null&&y.open,C=SA();return m.useEffect(()=>{if(w)return()=>{C.setActiveAria(e,null)}},[C,e,w]),m.useEffect(()=>{w&&C.setActiveAria(e,{popoverId:l,highlightedItemId:y.highlightedItemId})},[C,e,l,w,y.highlightedItemId]),d.jsx($0.Provider,{value:g,children:d.jsx(Ip.Provider,{value:y,children:w?d.jsx(Ne.div,{role:"listbox",id:l,"aria-label":n??"Suggestions","aria-activedescendant":y.highlightedItemId,"data-state":"open",...s,ref:i,children:r}):r})})});V0.displayName="ComposerPrimitive.TriggerPopover";const H0=()=>{const{disabled:e,send:t}=_j(),n=m.useCallback(()=>t(),[t]);return e?null:n},LA=Wn("ComposerPrimitive.Send",H0),W0=m.forwardRef(({onSubmit:e,...t},n)=>{const r=H0(),s=i=>{i.preventDefault(),r&&r()};return d.jsx(Ne.form,{...t,ref:n,onSubmit:Ke(e,s)})});W0.displayName="ComposerPrimitive.Root";const K0=e=>{const t=Us(e),n=qs(r=>r.onScrollToBottom);m.useEffect(()=>n(t),[n,t])},zA=()=>!1,FA=()=>{},BA=e=>m.useSyncExternalStore(m.useCallback(t=>{if(typeof window>"u"||e===null)return FA;const n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},[e]),m.useCallback(()=>typeof window>"u"||e===null?!1:window.matchMedia(e).matches,[e]),zA);function Df(){return Df=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Df.apply(null,arguments)}function $A(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var UA=m.useLayoutEffect,VA=function(t){var n=Bt.useRef(t);return UA(function(){n.current=t}),n},Oy=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},HA=function(t,n){var r=Bt.useRef();return Bt.useCallback(function(s){t.current=s,r.current&&Oy(r.current,null),r.current=n,n&&Oy(n,s)},[n])},Ly={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},WA=function(t){Object.keys(Ly).forEach(function(n){t.style.setProperty(n,Ly[n],"important")})},zy=WA,jt=null,Fy=function(t,n){var r=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?r+n.borderSize:r-n.paddingSize};function KA(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),jt||(jt=document.createElement("textarea"),jt.setAttribute("tabindex","-1"),jt.setAttribute("aria-hidden","true"),zy(jt)),jt.parentNode===null&&document.body.appendChild(jt);var s=e.paddingSize,i=e.borderSize,o=e.sizingStyle,a=o.boxSizing;Object.keys(o).forEach(function(h){var p=h;jt.style[p]=o[p]}),zy(jt),jt.value=t;var l=Fy(jt,e);jt.value=t,l=Fy(jt,e),jt.value="x";var u=jt.scrollHeight-s,c=u*n;a==="border-box"&&(c=c+s+i),l=Math.max(c,l);var f=u*r;return a==="border-box"&&(f=f+s+i),l=Math.min(f,l),[l,u]}var By=function(){},qA=function(t,n){return t.reduce(function(r,s){return r[s]=n[s],r},{})},GA=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],YA=!!document.documentElement.currentStyle,QA=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var r=qA(GA,n),s=r.boxSizing;if(s==="")return null;YA&&s==="border-box"&&(r.width=parseFloat(r.width)+parseFloat(r.borderRightWidth)+parseFloat(r.borderLeftWidth)+parseFloat(r.paddingRight)+parseFloat(r.paddingLeft)+"px");var i=parseFloat(r.paddingBottom)+parseFloat(r.paddingTop),o=parseFloat(r.borderBottomWidth)+parseFloat(r.borderTopWidth);return{sizingStyle:r,paddingSize:i,borderSize:o}},XA=QA;function Rp(e,t,n){var r=VA(n);m.useLayoutEffect(function(){var s=function(o){return r.current(o)};if(e)return e.addEventListener(t,s),function(){return e.removeEventListener(t,s)}},[])}var JA=function(t,n){Rp(document.body,"reset",function(r){t.current.form===r.target&&n(r)})},ZA=function(t){Rp(window,"resize",t)},eN=function(t){Rp(document.fonts,"loadingdone",t)},tN=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],nN=function(t,n){var r=t.cacheMeasurements,s=t.maxRows,i=t.minRows,o=t.onChange,a=o===void 0?By:o,l=t.onHeightChange,u=l===void 0?By:l,c=$A(t,tN),f=c.value!==void 0,h=m.useRef(null),p=HA(h,n),g=m.useRef(0),y=m.useRef(),_=function(){var w=h.current,C=r&&y.current?y.current:XA(w);if(C){y.current=C;var S=KA(C,w.value||w.placeholder||"x",i,s),k=S[0],T=S[1];g.current!==k&&(g.current=k,w.style.setProperty("height",k+"px","important"),u(k,{rowHeight:T}))}},x=function(w){f||_(),a(w)};return m.useLayoutEffect(_),JA(h,function(){if(!f){var v=h.current.value;requestAnimationFrame(function(){var w=h.current;w&&v!==w.value&&_()})}}),ZA(_),eN(_),m.createElement("textarea",Df({},c,{onChange:x,ref:p}))},rN=m.forwardRef(nN);const sN="(pointer: coarse) and (not (any-pointer: fine))",q0=m.forwardRef(({autoFocus:e=!1,asChild:t,render:n,disabled:r,onChange:s,onKeyDown:i,onPaste:o,onSelect:a,submitOnEnter:l,submitMode:u,cancelOnEscape:c=!0,unstable_focusOnRunStart:f=!0,unstable_focusOnScrollToBottom:h=!0,unstable_focusOnThreadSwitched:p=!0,unstable_insertNewlineOnTouchEnter:g=!1,addAttachmentOnPaste:y=!0,..._},x)=>{const v=ue(),w=cc(),C=IA(),S=u??(l===!1?"none":"enter"),k=BA(g?sN:null),T=g&&k&&S==="enter"?"none":S,R=G(z=>z.composer.isEditing?z.composer.text:""),P=G(z=>z.thread.isDisabled||z.composer.dictation?.inputDisabled)||r,E=m.useRef(null),M=Ys(x,E),O=m.useRef(!1);I0(z=>{if(!E.current?.contains(z.target))return;if(w){for(const H of w.getPlugins())if(H.handleKeyDown(z))return}if(!c)return;const b=v.composer();b.getState().canCancel&&(b.cancel(),z.preventDefault())});const W=z=>{if(!P&&!z.nativeEvent.isComposing){if(w){for(const b of w.getPlugins())if(b.handleKeyDown(z))return}if(z.key==="Enter"){const b=v.thread().getState(),H=b.capabilities.queue;if(z.shiftKey&&(z.ctrlKey||z.metaKey)&&H&&S!=="none"&&v.composer().getState().canSend){z.preventDefault(),v.composer().send({steer:!0});return}if(z.shiftKey||b.isRunning&&!H)return;let X=!1;T==="ctrlEnter"?X=z.ctrlKey||z.metaKey:T==="enter"&&(X=!0),X&&(z.preventDefault(),E.current?.closest("form")?.requestSubmit())}}},Q=async z=>{if(!y)return;const b=v.thread().getState().capabilities,H=Array.from(z.clipboardData?.files||[]);if(b.attachments&&H.length>0)try{z.preventDefault(),await Promise.all(H.map(X=>v.composer().addAttachment(X)))}catch(X){console.error("Error adding attachment:",X)}},$=e&&!P,te=m.useCallback(()=>{const z=E.current;!z||!$||(z.focus({preventScroll:!0}),z.setSelectionRange(z.value.length,z.value.length))},[$]);m.useEffect(()=>te(),[te]),K0(()=>{v.composer().getState().type==="thread"&&h&&te()}),m.useEffect(()=>{if(!(v.composer().getState().type!=="thread"||!f))return v.on("thread.runStart",te)},[f,te,v]),m.useEffect(()=>{if(!(v.composer().getState().type!=="thread"||!p))return v.on("threadListItem.switchedTo",te)},[p,te,v]);const ee=C?{"aria-controls":C.popoverId,"aria-expanded":!0,"aria-haspopup":"listbox","aria-activedescendant":C.highlightedItemId}:{},F={name:"input",value:R,..._,...ee,ref:M,disabled:P,onChange:Ke(s,z=>{if(!v.composer().getState().isEditing)return;const b=z.nativeEvent.isComposing===!0;O.current&&!b&&(O.current=!1);const H=b||O.current;if(qg(()=>{v.composer().setText(z.target.value)}),H)return;const X=z.target.selectionStart??z.target.value.length;if(w)for(const I of w.getPlugins())I.setCursorPosition(X)}),onKeyDown:Ke(i,W),onCompositionStart:Ke(_.onCompositionStart,()=>{O.current=!0}),onCompositionEnd:Ke(_.onCompositionEnd,z=>{if(O.current=!1,!v.composer().getState().isEditing)return;const b=z.target;qg(()=>{v.composer().setText(b.value)});const H=b.selectionStart??b.value.length;if(w)for(const X of w.getPlugins())X.setCursorPosition(H)}),onSelect:Ke(a,z=>{if(O.current)return;const b=z.target,H=b.selectionStart??b.value.length;if(w)for(const X of w.getPlugins())X.setCursorPosition(H)}),onPaste:Ke(o,Q)};if(n&&m.isValidElement(n)){const z=_.children!==void 0?_.children:n.props.children;return d.jsx(ku,{...F,children:m.cloneElement(n,void 0,z)})}return d.jsx(t?ku:rN,{...F})});q0.displayName="ComposerPrimitive.Input";const iN=()=>{const{disabled:e,cancel:t}=bj();return e?null:t},oN=Wn("ComposerPrimitive.Cancel",iN),aN=({multiple:e=!0}={})=>{const{disabled:t,addAttachment:n}=Sj(),r=ue(),s=m.useCallback(()=>{const i=document.createElement("input");i.type="file",i.multiple=e,i.hidden=!0;const o=r.composer().getState().attachmentAccept;o!=="*"&&(i.accept=o),document.body.appendChild(i),i.onchange=a=>{const l=a.target.files;if(l){for(const u of l)n(u);document.body.removeChild(i)}},i.oncancel=()=>{(!i.files||i.files.length===0)&&document.body.removeChild(i)},i.click()},[r,e,n]);return t?null:s},lN=Wn("ComposerPrimitive.AddAttachment",aN,["multiple"]),G0=m.forwardRef(({disabled:e,asChild:t=!1,render:n,children:r,...s},i)=>{const[o,a]=m.useState(!1),l=ue(),u=m.useCallback(g=>{e||(g.preventDefault(),a(!0))},[e]),c=m.useCallback(g=>{e||(g.preventDefault(),o||a(!0))},[e,o]),f=m.useCallback(g=>{if(e)return;g.preventDefault();const y=g.relatedTarget;y&&g.currentTarget.contains(y)||a(!1)},[e]),h=m.useCallback(async g=>{if(e)return;g.preventDefault(),a(!1);const y=Array.from(g.dataTransfer.files);await Promise.all(y.map(async _=>{try{await l.composer().addAttachment(_)}catch(x){console.error("Failed to add attachment:",x)}}))},[e,l]),p={...o?{"data-dragging":"true"}:null,...s,onDragEnterCapture:Ke(s.onDragEnterCapture,u),onDragOverCapture:Ke(s.onDragOverCapture,c),onDragLeaveCapture:Ke(s.onDragLeaveCapture,f),onDropCapture:Ke(s.onDropCapture,h),ref:i};if(n&&m.isValidElement(n)){const g=r!==void 0?r:n.props.children;return d.jsx(ku,{...p,children:m.cloneElement(n,void 0,g)})}return d.jsx(t?ku:"div",{...p,children:r})});G0.displayName="ComposerPrimitive.AttachmentDropzone";const uN=()=>{const{disabled:e,startDictation:t}=kj();return e?null:t},cN=Wn("ComposerPrimitive.Dictate",uN),dN=()=>{const e=ue(),t=G(r=>r.composer.dictation!=null),n=m.useCallback(()=>{e.composer().stopDictation()},[e]);return t?n:null},fN=Wn("ComposerPrimitive.StopDictation",dN),Y0=m.forwardRef(({children:e,...t},n)=>{const r=G(s=>s.composer.dictation?.transcript);return r?d.jsx(Ne.span,{...t,ref:n,children:e??r}):null});Y0.displayName="ComposerPrimitive.DictationTranscript";const Q0=m.forwardRef((e,t)=>G(n=>n.composer.quote)?d.jsx(Ne.div,{...e,ref:t}):null);Q0.displayName="ComposerPrimitive.Quote";const X0=m.forwardRef(({children:e,...t},n)=>{const r=G(s=>s.composer.quote?.text);return r?d.jsx(Ne.span,{...t,ref:n,children:e??r}):null});X0.displayName="ComposerPrimitive.QuoteText";const J0=m.forwardRef(({onClick:e,...t},n)=>{const r=ue(),s=m.useCallback(()=>{r.composer().setQuote(void 0)},[r]);return d.jsx(Ne.button,{type:"button",...t,ref:n,onClick:Ke(e,s)})});J0.displayName="ComposerPrimitive.QuoteDismiss";const Z0=m.forwardRef(({children:e,"aria-label":t,...n},r)=>{const{categories:s,activeCategoryId:i,isSearchMode:o,open:a}=io();return!a||i||o?null:d.jsx(Ne.div,{role:"group","aria-label":t??"Categories",...n,ref:r,children:e(s)})});Z0.displayName="ComposerPrimitive.TriggerPopoverCategories";const ek=m.forwardRef(({categoryId:e,onClick:t,onMouseMove:n,...r},s)=>{const{selectCategory:i,highlightIndex:o,categories:a,highlightedIndex:l,activeCategoryId:u,isSearchMode:c,popoverId:f}=io(),h=m.useCallback(()=>{i(e)},[i,e]),p=a.findIndex(_=>_.id===e),g=!u&&!c&&p===l,y=m.useCallback(()=>{o(p)},[o,p]);return d.jsx(Ne.button,{type:"button",role:"option",id:`${f}-option-${e}`,"aria-selected":g,"data-highlighted":g?"":void 0,...r,ref:s,onClick:Ke(t,h),onMouseMove:Ke(n,y)})});ek.displayName="ComposerPrimitive.TriggerPopoverCategoryItem";const tk=m.forwardRef(({children:e,"aria-label":t,...n},r)=>{const{items:s,activeCategoryId:i,isSearchMode:o,open:a}=io();return!a||!i&&!o?null:d.jsx(Ne.div,{role:"group","aria-label":t??"Items",...n,ref:r,children:e(s)})});tk.displayName="ComposerPrimitive.TriggerPopoverItems";const nk=m.forwardRef(({item:e,index:t,onClick:n,onMouseMove:r,...s},i)=>{const{selectItem:o,highlightIndex:a,items:l,highlightedIndex:u,activeCategoryId:c,isSearchMode:f,popoverId:h}=io(),p=m.useCallback(()=>{o(e)},[o,e]),g=t??l.findIndex(x=>x.id===e.id),y=(f||c!==null)&&g===u,_=m.useCallback(()=>{a(g)},[a,g]);return d.jsx(Ne.button,{type:"button",role:"option",id:`${h}-option-${e.id}`,"aria-selected":y,"data-highlighted":y?"":void 0,...s,ref:i,onClick:Ke(n,p),onMouseMove:Ke(r,_)})});nk.displayName="ComposerPrimitive.TriggerPopoverItem";const rk=m.forwardRef(({onClick:e,...t},n)=>{const{activeCategoryId:r,isSearchMode:s,goBack:i,open:o}=io();return!o||!r||s?null:d.jsx(Ne.button,{type:"button",...t,ref:n,onClick:Ke(e,i)})});rk.displayName="ComposerPrimitive.TriggerPopoverBack";const sk=({formatter:e,onExecute:t,removeOnExecute:n})=>{const{register:r}=U0(),s=m.useRef(t);return s.current=t,m.useEffect(()=>r({kind:"action",formatter:e??_0,onExecute:i=>s.current(i),...n!==void 0?{removeOnExecute:n}:{}}),[r,e,n]),null};sk.displayName="ComposerPrimitive.TriggerPopoverAction";const ik=({formatter:e,onInserted:t})=>{const{register:n}=U0(),r=m.useRef(t);return r.current=t,m.useEffect(()=>n({kind:"directive",formatter:e??_0,onInserted:s=>r.current?.(s)}),[n,e]),null};ik.displayName="ComposerPrimitive.TriggerPopoverDirective";const hN=Object.assign(V0,{Directive:ik,Action:sk});var ml=so({AddAttachment:()=>lN,AttachmentByIndex:()=>p0,AttachmentDropzone:()=>G0,Attachments:()=>m0,Cancel:()=>oN,Dictate:()=>cN,DictationTranscript:()=>Y0,If:()=>w0,Input:()=>q0,Queue:()=>g0,Quote:()=>Q0,QuoteDismiss:()=>J0,QuoteText:()=>X0,Root:()=>W0,Send:()=>LA,StopDictation:()=>fN,Unstable_TriggerPopover:()=>hN,Unstable_TriggerPopoverBack:()=>rk,Unstable_TriggerPopoverCategories:()=>Z0,Unstable_TriggerPopoverCategoryItem:()=>ek,Unstable_TriggerPopoverItem:()=>nk,Unstable_TriggerPopoverItems:()=>tk,Unstable_TriggerPopoverRoot:()=>B0,unstable_useTriggerPopoverRootContext:()=>Ep,unstable_useTriggerPopoverRootContextOptional:()=>Tp,unstable_useTriggerPopoverScopeContext:()=>io,unstable_useTriggerPopoverScopeContextOptional:()=>OA,unstable_useTriggerPopoverTriggers:()=>CA,unstable_useTriggerPopoverTriggersOptional:()=>TA});const ok=()=>G(e=>{if(e.part.type!=="text"&&e.part.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return e.part}),pN=()=>G(e=>{if(e.part.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return e.part}),ak=m.createContext(null),mN=e=>({useSmoothStatus:bb(()=>e)}),gN=({children:e})=>{const t=lk({optional:!0}),n=ue(),[r]=m.useState(()=>mN(n.part().getState().status));return t?e:d.jsx(ak.Provider,{value:r,children:e})},yN=e=>{const t=m.forwardRef((n,r)=>d.jsx(gN,{children:d.jsx(e,{...n,ref:r})}));return t.displayName=e.displayName,t};function lk(e){const t=m.useContext(ak);if(!e?.optional&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}const{useSmoothStatus:vN,useSmoothStatusStore:xN}=b0(lk,"useSmoothStatus");var wN=class{constructor(e,t){A(this,"currentText");A(this,"setText");A(this,"animationFrameId",null);A(this,"lastUpdateTime",Date.now());A(this,"targetText","");A(this,"animate",()=>{const e=Date.now();let t=e-this.lastUpdateTime;const n=this.targetText.length-this.currentText.length,r=Math.min(5,250/n);let s=0;for(;t>=r&&s<n;)s++,t-=r;s!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,s!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+s),this.lastUpdateTime=e-t,this.setText(this.currentText))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}};const sd=Object.freeze({type:"running"}),uk=(e,t=!1)=>{const{text:n}=e,[r,s]=m.useState(e.status.type==="running"?"":n),i=ue(),o=G(()=>i.part()),[a,l]=m.useState(o);(o!==a||!n.startsWith(r))&&(l(o),s(e.status.type==="running"?"":n));const u=xN({optional:!0}),c=Us(p=>{if(s(p),u){const g=r!==p||e.status.type==="running"?sd:e.status;_u(u).setState(g,!0)}});m.useEffect(()=>{if(u){const p=t&&(r!==n||e.status.type==="running")?sd:e.status;_u(u).setState(p,!0)}},[u,t,n,r,e.status]);const[f]=m.useState(new wN(r,c)),h=m.useRef(o);return m.useEffect(()=>{if(!t){f.stop();return}const p=h.current!==o;if(h.current=o,p||!n.startsWith(f.targetText)){e.status.type==="running"?(f.currentText="",f.targetText=n,f.start()):(f.currentText=n,f.targetText=n,f.stop());return}f.targetText=n,f.start()},[f,t,n,e.status.type,o]),m.useEffect(()=>()=>{f.stop()},[f]),m.useMemo(()=>t?{type:"text",text:r,status:n===r?e.status:sd}:e,[t,r,e,n])},Pp=m.forwardRef(({smooth:e=!0,component:t="span",...n},r)=>{const{text:s,status:i}=uk(ok(),e);return d.jsx(t,{"data-status":i.type,...n,ref:r,children:s})});Pp.displayName="MessagePartPrimitive.Text";const jp=m.forwardRef((e,t)=>{const{image:n}=pN();return d.jsx(Ne.img,{src:n,...e,ref:t})});jp.displayName="MessagePartPrimitive.Image";const Qs=e=>{const t=m.useRef(void 0);return m.useCallback(n=>{t.current&&(t.current(),t.current=void 0),n&&(t.current=e(n))},[e])},$y=(e,t)=>{const n=e.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(em|px|rem)$/);if(!n)return Number.POSITIVE_INFINITY;const r=Number(n[1]),s=n[2];return s==="px"?r:s==="em"?r*(parseFloat(getComputedStyle(t).fontSize)||16):s==="rem"?r*(parseFloat(getComputedStyle(document.documentElement).fontSize)||16):Number.POSITIVE_INFINITY},_N=e=>e.dataset.messageId,bN=()=>{const e=document.createElement("div");return e.dataset.auiTopAnchorReserve="",e.style.height="0px",e.style.flexShrink="0",e.style.pointerEvents="none",e.setAttribute("aria-hidden","true"),e},Uy=(e,t)=>{const n=`${t}px`;return e.style.height!==n?(e.style.height=n,!0):!1},kN=e=>{const t=window.devicePixelRatio||1;return Math.round(e*t)/t},ck=()=>{const e=ue(),t=G(()=>e.message());return Qs(m.useCallback(n=>{const r=()=>{t.setIsHovering(!0)},s=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",r),n.addEventListener("mouseleave",s),n.matches(":hover")&&queueMicrotask(()=>t.setIsHovering(!0)),()=>{n.removeEventListener("mouseenter",r),n.removeEventListener("mouseleave",s),t.setIsHovering(!1)}},[t]))},SN=()=>{const e=qs(t=>t.topAnchorTurn?.anchorId);return G(t=>t.message.role==="user"&&t.message.index>0&&t.message.index===t.thread.messages.length-2&&t.thread.messages.at(-1)?.role==="assistant"&&(t.message.id===e||t.thread.isRunning))},CN=()=>{const e=qs(t=>t.topAnchorTurn?.targetId);return G(t=>t.message.isLast&&t.message.role==="assistant"&&t.message.index>=1&&t.thread.messages.at(t.message.index-1)?.role==="user"&&(t.message.id===e||t.thread.isRunning))},EN=(e,t)=>Qs(m.useCallback(n=>{if(e)return t.getState().registerAnchorElement(n)},[e,t])),TN=({active:e,threadViewportStore:t})=>Qs(m.useCallback(n=>{if(!e)return;const r=t.getState(),s=r.topAnchorMessageClamp;return r.registerAnchorTargetElement(n,{tallerThan:$y(s.tallerThan,n),visibleHeight:$y(s.visibleHeight,n)})},[e,t])),IN=({forwardedRef:e,...t})=>{const n=Ys(e,ck()),r=G(s=>s.message.id);return d.jsx(Ne.div,{...t,ref:n,"data-message-id":r})},RN=({forwardedRef:e,threadViewportStore:t,...n})=>{const r=ck(),s=SN(),i=CN(),o=Ys(e,r,EN(s,t),TN({active:i,threadViewportStore:t})),a=G(l=>l.message.id);return d.jsx(Ne.div,{...n,ref:o,"data-message-id":a,"data-aui-top-anchor-user":s?"":void 0,"data-aui-top-anchor-target":i?"":void 0})},dk=m.forwardRef((e,t)=>{const n=Gs();return n.getState().turnAnchor==="top"?d.jsx(RN,{...e,forwardedRef:t,threadViewportStore:n}):d.jsx(IN,{...e,forwardedRef:t})});dk.displayName="MessagePrimitive.Root";const id={...St,Text:()=>d.jsxs("p",{style:{whiteSpace:"pre-line"},children:[d.jsx(Pp,{}),d.jsx(kp,{children:d.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Image:()=>d.jsx(jp,{})},Of=e=>{if("children"in e)return d.jsx(Mf,{children:e.children});const{components:t,...n}=e;return d.jsx(Mf,{components:t?{Text:t.Text??id.Text,Image:t.Image??id.Image,Reasoning:t.Reasoning??St.Reasoning,Source:t.Source??St.Source,File:t.File??St.File,Unstable_Audio:t.Unstable_Audio??St.Unstable_Audio,..."ChainOfThought"in t?{ChainOfThought:t.ChainOfThought}:{tools:t.tools,data:t.data,ToolGroup:t.ToolGroup??St.ToolGroup,ReasoningGroup:t.ReasoningGroup??St.ReasoningGroup},Empty:t.Empty,Quote:t.Quote,generativeUI:t.generativeUI}:id,...n})};Of.displayName="MessagePrimitive.Parts";const fk=({children:e})=>Nj()!==void 0?e:null;fk.displayName="MessagePrimitive.Error";const PN=e=>{const t=new Map;for(let r=0;r<e.length;r++){const s=e[r]?.parentId??`__ungrouped_${r}`,i=t.get(s)??[];i.push(r),t.set(s,i)}const n=[];for(const[r,s]of t){const i=r.startsWith("__ungrouped_")?void 0:r;n.push({groupKey:i,indices:s})}return n},jN=e=>{const t=G(n=>n.message.parts);return m.useMemo(()=>t.length===0?[]:e(t),[t,e])},AN=({Fallback:e,...t})=>{const n=G(r=>{const s=r.tools.tools[t.toolName]??e;return Array.isArray(s)?s[0]??e:s});return n?d.jsx(n,{...t}):null},NN=({Fallback:e,...t})=>{const n=G(r=>{const s=r.dataRenderers.renderers[t.name]??e;return Array.isArray(s)?s[0]??e:s});return n?d.jsx(n,{...t}):null},Or={Text:()=>d.jsxs("p",{style:{whiteSpace:"pre-line"},children:[d.jsx(Pp,{}),d.jsx(kp,{children:d.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>d.jsx(jp,{}),File:()=>null,Unstable_Audio:()=>null,Group:({children:e})=>e},MN=({components:{Text:e=Or.Text,Reasoning:t=Or.Reasoning,Image:n=Or.Image,Source:r=Or.Source,File:s=Or.File,Unstable_Audio:i=Or.Unstable_Audio,tools:o={},data:a}={}})=>{const l=ue(),u=G(f=>f.part),c=u.type;if(c==="tool-call"){const f=l.part().addToolResult,h=l.part().resumeToolCall,p=l.part().respondToToolApproval;if("Override"in o)return d.jsx(o.Override,{...u,addResult:f,resume:h,respondToApproval:p});const g=o.by_name?.[u.toolName]??o.Fallback;return d.jsx(AN,{...u,Fallback:g,addResult:f,resume:h,respondToApproval:p})}if(u.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(c){case"text":return d.jsx(e,{...u});case"reasoning":return d.jsx(t,{...u});case"source":return d.jsx(r,{...u});case"image":return d.jsx(n,{...u});case"file":return d.jsx(s,{...u});case"audio":return d.jsx(i,{...u});case"data":{const f=a?.by_name?.[u.name]??a?.Fallback;return d.jsx(NN,{...u,Fallback:f})}default:return console.warn(`Unknown message part type: ${c}`),null}},DN=({partIndex:e,components:t})=>d.jsx(yp,{index:e,children:d.jsx(MN,{components:t})}),ON=m.memo(DN,(e,t)=>e.partIndex===t.partIndex&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.Group===t.components?.Group),LN=({status:e,component:t})=>d.jsx(vp,{text:"",isRunning:e.type==="running",children:d.jsx(t,{type:"text",text:"",status:e})}),zN=Object.freeze({type:"complete"}),FN=({components:e})=>{const t=G(n=>n.message.status??zN);return e?.Empty?d.jsx(e.Empty,{status:t}):d.jsx(LN,{status:t,component:e?.Text??Or.Text})},BN=m.memo(FN,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),Ap=({groupingFunction:e,components:t})=>{const n=G(s=>s.message.parts.length),r=jN(e);return d.jsx(d.Fragment,{children:m.useMemo(()=>n===0?d.jsx(BN,{components:t}):r.map((s,i)=>d.jsx(t?.Group??Or.Group,{groupKey:s.groupKey,indices:s.indices,children:s.indices.map(o=>d.jsx(ON,{partIndex:o,components:t},o))},`group-${i}-${s.groupKey??"ungrouped"}`)),[r,t,n])})};Ap.displayName="MessagePrimitive.Unstable_PartsGrouped";const hk=({components:e,...t})=>d.jsx(Ap,{...t,components:e,groupingFunction:PN});hk.displayName="MessagePrimitive.Unstable_PartsGroupedByParentId";var Su=so({AttachmentByIndex:()=>d0,Attachments:()=>f0,Content:()=>Of,Error:()=>fk,GenerativeUI:()=>Zb,GroupedParts:()=>l0,If:()=>O0,PartByIndex:()=>Uo,Parts:()=>Of,Quote:()=>u0,Root:()=>dk,Unstable_PartsGrouped:()=>Ap,Unstable_PartsGroupedByParentId:()=>hk});const $N=e=>{const t=Us(e);return Qs(m.useCallback(n=>{const r=new ResizeObserver(()=>{t()}),s=new MutationObserver(i=>{i.some(o=>o.type!=="attributes"||o.attributeName!=="style")&&t()});return r.observe(n),s.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{r.disconnect(),s.disconnect()}},[t]))},UN=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{const s=m.useRef(null),i=G(C=>C.thread.messages.length>0),o=m.useRef(!1),a=m.useRef(null),l=Gs();e===void 0&&(e=l.getState().turnAnchor!=="top");const u=m.useRef(0),c=m.useRef(0),f=m.useRef(0),h=m.useRef(0),p=m.useRef(null),g=m.useCallback(C=>{const S=s.current;S&&(p.current=C,S.scrollTo({top:S.scrollHeight,behavior:C}))},[]),y=m.useCallback(C=>{p.current=C,a.current!==null&&cancelAnimationFrame(a.current),a.current=requestAnimationFrame(()=>{a.current=null,g(C)})},[g]);m.useLayoutEffect(()=>()=>{a.current!==null&&cancelAnimationFrame(a.current)},[]);const _=m.useCallback(()=>{const C=l.getState();return C.turnAnchor==="top"&&C.element.viewport===s.current&&C.element.anchor!==null},[l]),x=()=>{const C=s.current;if(!C)return;const S=l.getState().isAtBottom,k=Math.abs(C.scrollHeight-C.scrollTop-C.clientHeight)<=1||C.scrollHeight<=C.clientHeight;!k&&u.current<C.scrollTop||(k?C.scrollHeight>C.clientHeight+1&&(p.current=null):u.current>C.scrollTop&&c.current===C.scrollHeight&&(p.current=null),(k||p.current===null)&&k!==S&&_u(l).setState({isAtBottom:k})),u.current=C.scrollTop,c.current=C.scrollHeight},v=$N(()=>{const C=s.current;if(!C)return;const{scrollHeight:S,clientHeight:k}=C;if(S===f.current&&k===h.current)return;f.current=S,h.current=k;const T=p.current;T&&_()?p.current=null:T?g(T):e&&l.getState().isAtBottom&&g("instant"),x()}),w=Qs(C=>(C.addEventListener("scroll",x),()=>{C.removeEventListener("scroll",x)}));return m.useLayoutEffect(()=>{if(n){if(!i){o.current=!1;return}o.current||(o.current=!0,p.current===null&&y("instant"))}},[i,y,n]),K0(({behavior:C})=>{g(C)}),yu("thread.runStart",()=>{t&&l.getState().turnAnchor!=="top"&&y("auto")}),yu("threadListItem.switchedTo",()=>{r&&y("instant")}),Ys(v,w,s)},pk=m.forwardRef((e,t)=>d.jsx(Ne.div,{...e,ref:t}));pk.displayName="ThreadPrimitive.Root";const mk=({children:e})=>G(t=>t.thread.isEmpty)?e:null;mk.displayName="ThreadPrimitive.Empty";const VN=e=>G(t=>!(e.empty===!0&&!t.thread.isEmpty||e.empty===!1&&t.thread.isEmpty||e.running===!0&&!t.thread.isRunning||e.running===!1&&t.thread.isRunning||e.disabled===!0&&!t.thread.isDisabled||e.disabled===!1&&t.thread.isDisabled)),gk=({children:e,...t})=>VN(t)?e:null;gk.displayName="ThreadPrimitive.If";const yk=(e,t)=>Qs(m.useCallback(n=>{if(!e)return;const r=e(),s=()=>{const o=t?t(n):n.offsetHeight;r.setHeight(o)},i=new ResizeObserver(s);return i.observe(n),s(),()=>{i.disconnect(),r.unregister()}},[e,t])),Vy=e=>{let t=0,n=e;for(;n;)t+=n.offsetTop,n=n.offsetParent;return t},HN=(e,t)=>{let n=0,r=e;for(;r&&r!==t;)n+=r.offsetTop,r=r.offsetParent;return r===t?n:Vy(e)-Vy(t)},vk=({viewport:e,anchor:t,tallerThan:n,visibleHeight:r})=>{const s=HN(t,e),i=t.offsetHeight;return s+Math.max(0,i-(i<=n?i:r))},WN=({scrollHeight:e,...t})=>{const{viewport:n}=t,r=vk(t)+n.clientHeight;return Math.max(0,r-e)},KN=({viewport:e,reserve:t,...n})=>WN({viewport:e,...n,scrollHeight:e.scrollHeight-t.offsetHeight}),qN=e=>{const t=new ResizeObserver(e),n=new MutationObserver(e);let r=null,s=null,i=null;const o=()=>{t.disconnect(),n.disconnect(),r=null,s=null,i=null};return{target:(a,l,u)=>{r===a&&s===l&&i===u||(o(),t.observe(a),t.observe(l),t.observe(u),n.observe(u,{childList:!0,subtree:!0,characterData:!0}),r=a,s=l,i=u)},disconnect:o}},GN=e=>{let t=null;return{schedule:()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))},cancel:()=>{t!==null&&(cancelAnimationFrame(t),t=null)}}},YN=e=>{let t=null,n;function r(){const a=e.getState(),{viewport:l,anchor:u,target:c}=a.element,f=a.targetConfig;if(a.turnAnchor!=="top"||!l||!u||!c||!f){i.disconnect(),t&&(Uy(t,0),t.remove());return}if(t??(t=bN()),(t.parentElement!==c.parentElement||t.previousElementSibling!==c)&&c.after(t),i.target(l,u,c),Uy(t,KN({viewport:l,anchor:u,reserve:t,...f}))){s.schedule();return}const h=_N(u);if(h!==void 0&&n===h)return;const p=kN(vk({viewport:l,anchor:u,...f}));Math.abs(l.scrollTop-p)>1&&l.scrollTo({top:p,behavior:"smooth"}),h!==void 0&&(n=h)}const s=GN(r),i=qN(s.schedule);s.schedule();const o=e.subscribe(s.schedule);return()=>{s.cancel(),o(),i.disconnect(),t?.remove()}},QN=e=>{const t=Gs();m.useLayoutEffect(()=>{if(e)return YN(t)},[e,t])},xk=({isRunning:e,messages:t})=>{if(!e)return null;const n=t.at(-1),r=t.at(-2);return r?.role!=="user"||n?.role!=="assistant"?null:{anchorId:r.id,targetId:n.id}},XN=e=>xk(e)?.anchorId,JN=e=>xk(e)?.targetId,ZN=()=>yk(qs(e=>e.registerViewport),m.useCallback(e=>e.clientHeight,[])),eM=()=>Qs(qs(e=>e.registerViewportElement)),tM=e=>{const t=Gs(),n=G(o=>{if(e)return XN(o.thread)}),r=G(o=>{if(e)return JN(o.thread)}),s=m.useMemo(()=>!n||!r?null:{anchorId:n,targetId:r},[n,r]);m.useLayoutEffect(()=>{if(!s)return;const o=t.getState(),a=o.topAnchorTurn;a?.anchorId===s.anchorId&&a.targetId===s.targetId||o.setTopAnchorTurn(s)},[s,t]);const i=m.useCallback(()=>{t.getState().setTopAnchorTurn(null)},[t]);yu("thread.initialize",i),yu("threadListItem.switchedTo",i)},wk=m.forwardRef(({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r,children:s,...i},o)=>{const a=UN({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r}),l=ZN(),u=eM(),c=Gs().getState().turnAnchor==="top";tM(c),QN(c);const f=Ys(o,a,l,u);return d.jsx(Ne.div,{...i,ref:f,children:s})});wk.displayName="ThreadPrimitive.ViewportScrollable";const _k=m.forwardRef(({turnAnchor:e,topAnchorMessageClamp:t,...n},r)=>d.jsx(Sp,{options:{turnAnchor:e,topAnchorMessageClamp:t},children:d.jsx(wk,{...n,ref:r})}));_k.displayName="ThreadPrimitive.Viewport";const bk=m.forwardRef((e,t)=>{const n=Ys(t,yk(qs(r=>r.registerContentInset),m.useCallback(r=>{const s=parseFloat(getComputedStyle(r).marginTop)||0;return r.offsetHeight+s},[])));return d.jsx(Ne.div,{...e,ref:n})});bk.displayName="ThreadPrimitive.ViewportFooter";const nM=({behavior:e}={})=>{const t=qs(s=>s.isAtBottom),n=Gs(),r=m.useCallback(()=>{n.getState().scrollToBottom({behavior:e})},[n,e]);return t?null:r},rM=Wn("ThreadPrimitive.ScrollToBottom",nM,["behavior"]),sM=({prompt:e,send:t,clearComposer:n,autoSend:r,method:s})=>{const{disabled:i,trigger:o}=Aj({prompt:e,send:t??r??!1,clearComposer:n});return i?null:o},iM=Wn("ThreadPrimitive.Suggestion",sM,["prompt","send","clearComposer","autoSend","method"]);var mt=so({Empty:()=>mk,If:()=>gk,MessageByIndex:()=>Yb,Messages:()=>BP,Root:()=>pk,ScrollToBottom:()=>rM,Suggestion:()=>iM,SuggestionByIndex:()=>v0,Suggestions:()=>xj,Viewport:()=>_k,ViewportFooter:()=>bk,ViewportProvider:()=>Sp}),oM=so({AssistantRuntimeImpl:()=>Ub,BaseAssistantRuntimeCore:()=>Vb,CompositeContextProvider:()=>dp,DefaultThreadComposerRuntimeCore:()=>Kb,MessageRepository:()=>wp,ThreadRuntimeImpl:()=>$b,fromThreadMessageLike:()=>ga,generateId:()=>is,getAutoStatus:()=>xu,splitLocalRuntimeOptions:()=>Mj,useComposerInputPluginRegistryOptional:()=>cc,useSmooth:()=>uk,useSmoothStatus:()=>vN,withSmoothContextProvider:()=>yN});const Np="claude-control.token";let Cu=null,Eu=!1;function aM(){try{return window.localStorage.getItem(Np)}catch{return null}}const lM="claude-control";function dc(){return Eu||(Cu=aM(),Eu=!0),Cu}function kk(e){Cu=e,Eu=!0;try{window.localStorage.setItem(Np,e)}catch{}}function Sk(){Cu=null,Eu=!0;try{window.localStorage.removeItem(Np)}catch{}}function uM(){if(typeof window>"u"||!window.location)return;let e;try{e=new URLSearchParams(window.location.search)}catch{return}const t=e.get("token");if(!t)return;kk(t),e.delete("token");const n=e.toString(),r=window.location.pathname+(n?`?${n}`:"")+window.location.hash;try{window.history.replaceState(null,"",r)}catch{}}uM();const Lf=new Set;function cM(e){return Lf.add(e),()=>Lf.delete(e)}function Ck(){Sk();for(const e of Lf)e()}function dM(e){const t=dc(),n={...e??{}};return t&&(n.Authorization=`Bearer ${t}`),n}async function nt(e,t){const n=await fetch(e,{...t,headers:dM(t?.headers)});return n.status===401&&Ck(),n}function fM(e){const t=`/term/${encodeURIComponent(e)}/`,n=dc();return n?`${t}?token=${encodeURIComponent(n)}`:t}function hM(){const e=window.location;return`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}/`}async function Ek(){try{const e=await nt("/api/version");return e.ok?await e.json():null}catch{return null}}async function pM(){try{const e=await nt("/api/update",{method:"POST"}),t=await e.json().catch(()=>({}));return e.ok&&!!t.ok}catch{return!0}}async function mM(){try{const e=await nt("/api/push/vapid");return e.ok?(await e.json()).publicKey??null:null}catch{return null}}async function gM(e){try{return(await nt("/api/push/subscribe",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})).ok}catch{return!1}}async function yM(e){try{return(await nt("/api/push/unsubscribe",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({endpoint:e})})).ok}catch{return!1}}async function vM(e){const t=await nt("/api/icon",{method:"POST",body:e}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw new Error(n.error||`HTTP ${t.status}`)}async function xM(){const e=await nt("/api/icon",{method:"DELETE"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.ok)throw new Error(t.error||`HTTP ${e.status}`)}async function wM(){const e=await nt("/api/models");if(!e.ok)throw new Error(`HTTP ${e.status}`);return await e.json()}async function _M(e,t){const n=await nt("/api/optimize",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})}),r=await n.json().catch(()=>({}));if(!n.ok||typeof r.optimized!="string")throw new Error(r.error||`HTTP ${n.status}`);return{optimized:r.optimized,rationale:r.rationale??[],changes:r.changes??[],mode:r.mode==="rules"?"rules":"llm"}}async function bM(e,t="webm"){const n=await nt(`/api/transcribe?ext=${encodeURIComponent(t)}`,{method:"POST",body:e}),r=await n.json().catch(()=>({}));if(!n.ok||!r.ok)throw new Error(r.error||`HTTP ${n.status}`);return r.text??""}async function Tk(){const e=await nt("/api/config");if(!e.ok)throw new Error(`HTTP ${e.status}`);return await e.json()}async function kM(e){const t=await nt("/api/config",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error("error"in n&&n.error||`HTTP ${t.status}`);return n}async function Ik(e){const t=await nt("/api/session/new",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e??{})}),n=await t.json().catch(()=>({}));if(!t.ok||!("ok"in n)||!n.ok){const r="error"in n&&n.error||`HTTP ${t.status}`;throw new Error(r)}return n}async function SM(e,t){const n=await nt("/api/session/rename",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({id:e,name:t})}),r=await n.json().catch(()=>({}));if(!n.ok||!("ok"in r)||!r.ok){const s="error"in r&&r.error||`HTTP ${n.status}`;throw new Error(s)}}function CM(e){return`/api/uploads/${encodeURIComponent(e)}`}async function EM(){const e=await nt("/api/ps");if(!e.ok)throw new Error(`HTTP ${e.status}`);return(await e.json()).processes??[]}async function TM(e,t){const n=await nt("/api/kill",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pid:e,signal:t})}),r=await n.json().catch(()=>({}));if(!n.ok||!r.ok)throw new Error(r.error||`HTTP ${n.status}`)}async function Rk(e){const t=e?`/api/skills?id=${encodeURIComponent(e)}`:"/api/skills",n=await nt(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);return(await n.json()).skills??[]}async function IM(e){const t=e?`/api/agents?id=${encodeURIComponent(e)}`:"/api/agents",n=await nt(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);return(await n.json()).agents??[]}async function RM(e){const t=`/api/upload?name=${encodeURIComponent(e.name)}`,n=await nt(t,{method:"POST",body:e});let r=null;try{r=await n.json()}catch{}const s=r??{};if(!n.ok||!s.ok||!s.path)throw new Error(s.error||`HTTP ${n.status}`);return{ok:!0,path:s.path,name:s.name??e.name}}const PM=1008,Hy=1e3,jM=3e4;class AM{constructor(){A(this,"ws",null);A(this,"reconnectTimer",null);A(this,"reconnectDelay",Hy);A(this,"selectedId",null);A(this,"closed",!1);A(this,"msgHandlers",new Set);A(this,"stateHandlers",new Set)}connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.emitState("connecting");const t=dc(),n=t?[lM,t]:void 0,r=new WebSocket(hM(),n);this.ws=r,r.addEventListener("open",()=>{this.reconnectDelay=Hy,this.emitState("connected"),this.selectedId&&this.send({type:"subscribe",id:this.selectedId})}),r.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}for(const o of this.msgHandlers)o(i)}),r.addEventListener("close",s=>{if(this.ws=null,this.emitState("disconnected"),s.code===PM){Ck();return}this.closed||this.scheduleReconnect()}),r.addEventListener("error",()=>{})}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>this.connect(),this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*2,jM)}send(t){return this.ws&&this.ws.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(t)),!0):!1}isOpen(){return this.ws?.readyState===WebSocket.OPEN}select(t){this.selectedId!==t&&(this.selectedId&&this.send({type:"unsubscribe",id:this.selectedId}),this.selectedId=t,t&&this.send({type:"subscribe",id:t}))}resubscribe(){const t=this.selectedId;t&&(this.send({type:"unsubscribe",id:t}),this.send({type:"subscribe",id:t}))}onMessage(t){return this.msgHandlers.add(t),()=>this.msgHandlers.delete(t)}onState(t){return this.stateHandlers.add(t),()=>this.stateHandlers.delete(t)}emitState(t){for(const n of this.stateHandlers)n(t)}close(){this.closed=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close(),this.ws=null}}const Wy=2e3;function NM(e,t){if(!e||e.length===0)return Ky(t);if(t.length===0)return e;const n=new Set;for(const s of e)n.add(s.uuid);const r=t.filter(s=>!n.has(s.uuid));return r.length===0?e:Ky([...e,...r])}function Ky(e){return e.length>Wy?e.slice(e.length-Wy):e}const MM=10*6e4;function DM(){const e=m.useRef(null);e.current||(e.current=new AM);const t=e.current,[n,r]=m.useState([]),[s,i]=m.useState(null),[o,a]=m.useState("connecting"),[l,u]=m.useState({snapshot:null,warning:null}),[c,f]=m.useState([]),[h,p]=m.useState(null),[g,y]=m.useState(null),[_,x]=m.useState({}),[v,w]=m.useState({}),[C,S]=m.useState({}),[k,T]=m.useState({}),R=m.useRef(null);R.current=s;const P=m.useRef([]);P.current=n,m.useEffect(()=>{const ne=t.onState(a),J=t.onMessage(re=>{switch(re.type){case"sessions":r(he=>{const Fe=new Map(he.map(xt=>[xt.id,xt]));return(re.sessions??[]).map(xt=>{const Xt=Fe.get(xt.id);return Xt?{...xt,model:xt.model??Xt.model,ctxPct:xt.ctxPct??Xt.ctxPct}:xt})});break;case"messages":x(he=>({...he,[re.id]:NM(he[re.id],re.messages??[])})),w(he=>({...he,[re.id]:re.pending??null}));break;case"append":x(he=>({...he,[re.id]:[...he[re.id]??[],...re.messages??[]]}));break;case"pending":w(he=>({...he,[re.id]:re.pending})),r(he=>he.map(Fe=>Fe.id===re.id?{...Fe,pending:!!re.pending}:Fe));break;case"resources":{const he=re.snapshot??null;if(u({snapshot:he,warning:re.warning??null}),he){const Fe=Date.now(),xt={t:Fe,cpu:he.self?.cpuPct??0,mem:he.system?.memUsedPct??0};f(Xt=>[...Xt,xt].filter(wt=>Fe-wt.t<=MM))}break}case"capture":re.id===R.current&&p(re.text??"");break;case"shell-output":(!re.id||re.id===R.current)&&y(re.text??"");break;case"prompt":T(he=>({...he,[re.id]:re.prompt}));break;case"subagents":S(he=>({...he,[re.id]:Object.fromEntries((re.subagents??[]).map(Fe=>[Fe.agentId,Fe]))}));break;case"subagent":S(he=>({...he,[re.id]:{...he[re.id]??{},[re.subagent.agentId]:re.subagent}}));break;case"ack":window.dispatchEvent(new CustomEvent("cockpit:ack",{detail:re}));break}});return t.connect(),()=>{ne(),J()}},[t]),m.useEffect(()=>()=>t.close(),[t]);const E=m.useCallback(ne=>{ne!==R.current&&(i(ne),p(null),t.select(ne))},[t]),M=m.useCallback(ne=>{const J=R.current;return!J||!ne.trim()?!1:t.send({type:"reply",id:J,text:ne})},[t]),O=m.useCallback((ne,J)=>{const re=R.current;return re?t.send({type:"answer",id:re,toolUseId:ne,selections:J}):!1},[t]),W=m.useCallback((ne,J)=>{const re=R.current;return re?t.send({type:"capture",id:re,lines:ne,escapes:J}):!1},[t]),Q=m.useCallback(()=>p(null),[]),$=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"pane-text",id:J,text:ne}):!1},[t]),te=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"pane-key",id:J,key:ne}):!1},[t]),ee=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"shell-input",id:J,line:ne}):!1},[t]),F=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"shell-text",id:J,text:ne}):!1},[t]),z=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"shell-key",id:J,key:ne}):!1},[t]),b=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"shell-capture",id:J,lines:ne}):!1},[t]),H=m.useCallback(()=>y(null),[]),X=m.useCallback(()=>t.resubscribe(),[t]),I=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"promptkey",id:J,key:ne}):!1},[t]),le=m.useCallback((ne,J)=>t.send({type:"promptselect",id:ne,labels:J}),[t]),we=m.useMemo(()=>s?_[s]??[]:[],[s,_]),de=m.useMemo(()=>s?v[s]??null:null,[s,v]),Je=m.useMemo(()=>s?k[s]??null:null,[s,k]),Ue=m.useMemo(()=>{const ne=s?C[s]:null;return ne?Object.values(ne).sort((J,re)=>(re.createdAt??-1/0)-(J.createdAt??-1/0)):[]},[s,C]);return{sessions:n,selectedId:s,messages:we,pending:de,prompt:Je,subagents:Ue,conn:o,resources:l,resourceHistory:c,capture:h,shellOutput:g,select:E,resubscribe:X,sendReply:M,sendPromptKey:I,sendPromptSelect:le,sendAnswer:O,requestCapture:W,clearCapture:Q,sendPaneText:$,sendPaneKey:te,sendShellInput:ee,sendShellText:F,sendShellKey:z,requestShellCapture:b,clearShellOutput:H}}const od="cc:push:intent";function OM(){return typeof window>"u"||!("serviceWorker"in navigator)||!("PushManager"in window)||!("Notification"in window)?!1:window.isSecureContext===!0}function LM(){if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",t=/iPad|iPhone|iPod/.test(e),n=navigator.platform==="MacIntel"&&typeof navigator.maxTouchPoints=="number"&&navigator.maxTouchPoints>1;return t||n}function qy(e){const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),s=new ArrayBuffer(r.length),i=new Uint8Array(s);for(let o=0;o<r.length;o+=1)i[o]=r.charCodeAt(o);return s}function zM(){const e=OM(),t=LM(),[n,r]=m.useState(e?"off":"unsupported"),s=m.useCallback(async()=>{const a=await navigator.serviceWorker.register("/sw.js");if(await navigator.serviceWorker.ready,await Notification.requestPermission()!=="granted")return r("denied"),!1;const u=await mM();if(!u)return r("off"),!1;let c=await a.pushManager.getSubscription();if(c)try{const h=qy(u),p=c.options?.applicationServerKey;let g=!1;if(p instanceof ArrayBuffer){const y=new Uint8Array(p),_=new Uint8Array(h);if(y.length!==_.length)g=!0;else for(let x=0;x<y.length;x++)if(y[x]!==_[x]){g=!0;break}}g&&(await c.unsubscribe(),c=null)}catch{}return c||(c=await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:qy(u)})),await gM(c.toJSON())},[]),i=m.useCallback(async()=>{if(e){r("working");try{await s()?(localStorage.setItem(od,"1"),r("on")):r(l=>l==="denied"?"denied":"off")}catch{r("off")}}},[e,s]),o=m.useCallback(async()=>{r("working"),localStorage.removeItem(od);try{const l=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();l&&(await yM(l.endpoint),await l.unsubscribe())}catch{}r("off")},[]);return m.useEffect(()=>{if(!e||localStorage.getItem(od)!=="1")return;if(Notification.permission!=="granted"){r(Notification.permission==="denied"?"denied":"off");return}let a=!1;return(async()=>{try{const l=await s();a||r(l?"on":"off")}catch{a||r("off")}})(),()=>{a=!0}},[e,s]),{status:n,supported:e,iosHint:t,enable:i,disable:o}}const zf=70,FM=110,BM=.5,$M=".thread-viewport, .rail-scroll, .live-pane-body";function UM(e,t=()=>window.location.reload()){const[n,r]=m.useState(0),[s,i]=m.useState(!1),o=m.useRef(0),a=m.useRef(!1),l=m.useRef(0),u=m.useRef(null),c=f=>{o.current=f,r(f)};return m.useEffect(()=>{const f=e.current;if(!f)return;const h=y=>{if(y.touches.length!==1){a.current=!1;return}const x=y.target?.closest($M)??null;x&&x.scrollTop<=0?(u.current=x,l.current=y.touches[0].clientY,a.current=!0):a.current=!1},p=y=>{if(!a.current)return;const _=y.touches[0].clientY-l.current,x=u.current;if(_<=0||x&&x.scrollTop>0){o.current!==0&&c(0),x&&x.scrollTop>0&&(a.current=!1);return}const v=Math.min(FM,_*BM);c(v),y.cancelable&&y.preventDefault()},g=()=>{a.current&&(a.current=!1,o.current>=zf?(c(zf),i(!0),setTimeout(t,150)):c(0))};return f.addEventListener("touchstart",h,{passive:!0}),f.addEventListener("touchmove",p,{passive:!1}),f.addEventListener("touchend",g,{passive:!0}),f.addEventListener("touchcancel",g,{passive:!0}),()=>{f.removeEventListener("touchstart",h),f.removeEventListener("touchmove",p),f.removeEventListener("touchend",g),f.removeEventListener("touchcancel",g)}},[e,t]),{pull:n,refreshing:s}}const VM=zf,Tu="__cockpitSummary";function HM(e){if(e&&typeof e=="object"&&Tu in e){const t=e[Tu];return typeof t=="string"?t:""}return""}function Pk(e){if(!e||typeof e!="object")return e;const t={};for(const[n,r]of Object.entries(e))n!==Tu&&(t[n]=r);return t}function WM(e){if(e&&typeof e=="object"&&"text"in e){const t=e;return{text:String(t.text??""),isError:!!t.isError}}return null}function jk(e){const t=new Map;for(const r of e)for(const s of r.blocks??[])s.kind==="tool_result"&&t.set(s.forId,{text:s.text??"",isError:!!s.isError});const n=[];return e.forEach((r,s)=>{const i=GM(r.blocks??[],t,r.role==="user");if(i.length===0)return;const o=r.role==="user"?"user":"assistant";n.push({role:o,id:r.uuid||`m-${s}`,createdAt:r.ts?new Date(r.ts):void 0,content:i,metadata:{custom:{cockpitRole:r.role}}})}),KM(n)}function KM(e){const t=r=>r.role==="assistant"&&(r.metadata?.custom?.cockpitRole??"assistant")==="assistant",n=[];for(const r of e){const s=n[n.length-1];s&&t(s)&&t(r)?n[n.length-1]={...s,content:[...s.content,...r.content]}:n.push(r)}return n}function qM(e){const t=e.trimStart();if(!t.startsWith("<"))return null;const n=/<summary>([\s\S]*?)<\/summary>/.exec(t)?.[1]?.trim();return t.startsWith("<task-notification")?`⚙ background task ${n?`— ${n}`:"update"}`:t.startsWith("<system-reminder")?"⚙ system reminder":t.startsWith("<command-name")||t.startsWith("<command-message")?"⌘ slash command":t.startsWith("<local-command-stdout")?"⌘ command output":t.startsWith("<user-prompt-submit-hook")||t.startsWith("<session-")?"⚙ session hook":null}function GM(e,t,n=!1){const r=[];for(const s of e)switch(s.kind){case"text":{if(s.text&&s.text.length>0){const i=n?qM(s.text):null;r.push({type:"text",text:i??s.text})}break}case"thinking":{s.text&&s.text.trim().length>0&&r.push({type:"reasoning",text:s.text});break}case"tool_use":{const i=t.get(s.id),o=s.input&&typeof s.input=="object"?s.input:s.input!=null?{value:s.input}:{};r.push({type:"tool-call",toolCallId:s.id,toolName:s.name||"tool",args:{...o,[Tu]:s.inputSummary??""},argsText:s.inputSummary??"",result:i??void 0,isError:i?.isError});break}}return r}const YM="image/*,application/pdf,text/*,.md,.json,.csv,.log",Ff=" cockpit-path:";function QM(e){return Ff+e}const zl=new Map;function XM(e){return zl.get(e)??null}function JM(e){for(const t of e.content??[])if(t.type==="text"&&t.text.startsWith(Ff))return t.text.slice(Ff.length);return XM(e.id)}function ZM(e){return`${e.name}-${e.size}-${e.lastModified}`}function e2(e){return{accept:YM,async add({file:t}){const n=ZM(t),r=t.type.startsWith("image/"),s=t.type==="application/pdf",i={id:n,type:r?"image":s?"document":"file",name:t.name,contentType:t.type||"application/octet-stream",file:t};e(`Uploading ${t.name}…`);try{const o=await RM(t);return zl.set(n,o.path),e(`Attached ${o.name}`,"ok"),{...i,status:{type:"requires-action",reason:"composer-send"}}}catch(o){const a=o instanceof Error?o.message:String(o);return e(`Attach failed: ${a}`,"error"),{...i,status:{type:"incomplete",reason:"error"}}}},async send(t){const n=zl.get(t.id);if(!n)throw new Error(`attachment ${t.name} was not uploaded`);return{...t,status:{type:"complete"},content:[{type:"text",text:QM(n)}]}},async remove(t){zl.delete(t.id)}}}function mr(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ak(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}/*!
44
+ `);var oy=class{constructor(e,t,n){A(this,"contentBinding");A(this,"messageApi");A(this,"threadApi");this.contentBinding=e,this.messageApi=t,this.threadApi=n,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.respondToToolApproval=this.respondToToolApproval.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const n=this.messageApi.getState();if(!n)throw new Error("Message is not available");const r=t.toolName,s=t.toolCallId,i=wr.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:s,result:i.result,artifact:i.artifact,isError:i.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e})}respondToToolApproval(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to respond to tool approval on non-tool message part");if(!t.approval||t.approval.approved!==void 0)throw new Error("Tool call has no pending approval");if(!this.threadApi)throw new Error("Thread API is not available");this.threadApi.getState().respondToToolApproval({approvalId:t.approval.id,approved:e.approved,...e.reason!=null&&{reason:e.reason}})}subscribe(e){return this.contentBinding.subscribe(e)}};const cl=Object.freeze({type:"complete"}),oP=(e,t,n)=>{if(e.role!=="assistant")return cl;if(n.type==="tool-call")return n.result?cl:e.status;const r=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?cl:r?e.status:cl},ay=(e,t)=>{const n=e.content[t];if(!n)return Hn;const r=oP(e,t,n);return Object.freeze({...n,[$s]:n[$s],status:r})};var aP=class{constructor(e,t){A(this,"_core");A(this,"_threadBinding");A(this,"composer");A(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new iP(new vu({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:n=>this._threadBinding.subscribe(n)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(e={}){const t=this._getEditComposerRuntimeCore(),n=t??this._threadBinding.getState().composer,r=t??n,{runConfig:s=r.runConfig}=e,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:s})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){const e=this._core.getState();if(this._threadBinding.getState().speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const n=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");if(!t&&!e)throw new Error("Must specify either branchId or position");const r=this._threadBinding.getState().getBranches(n.id);let s=t;if(e==="previous"?s=r[n.branchNumber-2]:e==="next"&&(s=r[n.branchNumber]),!s)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(s)}unstable_getCopyText(){return ma(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new oy(new Fn({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}},getState:()=>ay(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new oy(new Fn({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}},getState:()=>{const t=this._core.getState(),n=t.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===e);return n===-1?Hn:ay(t,n)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new tP(new Fn({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}},getState:()=>{const t=this.getState().attachments?.[e];return t?{...t,source:"message"}:Hn},subscribe:t=>this._core.subscribe(t)}))}};const lP=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),uP=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),cP=(e,t)=>typeof t=="string"?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId??e.at(-1)?.id??null,sourceId:t.sourceId??null,role:t.role??"user",content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},dP=(e,t)=>{const n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:e.isRunning??(n?.role!=="assistant"?!1:n.status.type==="running"),messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech,voice:e.voice})};var $b=class{constructor(e,t){A(this,"_threadBinding");A(this,"composer");A(this,"_eventSubscriptionSubjects",new Map);const n=new Fn({path:e.path,getState:()=>dP(e.getState(),t.getState()),subscribe:r=>{const s=e.subscribe(r),i=t.subscribe(r);return()=>{s(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:r=>e.outerSubscribe(r),subscribe:r=>e.subscribe(r)},this.composer=new sP(new vu({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.resumeRun=this.resumeRun.bind(this),this.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.connectVoice=this.connectVoice.bind(this),this.disconnectVoice=this.disconnectVoice.bind(this),this.muteVoice=this.muteVoice.bind(this),this.unmuteVoice=this.unmuteVoice.bind(this),this.getVoiceVolume=this.getVoiceVolume.bind(this),this.subscribeVoiceVolume=this.subscribeVoiceVolume.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(cP(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}startRun(e){return this._threadBinding.getState().startRun(uP(e))}resumeRun(e){return this._threadBinding.getState().resumeRun(lP(e))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}connectVoice(){this._threadBinding.getState().connectVoice()}disconnectVoice(){this._threadBinding.getState().disconnectVoice()}getVoiceVolume(){return this._threadBinding.getState().getVoiceVolume()}subscribeVoiceVolume(e){return this._threadBinding.getState().subscribeVoiceVolume(e)}muteVoice(){this._threadBinding.getState().muteVoice()}unmuteVoice(){this._threadBinding.getState().unmuteVoice()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}},()=>{const t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:t[e-1]?.id??null,index:e}})}getMessageById(e){return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}},()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new aP(new Fn({path:e,getState:()=>{const{message:n,parentId:r,index:s}=t()??{},{messages:i,speech:o}=this._threadBinding.getState();if(!n||r===void 0||s===void 0)return Hn;const a=this._threadBinding.getState().getBranches(n.id);return{...n,[$s]:n[$s],index:s,isLast:i.at(-1)?.id===n.id,parentId:r,branchNumber:a.indexOf(n.id)+1,branchCount:a.length,speech:o?.messageId===n.id?o:void 0}},subscribe:n=>this._threadBinding.subscribe(n)}),this._threadBinding)}unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new Db({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}};const fP=m.createContext(null),hP=()=>m.useContext(fP);var dl=class{constructor(e,t){A(this,"_core");A(this,"_threadListBinding");this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.updateCustom=this.updateCustom.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(e){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id,e)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}updateCustom(e){const t=this._core.getState();if(!this._threadListBinding.updateCustom)throw new Error("Thread list runtime does not support updating custom metadata");return this._threadListBinding.updateCustom(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{const s=this._core.getState(),i=s.isMain,o=s.id;n===i&&r===o||(n=i,r=o,!(e==="switchedTo"&&!i)&&(e==="switchedAway"&&i||t({})))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};const ly=Promise.resolve(),pP=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,isLoadingMore:e.isLoadingMore??!1,hasMore:e.hasMore??!1,threadItems:e.threadItems}),fl=(e,t)=>{if(t===void 0)return Hn;const n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,custom:n.custom,isMain:n.id===e.mainThreadId}:Hn};var mP=class{constructor(e,t=$b){A(this,"_core");A(this,"_runtimeFactory");A(this,"_getState");A(this,"_mainThreadListItemRuntime");A(this,"main");this._core=e,this._runtimeFactory=t;const n=new xp({path:{},getState:()=>pP(e),subscribe:r=>e.subscribe(r)});this._getState=n.getState.bind(n),this._mainThreadListItemRuntime=new dl(new Fn({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>fl(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new t(new vu({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:r=>e.subscribe(r)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getLoadThreadsPromise=this.getLoadThreadsPromise.bind(this),this.reload=this.reload.bind(this),this.loadMore=this.loadMore.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e,t){return this._core.switchToThread(e,t)}switchToNewThread(){return this._core.switchToNewThread()}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}reload(){return this._core.reload?.()??ly}loadMore(){return this._core.loadMore?.()??ly}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new vu({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new dl(new Fn({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>fl(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new dl(new Fn({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>fl(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new dl(new Fn({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>fl(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},Ub=class{constructor(e){A(this,"_core");A(this,"threads");A(this,"_thread");this._core=e,this.threads=new mP(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.registerModelContextProvider=this.registerModelContextProvider.bind(this)}get thread(){return this._thread}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}},Vb=class{constructor(){A(this,"_contextProvider",new dp)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}};const gs=Object.freeze([]),ji="DEFAULT_THREAD_ID",gP=Object.freeze([ji]),yP=Object.freeze({id:ji,remoteId:void 0,externalId:void 0,status:"regular"}),vP=Promise.resolve(),uy=Object.freeze({[ji]:yP});var xP=class{constructor(e={},t){A(this,"threadFactory");A(this,"_mainThreadId",ji);A(this,"_threads",gP);A(this,"_archivedThreads",gs);A(this,"_threadData",uy);A(this,"adapter",{});A(this,"_mainThread");A(this,"_subscriptions",new Set);this.threadFactory=t,this.__internal_setAdapter(e,!0)}get isLoading(){return this.adapter.isLoading??!1}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}get threadItems(){return this._threadData}getLoadThreadsPromise(){return vP}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(e){return this._threadData[e]}__internal_setAdapter(e,t=!1){const n=this.adapter;this.adapter=e;const r=e.threadId??ji,s=e.threads??gs,i=e.archivedThreads??gs,o=n.threadId??ji,a=n.threads??gs,l=n.archivedThreads??gs;!t&&o===r&&a===s&&l===i||((a!==s||l!==i||o!==r)&&(this._threadData={...uy,...Object.fromEntries(e.threads?.map(u=>[u.id,{...u,remoteId:u.remoteId,externalId:u.externalId,status:"regular"}])??[]),...Object.fromEntries(e.archivedThreads?.map(u=>[u.id,{...u,remoteId:u.remoteId,externalId:u.externalId,status:"archived"}])??[])}),a!==s&&(this._threads=this.adapter.threads?.map(u=>u.id)??gs),l!==i&&(this._archivedThreads=this.adapter.archivedThreads?.map(u=>u.id)??gs),(t||o!==r)&&(this._mainThreadId=r,this._mainThread=this.threadFactory()),this._threadData[this._mainThreadId]||(this._threadData={...this._threadData,[this._mainThreadId]:{id:this._mainThreadId,remoteId:void 0,externalId:void 0,status:"regular"}}),this._notifySubscribers())}async switchToThread(e,t){if(this._mainThreadId===e)return;const n=this.adapter.onSwitchToThread;if(!n)throw new Error("External store adapter does not support switching to thread");await n(e)}async switchToNewThread(){const e=this.adapter.onSwitchToNewThread;if(!e)throw new Error("External store adapter does not support switching to new thread");await e()}async rename(e,t){const n=this.adapter.onRename;if(!n)throw new Error("External store adapter does not support renaming");await n(e,t)}async updateCustom(e,t){const n=this.adapter.onUpdateCustom;if(!n)throw new Error("External store adapter does not support updating custom metadata");await n(e,t)}async detach(){}async archive(e){const t=this.adapter.onArchive;if(!t)throw new Error("External store adapter does not support archiving");await t(e)}async unarchive(e){const t=this.adapter.onUnarchive;if(!t)throw new Error("External store adapter does not support unarchiving");await t(e)}async delete(e){const t=this.adapter.onDelete;if(!t)throw new Error("External store adapter does not support deleting");await t(e)}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}_notifySubscribers(){for(const e of this._subscriptions)e()}};const is=Eb("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),ro=Symbol("autoStatus"),wP=Object.freeze(Object.assign({type:"running"},{[ro]:!0})),_P=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[ro]:!0})),bP=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[ro]:!0})),kP=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[ro]:!0})),SP=e=>e[ro]===!0,xu=(e,t,n,r,s)=>e&&s?Object.assign({type:"incomplete",reason:"error",error:s},{[ro]:!0}):e&&t?wP:n?kP:r?bP:_P,td=(e,t)=>{if(e.startsWith("data-"))return{type:"data",name:e.substring(5),data:t}},ga=(e,t,n)=>{const{role:r,id:s,createdAt:i,attachments:o,status:a,metadata:l}=e,u={id:s??t,createdAt:i??new Date},c=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,f=({image:h,...p})=>h.match(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,(.*)$/)?{...p,image:h}:/^(https:\/\/|blob:)/.test(h)?{...p,image:h}:(console.warn("Invalid image data format detected"),null);if(r!=="user"&&o?.length)throw new Error("attachments are only supported for user messages");if(r!=="assistant"&&a)throw new Error("status is only supported for assistant messages");if(r!=="assistant"&&l?.steps)throw new Error("metadata.steps is only supported for assistant messages");switch(r){case"assistant":return{...u,role:r,content:c.map(h=>{const p=h.type;switch(p){case"text":case"reasoning":return h.text.trim().length===0?null:h;case"file":case"source":return h;case"image":return f(h);case"data":return h;case"generative-ui":return h;case"tool-call":{const{parentId:g,messages:y,..._}=h,x={..._,toolCallId:h.toolCallId??`tool-${is()}`,...g!==void 0&&{parentId:g},...y!==void 0&&{messages:y}};return h.args?{...x,args:h.args,argsText:h.argsText??JSON.stringify(h.args)}:{...x,args:Pf(h.argsText??"")??{},argsText:h.argsText??""}}default:{const g=td(p,h.data);if(g)return g;throw new Error(`Unsupported assistant message part type: ${p}`)}}}).filter(h=>!!h),status:a??n,metadata:{unstable_state:l?.unstable_state??null,unstable_annotations:l?.unstable_annotations??[],unstable_data:l?.unstable_data??[],custom:l?.custom??{},steps:l?.steps??[],...l?.timing&&{timing:l.timing},...l?.submittedFeedback&&{submittedFeedback:l.submittedFeedback},...l?.isOptimistic&&{isOptimistic:!0}}};case"user":return{...u,role:r,content:c.map(h=>{const p=h.type;switch(p){case"text":case"image":case"audio":case"file":case"data":return h;default:{const g=td(p,h.data);if(g)return g;throw new Error(`Unsupported user message part type: ${p}`)}}}),attachments:(o??[]).map(h=>({...h,content:h.content.map(p=>td(p.type,p.data)??p)})),metadata:{custom:l?.custom??{}}};case"system":if(c.length!==1||c[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return{...u,role:r,content:c,metadata:{custom:l?.custom??{}}};default:throw new Error(`Unknown message role: ${r}`)}},Hb={fromArray:e=>{const t=e.map(n=>ga(n,is(),xu(!1,!1,!1,!1,void 0)));return{messages:t.map((n,r)=>({parentId:r>0?t[r-1].id:null,message:n}))}},fromBranchableArray:(e,t)=>{const n=xu(!1,!1,!1,!1,void 0);return{...t?.headId!==void 0?{headId:t.headId}:void 0,messages:e.map(({message:r,parentId:s})=>{if(!r.id)throw new Error("ExportedMessageRepository.fromBranchableArray: Each message must have an 'id' field set.");return{parentId:s,message:ga(r,r.id,n)}})}}},Ll=e=>e.next?Ll(e.next):"current"in e?e:null;var CP=class{constructor(e){A(this,"func");A(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},wp=class{constructor(){A(this,"messages",new Map);A(this,"head",null);A(this,"root",{children:[],next:null});A(this,"_messages",new CP(()=>{const e=new Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e}))}updateLevels(e,t){e.level=t;for(const n of e.children){const r=this.messages.get(n);r&&this.updateLevels(r,t+1)}}performOp(e,t,n){const r=t.prev??this.root,s=e??this.root;if(!(n==="relink"&&r===s)){if(n!=="link"&&(r.children=r.children.filter(i=>i!==t.current.id),r.next===t)){const i=r.children.at(-1),o=i?this.messages.get(i):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=o}if(n!=="cut"){for(let o=e;o;o=o.prev)if(o.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");s.children=[...s.children,t.current.id],(Ll(t)===this.head||s.next===null)&&(s.next=t),t.prev=e;const i=e?e.level+1:0;this.updateLevels(t,i)}}}get headId(){return this.head?.current.id??null}getMessages(e){if(e===void 0||e===this.head?.current.id)return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const n=new Array(t.level+1);for(let r=t;r;r=r.prev)n[r.level]=r.current;return n}addOrUpdateMessage(e,t){const n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(n){n.current=t,this.performOp(r,n,"relink"),this._messages.dirty();return}const s={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,s),this.performOp(r,s,"link"),this.head===r&&(this.head=s),this._messages.dirty()}getMessage(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:t.prev?.current.id??null,message:t.current,index:t.level}}deleteMessage(e,t){const n=this.messages.get(e);if(!n)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const s of n.children){const i=this.messages.get(s);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,i,"relink")}this.performOp(null,n,"cut"),this.messages.delete(e),this.head===n&&(this.head=Ll(r??this.root)),this._messages.dirty()}getBranches(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:n}=t.prev??this.root;return n}evictOffBranchOptimisticMessages(e,t){if(!e)return;const n=new Set;for(let s=t;s;s=s.prev)n.add(s.current.id);const r=[];for(let s=e;s&&!n.has(s.current.id);s=s.prev)s.current.metadata?.isOptimistic&&r.push(s.current.id);for(const s of r)this.messages.has(s)&&this.deleteMessage(s)}switchToBranch(e){const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const n=this.head,r=t.prev??this.root;r.next=t,this.head=Ll(t),this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");const n=this.head;if(t.children.length>0){const r=s=>{for(const i of s.children){const o=this.messages.get(i);o&&(r(o),this.messages.delete(i))}};r(t),t.children=[],t.next=null}this.head=t;for(let r=t;r;r=r.prev)r.prev?r.prev.next=r:this.root.next=r;this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){const e=[];for(const[,n]of this.messages)n.current.metadata?.isOptimistic||e.push({message:n.current,parentId:n.prev?.current.id??null});let t=this.head;for(;t?.current.metadata?.isOptimistic;)t=t.prev;return{headId:t?.current.id??null,messages:e}}import({headId:e,messages:t}){for(const{message:n,parentId:r}of t)this.addOrUpdateMessage(r,n);this.resetHead(e??t.at(-1)?.message.id??null)}};function cy(e,t){if(t==="*")return!0;const n=t.split(",").map(i=>i.trim().toLowerCase()),r=`.${e.name.split(".").pop().toLowerCase()}`,s=e.type.toLowerCase();for(const i of n){if(i.startsWith(".")&&i===r||i.includes("/")&&i===s)return!0;if(i.endsWith("/*")){const o=i.split("/")[0];if(s.startsWith(`${o}/`))return!0}}return!1}function EP(e,t){return e.length!==t.length?!1:e.every((n,r)=>n.id===t[r].id)}function TP(e){const t=is();return e.type==="image"?{id:t,type:"image",name:e.filename??"image",content:[e],status:{type:"complete"}}:e.type==="file"?{id:t,type:"document",name:e.filename??"document",contentType:e.mimeType,content:[e],status:{type:"complete"}}:e.type==="audio"?{id:t,type:"audio",name:`audio.${e.audio.format}`,contentType:`audio/${e.audio.format}`,content:[e],status:{type:"complete"}}:{id:t,type:"data",name:e.name,content:[e],status:{type:"complete"}}}function IP(e){const t=[];for(const n of e)n.type!=="text"&&t.push(TP(n));return t}const nd=e=>e.status.type==="complete";var Wb=class extends JR{constructor(){super(...arguments);A(this,"isEditing",!0);A(this,"_attachments",[]);A(this,"_text","");A(this,"_role","user");A(this,"_runConfig",{});A(this,"_quote");A(this,"_dictation");A(this,"_dictationSession");A(this,"_dictationUnsubscribes",[]);A(this,"_dictationBaseText","");A(this,"_currentInterimText","");A(this,"_dictationSessionIdCounter",0);A(this,"_activeDictationSessionId");A(this,"_isCleaningDictation",!1);A(this,"_eventSubscribers",new Map)}get attachmentAccept(){return this.getAttachmentAdapter()?.accept??"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}get quote(){return this._quote}setQuote(t){this._quote!==t&&(this._quote=t,this._notifySubscribers())}setText(t){if(this._text!==t){if(this._text=t,this._dictation){this._dictationBaseText=t,this._currentInterimText="";const{status:n,inputDisabled:r}=this._dictation;this._dictation=r?{status:n,inputDisabled:r}:{status:n}}this._notifySubscribers()}}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){const t=this.getAttachmentAdapter();if(t){const n=this._attachments.filter(r=>!nd(r));await Promise.all(n.map(r=>t.remove(r)))}}async reset(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0&&this._quote===void 0)return;this._role="user",this._runConfig={},this._quote=void 0;const t=this._onClearAttachments();this._emptyTextAndAttachments(),await t}async clearAttachments(){const t=this._onClearAttachments();this.setAttachments([]),await t}async send(t){if(!this.canSend)return;this._dictationSession&&(this._dictationSession.cancel(),this._cleanupDictation());const n=this.getAttachmentAdapter(),r=this.attachments.length>0?Promise.all(this.attachments.map(async a=>{if(nd(a))return a;if(!n)throw new Error("Attachments are not supported");return await n.send(a)})):[],s=this.text,i=this._quote;this._quote=void 0,this._emptyTextAndAttachments();const o={createdAt:new Date,role:this.role,content:s?[{type:"text",text:s}]:[],attachments:await r,runConfig:this.runConfig,metadata:{custom:{...i?{quote:i}:{}}}};this.handleSend(o,t),this._notifyEventSubscribers("send",{})}cancel(){this.handleCancel()}async addAttachment(t){if(!(t instanceof File)){const i=this.getAttachmentAdapter();if(i&&!cy({name:t.name,type:t.contentType??""},i.accept)){const a=`File type ${t.contentType||"unknown"} is not accepted. Accepted types: ${i.accept}`,l=new Error(a);throw this._safeEmitAttachmentAddError("not-accepted",a,void 0,l),l}const o={id:t.id??is(),type:t.type??"document",name:t.name,contentType:t.contentType,content:t.content,status:{type:"complete"}};this._attachments=[...this._attachments,o],this._notifySubscribers(),this._notifyEventSubscribers("attachmentAdd",{});return}const n=i=>{const o=this._attachments.findIndex(a=>a.id===i.id);o!==-1?this._attachments=[...this._attachments.slice(0,o),i,...this._attachments.slice(o+1)]:this._attachments=[...this._attachments,i],this._notifySubscribers()},r=this.getAttachmentAdapter();if(!r){const i="Attachments are not supported",o=new Error(i);throw this._safeEmitAttachmentAddError("no-adapter",i,void 0,o),o}if(!cy({name:t.name,type:t.type},r.accept)){const i=`File type ${t.type||"unknown"} is not accepted. Accepted types: ${r.accept}`,o=new Error(i);throw this._safeEmitAttachmentAddError("not-accepted",i,void 0,o),o}let s;try{const i=r.add({file:t});if(Symbol.asyncIterator in i)for await(const o of i)s=o,n(o);else s=await i,n(s)}catch(i){throw s&&n({...s,status:{type:"incomplete",reason:"error"}}),this._safeEmitAttachmentAddError("adapter-error",i instanceof Error?i.message:String(i),s?.id,i instanceof Error?i:void 0),i}s?.status.type==="incomplete"&&s.status.reason==="error"?this._safeEmitAttachmentAddError("adapter-error","Attachment upload did not complete successfully.",s?.id):this._notifyEventSubscribers("attachmentAdd",{})}_safeEmitAttachmentAddError(t,n,r,s){try{this._notifyEventSubscribers("attachmentAddError",{reason:t,message:n,...r!==void 0&&{attachmentId:r},...s!==void 0&&{error:s}})}catch(i){console.error("[assistant-ui] attachmentAddError subscriber threw:",i)}}async removeAttachment(t){const n=this._attachments.findIndex(s=>s.id===t);if(n===-1)throw new Error("Attachment not found");const r=this._attachments[n];if(!nd(r)){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");await s.remove(r)}this._attachments=this._attachments.filter(s=>s.id!==t),this._notifySubscribers()}get dictation(){return this._dictation}_isActiveSession(t,n){return this._activeDictationSessionId===t&&this._dictationSession===n}startDictation(){const t=this.getDictationAdapter();if(!t)throw new Error("Dictation adapter not configured");if(this._dictationSession){for(const u of this._dictationUnsubscribes)u();this._dictationUnsubscribes=[],this._dictationSession.stop().catch(()=>{}),this._dictationSession=void 0}const n=t.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText="";const r=t.listen();this._dictationSession=r;const s=++this._dictationSessionIdCounter;this._activeDictationSessionId=s,this._dictation={status:r.status,inputDisabled:n},this._notifySubscribers();const i=r.onSpeech(u=>{if(!this._isActiveSession(s,r))return;const c=u.isFinal!==!1,f=this._dictationBaseText&&!this._dictationBaseText.endsWith(" ")&&u.transcript?" ":"";if(c){if(this._dictationBaseText=this._dictationBaseText+f+u.transcript,this._currentInterimText="",this._text=this._dictationBaseText,this._dictation){const{transcript:h,...p}=this._dictation;this._dictation=p}this._notifySubscribers()}else this._currentInterimText=f+u.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&(this._dictation={...this._dictation,transcript:u.transcript}),this._notifySubscribers()});this._dictationUnsubscribes.push(i);const o=r.onSpeechStart(()=>{this._isActiveSession(s,r)&&(this._dictation={status:{type:"running"},inputDisabled:n,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())});this._dictationUnsubscribes.push(o);const a=r.onSpeechEnd(()=>{this._cleanupDictation({sessionId:s})});this._dictationUnsubscribes.push(a);const l=setInterval(()=>{this._isActiveSession(s,r)&&r.status.type==="ended"&&this._cleanupDictation({sessionId:s})},100);this._dictationUnsubscribes.push(()=>clearInterval(l))}stopDictation(){if(!this._dictationSession)return;const t=this._dictationSession,n=this._activeDictationSessionId;t.stop().finally(()=>{this._cleanupDictation({sessionId:n})})}_cleanupDictation(t){if(!(t?.sessionId!==void 0&&t.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)){this._isCleaningDictation=!0;try{for(const n of this._dictationUnsubscribes)n();this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText="",this._currentInterimText="",this._notifySubscribers()}finally{this._isCleaningDictation=!1}}}_notifyEventSubscribers(t,n){const r=this._eventSubscribers.get(t);if(r)for(const s of r)s(n)}unstable_on(t,n){const r=n;let s=this._eventSubscribers.get(t);return s||(s=new Set,this._eventSubscribers.set(t,s)),s.add(r),()=>{this._eventSubscribers.get(t)?.delete(r)}}},Kb=class extends Wb{constructor(t){super();A(this,"runtime");A(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get canSend(){return!this.isEmpty&&!this.runtime.isSendDisabled}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}connect(){let t=this.runtime.isSendDisabled;return this.runtime.subscribe(()=>{let n=!1;this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,n=!0),t!==this.runtime.isSendDisabled&&(t=this.runtime.isSendDisabled,n=!0),n&&this._notifySubscribers()})}async handleSend(t,n){this.runtime.append({...t,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:n?.startRun})}async handleCancel(){this.runtime.cancelRun()}},RP=class extends Wb{constructor(t,n,{parentId:r,message:s}){super();A(this,"runtime");A(this,"endEditCallback");A(this,"_previousText");A(this,"_previousAttachments");A(this,"_nonTextPassthrough");A(this,"_parentId");A(this,"_sourceId");this.runtime=t,this.endEditCallback=n,this._parentId=r,this._sourceId=s.id,this._previousText=ma(s),this.setText(this._previousText),this.setRole(s.role),s.role==="user"?(this._previousAttachments=[...s.attachments??[],...IP(s.content)],this._nonTextPassthrough=[]):(this._previousAttachments=s.attachments??[],this._nonTextPassthrough=s.content.filter(i=>i.type!=="text")),this.setAttachments(this._previousAttachments),this.setRunConfig({...t.composer.runConfig})}get canCancel(){return!0}get canSend(){return!this.isEmpty}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}get parentId(){return this._parentId}get sourceId(){return this._sourceId}async handleSend(t,n){const r=ma(t),s=!EP(t.attachments??[],this._previousAttachments);if(r!==this._previousText||s||n?.startRun){const i=this._nonTextPassthrough.length>0?[...t.content,...this._nonTextPassthrough]:t.content;this.runtime.append({...t,content:i,parentId:this._parentId,sourceId:this._sourceId,startRun:n?.startRun})}this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},PP=class{constructor(e){A(this,"_contextProvider");A(this,"_subscriptions",new Set);A(this,"_isInitialized",!1);A(this,"repository",new wp);A(this,"_voiceMessages",[]);A(this,"_voiceGeneration",0);A(this,"_cachedMergedMessages",null);A(this,"_cachedVoiceGeneration",-1);A(this,"_cachedMergedBase",null);A(this,"composer",new Kb(this));A(this,"_editComposers",new Map);A(this,"_stopSpeaking");A(this,"speech");A(this,"_voiceSession");A(this,"_voiceUnsubs",[]);A(this,"voice");A(this,"_voiceVolume",0);A(this,"_voiceVolumeSubscribers",new Set);A(this,"getVoiceVolume",()=>this._voiceVolume);A(this,"subscribeVoiceVolume",e=>(this._voiceVolumeSubscribers.add(e),()=>this._voiceVolumeSubscribers.delete(e)));A(this,"_currentAssistantMsg",null);A(this,"_eventSubscribers",new Map);this._contextProvider=e}_markVoiceMessagesDirty(){this._voiceGeneration++,this._cachedMergedMessages=null}_getBaseMessages(){return this.repository.getMessages()}get messages(){if(this._voiceMessages.length===0)return this._getBaseMessages();const e=this._getBaseMessages();return(this._cachedVoiceGeneration!==this._voiceGeneration||this._cachedMergedBase!==e)&&(this._cachedMergedMessages=[...e,...this._voiceMessages],this._cachedVoiceGeneration=this._voiceGeneration,this._cachedMergedBase=e),this._cachedMergedMessages}get state(){let e;for(const t of this.messages)t.role==="assistant"&&(e=t);return e?.metadata.unstable_state??null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new RP(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{const t=this.repository.getMessages(),n=this._voiceMessages.findIndex(r=>r.id===e);return n!==-1?{parentId:n>0?this._voiceMessages[n-1].id:t.at(-1)?.id??null,message:this._voiceMessages[n],index:t.length+n}:void 0}}getBranches(e){return this._voiceMessages.some(t=>t.id===e)?[]:this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e,t){const n=this._eventSubscribers.get(e);if(n)for(const r of n)r(t)}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){const n=this.adapters?.feedback;if(!n)throw new Error("Feedback adapter not configured");const{message:r,parentId:s}=this.repository.getMessage(e);if(n.submit({message:r,type:t}),r.role==="assistant"){const i={...r,metadata:{...r.metadata,submittedFeedback:{type:t}}};this.repository.addOrUpdateMessage(s,i)}this._notifySubscribers()}speak(e){const t=this.adapters?.speech;if(!t)throw new Error("Speech adapter not configured");const{message:n}=this.repository.getMessage(e);this._stopSpeaking?.();const r=t.speak(ma(n)),s=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:r.status},this._notifySubscribers()});this.speech={messageId:e,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),s(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}connectVoice(){const e=this.adapters?.voice;if(!e)throw new Error("Voice adapter not configured");this.disconnectVoice();const t=e.connect({});this._voiceSession=t;const n=[];let r="listening";this.voice={status:t.status,isMuted:t.isMuted,mode:r},this._voiceVolume=0,this._notifySubscribers(),n.push(t.onStatusChange(s=>{s.type==="ended"?(this._finishVoiceAssistantMessage(),this._voiceSession=void 0,this.voice=void 0):this.voice={status:s,isMuted:t.isMuted,mode:r},this._notifySubscribers()})),n.push(t.onModeChange(s=>{r=s,this.voice&&(this.voice={...this.voice,mode:s},this._notifySubscribers())})),n.push(t.onVolumeChange(s=>{this._voiceVolume=s;for(const i of this._voiceVolumeSubscribers)i()})),n.push(t.onTranscript(s=>{this._handleVoiceTranscript(s)})),this._voiceUnsubs=n}_handleVoiceTranscript(e){if(this.ensureInitialized(),e.role==="user")this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null,e.isFinal&&(this._voiceMessages.push({id:is(),role:"user",content:[{type:"text",text:e.text}],metadata:{custom:{}},createdAt:new Date,status:{type:"complete",reason:"unknown"},attachments:[]}),this._markVoiceMessagesDirty(),this._notifySubscribers());else{if(!this._currentAssistantMsg)this._currentAssistantMsg={id:is(),role:"assistant",content:[{type:"text",text:e.text}],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},status:{type:"running"},createdAt:new Date},this._voiceMessages.push(this._currentAssistantMsg);else{const t=this._voiceMessages.indexOf(this._currentAssistantMsg);if(t===-1)return;const n={...this._currentAssistantMsg,content:[{type:"text",text:e.text}],...e.isFinal?{status:{type:"complete",reason:"stop"}}:{}};this._voiceMessages[t]=n,this._currentAssistantMsg=n}e.isFinal&&(this._currentAssistantMsg=null),this._markVoiceMessagesDirty(),this._notifySubscribers()}}_finishVoiceAssistantMessage(){const e=this._voiceMessages.at(-1);if(e?.role==="assistant"&&e.status.type==="running"){const t=this._voiceMessages.length-1;this._voiceMessages[t]={...e,status:{type:"complete",reason:"stop"}},this._markVoiceMessagesDirty(),this._notifySubscribers()}}disconnectVoice(){this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null;for(const e of this._voiceUnsubs)e();this._voiceUnsubs=[],this._voiceSession?.disconnect(),this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;for(const e of this._voiceVolumeSubscribers)e();this._voiceMessages=[],this._markVoiceMessagesDirty(),this._notifySubscribers()}muteVoice(){if(!this._voiceSession)throw new Error("No active voice session");this._voiceSession.mute(),this.voice={...this.voice,isMuted:!0},this._notifySubscribers()}unmuteVoice(){if(!this._voiceSession)throw new Error("No active voice session");this._voiceSession.unmute(),this.voice={...this.voice,isMuted:!1},this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize",{}))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(Hb.fromArray(e??[]))}unstable_on(e,t){const n=t;if(e==="modelContextUpdate")return this._contextProvider.subscribe?.(()=>n({}))??(()=>{});let r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),e==="initialize"&&this._isInitialized&&queueMicrotask(()=>{r.has(n)&&n({})}),()=>{this._eventSubscribers.get(e)?.delete(n)}}},dy=class{constructor(){A(this,"cache",new WeakMap)}convertMessages(e,t){return e.map((n,r)=>{const s=t(this.cache.get(n),n,r);return this.cache.set(n,s),s})}};function Af(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function wu(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(n=>wu(n,t+1)):Af(e)?Object.entries(e).every(([n,r])=>typeof n=="string"&&wu(r,t+1)):!1}const jP=100,Nf=(e,t,n)=>{if(e===t)return!0;if(n>jP||e==null||t==null)return!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((i,o)=>Nf(i,t[o],n+1));if(Array.isArray(t)||!Af(e)||!Af(t))return!1;const r=Object.keys(e),s=Object.keys(t);return r.length!==s.length?!1:r.every(i=>Object.hasOwn(t,i)&&Nf(e[i],t[i],n+1))},AP=(e,t)=>!wu(e)||!wu(t)?!1:Nf(e,t,0),hl=e=>{try{return JSON.parse(e),!0}catch{return!1}},fy=e=>{try{return JSON.parse(e)}catch{return}},hy=(e,t)=>{const n=fy(e),r=fy(t);return n===void 0||r===void 0?!1:AP(n,r)};var NP=class{constructor(e,t){A(this,"_getTools");A(this,"_callbacks");A(this,"_entries",new Map);A(this,"_skipExecuteStreamIds",new Set);A(this,"_humanInput",new Map);A(this,"_executing",new Set);A(this,"_settledResolvers",[]);A(this,"_statuses",new Map);A(this,"_ac",new AbortController);A(this,"_pendingRestore",!0);A(this,"_lastSnapshot",null);A(this,"_isRunning",!1);A(this,"_controller");A(this,"_pipelineDead",!1);A(this,"_pipelineRestartUsed",!1);this._getTools=e,this._callbacks=t,this._initPipeline()}_initPipeline(){const[e,t]=kR();this._controller=t;const n=UR(()=>this._getWrappedTools(),()=>this._ac.signal,(r,s)=>this._onHumanInput(r,s),{onExecutionStart:r=>this._onExecutionStart(r),onExecutionEnd:r=>this._onExecutionEnd(r)});e.pipeThrough(n).pipeThrough(new Cb).pipeTo(new WritableStream({write:r=>{try{if(r.type!=="result")return;this._handleResultChunk(r)}catch(s){console.error("[ToolInvocationTracker] result chunk handling failed",s)}}})).catch(r=>{console.error("[ToolInvocationTracker] stream pipeline failed; will attempt single restart on next setState",r),this._pipelineDead=!0})}setState(e){try{if(this._pipelineDead){if(this._pipelineRestartUsed)return;this._pipelineRestartUsed=!0,this._pipelineDead=!1,this._demoteEntriesToRestored(),this._executing.clear(),this._ac=new AbortController,this._initPipeline()}if(this._lastSnapshot&&this._lastSnapshot.messages===e.messages&&this._lastSnapshot.isRunning===e.isRunning&&this._lastSnapshot.isLoading===e.isLoading)return;e.isLoading===!0&&(this._pendingRestore=!0);const t=this._isRunning;this._isRunning=e.isRunning;try{this._processMessages(e.messages)}catch(n){throw this._isRunning=t,n}this._lastSnapshot=e,this._pendingRestore=!1}catch(t){console.error("[ToolInvocationTracker] setState failed; snapshot dropped",t)}}reset(){try{this._pendingRestore=!0,this._entries.clear(),this._lastSnapshot=null,this.abort().finally(()=>{this._executing.clear()})}catch(e){console.error("[ToolInvocationTracker] reset failed",e)}}abort(){try{return this._humanInput.forEach(({reject:e})=>{try{e(new Error("Tool execution aborted"))}catch{}}),this._humanInput.clear(),this._ac.abort(),this._ac=new AbortController,this._executing.size===0?Promise.resolve():new Promise(e=>{this._settledResolvers.push(e)})}catch(e){return console.error("[ToolInvocationTracker] abort failed",e),Promise.resolve()}}resume(e,t){try{const n=this._humanInput.get(e);return n?(this._humanInput.delete(e),this._setStatus(e,{type:"executing"}),n.resolve(t),!0):!1}catch(n){return console.error("[ToolInvocationTracker] resume failed",n),!1}}getStatuses(){return this._statuses}_getWrappedTools(){const e=this._getTools();if(e)return Object.fromEntries(Object.entries(e).map(([t,n])=>{const r=n.execute;return r===void 0?[t,n]:[t,{...n,execute:(...[s,i])=>this._skipExecuteStreamIds.has(i.toolCallId)?new Promise(()=>{}):r(s,i)}]}))}_onHumanInput(e,t){return new Promise((n,r)=>{const s=this._humanInput.get(e);if(s)try{s.reject(new Error("Human input request was superseded by a new request"))}catch{}this._humanInput.set(e,{resolve:n,reject:r}),this._setStatus(e,{type:"interrupt",payload:{type:"human",payload:t}})})}_onExecutionStart(e){this._skipExecuteStreamIds.has(e)||(this._executing.add(e),this._setStatus(e,{type:"executing"}))}_onExecutionEnd(e){this._executing.delete(e)&&(this._deleteStatus(e),this._executing.size===0&&this._settledResolvers.splice(0).forEach(t=>{try{t()}catch{}}))}_handleResultChunk(e){const t=e.meta.toolCallId,n=this._entries.get(t);!n&&this._skipExecuteStreamIds.has(t)||n?.hasResult||this._invokeOnResult({type:"add-tool-result",toolCallId:t,toolName:e.meta.toolName,result:e.result,isError:e.isError,...e.artifact!==void 0&&{artifact:e.artifact},...e.modelContent!==void 0&&{modelContent:e.modelContent}})}_invokeOnResult(e){try{this._callbacks.onResult(e)}catch(t){console.error("[ToolInvocationTracker] onResult callback threw; result dropped",t)}}_invokeOnStatusesChange(){try{this._callbacks.onStatusesChange(this._statuses)}catch(e){console.error("[ToolInvocationTracker] onStatusesChange callback threw; status change not propagated",e)}}_setStatus(e,t){const n=new Map(this._statuses);n.set(e,t),this._statuses=n,this._invokeOnStatusesChange()}_deleteStatus(e){if(!this._statuses.has(e))return;const t=new Map(this._statuses);t.delete(e),this._statuses=t,this._invokeOnStatusesChange()}_hasExecutableTool(e){const t=this._getTools()?.[e];return t?.execute!==void 0||t?.streamCall!==void 0}_shouldCloseArgsStream({toolName:e,argsText:t,hasResult:n}){return n?!0:(this._hasExecutableTool(e)||!this._isRunning)&&hl(t)}_startActiveEntry(e,t,n){const r=this._controller.addToolCallPart({toolName:t,toolCallId:e});n&&this._skipExecuteStreamIds.add(e);const s={toolName:t,controller:r,argsText:"",hasResult:!1,argsComplete:!1};return this._entries.set(e,s),s}_demoteEntriesToRestored(){for(const[e,t]of this._entries)t.controller&&this._entries.set(e,{toolName:t.toolName,argsText:t.argsText,hasResult:t.hasResult})}_processArgsText(e,t){if(!e.controller)return;const n=t.result!==void 0;if(t.argsText!==e.argsText){let r=!0;if(e.argsComplete)hy(e.argsText,t.argsText)&&(e.argsText=t.argsText),r=!1;else if(!t.argsText.startsWith(e.argsText))if(hl(e.argsText)&&hl(t.argsText)&&hy(e.argsText,t.argsText)){const s=this._shouldCloseArgsStream({toolName:t.toolName,argsText:t.argsText,hasResult:n});s&&e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=s,r=!1}else r=!1;if(r&&e.controller){const s=t.argsText.slice(e.argsText.length);e.controller.argsText.append(s);const i=this._shouldCloseArgsStream({toolName:t.toolName,argsText:t.argsText,hasResult:n});i&&e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=i}}!e.argsComplete&&e.controller&&this._shouldCloseArgsStream({toolName:t.toolName,argsText:t.argsText,hasResult:n})&&(e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=!0)}_processMessages(e){const t=this._pendingRestore;for(const n of e)if(!(!n||!Array.isArray(n.content)))for(const r of n.content){if(!r||r.type!=="tool-call")continue;const s=this._entries.get(r.toolCallId);if(t){s?.controller||this._entries.set(r.toolCallId,{toolName:r.toolName,argsText:r.argsText,hasResult:r.result!==void 0}),r.messages&&this._processMessages(r.messages);continue}let i=s;if(i&&!i.controller){if(!(r.argsText!==i.argsText||r.result!==void 0!==i.hasResult)){r.messages&&this._processMessages(r.messages);continue}this._entries.delete(r.toolCallId),i=void 0}if(i||(i=this._startActiveEntry(r.toolCallId,r.toolName,r.result!==void 0)),this._processArgsText(i,r),r.result!==void 0&&!i.hasResult){const{controller:o}=i;if(!o)continue;i.hasResult=!0,i.argsComplete=!0,o.setResponse(new wr({result:r.result,artifact:r.artifact,isError:r.isError,...r.modelContent!==void 0?{modelContent:r.modelContent}:{}})),o.close()}r.messages&&this._processMessages(r.messages)}}};const MP=Object.freeze([]),py=(e,t)=>{const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(e[r]!==t[r])return!1;return!0},DP=(e,t)=>e&&t[t.length-1]?.role!=="assistant";var OP=class extends PP{constructor(t,n){super(t);A(this,"_capabilities",{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1});A(this,"_messages");A(this,"isDisabled");A(this,"isSendDisabled");A(this,"suggestions",[]);A(this,"extras");A(this,"_converter",new dy);A(this,"_store");A(this,"_toolInvocations",null);A(this,"_toolCallToMessageId",new Map);A(this,"_messagesForToolCallIndex",null);A(this,"updateMessages",t=>{this._store.convertMessage!==void 0?this._store.setMessages?.(t.flatMap(QR)):this._store.setMessages?.(t)});this.__internal_setAdapter(n)}get capabilities(){return this._capabilities}get isLoading(){return this._store.isLoading??!1}get isRunning(){return this._store.isRunning}_getBaseMessages(){return this._messages}get state(){return this._store.state??super.state}get adapters(){return this._store.adapters}beginEdit(t){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(t)}__internal_setAdapter(t){if(this._store===t)return;const n=t.isRunning??!1;this.isDisabled=t.isDisabled??!1,this.isSendDisabled=t.isSendDisabled??!1;const r=this._store;this._store=t,this.extras!==t.extras&&(this.extras=t.extras);const s=t.suggestions??MP;py(this.suggestions,s)||(this.suggestions=s);const i={switchToBranch:this._store.setMessages!==void 0,switchBranchDuringRun:!1,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:this._store.adapters?.speech!==void 0,dictation:this._store.adapters?.dictation!==void 0,voice:this._store.adapters?.voice!==void 0,unstable_copy:this._store.unstable_capabilities?.copy!==!1,attachments:!!this._store.adapters?.attachments,feedback:!!this._store.adapters?.feedback,queue:!1};py(this._capabilities,i)||(this._capabilities=i);let o;if(t.messageRepository){if(r&&r.isRunning===t.isRunning&&r.messageRepository===t.messageRepository){this._notifySubscribers();return}this.repository.clear(),this.repository.import(t.messageRepository),o=this.repository.getMessages()}else if(t.messages){if(r){if(r.convertMessage!==t.convertMessage)this._converter=new dy;else if(r.isRunning===t.isRunning&&r.messages===t.messages){this._notifySubscribers();return}}o=t.convertMessage?this._converter.convertMessages(t.messages,(l,u,c)=>{if(!t.convertMessage)return u;const f=xu(c===(t.messages?.length??0)-1,n,!1,!1,void 0);if(l&&(l.role!=="assistant"||!SP(l.status)||l.status===f))return l;const h=ga(t.convertMessage(u,c),c.toString(),f);return YR(h,u),h}):t.messages;for(let l=0;l<o.length;l++){const u=o[l],c=o[l-1];this.repository.addOrUpdateMessage(c?.id??null,u)}}else throw new Error("ExternalStoreAdapter must provide either 'messages' or 'messageRepository'");o.length>0&&this.ensureInitialized(),(r?.isRunning??!1)!==(t.isRunning??!1)&&(t.isRunning?this._notifyEventSubscribers("runStart",{}):this._notifyEventSubscribers("runEnd",{}));let a=null;DP(n,o)&&(a=is(),this.repository.addOrUpdateMessage(o.at(-1)?.id??null,ga({role:"assistant",content:[],metadata:{isOptimistic:!0}},a,{type:"running"}))),this.repository.resetHead(a??o.at(-1)?.id??null),this._messages=this.repository.getMessages(),this._driveToolInvocations(),this._notifySubscribers()}_driveToolInvocations(){if(!this._store.unstable_enableToolInvocations){this._toolInvocations&&(this._toolInvocations.reset(),this._toolInvocations=null,this._store.setToolStatuses?.({}));return}this._toolInvocations||(this._toolInvocations=new NP(()=>this.getModelContext().tools,{onResult:t=>{try{const n=this._findMessageIdForToolCall(t.toolCallId);if(n===void 0)return;this._store.onAddToolResult?.({messageId:n,toolCallId:t.toolCallId,toolName:t.toolName,result:t.result,isError:t.isError,...t.artifact!==void 0&&{artifact:t.artifact},...t.modelContent!==void 0&&{modelContent:t.modelContent}})}catch(n){console.error("[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed",n)}},onStatusesChange:t=>{this._store.setToolStatuses?.(Object.fromEntries(t))}})),this._toolInvocations.setState({messages:this._messages,isRunning:this._store.isRunning??!1,...this._store.isLoading!==void 0&&{isLoading:this._store.isLoading}})}_findMessageIdForToolCall(t){if(this._messagesForToolCallIndex!==this._messages){this._toolCallToMessageId.clear();const n=r=>{for(const s of r)if(Array.isArray(s.content))for(const i of s.content)!i||i.type!=="tool-call"||(this._toolCallToMessageId.set(i.toolCallId,s.id),i.messages&&n(i.messages))};n(this._messages),this._messagesForToolCallIndex=this._messages}return this._toolCallToMessageId.get(t)}switchToBranch(t){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this._store.isRunning||(this.repository.switchToBranch(t),this.updateMessages(this.repository.getMessages()))}async append(t){if((t.startRun??t.role==="user")&&await this._toolInvocations?.abort(),t.parentId!==(this.messages.at(-1)?.id??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(t)}else await this._store.onNew(t)}async startRun(t){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._toolInvocations?.abort(),await this._store.onReload(t.parentId,t)}async resumeRun(t){if(!this._store.onResume)throw new Error("Runtime does not support resuming runs.");await this._store.onResume(t)}exportExternalState(){if(!this._store.onExportExternalState)throw new Error("Runtime does not support exporting external states.");return this._store.onExportExternalState()}importExternalState(t){if(!this._store.onLoadExternalState)throw new Error("Runtime does not support importing external states.");this._toolInvocations&&(this._toolInvocations.reset(),this._store.setToolStatuses?.({})),this._store.onLoadExternalState(t)}cancelRun(){if(!this._store.onCancel)throw new Error("Runtime does not support cancelling runs.");this._toolInvocations?.abort(),this._store.onCancel();const t=this.repository.getMessages().at(-1);t&&t.metadata.isOptimistic&&t.content.length===0&&this.repository.deleteMessage(t.id);let n=this.repository.getMessages();const r=n[n.length-1];r?.role==="user"&&r.id===n.at(-1)?.id?(this.repository.deleteMessage(r.id),this.composer.text.trim()||this.composer.setText(ma(r)),n=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(n)},0)}addToolResult(t){if(!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult?.(t)}resumeToolCall(t){if(!(this._toolInvocations?.resume(t.toolCallId,t.payload)??!1)){if(this._store.onResumeToolCall){this._store.onResumeToolCall(t);return}throw new Error(`Tool call ${t.toolCallId} is not waiting for resume.`)}}respondToToolApproval(t){if(!this._store.onRespondToToolApproval)throw new Error("Runtime does not support tool approvals.");this._store.onRespondToToolApproval(t)}reset(t){const n=new wp;n.import(Hb.fromArray(t??[])),this.updateMessages(n.getMessages())}import(t){super.import(t),this._store.onImport&&this._store.onImport(this.repository.getMessages())}};const my=e=>e.adapters?.threadList??{};var LP=class extends Vb{constructor(t){super();A(this,"threads");this.threads=new xP(my(t),()=>new OP(this._contextProvider,t))}setAdapter(t){this.threads.__internal_setAdapter(my(t)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(t)}};const Ma=e=>{const[t]=m.useState(()=>new LP(e));m.useEffect(()=>{t.setAdapter(e)});const{modelContext:n}=hP()??{};return m.useEffect(()=>{if(n)return t.registerModelContextProvider(n)},[n,t]),m.useMemo(()=>new Ub(t),[t])},qb=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,zP=()=>null,FP=(e,t,n)=>{switch(t){case"user":return n?e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message:e.UserMessage??e.Message;case"assistant":return n?e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message:e.AssistantMessage??e.Message;case"system":return n?e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message:e.SystemMessage??e.Message??zP;default:throw new Error(`Unknown message role: ${t}`)}},Gb=({components:e})=>d.jsx(FP(e,G(t=>t.message.role),G(t=>t.message.composer.isEditing)),{}),Yb=m.memo(({index:e,components:t})=>d.jsx(Nb,{index:e,children:d.jsx(Gb,{components:t})}),(e,t)=>e.index===t.index&&qb(e.components,t.components));Yb.displayName="ThreadPrimitive.MessageByIndex";const gy=({children:e})=>{const t=G(n=>n.thread.messages.length);return m.useMemo(()=>t===0?null:Array.from({length:t},(n,r)=>d.jsx(Nb,{index:r,children:d.jsx(to,{getItemState:s=>s.thread().message({index:r}).getState(),children:s=>e({get message(){return s()}})})},r)),[t,e])},Qb=({components:e,children:t})=>e?d.jsx(gy,{children:()=>d.jsx(Gb,{components:e})}):d.jsx(gy,{children:t});Qb.displayName="ThreadPrimitive.Messages";const BP=m.memo(Qb,(e,t)=>e.children||t.children?e.children===t.children:qb(e.components,t.components)),Xb=e=>{const t=e.message.metadata;if(!(!t||typeof t!="object"))return t.custom?.quote};var $P=class extends Error{constructor(t,n=`Component "${t}" is not in the generative-ui allowlist.`){super(n);A(this,"componentName");this.name="GenerativeUIRenderError",this.componentName=t}};const UP=e=>typeof e=="object"&&e!==null,Jb=(e,t,n,r)=>{if(e==null)return null;if(typeof e=="string")return e;if(!UP(e)||!("component"in e))return null;const{component:s,props:i,children:o,key:a}=e,l=t[s];if(!l){if(n)return d.jsx(n,{component:s,props:i},a??r);throw new $P(s)}const u=o?.length?o.map((c,f)=>Jb(c,t,n,`${r}/${f}`)):void 0;return m.createElement(l,{...i??{},key:a??r},...u??[])},VP=e=>{if(!e||e.root===void 0||e.root===null)return[];const t=e.root;return Array.isArray(t)?t:[t]},_p=({spec:e,components:t,Fallback:n})=>d.jsx(d.Fragment,{children:m.useMemo(()=>VP(e),[e]).map((r,s)=>Jb(r,t,n,`${s}`))});_p.displayName="GenerativeUIRender";const Zb=({components:e,spec:t,Fallback:n})=>{const r=G(i=>{const o=i.part;return o?.type==="generative-ui"?o.spec:void 0}),s=t??r;return s?d.jsx(_p,{spec:s,components:e,Fallback:n}):null};Zb.displayName="MessagePrimitive.GenerativeUI";const HP="ui://",WP=e=>!!e?.startsWith(HP),yy=e=>Symbol.iterator in e,vy=e=>"entries"in e,xy=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[s,i]of n)if(!r.has(s)||!Object.is(i,r.get(s)))return!1;return!0},KP=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=n.next(),i=r.next();for(;!s.done&&!i.done;){if(!Object.is(s.value,i.value))return!1;s=n.next(),i=r.next()}return!!s.done&&!!i.done};function qP(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:yy(e)&&yy(t)?vy(e)&&vy(t)?xy(e,t):KP(e,t):xy({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function e0(e){const t=Bt.useRef(void 0);return n=>{const r=e(n);return qP(t.current,r)?t.current:t.current=r}}const rd=e=>{let t=-1;return{startGroup:n=>{t===-1&&(t=n)},endGroup:(n,r)=>{t!==-1&&(r.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,r)=>{t!==-1&&r.push({type:e,startIndex:t,endIndex:n})}}},GP=(e,t)=>{const n=[];if(t){const r=rd("chainOfThoughtGroup");for(let s=0;s<e.length;s++){const i=e[s];i==="tool-call"||i==="reasoning"?r.startGroup(s):(r.endGroup(s-1,n),n.push({type:"single",index:s}))}r.finalize(e.length-1,n)}else{const r=rd("toolGroup"),s=rd("reasoningGroup");for(let i=0;i<e.length;i++){const o=e[i];o==="tool-call"?(s.endGroup(i-1,n),r.startGroup(i)):o==="reasoning"?(r.endGroup(i-1,n),s.startGroup(i)):(r.endGroup(i-1,n),s.endGroup(i-1,n),n.push({type:"single",index:i}))}r.finalize(e.length-1,n),s.finalize(e.length-1,n)}return n},YP=e=>{const t=G(e0(n=>n.message.parts.map(r=>r.type)));return m.useMemo(()=>t.length===0?[]:GP(t,e),[t,e])},QP=({Fallback:e,...t})=>{const n=G(r=>r.tools.toolUIs[t.toolName]?.[0]?.render??e);return n?d.jsx(n,{...t}):null},bp=(e,t,n)=>{const r=e.renderers[t]?.[0];return r||(e.fallbacks[0]??n)},XP=({Fallback:e,...t})=>{const n=G(r=>bp(r.dataRenderers,t.name,e));return n?d.jsx(n,{...t}):null},St={Text:()=>null,Reasoning:()=>null,Source:()=>null,Image:()=>null,File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},JP=({components:{Text:e=St.Text,Reasoning:t=St.Reasoning,Image:n=St.Image,Source:r=St.Source,File:s=St.File,Unstable_Audio:i=St.Unstable_Audio,tools:o={},data:a,generativeUI:l}={}})=>{const u=ue(),c=G(h=>h.part),f=c.type;if(f==="tool-call"){const h=u.part().addToolResult,p=u.part().resumeToolCall,g=u.part().respondToToolApproval;if("Override"in o)return d.jsx(o.Override,{...c,addResult:h,resume:p,respondToApproval:g});const y=o.by_name?.[c.toolName]??o.Fallback;return d.jsx(QP,{...c,Fallback:y,addResult:h,resume:p,respondToApproval:g})}if(c.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(f){case"text":return d.jsx(e,{...c});case"reasoning":return d.jsx(t,{...c});case"source":return d.jsx(r,{...c});case"image":return d.jsx(n,{...c});case"file":return d.jsx(s,{...c});case"audio":return d.jsx(i,{...c});case"data":{const h=a?.by_name?.[c.name]??a?.Fallback;return d.jsx(XP,{...c,Fallback:h})}case"generative-ui":return l?.components?d.jsx(_p,{spec:c.spec,components:l.components,Fallback:l.Fallback}):null;default:return console.warn(`Unknown message part type: ${f}`),null}},Uo=m.memo(({index:e,components:t})=>d.jsx(yp,{index:e,children:d.jsx(JP,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.generativeUI===t.components?.generativeUI&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);Uo.displayName="MessagePrimitive.PartByIndex";const ZP=({status:e,component:t})=>d.jsx(vp,{text:"",isRunning:e.type==="running",children:d.jsx(t,{type:"text",text:"",status:e})}),ej=Object.freeze({type:"complete"}),tj=Object.freeze({type:"running"}),nj=({components:e})=>{const t=G(n=>n.message.status??ej);return e?.Empty?d.jsx(e.Empty,{status:t}):t.type!=="running"?null:d.jsx(ZP,{status:t,component:e?.Text??St.Text})},t0=m.memo(nj,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),rj=({components:e,enabled:t})=>G(n=>{if(!t||n.message.parts.length===0)return!1;const r=n.message.parts[n.message.parts.length-1];return r?.type!=="text"&&r?.type!=="reasoning"})?d.jsx(t0,{components:e}):null,sj=m.memo(rj,(e,t)=>e.enabled===t.enabled&&e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),ij=({Quote:e})=>{const t=G(Xb);return t?d.jsx(e,{text:t.text,messageId:t.messageId}):null},oj=m.memo(ij);function n0(e,t){const n=e.toolUIs[t.toolName]?.[0]?.render??null;return n||(WP(t.mcp?.app?.resourceUri)&&e.mcpApp?e.mcpApp.render:null)}const r0=()=>{const e=ue(),t=G(r=>r.part),n=G(r=>r.part.type==="tool-call"?n0(r.tools,r.part):null);return!n||t.type!=="tool-call"?null:d.jsx(n,{...t,addResult:e.part().addToolResult,resume:e.part().resumeToolCall,respondToApproval:e.part().respondToToolApproval})},s0=()=>{const e=G(n=>n.part),t=G(n=>n.part.type==="data"?bp(n.dataRenderers,n.part.name,void 0)??null:null);return!t||e.type!=="data"?null:d.jsx(t,{...e})},aj=()=>{const e=G(t=>t.part.type);return e==="tool-call"?d.jsx(r0,{}):e==="data"?d.jsx(s0,{}):null},lj=Object.freeze({type:"text",text:"",status:tj}),i0=({index:e,children:t})=>{const n=ue(),r=G(s=>s.dataRenderers);return d.jsx(yp,{index:e,children:d.jsx(to,{getItemState:s=>s.message().part({index:e}).getState(),children:s=>t({get part(){const i=s();if(i.type==="tool-call"){const o=n0(n.tools().getState(),i)!==null,a=n.message().part({index:e});return{...i,toolUI:o?d.jsx(r0,{}):null,addResult:a.addToolResult,resume:a.resumeToolCall,respondToApproval:a.respondToToolApproval}}if(i.type==="data"){const o=bp(r,i.name,void 0)!==void 0;return{...i,dataRendererUI:o?d.jsx(s0,{}):null}}return i}})})})},uj=({children:e})=>{const t=G(s=>s.message.parts.length),n=G(s=>(s.message.status?.type??"complete")==="running"),r=t===0&&n;return t===0?r?d.jsx(vp,{text:"",isRunning:!0,children:e({part:lj})}):null:d.jsx(d.Fragment,{children:Array.from({length:t},(s,i)=>d.jsx(i0,{index:i,children:o=>e(o)??d.jsx(aj,{})},i))})},Mf=({components:e,unstable_showEmptyOnNonTextEnd:t=!0,children:n})=>n?d.jsx(uj,{children:n}):d.jsx(cj,{components:e,unstable_showEmptyOnNonTextEnd:t});Mf.displayName="MessagePrimitive.Parts";const cj=({components:e,unstable_showEmptyOnNonTextEnd:t})=>{const n=G(i=>i.message.parts.length),r=YP(!!e?.ChainOfThought),s=m.useMemo(()=>n===0?d.jsx(t0,{components:e}):r.map(i=>{if(i.type==="single")return d.jsx(Uo,{index:i.index,components:e},i.index);if(i.type==="chainOfThoughtGroup"){const o=e?.ChainOfThought;return o?d.jsx(KR,{startIndex:i.startIndex,endIndex:i.endIndex,children:d.jsx(o,{})},`chainOfThought-${i.startIndex}`):null}else return i.type==="toolGroup"?d.jsx(e?.ToolGroup??St.ToolGroup,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(o,a)=>{const l=i.startIndex+a;return d.jsx(Uo,{index:l,components:e},`part-${l}`)})},`tool-${i.startIndex}`):d.jsx(e?.ReasoningGroup??St.ReasoningGroup,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(o,a)=>{const l=i.startIndex+a;return d.jsx(Uo,{index:l,components:e},`part-${l}`)})},`reasoning-${i.startIndex}`)}),[r,e,n]);return d.jsxs(d.Fragment,{children:[e?.Quote&&d.jsx(oj,{Quote:e.Quote}),s,d.jsx(sj,{components:e,enabled:t})]})},dj=Symbol.for("@assistant-ui/groupBy.memoKey"),wy=e=>{const t=e.nextChildIdx++;return e.nodeKey===""?String(t):`${e.nodeKey}.${t}`},fj=e=>{const t={key:"",nodeKey:"",indices:[],children:[],nextChildIdx:0},n=[t],r=()=>{const s=n.pop();n[n.length-1].children.push({type:"group",key:s.key,nodeKey:s.nodeKey,indices:s.indices,children:s.children})};for(let s=0;s<e.length;s++){const i=e[s];let o=0;for(;o<n.length-1&&o<i.length&&n[o+1].key===i[o];)o++;for(;n.length-1>o;)r();for(;n.length-1<i.length;){const l=n[n.length-1];n.push({key:i[n.length-1],nodeKey:wy(l),indices:[],children:[],nextChildIdx:0})}const a=n[n.length-1];a.children.push({type:"part",index:s,nodeKey:wy(a)});for(let l=1;l<n.length;l++)n[l].indices.push(s)}for(;n.length>1;)r();return t.children},hj=Object.freeze({type:"complete"}),pj=(e,t,n)=>{if(!n)return!1;switch(e){case"never":return!1;case"always":return!0;case"empty":return t.length===0;case"no-text":{const r=t[t.length-1];return r!==void 0&&r.type!=="text"&&r.type!=="reasoning"}}},o0=()=>{throw new Error("MessagePrimitive.GroupedParts: rendered `children` under a leaf part. `children` is only meaningful for `group-…` cases — add a matching case for the part type or return `null` to skip it.")},a0=(e,t,n)=>{if(e.type==="part")return d.jsx(i0,{index:e.index,children:({part:s})=>n({part:s,children:d.jsx(o0,{})})},`part-${e.index}`);const r=t[e.indices.at(-1)]?.status??hj;return d.jsx(m.Fragment,{children:n({part:{type:e.key,status:r,indices:e.indices},children:d.jsx(d.Fragment,{children:e.children.map(s=>a0(s,t,n))})})},e.nodeKey)},l0=({groupBy:e,indicator:t="no-text",children:n})=>{const r=G(e0(o=>o.message.parts)),s=G(o=>o.tools.toolUIs),i=G(o=>t==="never"?!1:o.message.status?.type==="running");return d.jsxs(d.Fragment,{children:[m.useMemo(()=>{const o={toolUIs:s};return fj(r.map(a=>e(a,o)??[]))},[r,e[dj]??e,s]).map(o=>a0(o,r,n)),pj(t,r,i)&&n({part:{type:"indicator"},children:d.jsx(o0,{})})]})};l0.displayName="MessagePrimitive.GroupedParts";const mj=({children:e})=>{const t=G(Xb);return t?d.jsx(d.Fragment,{children:e(t)}):null},u0=m.memo(mj);u0.displayName="MessagePrimitive.Quote";const c0=(e,t)=>{switch(t.type){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:return e?.Attachment}},gj=({components:e})=>{const t=G(r=>r.attachment);if(!t)return null;const n=c0(e,t);return n?d.jsx(n,{}):null},d0=m.memo(({index:e,components:t})=>d.jsx(jb,{index:e,children:d.jsx(gj,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);d0.displayName="MessagePrimitive.AttachmentByIndex";const _y=({children:e})=>{const t=G(n=>n.message.role!=="user"?0:(n.message.attachments??[]).length);return m.useMemo(()=>Array.from({length:t},(n,r)=>d.jsx(jb,{index:r,children:d.jsx(to,{getItemState:s=>s.message().attachment({index:r}).getState(),children:s=>e({get attachment(){return s()}})})},r)),[t,e])},f0=({components:e,children:t})=>e?d.jsx(_y,{children:({attachment:n})=>{const r=c0(e,n);return r?d.jsx(r,{}):null}}):d.jsx(_y,{children:t});f0.displayName="MessagePrimitive.Attachments";const h0=(e,t)=>{switch(t.type){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:return e?.Attachment}},yj=({components:e})=>{const t=G(r=>r.attachment);if(!t)return null;const n=h0(e,t);return n?d.jsx(n,{}):null},p0=m.memo(({index:e,components:t})=>d.jsx(Ab,{index:e,children:d.jsx(yj,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);p0.displayName="ComposerPrimitive.AttachmentByIndex";const by=({children:e})=>{const t=G(n=>n.composer.attachments.length);return m.useMemo(()=>Array.from({length:t},(n,r)=>d.jsx(Ab,{index:r,children:d.jsx(to,{getItemState:s=>s.composer().attachment({index:r}).getState(),children:s=>e({get attachment(){return s()}})})},r)),[t,e])},m0=({components:e,children:t})=>e?d.jsx(by,{children:({attachment:n})=>{const r=h0(e,n);return r?d.jsx(r,{}):null}}):d.jsx(by,{children:t});m0.displayName="ComposerPrimitive.Attachments";const vj=({children:e})=>{const t=G(n=>n.composer.queue.length);return m.useMemo(()=>Array.from({length:t},(n,r)=>d.jsx(qR,{index:r,children:d.jsx(to,{getItemState:s=>s.composer().queueItem({index:r}).getState(),children:s=>e({get queueItem(){return s()}})})},r)),[t,e])},g0=m.memo(vj);g0.displayName="ComposerPrimitive.Queue";const kp=({children:e})=>G(t=>t.part.status.type==="running")?e:null;kp.displayName="MessagePartPrimitive.InProgress";const y0=({components:e})=>{const t=e.Suggestion;return d.jsx(t,{})},v0=m.memo(({index:e,components:t})=>d.jsx(Mb,{index:e,children:d.jsx(y0,{components:t})}),(e,t)=>e.index===t.index&&e.components.Suggestion===t.components.Suggestion);v0.displayName="ThreadPrimitive.SuggestionByIndex";const ky=({children:e})=>{const t=G(n=>n.suggestions.suggestions.length);return m.useMemo(()=>t===0?null:Array.from({length:t},(n,r)=>d.jsx(Mb,{index:r,children:d.jsx(to,{getItemState:s=>s.suggestions().suggestion({index:r}).getState(),children:s=>e({get suggestion(){return s()}})})},r)),[t,e])},x0=({components:e,children:t})=>e?d.jsx(ky,{children:()=>d.jsx(y0,{components:e})}):d.jsx(ky,{children:t});x0.displayName="ThreadPrimitive.Suggestions";const xj=m.memo(x0,(e,t)=>e.children||t.children?e.children===t.children:e.components.Suggestion===t.components.Suggestion),wj=e=>G(t=>{if(e.editing===!0&&!t.composer.isEditing||e.editing===!1&&t.composer.isEditing)return!1;const n=t.composer.dictation!=null;return!(e.dictation===!0&&!n||e.dictation===!1&&n)}),w0=({children:e,...t})=>wj(t)?e:null;w0.displayName="ComposerPrimitive.If";const _j=()=>{const e=ue(),t=G(n=>!n.composer.canSend||n.thread.isRunning&&!n.thread.capabilities.queue);return{send:m.useCallback(n=>{e.composer().send(n)},[e]),disabled:t}},bj=()=>{const e=ue(),t=G(n=>!n.composer.canCancel);return{cancel:m.useCallback(()=>{e.composer().cancel()},[e]),disabled:t}},kj=()=>{const e=ue(),t=G(n=>n.composer.dictation!=null||!n.thread.capabilities.dictation||!n.composer.isEditing);return{startDictation:m.useCallback(()=>{e.composer().startDictation()},[e]),disabled:t}},Sj=()=>{const e=ue(),t=G(n=>!n.composer.isEditing);return{addAttachment:m.useCallback(n=>e.composer().addAttachment(n),[e]),disabled:t}},Cj=({copiedDuration:e=3e3,copyToClipboard:t}={})=>{const n=ue(),r=G(a=>!((a.message.role!=="assistant"||a.message.status?.type!=="running")&&a.message.parts.some(l=>l.type==="text"&&l.text.length>0))),s=G(a=>a.message.isCopied),i=G(a=>a.composer.isEditing),o=G(a=>a.composer.text);return{copy:m.useCallback(()=>{const a=i?o:n.message().getCopyText();if(!a)return;const l=t??(()=>{});Promise.resolve(l(a)).then(()=>{n.message().setIsCopied(!0),setTimeout(()=>n.message().setIsCopied(!1),e)},()=>{})},[n,i,o,e,t]),disabled:r,isCopied:s}},Ej=()=>{const e=ue(),t=G(n=>n.composer.isEditing);return{edit:m.useCallback(()=>{e.composer().beginEdit()},[e]),disabled:t}},Tj=()=>{const e=ue(),t=G(n=>n.thread.isRunning||n.thread.isDisabled||n.message.role!=="assistant");return{reload:m.useCallback(()=>{e.message().reload()},[e]),disabled:t}},Ij=()=>{const e=ue(),t=G(n=>n.message.metadata.submittedFeedback?.type==="positive");return{submit:m.useCallback(()=>{e.message().submitFeedback({type:"positive"})},[e]),isSubmitted:t}},Rj=()=>{const e=ue(),t=G(n=>n.message.metadata.submittedFeedback?.type==="negative");return{submit:m.useCallback(()=>{e.message().submitFeedback({type:"negative"})},[e]),isSubmitted:t}},Pj=()=>{const e=ue(),t=G(n=>!((n.message.role!=="assistant"||n.message.status?.type!=="running")&&n.message.parts.some(r=>r.type==="text"&&r.text.length>0)));return{speak:m.useCallback(async()=>{e.message().speak()},[e]),disabled:t}},jj=()=>{const e=ue(),t=G(n=>n.message.speech==null);return{stopSpeaking:m.useCallback(()=>{e.message().stopSpeaking()},[e]),disabled:t}},Aj=({prompt:e,send:t,clearComposer:n=!0})=>{const r=ue(),s=G(o=>o.thread.isDisabled),i=t??!1;return{trigger:m.useCallback(()=>{const o=r.thread().getState().isRunning;if(i&&!o)r.thread().append({content:[{type:"text",text:e}],runConfig:r.composer().getState().runConfig}),n&&r.composer().setText("");else if(n)r.composer().setText(e);else{const a=r.composer().getState().text;r.composer().setText(a.trim()?`${a} ${e}`:e)}},[r,i,n,e]),disabled:s}},Nj=()=>G(e=>e.message.status?.type==="incomplete"&&e.message.status.reason==="error"?e.message.status.error??"An error occurred":void 0),Mj=e=>{const{cloud:t,initialMessages:n,maxSteps:r,adapters:s,unstable_humanToolNames:i,...o}=e;return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:r,adapters:s,unstable_humanToolNames:i},otherOptions:o}},Dj=/:([\w-]{1,64})\[([^\]\n]{1,1024})\](?:\{name=([^}\n]{1,1024})\})?/gu,_0={serialize(e){const t=e.id!==e.label?`{name=${e.id}}`:"";return`:${e.type}[${e.label}]${t}`},parse(e){const t=[];let n=0;for(const r of e.matchAll(Dj)){r.index>n&&t.push({kind:"text",text:e.slice(n,r.index)});const s=r[2];t.push({kind:"mention",type:r[1],label:s,id:r[3]??s}),n=r.index+r[0].length}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t}};function Oj(e,t){function n(r){const s=m.useContext(e);if(!r?.optional&&!s)throw new Error(`This component must be used within ${t}.`);return s}return n}function b0(e,t){function n(s){const i=e(s);return i?i[t]:null}function r(s){let i=!1,o;typeof s=="function"?o=s:s&&typeof s=="object"&&(i=!!s.optional,o=s.selector);const a=n({optional:i});return a?o?a(o):a():null}return{[t]:r,[`${t}Store`]:n}}const k0=m.createContext(null),{useThreadViewport:qs,useThreadViewportStore:Gs}=b0(Oj(k0,"ThreadPrimitive.Viewport"),"useThreadViewport"),Sy=e=>{const t=new Map,n=()=>{let r=0;for(const s of t.values())r+=s;e(r)};return{register:()=>{const r=Symbol();return t.set(r,0),{setHeight:s=>{t.get(r)!==s&&(t.set(r,s),n())},unregister:()=>{t.delete(r),n()}}}}},Lj=(e={})=>{const t=new Set,n=Sy(o=>{i.setState({height:{...i.getState().height,viewport:o}})}),r=Sy(o=>{i.setState({height:{...i.getState().height,inset:o}})}),s=(o,a)=>(i.setState({element:{...i.getState().element,[o]:a}}),()=>{i.getState().element[o]===a&&i.setState({element:{...i.getState().element,[o]:null}})}),i=bb(()=>({isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const a of t)a({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:e.turnAnchor??"bottom",topAnchorMessageClamp:{tallerThan:e.topAnchorMessageClamp?.tallerThan??"10em",visibleHeight:e.topAnchorMessageClamp?.visibleHeight??"6em"},height:{viewport:0,inset:0},element:{viewport:null,anchor:null,target:null},targetConfig:null,topAnchorTurn:null,registerViewport:n.register,registerContentInset:r.register,registerViewportElement:o=>s("viewport",o),registerAnchorElement:o=>s("anchor",o),registerAnchorTargetElement:(o,a)=>(i.setState({element:{...i.getState().element,target:o},targetConfig:o&&a?a:null}),()=>{i.getState().element.target===o&&i.setState({element:{...i.getState().element,target:null},targetConfig:null})}),setTopAnchorTurn:o=>{i.setState({topAnchorTurn:o})}}));return i},_u=e=>e,zj=e=>{const t=Gs({optional:!0}),[n]=m.useState(()=>Lj(e));return m.useEffect(()=>t?.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),m.useEffect(()=>{if(t)return n.subscribe(r=>{t.getState().isAtBottom!==r.isAtBottom&&_u(t).setState({isAtBottom:r.isAtBottom})})},[n,t]),n},Sp=({children:e,options:t={}})=>{const n=zj(t),[r]=m.useState(()=>({useThreadViewport:n}));return d.jsx(k0.Provider,{value:r,children:e})},Fj=()=>{const e=ue();return m.useEffect(()=>{},[e]),null},Bj=({children:e,aui:t,runtime:n})=>d.jsxs(cR,{runtime:n,aui:t??null,children:[d.jsx(Fj,{}),d.jsx(Sp,{children:e})]}),Da=m.memo(Bj),$j=e=>{const t=e;t.__isBound||(t.__internal_bindMethods?.(),t.__isBound=!0)};function Uj(e,t=Vj){$j(e);const n=m.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return m.useDebugValue(n),n}const Vj=e=>e;function Hj(e){function t(n){let r=!1,s;typeof n=="function"?s=n:n&&(r=!!n.optional,s=n.selector);const i=e({optional:r});return i?Uj(i,s):null}return t}function S0(e){const t=ue(),n=G(()=>t.composer.source?t.composer().__internal_getRuntime?.()??null:null);if(!n&&!e?.optional)throw new Error("ComposerRuntime is not available");return n}function Wj(e){const t=ue(),n=G(()=>t.message.source?t.message().__internal_getRuntime?.()??null:null);if(!n&&!e?.optional)throw new Error("MessageRuntime is not available");return n}const bu=Hj(Wj);function Cy(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Kj(...e){return t=>{let n=!1;const r=e.map(s=>{const i=Cy(s,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let s=0;s<r.length;s++){const i=r[s];typeof i=="function"?i():Cy(e[s],null)}}}}function Ys(...e){return m.useCallback(Kj(...e),e)}var Ey=Object.defineProperty,so=(e,t)=>{let n={};for(var r in e)Ey(n,r,{get:e[r],enumerable:!0});return Ey(n,Symbol.toStringTag,{value:"Module"}),n};function C0(e){const t=m.forwardRef((n,r)=>{let{children:s,...i}=n,o=null,a=!1;const l=[];Ty(s)&&typeof pl=="function"&&(s=pl(s._payload)),m.Children.forEach(s,h=>{if(Xj(h)){a=!0;const p=h;let g="child"in p.props?p.props.child:p.props.children;Ty(g)&&typeof pl=="function"&&(g=pl(g._payload)),o=Gj(p,g),l.push(o?.props?.children)}else l.push(h)}),o?o=m.cloneElement(o,void 0,l):!a&&m.Children.count(s)===1&&m.isValidElement(s)&&(o=s);const u=o?Qj(o):void 0,c=Ys(r,u);if(!o){if(s||s===0)throw new Error(a?tA(e):eA(e));return s}const f=Yj(i,o.props??{});return o.type!==m.Fragment&&(f.ref=r?c:u),m.cloneElement(o,f)});return t.displayName=`${e}.Slot`,t}var ku=C0("Slot"),qj=Symbol.for("radix.slottable"),Gj=(e,t)=>{if("child"in e.props){const n=e.props.child;return m.isValidElement(n)?m.cloneElement(n,void 0,e.props.children(n.props.children)):null}return m.isValidElement(t)?t:null};function Yj(e,t){const n={...t};for(const r in t){const s=e[r],i=t[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...a)=>{const l=i(...a);return s(...a),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...e,...n}}function Qj(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function Xj(e){return m.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===qj}var Jj=Symbol.for("react.lazy");function Ty(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Jj&&"_payload"in e&&Zj(e._payload)}function Zj(e){return typeof e=="object"&&e!==null&&"then"in e}var eA=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,tA=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,pl=DC[" use ".trim().toString()],nA=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rA=nA.reduce((e,t)=>{const n=C0(`Primitive.${t}`),r=m.forwardRef((s,i)=>{const{asChild:o,...a}=s,l=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});const sA=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"];function iA(e){const t=m.forwardRef(({render:n,asChild:r,children:s,...i},o)=>{const a=e;if(n&&m.isValidElement(n)){const l=s!==void 0?s:n.props.children;return d.jsx(a,{...i,asChild:!0,ref:o,children:m.cloneElement(n,void 0,l)})}return d.jsx(a,{...i,asChild:r,ref:o,children:s})});return t.displayName=typeof e=="string"?e:e.displayName??e.name??"Component",t}function oA(e){const t=rA[e],n=iA(t);return n.displayName=`Primitive.${e}`,n}const Ne=sA.reduce((e,t)=>(e[t]=oA(t),e),{}),aA=({hideWhenRunning:e,autohide:t,autohideFloat:n,forceVisible:r})=>G(s=>{if(e&&s.thread.isRunning)return"hidden";const i=t==="always"||t==="not-last"&&!s.message.isLast,o=r||s.message.isHovering;return i?o?n==="always"||n==="single-branch"&&s.message.branchCount<=1?"floating":"normal":"hidden":"normal"}),lA=m.createContext(null),E0=m.forwardRef(({hideWhenRunning:e,autohide:t,autohideFloat:n,...r},s)=>{const[i,o]=m.useState(0),a=m.useCallback(()=>{let c=!1;return o(f=>f+1),()=>{c||(c=!0,o(f=>Math.max(0,f-1)))}},[]),l=m.useMemo(()=>({acquireInteractionLock:a}),[a]),u=aA({hideWhenRunning:e,autohide:t,autohideFloat:n,forceVisible:i>0});return u==="hidden"?null:d.jsx(lA.Provider,{value:l,children:d.jsx(Ne.div,{...u==="floating"?{"data-floating":"true"}:null,...r,ref:s})})});E0.displayName="ActionBarPrimitive.Root";function Ke(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e?.(s),n===!1||!s.defaultPrevented)return t?.(s)}}const uA=({copiedDuration:e=3e3}={})=>{const{copy:t,disabled:n}=Cj({copiedDuration:e,copyToClipboard:r=>typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("Clipboard API is unavailable")):navigator.clipboard.writeText(r)});return n?null:t},T0=m.forwardRef(({copiedDuration:e,onClick:t,disabled:n,...r},s)=>{const i=G(a=>a.message.isCopied),o=uA({copiedDuration:e});return d.jsx(Ne.button,{type:"button",...i?{"data-copied":"true"}:{},...r,ref:s,disabled:n||!o,onClick:Ke(t,()=>{o?.()})})});T0.displayName="ActionBarPrimitive.Copy";const Wn=(e,t,n=[])=>{const r=m.forwardRef((s,i)=>{const o={},a={};Object.keys(s).forEach(u=>{n.includes(u)?o[u]=s[u]:a[u]=s[u]});const l=t(o)??void 0;return d.jsx(Ne.button,{...a,type:"button",ref:i,disabled:a.disabled||!l,onClick:Ke(a.onClick,l)})});return r.displayName=e,r},cA=()=>{const{disabled:e,reload:t}=Tj();return e?null:t},dA=Wn("ActionBarPrimitive.Reload",cA),fA=()=>{const{disabled:e,edit:t}=Ej();return e?null:t},hA=Wn("ActionBarPrimitive.Edit",fA),pA=()=>{const{disabled:e,speak:t}=Pj();return e?null:t},mA=Wn("ActionBarPrimitive.Speak",pA);function Us(e){const t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>(...n)=>t.current?.(...n),[])}function I0(e,t=globalThis?.document){const n=Us(e);m.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}const gA=()=>{const{disabled:e,stopSpeaking:t}=jj();return e?null:t},R0=m.forwardRef((e,t)=>{const n=gA();return I0(r=>{n&&(r.preventDefault(),n())}),d.jsx(Ne.button,{type:"button",disabled:!n,...e,ref:t,onClick:Ke(e.onClick,()=>{n?.()})})});R0.displayName="ActionBarPrimitive.StopSpeaking";const yA=()=>{const{submit:e}=Ij();return e},P0=m.forwardRef(({onClick:e,disabled:t,...n},r)=>{const s=G(o=>o.message.metadata.submittedFeedback?.type==="positive"),i=yA();return d.jsx(Ne.button,{type:"button",...s?{"data-submitted":"true"}:{},...n,ref:r,disabled:t||!i,onClick:Ke(e,()=>{i?.()})})});P0.displayName="ActionBarPrimitive.FeedbackPositive";const vA=()=>{const{submit:e}=Rj();return e},j0=m.forwardRef(({onClick:e,disabled:t,...n},r)=>{const s=G(o=>o.message.metadata.submittedFeedback?.type==="negative"),i=vA();return d.jsx(Ne.button,{type:"button",...s?{"data-submitted":"true"}:{},...n,ref:r,disabled:t||!i,onClick:Ke(e,()=>{i?.()})})});j0.displayName="ActionBarPrimitive.FeedbackNegative";const xA=({filename:e,onExport:t}={})=>{const n=ue(),r=G(i=>(i.message.role!=="assistant"||i.message.status?.type!=="running")&&i.message.parts.some(o=>o.type==="text"&&o.text.length>0)),s=m.useCallback(async()=>{const i=n.message().getCopyText();if(!i)return;if(t){await t(i);return}const o=new Blob([i],{type:"text/markdown"}),a=URL.createObjectURL(o),l=document.createElement("a");l.href=a,l.download=e??`message-${Date.now()}.md`,l.click(),URL.revokeObjectURL(a)},[n,e,t]);return r?s:null},A0=m.forwardRef(({filename:e,onExport:t,onClick:n,disabled:r,...s},i)=>{const o=xA({filename:e,onExport:t});return d.jsx(Ne.button,{type:"button",...s,ref:i,disabled:r||!o,onClick:Ke(n,()=>{o?.()})})});A0.displayName="ActionBarPrimitive.ExportMarkdown";var Iy=so({Copy:()=>T0,Edit:()=>hA,ExportMarkdown:()=>A0,FeedbackNegative:()=>j0,FeedbackPositive:()=>P0,Reload:()=>dA,Root:()=>E0,Speak:()=>mA,StopSpeaking:()=>R0});const N0=m.forwardRef((e,t)=>d.jsx(Ne.div,{...e,ref:t}));N0.displayName="AttachmentPrimitive.Root";const M0=m.forwardRef((e,t)=>{const n=G(r=>{const s=r.attachment.name.split(".");return s.length>1?s.pop():""});return d.jsxs(Ne.div,{...e,ref:t,children:[".",n]})});M0.displayName="AttachmentPrimitive.unstable_Thumb";const D0=()=>d.jsx(d.Fragment,{children:G(e=>e.attachment.name)});D0.displayName="AttachmentPrimitive.Name";const wA=()=>{const e=ue();return m.useCallback(()=>{e.attachment().remove()},[e])},_A=Wn("AttachmentPrimitive.Remove",wA);var Ry=so({Name:()=>D0,Remove:()=>_A,Root:()=>N0,unstable_Thumb:()=>M0});const bA=e=>G(t=>{const{role:n,attachments:r,parts:s,branchCount:i,isLast:o,speech:a,isCopied:l,isHovering:u}=t.message;return!(e.hasBranches===!0&&i<2||e.user&&n!=="user"||e.assistant&&n!=="assistant"||e.system&&n!=="system"||e.lastOrHover===!0&&!u&&!o||e.last!==void 0&&e.last!==o||e.copied===!0&&!l||e.copied===!1&&l||e.speaking===!0&&a==null||e.speaking===!1&&a!=null||e.hasAttachments===!0&&(n!=="user"||!r?.length)||e.hasAttachments===!1&&n==="user"&&r?.length||e.hasContent===!0&&s.length===0||e.hasContent===!1&&s.length>0||e.submittedFeedback!==void 0&&(t.message.metadata.submittedFeedback?.type??null)!==e.submittedFeedback)}),O0=({children:e,...t})=>bA(t)?e:null;O0.displayName="MessagePrimitive.If";const L0=m.createContext(null),cc=()=>m.useContext(L0),kA=({children:e})=>{const t=m.useRef(new Map),n=m.useRef([]),r=m.useCallback(()=>{const a=Array.from(t.current.entries());a.sort((l,u)=>u[1]-l[1]),n.current=a.map(([l])=>l)},[]),s=m.useCallback((a,l)=>{const u=l?.priority??0;return t.current.set(a,u),r(),()=>{t.current.delete(a),r()}},[r]),i=m.useCallback(()=>n.current,[]),o=m.useMemo(()=>({register:s,getPlugins:i}),[s,i]);return d.jsx(L0.Provider,{value:o,children:e})},Cp=m.createContext(null),z0=m.createContext(null),Ep=()=>{const e=m.useContext(Cp);if(!e)throw new Error("useTriggerPopoverRootContext must be used within ComposerPrimitive.TriggerPopoverRoot");return e},Tp=()=>m.useContext(Cp),SA=()=>{const e=m.useContext(z0);if(!e)throw new Error("useTriggerPopoverAriaPublish must be used within ComposerPrimitive.TriggerPopoverRoot");return e},CA=()=>{const e=Ep();return m.useSyncExternalStore(e.subscribe,e.getTriggers,e.getTriggers)},EA=new Map,F0=()=>()=>{},Py=()=>EA,TA=()=>{const e=Tp();return m.useSyncExternalStore(e?e.subscribe:F0,e?e.getTriggers:Py,e?e.getTriggers:Py)},jy=()=>null,IA=()=>{const e=Tp();return m.useSyncExternalStore(e?e.subscribeAria:F0,e?e.getActiveAria:jy,e?e.getActiveAria:jy)};function Ay(){const e=m.useRef(new Set);return{notify:m.useCallback(()=>{for(const t of e.current)t()},[]),subscribe:m.useCallback(t=>(e.current.add(t),()=>{e.current.delete(t)}),[])}}const Ny=({children:e})=>{const t=m.useRef(new Map),n=m.useRef(new Set),{notify:r,subscribe:s}=Ay(),i=m.useCallback(_=>{const{char:x}=_;if(t.current.has(x))return()=>{};const v=new Map(t.current);v.set(x,_),t.current=v,r();for(const w of n.current)w.added(_);return()=>{const w=new Map(t.current);w.delete(x),t.current=w,r();for(const C of n.current)C.removed(x)}},[r]),o=m.useCallback(()=>t.current,[]),a=m.useCallback(_=>(n.current.add(_),()=>{n.current.delete(_)}),[]),l=m.useRef(null),u=m.useRef(null),{notify:c,subscribe:f}=Ay(),h=m.useCallback((_,x)=>{if(x===null){if(u.current!==_)return;l.current=null,u.current=null,c();return}const v=l.current;u.current===_&&v!==null&&v.popoverId===x.popoverId&&v.highlightedItemId===x.highlightedItemId||(l.current=x,u.current=_,c())},[c]),p=m.useCallback(()=>l.current,[]),g=m.useMemo(()=>({register:i,getTriggers:o,subscribe:s,subscribeLifecycle:a,getActiveAria:p,subscribeAria:f}),[i,o,s,a,p,f]),y=m.useMemo(()=>({setActiveAria:h}),[h]);return d.jsx(Cp.Provider,{value:g,children:d.jsx(z0.Provider,{value:y,children:e})})},B0=({children:e})=>cc()?d.jsx(Ny,{children:e}):d.jsx(kA,{children:d.jsx(Ny,{children:e})});B0.displayName="ComposerPrimitive.TriggerPopoverRoot";const My=/\s/u;function RA(e,t,n){const r=e.slice(0,n);for(let s=r.length-1;s>=0;s--){const i=r[s];if(My.test(i))return null;if(r.startsWith(t,s)){if(s>0&&!My.test(r[s-1]))continue;return{query:r.slice(s+t.length),offset:s}}}return null}const PA=ve(({text:e,triggerChar:t})=>{const[n,r]=dn(e.length),s=ce(()=>RA(e,t,Math.min(n,e.length)),[n,e,t]);return{trigger:s,query:s?.query??"",setCursorPosition:r}});function jA(e){return"type"in e}const AA=ve(({navigableList:e,isSearchMode:t,activeCategoryId:n,query:r,popoverId:s,open:i,selectItem:o,selectCategory:a,goBack:l,close:u})=>{const[c,f]=dn(0);tt(()=>{f(0)},[e]),tt(()=>{f(0)},[t,n]);const h=or(y=>{y<0||y>=e.length||y!==c&&f(y)}),p=or(y=>{if(!i)return!1;switch(y.key){case"ArrowDown":return y.preventDefault(),f(_=>{const x=e.length;return x===0?0:_<x-1?_+1:0}),!0;case"ArrowUp":return y.preventDefault(),f(_=>{const x=e.length;return x===0?0:_>0?_-1:x-1}),!0;case"Enter":case"Tab":{if(y.shiftKey)return!1;y.preventDefault();const _=e[c];return _&&(jA(_)?o(_):a(_.id)),!0}case"Escape":return y.preventDefault(),u(),!0;case"Backspace":return n&&r===""?(y.preventDefault(),l(),!0):!1;default:return!1}}),g=e[c];return{highlightedIndex:c,highlightedItemId:i&&g?`${s}-option-${g.id}`:void 0,highlightIndex:h,handleKeyDown:p}});function Dy(e,t){return e.id.toLowerCase().includes(t)||e.label.toLowerCase().includes(t)||(e.description?.toLowerCase().includes(t)??!1)}const NA=ve(({adapter:e,query:t,open:n})=>{const[r,s]=dn(null);tt(()=>{n||s(null)},[n]);const i=ce(()=>!n||!e?[]:e.categories(),[n,e]),o=n?r:null,a=ce(()=>!o||!e?[]:e.categoryItems(o),[o,e]),l=ce(()=>{if(!n||!e||o||!t&&i.length>0)return null;if(e.search)return e.search(t);const h=[],p=t.toLowerCase();for(const g of i)for(const y of e.categoryItems(g.id))Dy(y,p)&&h.push(y);return h},[n,e,t,o,i]),u=l!==null,c=ce(()=>{if(u)return[];if(!t)return i;const h=t.toLowerCase();return i.filter(p=>p.label.toLowerCase().includes(h))},[i,t,u]),f=ce(()=>{if(u)return l??[];if(!t)return a;const h=t.toLowerCase();return a.filter(p=>Dy(p,h))},[a,t,u,l]);return{categories:c,items:f,isSearchMode:u,activeCategoryId:o,navigableList:ce(()=>u?l??[]:o?f:c,[u,l,o,f,c]),selectCategory:or(h=>{s(h)}),goBack:or(()=>{s(null)})}}),MA=ve(({behavior:e,trigger:t,aui:n,triggerChar:r,setCursorPosition:s,onSelected:i})=>{const o=ir(null),a=or(l=>(o.current=l,()=>{o.current===l&&(o.current=null)}));return{selectItem:or(l=>{if(!t||!e)return;if(o.current?.(l)){i();return}const u=n.composer().getState().text,c=u.slice(0,t.offset),f=u.slice(t.offset+r.length+t.query.length),h=()=>{const p=e.formatter.serialize(l);n.composer().setText(c+p+(f.startsWith(" ")?f:` ${f}`))};e.kind==="directive"?(h(),e.onInserted?.(l)):(e.removeOnExecute?n.composer().setText(c+(f.startsWith(" ")?f.slice(1):f)):h(),e.onExecute(l)),i()}),close:or(()=>{i(),t&&s(t.offset)}),registerSelectItemOverride:a}}),DA=ve(({adapter:e,text:t,triggerChar:n,behavior:r,aui:s,popoverId:i})=>{const o=pt(PA({text:t,triggerChar:n})),a=o.trigger!==null&&e!==void 0&&r!==void 0,l=pt(NA({adapter:e,query:o.query,open:a})),u=or(()=>{l.goBack()}),c=pt(MA({behavior:r,trigger:o.trigger,aui:s,triggerChar:n,setCursorPosition:o.setCursorPosition,onSelected:u})),f=pt(AA({navigableList:l.navigableList,isSearchMode:l.isSearchMode,activeCategoryId:l.activeCategoryId,query:o.query,popoverId:i,open:a,selectItem:c.selectItem,selectCategory:l.selectCategory,goBack:l.goBack,close:c.close}));return{open:a,query:o.query,activeCategoryId:l.activeCategoryId,categories:l.categories,items:l.items,highlightedIndex:f.highlightedIndex,isSearchMode:l.isSearchMode,popoverId:i,highlightedItemId:f.highlightedItemId,selectCategory:l.selectCategory,goBack:l.goBack,selectItem:c.selectItem,close:c.close,highlightIndex:f.highlightIndex,handleKeyDown:f.handleKeyDown,setCursorPosition:o.setCursorPosition,registerSelectItemOverride:c.registerSelectItemOverride}}),Ip=m.createContext(null),io=()=>{const e=m.useContext(Ip);if(!e)throw new Error("useTriggerPopoverScopeContext must be used within ComposerPrimitive.TriggerPopover");return e},OA=()=>m.useContext(Ip),$0=m.createContext(null),U0=()=>{const e=m.useContext($0);if(!e)throw new Error("TriggerPopover.Directive / TriggerPopover.Action must be rendered inside ComposerPrimitive.TriggerPopover");return e},V0=m.forwardRef(({char:e,adapter:t,"aria-label":n,children:r,...s},i)=>{const o=ue(),a=G(S=>S.composer.text),l=m.useId(),u=m.useRef(null),[c,f]=m.useState(null),h=m.useRef(0),p=m.useCallback(S=>(h.current+=1,u.current=S,f(S),()=>{h.current=Math.max(0,h.current-1),u.current===S&&(u.current=null,f(null))}),[e]),g=m.useMemo(()=>({register:p}),[p]),y=gb(DA({adapter:t,text:a,triggerChar:e,behavior:c??void 0,aui:o,popoverId:l})),_=m.useRef(y);_.current=y;const x=Ep();m.useEffect(()=>x.register({char:e,...c?{behavior:c}:{},resource:_.current}),[x,e,c]);const v=cc();m.useEffect(()=>{if(v)return v.register(_.current)},[v]);const w=c!==null&&y.open,C=SA();return m.useEffect(()=>{if(w)return()=>{C.setActiveAria(e,null)}},[C,e,w]),m.useEffect(()=>{w&&C.setActiveAria(e,{popoverId:l,highlightedItemId:y.highlightedItemId})},[C,e,l,w,y.highlightedItemId]),d.jsx($0.Provider,{value:g,children:d.jsx(Ip.Provider,{value:y,children:w?d.jsx(Ne.div,{role:"listbox",id:l,"aria-label":n??"Suggestions","aria-activedescendant":y.highlightedItemId,"data-state":"open",...s,ref:i,children:r}):r})})});V0.displayName="ComposerPrimitive.TriggerPopover";const H0=()=>{const{disabled:e,send:t}=_j(),n=m.useCallback(()=>t(),[t]);return e?null:n},LA=Wn("ComposerPrimitive.Send",H0),W0=m.forwardRef(({onSubmit:e,...t},n)=>{const r=H0(),s=i=>{i.preventDefault(),r&&r()};return d.jsx(Ne.form,{...t,ref:n,onSubmit:Ke(e,s)})});W0.displayName="ComposerPrimitive.Root";const K0=e=>{const t=Us(e),n=qs(r=>r.onScrollToBottom);m.useEffect(()=>n(t),[n,t])},zA=()=>!1,FA=()=>{},BA=e=>m.useSyncExternalStore(m.useCallback(t=>{if(typeof window>"u"||e===null)return FA;const n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},[e]),m.useCallback(()=>typeof window>"u"||e===null?!1:window.matchMedia(e).matches,[e]),zA);function Df(){return Df=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Df.apply(null,arguments)}function $A(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var UA=m.useLayoutEffect,VA=function(t){var n=Bt.useRef(t);return UA(function(){n.current=t}),n},Oy=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},HA=function(t,n){var r=Bt.useRef();return Bt.useCallback(function(s){t.current=s,r.current&&Oy(r.current,null),r.current=n,n&&Oy(n,s)},[n])},Ly={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},WA=function(t){Object.keys(Ly).forEach(function(n){t.style.setProperty(n,Ly[n],"important")})},zy=WA,jt=null,Fy=function(t,n){var r=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?r+n.borderSize:r-n.paddingSize};function KA(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),jt||(jt=document.createElement("textarea"),jt.setAttribute("tabindex","-1"),jt.setAttribute("aria-hidden","true"),zy(jt)),jt.parentNode===null&&document.body.appendChild(jt);var s=e.paddingSize,i=e.borderSize,o=e.sizingStyle,a=o.boxSizing;Object.keys(o).forEach(function(h){var p=h;jt.style[p]=o[p]}),zy(jt),jt.value=t;var l=Fy(jt,e);jt.value=t,l=Fy(jt,e),jt.value="x";var u=jt.scrollHeight-s,c=u*n;a==="border-box"&&(c=c+s+i),l=Math.max(c,l);var f=u*r;return a==="border-box"&&(f=f+s+i),l=Math.min(f,l),[l,u]}var By=function(){},qA=function(t,n){return t.reduce(function(r,s){return r[s]=n[s],r},{})},GA=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],YA=!!document.documentElement.currentStyle,QA=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var r=qA(GA,n),s=r.boxSizing;if(s==="")return null;YA&&s==="border-box"&&(r.width=parseFloat(r.width)+parseFloat(r.borderRightWidth)+parseFloat(r.borderLeftWidth)+parseFloat(r.paddingRight)+parseFloat(r.paddingLeft)+"px");var i=parseFloat(r.paddingBottom)+parseFloat(r.paddingTop),o=parseFloat(r.borderBottomWidth)+parseFloat(r.borderTopWidth);return{sizingStyle:r,paddingSize:i,borderSize:o}},XA=QA;function Rp(e,t,n){var r=VA(n);m.useLayoutEffect(function(){var s=function(o){return r.current(o)};if(e)return e.addEventListener(t,s),function(){return e.removeEventListener(t,s)}},[])}var JA=function(t,n){Rp(document.body,"reset",function(r){t.current.form===r.target&&n(r)})},ZA=function(t){Rp(window,"resize",t)},eN=function(t){Rp(document.fonts,"loadingdone",t)},tN=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],nN=function(t,n){var r=t.cacheMeasurements,s=t.maxRows,i=t.minRows,o=t.onChange,a=o===void 0?By:o,l=t.onHeightChange,u=l===void 0?By:l,c=$A(t,tN),f=c.value!==void 0,h=m.useRef(null),p=HA(h,n),g=m.useRef(0),y=m.useRef(),_=function(){var w=h.current,C=r&&y.current?y.current:XA(w);if(C){y.current=C;var S=KA(C,w.value||w.placeholder||"x",i,s),k=S[0],T=S[1];g.current!==k&&(g.current=k,w.style.setProperty("height",k+"px","important"),u(k,{rowHeight:T}))}},x=function(w){f||_(),a(w)};return m.useLayoutEffect(_),JA(h,function(){if(!f){var v=h.current.value;requestAnimationFrame(function(){var w=h.current;w&&v!==w.value&&_()})}}),ZA(_),eN(_),m.createElement("textarea",Df({},c,{onChange:x,ref:p}))},rN=m.forwardRef(nN);const sN="(pointer: coarse) and (not (any-pointer: fine))",q0=m.forwardRef(({autoFocus:e=!1,asChild:t,render:n,disabled:r,onChange:s,onKeyDown:i,onPaste:o,onSelect:a,submitOnEnter:l,submitMode:u,cancelOnEscape:c=!0,unstable_focusOnRunStart:f=!0,unstable_focusOnScrollToBottom:h=!0,unstable_focusOnThreadSwitched:p=!0,unstable_insertNewlineOnTouchEnter:g=!1,addAttachmentOnPaste:y=!0,..._},x)=>{const v=ue(),w=cc(),C=IA(),S=u??(l===!1?"none":"enter"),k=BA(g?sN:null),T=g&&k&&S==="enter"?"none":S,R=G(z=>z.composer.isEditing?z.composer.text:""),P=G(z=>z.thread.isDisabled||z.composer.dictation?.inputDisabled)||r,E=m.useRef(null),M=Ys(x,E),O=m.useRef(!1);I0(z=>{if(!E.current?.contains(z.target))return;if(w){for(const H of w.getPlugins())if(H.handleKeyDown(z))return}if(!c)return;const b=v.composer();b.getState().canCancel&&(b.cancel(),z.preventDefault())});const W=z=>{if(!P&&!z.nativeEvent.isComposing){if(w){for(const b of w.getPlugins())if(b.handleKeyDown(z))return}if(z.key==="Enter"){const b=v.thread().getState(),H=b.capabilities.queue;if(z.shiftKey&&(z.ctrlKey||z.metaKey)&&H&&S!=="none"&&v.composer().getState().canSend){z.preventDefault(),v.composer().send({steer:!0});return}if(z.shiftKey||b.isRunning&&!H)return;let X=!1;T==="ctrlEnter"?X=z.ctrlKey||z.metaKey:T==="enter"&&(X=!0),X&&(z.preventDefault(),E.current?.closest("form")?.requestSubmit())}}},Q=async z=>{if(!y)return;const b=v.thread().getState().capabilities,H=Array.from(z.clipboardData?.files||[]);if(b.attachments&&H.length>0)try{z.preventDefault(),await Promise.all(H.map(X=>v.composer().addAttachment(X)))}catch(X){console.error("Error adding attachment:",X)}},$=e&&!P,te=m.useCallback(()=>{const z=E.current;!z||!$||(z.focus({preventScroll:!0}),z.setSelectionRange(z.value.length,z.value.length))},[$]);m.useEffect(()=>te(),[te]),K0(()=>{v.composer().getState().type==="thread"&&h&&te()}),m.useEffect(()=>{if(!(v.composer().getState().type!=="thread"||!f))return v.on("thread.runStart",te)},[f,te,v]),m.useEffect(()=>{if(!(v.composer().getState().type!=="thread"||!p))return v.on("threadListItem.switchedTo",te)},[p,te,v]);const ee=C?{"aria-controls":C.popoverId,"aria-expanded":!0,"aria-haspopup":"listbox","aria-activedescendant":C.highlightedItemId}:{},F={name:"input",value:R,..._,...ee,ref:M,disabled:P,onChange:Ke(s,z=>{if(!v.composer().getState().isEditing)return;const b=z.nativeEvent.isComposing===!0;O.current&&!b&&(O.current=!1);const H=b||O.current;if(qg(()=>{v.composer().setText(z.target.value)}),H)return;const X=z.target.selectionStart??z.target.value.length;if(w)for(const I of w.getPlugins())I.setCursorPosition(X)}),onKeyDown:Ke(i,W),onCompositionStart:Ke(_.onCompositionStart,()=>{O.current=!0}),onCompositionEnd:Ke(_.onCompositionEnd,z=>{if(O.current=!1,!v.composer().getState().isEditing)return;const b=z.target;qg(()=>{v.composer().setText(b.value)});const H=b.selectionStart??b.value.length;if(w)for(const X of w.getPlugins())X.setCursorPosition(H)}),onSelect:Ke(a,z=>{if(O.current)return;const b=z.target,H=b.selectionStart??b.value.length;if(w)for(const X of w.getPlugins())X.setCursorPosition(H)}),onPaste:Ke(o,Q)};if(n&&m.isValidElement(n)){const z=_.children!==void 0?_.children:n.props.children;return d.jsx(ku,{...F,children:m.cloneElement(n,void 0,z)})}return d.jsx(t?ku:rN,{...F})});q0.displayName="ComposerPrimitive.Input";const iN=()=>{const{disabled:e,cancel:t}=bj();return e?null:t},oN=Wn("ComposerPrimitive.Cancel",iN),aN=({multiple:e=!0}={})=>{const{disabled:t,addAttachment:n}=Sj(),r=ue(),s=m.useCallback(()=>{const i=document.createElement("input");i.type="file",i.multiple=e,i.hidden=!0;const o=r.composer().getState().attachmentAccept;o!=="*"&&(i.accept=o),document.body.appendChild(i),i.onchange=a=>{const l=a.target.files;if(l){for(const u of l)n(u);document.body.removeChild(i)}},i.oncancel=()=>{(!i.files||i.files.length===0)&&document.body.removeChild(i)},i.click()},[r,e,n]);return t?null:s},lN=Wn("ComposerPrimitive.AddAttachment",aN,["multiple"]),G0=m.forwardRef(({disabled:e,asChild:t=!1,render:n,children:r,...s},i)=>{const[o,a]=m.useState(!1),l=ue(),u=m.useCallback(g=>{e||(g.preventDefault(),a(!0))},[e]),c=m.useCallback(g=>{e||(g.preventDefault(),o||a(!0))},[e,o]),f=m.useCallback(g=>{if(e)return;g.preventDefault();const y=g.relatedTarget;y&&g.currentTarget.contains(y)||a(!1)},[e]),h=m.useCallback(async g=>{if(e)return;g.preventDefault(),a(!1);const y=Array.from(g.dataTransfer.files);await Promise.all(y.map(async _=>{try{await l.composer().addAttachment(_)}catch(x){console.error("Failed to add attachment:",x)}}))},[e,l]),p={...o?{"data-dragging":"true"}:null,...s,onDragEnterCapture:Ke(s.onDragEnterCapture,u),onDragOverCapture:Ke(s.onDragOverCapture,c),onDragLeaveCapture:Ke(s.onDragLeaveCapture,f),onDropCapture:Ke(s.onDropCapture,h),ref:i};if(n&&m.isValidElement(n)){const g=r!==void 0?r:n.props.children;return d.jsx(ku,{...p,children:m.cloneElement(n,void 0,g)})}return d.jsx(t?ku:"div",{...p,children:r})});G0.displayName="ComposerPrimitive.AttachmentDropzone";const uN=()=>{const{disabled:e,startDictation:t}=kj();return e?null:t},cN=Wn("ComposerPrimitive.Dictate",uN),dN=()=>{const e=ue(),t=G(r=>r.composer.dictation!=null),n=m.useCallback(()=>{e.composer().stopDictation()},[e]);return t?n:null},fN=Wn("ComposerPrimitive.StopDictation",dN),Y0=m.forwardRef(({children:e,...t},n)=>{const r=G(s=>s.composer.dictation?.transcript);return r?d.jsx(Ne.span,{...t,ref:n,children:e??r}):null});Y0.displayName="ComposerPrimitive.DictationTranscript";const Q0=m.forwardRef((e,t)=>G(n=>n.composer.quote)?d.jsx(Ne.div,{...e,ref:t}):null);Q0.displayName="ComposerPrimitive.Quote";const X0=m.forwardRef(({children:e,...t},n)=>{const r=G(s=>s.composer.quote?.text);return r?d.jsx(Ne.span,{...t,ref:n,children:e??r}):null});X0.displayName="ComposerPrimitive.QuoteText";const J0=m.forwardRef(({onClick:e,...t},n)=>{const r=ue(),s=m.useCallback(()=>{r.composer().setQuote(void 0)},[r]);return d.jsx(Ne.button,{type:"button",...t,ref:n,onClick:Ke(e,s)})});J0.displayName="ComposerPrimitive.QuoteDismiss";const Z0=m.forwardRef(({children:e,"aria-label":t,...n},r)=>{const{categories:s,activeCategoryId:i,isSearchMode:o,open:a}=io();return!a||i||o?null:d.jsx(Ne.div,{role:"group","aria-label":t??"Categories",...n,ref:r,children:e(s)})});Z0.displayName="ComposerPrimitive.TriggerPopoverCategories";const ek=m.forwardRef(({categoryId:e,onClick:t,onMouseMove:n,...r},s)=>{const{selectCategory:i,highlightIndex:o,categories:a,highlightedIndex:l,activeCategoryId:u,isSearchMode:c,popoverId:f}=io(),h=m.useCallback(()=>{i(e)},[i,e]),p=a.findIndex(_=>_.id===e),g=!u&&!c&&p===l,y=m.useCallback(()=>{o(p)},[o,p]);return d.jsx(Ne.button,{type:"button",role:"option",id:`${f}-option-${e}`,"aria-selected":g,"data-highlighted":g?"":void 0,...r,ref:s,onClick:Ke(t,h),onMouseMove:Ke(n,y)})});ek.displayName="ComposerPrimitive.TriggerPopoverCategoryItem";const tk=m.forwardRef(({children:e,"aria-label":t,...n},r)=>{const{items:s,activeCategoryId:i,isSearchMode:o,open:a}=io();return!a||!i&&!o?null:d.jsx(Ne.div,{role:"group","aria-label":t??"Items",...n,ref:r,children:e(s)})});tk.displayName="ComposerPrimitive.TriggerPopoverItems";const nk=m.forwardRef(({item:e,index:t,onClick:n,onMouseMove:r,...s},i)=>{const{selectItem:o,highlightIndex:a,items:l,highlightedIndex:u,activeCategoryId:c,isSearchMode:f,popoverId:h}=io(),p=m.useCallback(()=>{o(e)},[o,e]),g=t??l.findIndex(x=>x.id===e.id),y=(f||c!==null)&&g===u,_=m.useCallback(()=>{a(g)},[a,g]);return d.jsx(Ne.button,{type:"button",role:"option",id:`${h}-option-${e.id}`,"aria-selected":y,"data-highlighted":y?"":void 0,...s,ref:i,onClick:Ke(n,p),onMouseMove:Ke(r,_)})});nk.displayName="ComposerPrimitive.TriggerPopoverItem";const rk=m.forwardRef(({onClick:e,...t},n)=>{const{activeCategoryId:r,isSearchMode:s,goBack:i,open:o}=io();return!o||!r||s?null:d.jsx(Ne.button,{type:"button",...t,ref:n,onClick:Ke(e,i)})});rk.displayName="ComposerPrimitive.TriggerPopoverBack";const sk=({formatter:e,onExecute:t,removeOnExecute:n})=>{const{register:r}=U0(),s=m.useRef(t);return s.current=t,m.useEffect(()=>r({kind:"action",formatter:e??_0,onExecute:i=>s.current(i),...n!==void 0?{removeOnExecute:n}:{}}),[r,e,n]),null};sk.displayName="ComposerPrimitive.TriggerPopoverAction";const ik=({formatter:e,onInserted:t})=>{const{register:n}=U0(),r=m.useRef(t);return r.current=t,m.useEffect(()=>n({kind:"directive",formatter:e??_0,onInserted:s=>r.current?.(s)}),[n,e]),null};ik.displayName="ComposerPrimitive.TriggerPopoverDirective";const hN=Object.assign(V0,{Directive:ik,Action:sk});var ml=so({AddAttachment:()=>lN,AttachmentByIndex:()=>p0,AttachmentDropzone:()=>G0,Attachments:()=>m0,Cancel:()=>oN,Dictate:()=>cN,DictationTranscript:()=>Y0,If:()=>w0,Input:()=>q0,Queue:()=>g0,Quote:()=>Q0,QuoteDismiss:()=>J0,QuoteText:()=>X0,Root:()=>W0,Send:()=>LA,StopDictation:()=>fN,Unstable_TriggerPopover:()=>hN,Unstable_TriggerPopoverBack:()=>rk,Unstable_TriggerPopoverCategories:()=>Z0,Unstable_TriggerPopoverCategoryItem:()=>ek,Unstable_TriggerPopoverItem:()=>nk,Unstable_TriggerPopoverItems:()=>tk,Unstable_TriggerPopoverRoot:()=>B0,unstable_useTriggerPopoverRootContext:()=>Ep,unstable_useTriggerPopoverRootContextOptional:()=>Tp,unstable_useTriggerPopoverScopeContext:()=>io,unstable_useTriggerPopoverScopeContextOptional:()=>OA,unstable_useTriggerPopoverTriggers:()=>CA,unstable_useTriggerPopoverTriggersOptional:()=>TA});const ok=()=>G(e=>{if(e.part.type!=="text"&&e.part.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return e.part}),pN=()=>G(e=>{if(e.part.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return e.part}),ak=m.createContext(null),mN=e=>({useSmoothStatus:bb(()=>e)}),gN=({children:e})=>{const t=lk({optional:!0}),n=ue(),[r]=m.useState(()=>mN(n.part().getState().status));return t?e:d.jsx(ak.Provider,{value:r,children:e})},yN=e=>{const t=m.forwardRef((n,r)=>d.jsx(gN,{children:d.jsx(e,{...n,ref:r})}));return t.displayName=e.displayName,t};function lk(e){const t=m.useContext(ak);if(!e?.optional&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}const{useSmoothStatus:vN,useSmoothStatusStore:xN}=b0(lk,"useSmoothStatus");var wN=class{constructor(e,t){A(this,"currentText");A(this,"setText");A(this,"animationFrameId",null);A(this,"lastUpdateTime",Date.now());A(this,"targetText","");A(this,"animate",()=>{const e=Date.now();let t=e-this.lastUpdateTime;const n=this.targetText.length-this.currentText.length,r=Math.min(5,250/n);let s=0;for(;t>=r&&s<n;)s++,t-=r;s!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,s!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+s),this.lastUpdateTime=e-t,this.setText(this.currentText))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}};const sd=Object.freeze({type:"running"}),uk=(e,t=!1)=>{const{text:n}=e,[r,s]=m.useState(e.status.type==="running"?"":n),i=ue(),o=G(()=>i.part()),[a,l]=m.useState(o);(o!==a||!n.startsWith(r))&&(l(o),s(e.status.type==="running"?"":n));const u=xN({optional:!0}),c=Us(p=>{if(s(p),u){const g=r!==p||e.status.type==="running"?sd:e.status;_u(u).setState(g,!0)}});m.useEffect(()=>{if(u){const p=t&&(r!==n||e.status.type==="running")?sd:e.status;_u(u).setState(p,!0)}},[u,t,n,r,e.status]);const[f]=m.useState(new wN(r,c)),h=m.useRef(o);return m.useEffect(()=>{if(!t){f.stop();return}const p=h.current!==o;if(h.current=o,p||!n.startsWith(f.targetText)){e.status.type==="running"?(f.currentText="",f.targetText=n,f.start()):(f.currentText=n,f.targetText=n,f.stop());return}f.targetText=n,f.start()},[f,t,n,e.status.type,o]),m.useEffect(()=>()=>{f.stop()},[f]),m.useMemo(()=>t?{type:"text",text:r,status:n===r?e.status:sd}:e,[t,r,e,n])},Pp=m.forwardRef(({smooth:e=!0,component:t="span",...n},r)=>{const{text:s,status:i}=uk(ok(),e);return d.jsx(t,{"data-status":i.type,...n,ref:r,children:s})});Pp.displayName="MessagePartPrimitive.Text";const jp=m.forwardRef((e,t)=>{const{image:n}=pN();return d.jsx(Ne.img,{src:n,...e,ref:t})});jp.displayName="MessagePartPrimitive.Image";const Qs=e=>{const t=m.useRef(void 0);return m.useCallback(n=>{t.current&&(t.current(),t.current=void 0),n&&(t.current=e(n))},[e])},$y=(e,t)=>{const n=e.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(em|px|rem)$/);if(!n)return Number.POSITIVE_INFINITY;const r=Number(n[1]),s=n[2];return s==="px"?r:s==="em"?r*(parseFloat(getComputedStyle(t).fontSize)||16):s==="rem"?r*(parseFloat(getComputedStyle(document.documentElement).fontSize)||16):Number.POSITIVE_INFINITY},_N=e=>e.dataset.messageId,bN=()=>{const e=document.createElement("div");return e.dataset.auiTopAnchorReserve="",e.style.height="0px",e.style.flexShrink="0",e.style.pointerEvents="none",e.setAttribute("aria-hidden","true"),e},Uy=(e,t)=>{const n=`${t}px`;return e.style.height!==n?(e.style.height=n,!0):!1},kN=e=>{const t=window.devicePixelRatio||1;return Math.round(e*t)/t},ck=()=>{const e=ue(),t=G(()=>e.message());return Qs(m.useCallback(n=>{const r=()=>{t.setIsHovering(!0)},s=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",r),n.addEventListener("mouseleave",s),n.matches(":hover")&&queueMicrotask(()=>t.setIsHovering(!0)),()=>{n.removeEventListener("mouseenter",r),n.removeEventListener("mouseleave",s),t.setIsHovering(!1)}},[t]))},SN=()=>{const e=qs(t=>t.topAnchorTurn?.anchorId);return G(t=>t.message.role==="user"&&t.message.index>0&&t.message.index===t.thread.messages.length-2&&t.thread.messages.at(-1)?.role==="assistant"&&(t.message.id===e||t.thread.isRunning))},CN=()=>{const e=qs(t=>t.topAnchorTurn?.targetId);return G(t=>t.message.isLast&&t.message.role==="assistant"&&t.message.index>=1&&t.thread.messages.at(t.message.index-1)?.role==="user"&&(t.message.id===e||t.thread.isRunning))},EN=(e,t)=>Qs(m.useCallback(n=>{if(e)return t.getState().registerAnchorElement(n)},[e,t])),TN=({active:e,threadViewportStore:t})=>Qs(m.useCallback(n=>{if(!e)return;const r=t.getState(),s=r.topAnchorMessageClamp;return r.registerAnchorTargetElement(n,{tallerThan:$y(s.tallerThan,n),visibleHeight:$y(s.visibleHeight,n)})},[e,t])),IN=({forwardedRef:e,...t})=>{const n=Ys(e,ck()),r=G(s=>s.message.id);return d.jsx(Ne.div,{...t,ref:n,"data-message-id":r})},RN=({forwardedRef:e,threadViewportStore:t,...n})=>{const r=ck(),s=SN(),i=CN(),o=Ys(e,r,EN(s,t),TN({active:i,threadViewportStore:t})),a=G(l=>l.message.id);return d.jsx(Ne.div,{...n,ref:o,"data-message-id":a,"data-aui-top-anchor-user":s?"":void 0,"data-aui-top-anchor-target":i?"":void 0})},dk=m.forwardRef((e,t)=>{const n=Gs();return n.getState().turnAnchor==="top"?d.jsx(RN,{...e,forwardedRef:t,threadViewportStore:n}):d.jsx(IN,{...e,forwardedRef:t})});dk.displayName="MessagePrimitive.Root";const id={...St,Text:()=>d.jsxs("p",{style:{whiteSpace:"pre-line"},children:[d.jsx(Pp,{}),d.jsx(kp,{children:d.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Image:()=>d.jsx(jp,{})},Of=e=>{if("children"in e)return d.jsx(Mf,{children:e.children});const{components:t,...n}=e;return d.jsx(Mf,{components:t?{Text:t.Text??id.Text,Image:t.Image??id.Image,Reasoning:t.Reasoning??St.Reasoning,Source:t.Source??St.Source,File:t.File??St.File,Unstable_Audio:t.Unstable_Audio??St.Unstable_Audio,..."ChainOfThought"in t?{ChainOfThought:t.ChainOfThought}:{tools:t.tools,data:t.data,ToolGroup:t.ToolGroup??St.ToolGroup,ReasoningGroup:t.ReasoningGroup??St.ReasoningGroup},Empty:t.Empty,Quote:t.Quote,generativeUI:t.generativeUI}:id,...n})};Of.displayName="MessagePrimitive.Parts";const fk=({children:e})=>Nj()!==void 0?e:null;fk.displayName="MessagePrimitive.Error";const PN=e=>{const t=new Map;for(let r=0;r<e.length;r++){const s=e[r]?.parentId??`__ungrouped_${r}`,i=t.get(s)??[];i.push(r),t.set(s,i)}const n=[];for(const[r,s]of t){const i=r.startsWith("__ungrouped_")?void 0:r;n.push({groupKey:i,indices:s})}return n},jN=e=>{const t=G(n=>n.message.parts);return m.useMemo(()=>t.length===0?[]:e(t),[t,e])},AN=({Fallback:e,...t})=>{const n=G(r=>{const s=r.tools.tools[t.toolName]??e;return Array.isArray(s)?s[0]??e:s});return n?d.jsx(n,{...t}):null},NN=({Fallback:e,...t})=>{const n=G(r=>{const s=r.dataRenderers.renderers[t.name]??e;return Array.isArray(s)?s[0]??e:s});return n?d.jsx(n,{...t}):null},Or={Text:()=>d.jsxs("p",{style:{whiteSpace:"pre-line"},children:[d.jsx(Pp,{}),d.jsx(kp,{children:d.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>d.jsx(jp,{}),File:()=>null,Unstable_Audio:()=>null,Group:({children:e})=>e},MN=({components:{Text:e=Or.Text,Reasoning:t=Or.Reasoning,Image:n=Or.Image,Source:r=Or.Source,File:s=Or.File,Unstable_Audio:i=Or.Unstable_Audio,tools:o={},data:a}={}})=>{const l=ue(),u=G(f=>f.part),c=u.type;if(c==="tool-call"){const f=l.part().addToolResult,h=l.part().resumeToolCall,p=l.part().respondToToolApproval;if("Override"in o)return d.jsx(o.Override,{...u,addResult:f,resume:h,respondToApproval:p});const g=o.by_name?.[u.toolName]??o.Fallback;return d.jsx(AN,{...u,Fallback:g,addResult:f,resume:h,respondToApproval:p})}if(u.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(c){case"text":return d.jsx(e,{...u});case"reasoning":return d.jsx(t,{...u});case"source":return d.jsx(r,{...u});case"image":return d.jsx(n,{...u});case"file":return d.jsx(s,{...u});case"audio":return d.jsx(i,{...u});case"data":{const f=a?.by_name?.[u.name]??a?.Fallback;return d.jsx(NN,{...u,Fallback:f})}default:return console.warn(`Unknown message part type: ${c}`),null}},DN=({partIndex:e,components:t})=>d.jsx(yp,{index:e,children:d.jsx(MN,{components:t})}),ON=m.memo(DN,(e,t)=>e.partIndex===t.partIndex&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.Group===t.components?.Group),LN=({status:e,component:t})=>d.jsx(vp,{text:"",isRunning:e.type==="running",children:d.jsx(t,{type:"text",text:"",status:e})}),zN=Object.freeze({type:"complete"}),FN=({components:e})=>{const t=G(n=>n.message.status??zN);return e?.Empty?d.jsx(e.Empty,{status:t}):d.jsx(LN,{status:t,component:e?.Text??Or.Text})},BN=m.memo(FN,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),Ap=({groupingFunction:e,components:t})=>{const n=G(s=>s.message.parts.length),r=jN(e);return d.jsx(d.Fragment,{children:m.useMemo(()=>n===0?d.jsx(BN,{components:t}):r.map((s,i)=>d.jsx(t?.Group??Or.Group,{groupKey:s.groupKey,indices:s.indices,children:s.indices.map(o=>d.jsx(ON,{partIndex:o,components:t},o))},`group-${i}-${s.groupKey??"ungrouped"}`)),[r,t,n])})};Ap.displayName="MessagePrimitive.Unstable_PartsGrouped";const hk=({components:e,...t})=>d.jsx(Ap,{...t,components:e,groupingFunction:PN});hk.displayName="MessagePrimitive.Unstable_PartsGroupedByParentId";var Su=so({AttachmentByIndex:()=>d0,Attachments:()=>f0,Content:()=>Of,Error:()=>fk,GenerativeUI:()=>Zb,GroupedParts:()=>l0,If:()=>O0,PartByIndex:()=>Uo,Parts:()=>Of,Quote:()=>u0,Root:()=>dk,Unstable_PartsGrouped:()=>Ap,Unstable_PartsGroupedByParentId:()=>hk});const $N=e=>{const t=Us(e);return Qs(m.useCallback(n=>{const r=new ResizeObserver(()=>{t()}),s=new MutationObserver(i=>{i.some(o=>o.type!=="attributes"||o.attributeName!=="style")&&t()});return r.observe(n),s.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{r.disconnect(),s.disconnect()}},[t]))},UN=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{const s=m.useRef(null),i=G(C=>C.thread.messages.length>0),o=m.useRef(!1),a=m.useRef(null),l=Gs();e===void 0&&(e=l.getState().turnAnchor!=="top");const u=m.useRef(0),c=m.useRef(0),f=m.useRef(0),h=m.useRef(0),p=m.useRef(null),g=m.useCallback(C=>{const S=s.current;S&&(p.current=C,S.scrollTo({top:S.scrollHeight,behavior:C}))},[]),y=m.useCallback(C=>{p.current=C,a.current!==null&&cancelAnimationFrame(a.current),a.current=requestAnimationFrame(()=>{a.current=null,g(C)})},[g]);m.useLayoutEffect(()=>()=>{a.current!==null&&cancelAnimationFrame(a.current)},[]);const _=m.useCallback(()=>{const C=l.getState();return C.turnAnchor==="top"&&C.element.viewport===s.current&&C.element.anchor!==null},[l]),x=()=>{const C=s.current;if(!C)return;const S=l.getState().isAtBottom,k=Math.abs(C.scrollHeight-C.scrollTop-C.clientHeight)<=1||C.scrollHeight<=C.clientHeight;!k&&u.current<C.scrollTop||(k?C.scrollHeight>C.clientHeight+1&&(p.current=null):u.current>C.scrollTop&&c.current===C.scrollHeight&&(p.current=null),(k||p.current===null)&&k!==S&&_u(l).setState({isAtBottom:k})),u.current=C.scrollTop,c.current=C.scrollHeight},v=$N(()=>{const C=s.current;if(!C)return;const{scrollHeight:S,clientHeight:k}=C;if(S===f.current&&k===h.current)return;f.current=S,h.current=k;const T=p.current;T&&_()?p.current=null:T?g(T):e&&l.getState().isAtBottom&&g("instant"),x()}),w=Qs(C=>(C.addEventListener("scroll",x),()=>{C.removeEventListener("scroll",x)}));return m.useLayoutEffect(()=>{if(n){if(!i){o.current=!1;return}o.current||(o.current=!0,p.current===null&&y("instant"))}},[i,y,n]),K0(({behavior:C})=>{g(C)}),yu("thread.runStart",()=>{t&&l.getState().turnAnchor!=="top"&&y("auto")}),yu("threadListItem.switchedTo",()=>{r&&y("instant")}),Ys(v,w,s)},pk=m.forwardRef((e,t)=>d.jsx(Ne.div,{...e,ref:t}));pk.displayName="ThreadPrimitive.Root";const mk=({children:e})=>G(t=>t.thread.isEmpty)?e:null;mk.displayName="ThreadPrimitive.Empty";const VN=e=>G(t=>!(e.empty===!0&&!t.thread.isEmpty||e.empty===!1&&t.thread.isEmpty||e.running===!0&&!t.thread.isRunning||e.running===!1&&t.thread.isRunning||e.disabled===!0&&!t.thread.isDisabled||e.disabled===!1&&t.thread.isDisabled)),gk=({children:e,...t})=>VN(t)?e:null;gk.displayName="ThreadPrimitive.If";const yk=(e,t)=>Qs(m.useCallback(n=>{if(!e)return;const r=e(),s=()=>{const o=t?t(n):n.offsetHeight;r.setHeight(o)},i=new ResizeObserver(s);return i.observe(n),s(),()=>{i.disconnect(),r.unregister()}},[e,t])),Vy=e=>{let t=0,n=e;for(;n;)t+=n.offsetTop,n=n.offsetParent;return t},HN=(e,t)=>{let n=0,r=e;for(;r&&r!==t;)n+=r.offsetTop,r=r.offsetParent;return r===t?n:Vy(e)-Vy(t)},vk=({viewport:e,anchor:t,tallerThan:n,visibleHeight:r})=>{const s=HN(t,e),i=t.offsetHeight;return s+Math.max(0,i-(i<=n?i:r))},WN=({scrollHeight:e,...t})=>{const{viewport:n}=t,r=vk(t)+n.clientHeight;return Math.max(0,r-e)},KN=({viewport:e,reserve:t,...n})=>WN({viewport:e,...n,scrollHeight:e.scrollHeight-t.offsetHeight}),qN=e=>{const t=new ResizeObserver(e),n=new MutationObserver(e);let r=null,s=null,i=null;const o=()=>{t.disconnect(),n.disconnect(),r=null,s=null,i=null};return{target:(a,l,u)=>{r===a&&s===l&&i===u||(o(),t.observe(a),t.observe(l),t.observe(u),n.observe(u,{childList:!0,subtree:!0,characterData:!0}),r=a,s=l,i=u)},disconnect:o}},GN=e=>{let t=null;return{schedule:()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))},cancel:()=>{t!==null&&(cancelAnimationFrame(t),t=null)}}},YN=e=>{let t=null,n;function r(){const a=e.getState(),{viewport:l,anchor:u,target:c}=a.element,f=a.targetConfig;if(a.turnAnchor!=="top"||!l||!u||!c||!f){i.disconnect(),t&&(Uy(t,0),t.remove());return}if(t??(t=bN()),(t.parentElement!==c.parentElement||t.previousElementSibling!==c)&&c.after(t),i.target(l,u,c),Uy(t,KN({viewport:l,anchor:u,reserve:t,...f}))){s.schedule();return}const h=_N(u);if(h!==void 0&&n===h)return;const p=kN(vk({viewport:l,anchor:u,...f}));Math.abs(l.scrollTop-p)>1&&l.scrollTo({top:p,behavior:"smooth"}),h!==void 0&&(n=h)}const s=GN(r),i=qN(s.schedule);s.schedule();const o=e.subscribe(s.schedule);return()=>{s.cancel(),o(),i.disconnect(),t?.remove()}},QN=e=>{const t=Gs();m.useLayoutEffect(()=>{if(e)return YN(t)},[e,t])},xk=({isRunning:e,messages:t})=>{if(!e)return null;const n=t.at(-1),r=t.at(-2);return r?.role!=="user"||n?.role!=="assistant"?null:{anchorId:r.id,targetId:n.id}},XN=e=>xk(e)?.anchorId,JN=e=>xk(e)?.targetId,ZN=()=>yk(qs(e=>e.registerViewport),m.useCallback(e=>e.clientHeight,[])),eM=()=>Qs(qs(e=>e.registerViewportElement)),tM=e=>{const t=Gs(),n=G(o=>{if(e)return XN(o.thread)}),r=G(o=>{if(e)return JN(o.thread)}),s=m.useMemo(()=>!n||!r?null:{anchorId:n,targetId:r},[n,r]);m.useLayoutEffect(()=>{if(!s)return;const o=t.getState(),a=o.topAnchorTurn;a?.anchorId===s.anchorId&&a.targetId===s.targetId||o.setTopAnchorTurn(s)},[s,t]);const i=m.useCallback(()=>{t.getState().setTopAnchorTurn(null)},[t]);yu("thread.initialize",i),yu("threadListItem.switchedTo",i)},wk=m.forwardRef(({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r,children:s,...i},o)=>{const a=UN({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r}),l=ZN(),u=eM(),c=Gs().getState().turnAnchor==="top";tM(c),QN(c);const f=Ys(o,a,l,u);return d.jsx(Ne.div,{...i,ref:f,children:s})});wk.displayName="ThreadPrimitive.ViewportScrollable";const _k=m.forwardRef(({turnAnchor:e,topAnchorMessageClamp:t,...n},r)=>d.jsx(Sp,{options:{turnAnchor:e,topAnchorMessageClamp:t},children:d.jsx(wk,{...n,ref:r})}));_k.displayName="ThreadPrimitive.Viewport";const bk=m.forwardRef((e,t)=>{const n=Ys(t,yk(qs(r=>r.registerContentInset),m.useCallback(r=>{const s=parseFloat(getComputedStyle(r).marginTop)||0;return r.offsetHeight+s},[])));return d.jsx(Ne.div,{...e,ref:n})});bk.displayName="ThreadPrimitive.ViewportFooter";const nM=({behavior:e}={})=>{const t=qs(s=>s.isAtBottom),n=Gs(),r=m.useCallback(()=>{n.getState().scrollToBottom({behavior:e})},[n,e]);return t?null:r},rM=Wn("ThreadPrimitive.ScrollToBottom",nM,["behavior"]),sM=({prompt:e,send:t,clearComposer:n,autoSend:r,method:s})=>{const{disabled:i,trigger:o}=Aj({prompt:e,send:t??r??!1,clearComposer:n});return i?null:o},iM=Wn("ThreadPrimitive.Suggestion",sM,["prompt","send","clearComposer","autoSend","method"]);var mt=so({Empty:()=>mk,If:()=>gk,MessageByIndex:()=>Yb,Messages:()=>BP,Root:()=>pk,ScrollToBottom:()=>rM,Suggestion:()=>iM,SuggestionByIndex:()=>v0,Suggestions:()=>xj,Viewport:()=>_k,ViewportFooter:()=>bk,ViewportProvider:()=>Sp}),oM=so({AssistantRuntimeImpl:()=>Ub,BaseAssistantRuntimeCore:()=>Vb,CompositeContextProvider:()=>dp,DefaultThreadComposerRuntimeCore:()=>Kb,MessageRepository:()=>wp,ThreadRuntimeImpl:()=>$b,fromThreadMessageLike:()=>ga,generateId:()=>is,getAutoStatus:()=>xu,splitLocalRuntimeOptions:()=>Mj,useComposerInputPluginRegistryOptional:()=>cc,useSmooth:()=>uk,useSmoothStatus:()=>vN,withSmoothContextProvider:()=>yN});const Np="claude-control.token";let Cu=null,Eu=!1;function aM(){try{return window.localStorage.getItem(Np)}catch{return null}}const lM="claude-control";function dc(){return Eu||(Cu=aM(),Eu=!0),Cu}function kk(e){Cu=e,Eu=!0;try{window.localStorage.setItem(Np,e)}catch{}}function Sk(){Cu=null,Eu=!0;try{window.localStorage.removeItem(Np)}catch{}}function uM(){if(typeof window>"u"||!window.location)return;let e;try{e=new URLSearchParams(window.location.search)}catch{return}const t=e.get("token");if(!t)return;kk(t),e.delete("token");const n=e.toString(),r=window.location.pathname+(n?`?${n}`:"")+window.location.hash;try{window.history.replaceState(null,"",r)}catch{}}uM();const Lf=new Set;function cM(e){return Lf.add(e),()=>Lf.delete(e)}function Ck(){Sk();for(const e of Lf)e()}function dM(e){const t=dc(),n={...e??{}};return t&&(n.Authorization=`Bearer ${t}`),n}async function nt(e,t){const n=await fetch(e,{...t,headers:dM(t?.headers)});return n.status===401&&Ck(),n}function fM(e){const t=`/term/${encodeURIComponent(e)}/`,n=dc();return n?`${t}?token=${encodeURIComponent(n)}`:t}function hM(){const e=window.location;return`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}/`}async function Ek(){try{const e=await nt("/api/version");return e.ok?await e.json():null}catch{return null}}async function pM(){try{const e=await nt("/api/update",{method:"POST"}),t=await e.json().catch(()=>({}));return e.ok&&!!t.ok}catch{return!0}}async function mM(){try{const e=await nt("/api/push/vapid");return e.ok?(await e.json()).publicKey??null:null}catch{return null}}async function gM(e){try{return(await nt("/api/push/subscribe",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})).ok}catch{return!1}}async function yM(e){try{return(await nt("/api/push/unsubscribe",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({endpoint:e})})).ok}catch{return!1}}async function vM(e){const t=await nt("/api/icon",{method:"POST",body:e}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw new Error(n.error||`HTTP ${t.status}`)}async function xM(){const e=await nt("/api/icon",{method:"DELETE"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.ok)throw new Error(t.error||`HTTP ${e.status}`)}async function wM(){const e=await nt("/api/models");if(!e.ok)throw new Error(`HTTP ${e.status}`);return await e.json()}async function _M(e,t){const n=await nt("/api/optimize",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})}),r=await n.json().catch(()=>({}));if(!n.ok||typeof r.optimized!="string")throw new Error(r.error||`HTTP ${n.status}`);return{optimized:r.optimized,rationale:r.rationale??[],changes:r.changes??[],mode:r.mode==="rules"?"rules":"llm"}}async function bM(e,t="webm"){const n=await nt(`/api/transcribe?ext=${encodeURIComponent(t)}`,{method:"POST",body:e}),r=await n.json().catch(()=>({}));if(!n.ok||!r.ok)throw new Error(r.error||`HTTP ${n.status}`);return r.text??""}async function Tk(){const e=await nt("/api/config");if(!e.ok)throw new Error(`HTTP ${e.status}`);return await e.json()}async function kM(e){const t=await nt("/api/config",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error("error"in n&&n.error||`HTTP ${t.status}`);return n}async function Ik(e){const t=await nt("/api/session/new",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e??{})}),n=await t.json().catch(()=>({}));if(!t.ok||!("ok"in n)||!n.ok){const r="error"in n&&n.error||`HTTP ${t.status}`;throw new Error(r)}return n}async function SM(e,t){const n=await nt("/api/session/rename",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({id:e,name:t})}),r=await n.json().catch(()=>({}));if(!n.ok||!("ok"in r)||!r.ok){const s="error"in r&&r.error||`HTTP ${n.status}`;throw new Error(s)}}function CM(e){return`/api/uploads/${encodeURIComponent(e)}`}async function EM(){const e=await nt("/api/ps");if(!e.ok)throw new Error(`HTTP ${e.status}`);return(await e.json()).processes??[]}async function TM(e,t){const n=await nt("/api/kill",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pid:e,signal:t})}),r=await n.json().catch(()=>({}));if(!n.ok||!r.ok)throw new Error(r.error||`HTTP ${n.status}`)}async function Rk(e){const t=e?`/api/skills?id=${encodeURIComponent(e)}`:"/api/skills",n=await nt(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);return(await n.json()).skills??[]}async function IM(e){const t=e?`/api/agents?id=${encodeURIComponent(e)}`:"/api/agents",n=await nt(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);return(await n.json()).agents??[]}async function RM(e){const t=`/api/upload?name=${encodeURIComponent(e.name)}`,n=await nt(t,{method:"POST",body:e});let r=null;try{r=await n.json()}catch{}const s=r??{};if(!n.ok||!s.ok||!s.path)throw new Error(s.error||`HTTP ${n.status}`);return{ok:!0,path:s.path,name:s.name??e.name}}const PM=1008,Hy=1e3,jM=3e4;class AM{constructor(){A(this,"ws",null);A(this,"reconnectTimer",null);A(this,"reconnectDelay",Hy);A(this,"selectedId",null);A(this,"closed",!1);A(this,"msgHandlers",new Set);A(this,"stateHandlers",new Set)}connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.emitState("connecting");const t=dc(),n=t?[lM,t]:void 0,r=new WebSocket(hM(),n);this.ws=r,r.addEventListener("open",()=>{this.reconnectDelay=Hy,this.emitState("connected"),this.selectedId&&this.send({type:"subscribe",id:this.selectedId})}),r.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}for(const o of this.msgHandlers)o(i)}),r.addEventListener("close",s=>{if(this.ws=null,this.emitState("disconnected"),s.code===PM){Ck();return}this.closed||this.scheduleReconnect()}),r.addEventListener("error",()=>{})}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>this.connect(),this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*2,jM)}send(t){return this.ws&&this.ws.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(t)),!0):!1}isOpen(){return this.ws?.readyState===WebSocket.OPEN}select(t){this.selectedId!==t&&(this.selectedId&&this.send({type:"unsubscribe",id:this.selectedId}),this.selectedId=t,t&&this.send({type:"subscribe",id:t}))}resubscribe(){const t=this.selectedId;t&&(this.send({type:"unsubscribe",id:t}),this.send({type:"subscribe",id:t}))}onMessage(t){return this.msgHandlers.add(t),()=>this.msgHandlers.delete(t)}onState(t){return this.stateHandlers.add(t),()=>this.stateHandlers.delete(t)}emitState(t){for(const n of this.stateHandlers)n(t)}close(){this.closed=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close(),this.ws=null}}const Wy=2e3;function NM(e,t){if(!e||e.length===0)return Ky(t);if(t.length===0)return e;const n=new Set;for(const s of e)n.add(s.uuid);const r=t.filter(s=>!n.has(s.uuid));return r.length===0?e:Ky([...e,...r])}function Ky(e){return e.length>Wy?e.slice(e.length-Wy):e}const MM=10*6e4;function DM(){const e=m.useRef(null);e.current||(e.current=new AM);const t=e.current,[n,r]=m.useState([]),[s,i]=m.useState(null),[o,a]=m.useState("connecting"),[l,u]=m.useState({snapshot:null,warning:null}),[c,f]=m.useState([]),[h,p]=m.useState(null),[g,y]=m.useState(null),[_,x]=m.useState({}),[v,w]=m.useState({}),[C,S]=m.useState({}),[k,T]=m.useState({}),R=m.useRef(null);R.current=s;const P=m.useRef([]);P.current=n,m.useEffect(()=>{const ne=t.onState(a),J=t.onMessage(re=>{switch(re.type){case"sessions":r(he=>{const Fe=new Map(he.map(xt=>[xt.id,xt]));return(re.sessions??[]).map(xt=>{const Xt=Fe.get(xt.id);return Xt?{...xt,model:xt.model??Xt.model,ctxPct:xt.ctxPct??Xt.ctxPct}:xt})});break;case"messages":x(he=>({...he,[re.id]:NM(he[re.id],re.messages??[])})),w(he=>({...he,[re.id]:re.pending??null}));break;case"append":x(he=>({...he,[re.id]:[...he[re.id]??[],...re.messages??[]]}));break;case"pending":w(he=>({...he,[re.id]:re.pending})),r(he=>he.map(Fe=>Fe.id===re.id?{...Fe,pending:!!re.pending}:Fe));break;case"resources":{const he=re.snapshot??null;if(u({snapshot:he,warning:re.warning??null}),he){const Fe=Date.now(),xt={t:Fe,cpu:he.self?.cpuPct??0,mem:he.system?.memUsedPct??0};f(Xt=>[...Xt,xt].filter(wt=>Fe-wt.t<=MM))}break}case"capture":re.id===R.current&&p(re.text??"");break;case"shell-output":(!re.id||re.id===R.current)&&y(re.text??"");break;case"prompt":T(he=>({...he,[re.id]:re.prompt}));break;case"subagents":S(he=>({...he,[re.id]:Object.fromEntries((re.subagents??[]).map(Fe=>[Fe.agentId,Fe]))}));break;case"subagent":S(he=>({...he,[re.id]:{...he[re.id]??{},[re.subagent.agentId]:re.subagent}}));break;case"ack":window.dispatchEvent(new CustomEvent("cockpit:ack",{detail:re}));break}});return t.connect(),()=>{ne(),J()}},[t]),m.useEffect(()=>()=>t.close(),[t]);const E=m.useCallback(ne=>{ne!==R.current&&(i(ne),p(null),t.select(ne))},[t]),M=m.useCallback(ne=>{const J=R.current;return!J||!ne.trim()?!1:t.send({type:"reply",id:J,text:ne})},[t]),O=m.useCallback((ne,J)=>{const re=R.current;return re?t.send({type:"answer",id:re,toolUseId:ne,selections:J}):!1},[t]),W=m.useCallback((ne,J)=>{const re=R.current;return re?t.send({type:"capture",id:re,lines:ne,escapes:J}):!1},[t]),Q=m.useCallback(()=>p(null),[]),$=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"pane-text",id:J,text:ne}):!1},[t]),te=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"pane-key",id:J,key:ne}):!1},[t]),ee=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"shell-input",id:J,line:ne}):!1},[t]),F=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"shell-text",id:J,text:ne}):!1},[t]),z=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"shell-key",id:J,key:ne}):!1},[t]),b=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"shell-capture",id:J,lines:ne}):!1},[t]),H=m.useCallback(()=>y(null),[]),X=m.useCallback(()=>t.resubscribe(),[t]),I=m.useCallback(ne=>{const J=R.current;return J?t.send({type:"promptkey",id:J,key:ne}):!1},[t]),le=m.useCallback((ne,J)=>t.send({type:"promptselect",id:ne,labels:J}),[t]),we=m.useMemo(()=>s?_[s]??[]:[],[s,_]),de=m.useMemo(()=>s?v[s]??null:null,[s,v]),Je=m.useMemo(()=>s?k[s]??null:null,[s,k]),Ue=m.useMemo(()=>{const ne=s?C[s]:null;return ne?Object.values(ne).sort((J,re)=>(re.createdAt??-1/0)-(J.createdAt??-1/0)):[]},[s,C]);return{sessions:n,selectedId:s,messages:we,pending:de,prompt:Je,subagents:Ue,conn:o,resources:l,resourceHistory:c,capture:h,shellOutput:g,select:E,resubscribe:X,sendReply:M,sendPromptKey:I,sendPromptSelect:le,sendAnswer:O,requestCapture:W,clearCapture:Q,sendPaneText:$,sendPaneKey:te,sendShellInput:ee,sendShellText:F,sendShellKey:z,requestShellCapture:b,clearShellOutput:H}}const od="cc:push:intent";function OM(){return typeof window>"u"||!("serviceWorker"in navigator)||!("PushManager"in window)||!("Notification"in window)?!1:window.isSecureContext===!0}function LM(){if(typeof navigator>"u")return!1;const e=navigator.userAgent||"",t=/iPad|iPhone|iPod/.test(e),n=navigator.platform==="MacIntel"&&typeof navigator.maxTouchPoints=="number"&&navigator.maxTouchPoints>1;return t||n}function qy(e){const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),s=new ArrayBuffer(r.length),i=new Uint8Array(s);for(let o=0;o<r.length;o+=1)i[o]=r.charCodeAt(o);return s}function zM(){const e=OM(),t=LM(),[n,r]=m.useState(e?"off":"unsupported"),s=m.useCallback(async()=>{const a=await navigator.serviceWorker.register("/sw.js");if(await navigator.serviceWorker.ready,await Notification.requestPermission()!=="granted")return r("denied"),!1;const u=await mM();if(!u)return r("off"),!1;let c=await a.pushManager.getSubscription();if(c)try{const h=qy(u),p=c.options?.applicationServerKey;let g=!1;if(p instanceof ArrayBuffer){const y=new Uint8Array(p),_=new Uint8Array(h);if(y.length!==_.length)g=!0;else for(let x=0;x<y.length;x++)if(y[x]!==_[x]){g=!0;break}}g&&(await c.unsubscribe(),c=null)}catch{}return c||(c=await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:qy(u)})),await gM(c.toJSON())},[]),i=m.useCallback(async()=>{if(e){r("working");try{await s()?(localStorage.setItem(od,"1"),r("on")):r(l=>l==="denied"?"denied":"off")}catch{r("off")}}},[e,s]),o=m.useCallback(async()=>{r("working"),localStorage.removeItem(od);try{const l=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();l&&(await yM(l.endpoint),await l.unsubscribe())}catch{}r("off")},[]);return m.useEffect(()=>{if(!e||localStorage.getItem(od)!=="1")return;if(Notification.permission!=="granted"){r(Notification.permission==="denied"?"denied":"off");return}let a=!1;return(async()=>{try{const l=await s();a||r(l?"on":"off")}catch{a||r("off")}})(),()=>{a=!0}},[e,s]),{status:n,supported:e,iosHint:t,enable:i,disable:o}}const zf=70,FM=110,BM=.5,$M=".thread-viewport, .rail-scroll, .live-pane-body";function UM(e,t=()=>window.location.reload()){const[n,r]=m.useState(0),[s,i]=m.useState(!1),o=m.useRef(0),a=m.useRef(!1),l=m.useRef(0),u=m.useRef(null),c=f=>{o.current=f,r(f)};return m.useEffect(()=>{const f=e.current;if(!f)return;const h=y=>{if(y.touches.length!==1){a.current=!1;return}const x=y.target?.closest($M)??null;x&&x.scrollTop<=0?(u.current=x,l.current=y.touches[0].clientY,a.current=!0):a.current=!1},p=y=>{if(!a.current)return;const _=y.touches[0].clientY-l.current,x=u.current;if(_<=0||x&&x.scrollTop>0){o.current!==0&&c(0),x&&x.scrollTop>0&&(a.current=!1);return}const v=Math.min(FM,_*BM);c(v),y.cancelable&&y.preventDefault()},g=()=>{a.current&&(a.current=!1,o.current>=zf?(c(zf),i(!0),setTimeout(t,150)):c(0))};return f.addEventListener("touchstart",h,{passive:!0}),f.addEventListener("touchmove",p,{passive:!1}),f.addEventListener("touchend",g,{passive:!0}),f.addEventListener("touchcancel",g,{passive:!0}),()=>{f.removeEventListener("touchstart",h),f.removeEventListener("touchmove",p),f.removeEventListener("touchend",g),f.removeEventListener("touchcancel",g)}},[e,t]),{pull:n,refreshing:s}}const VM=zf,Tu="__cockpitSummary";function HM(e){if(e&&typeof e=="object"&&Tu in e){const t=e[Tu];return typeof t=="string"?t:""}return""}function Pk(e){if(!e||typeof e!="object")return e;const t={};for(const[n,r]of Object.entries(e))n!==Tu&&(t[n]=r);return t}function WM(e){if(e&&typeof e=="object"&&"text"in e){const t=e;return{text:String(t.text??""),isError:!!t.isError}}return null}function jk(e){const t=new Map;for(const s of e)for(const i of s.blocks??[])i.kind==="tool_result"&&t.set(i.forId,{text:i.text??"",isError:!!i.isError});const n=[],r=new Set;return e.forEach((s,i)=>{const o=GM(s.blocks??[],t,s.role==="user");if(o.length===0)return;const a=s.role==="user"?"user":"assistant";let l=s.uuid||`m-${i}`;r.has(l)&&(l=`${l}#${i}`),r.add(l),n.push({role:a,id:l,createdAt:s.ts?new Date(s.ts):void 0,content:o,metadata:{custom:{cockpitRole:s.role}}})}),KM(n)}function KM(e){const t=r=>r.role==="assistant"&&(r.metadata?.custom?.cockpitRole??"assistant")==="assistant",n=[];for(const r of e){const s=n[n.length-1];s&&t(s)&&t(r)?n[n.length-1]={...s,content:[...s.content,...r.content]}:n.push(r)}return n}function qM(e){const t=e.trimStart();if(!t.startsWith("<"))return null;const n=/<summary>([\s\S]*?)<\/summary>/.exec(t)?.[1]?.trim();return t.startsWith("<task-notification")?`⚙ background task ${n?`— ${n}`:"update"}`:t.startsWith("<system-reminder")?"⚙ system reminder":t.startsWith("<command-name")||t.startsWith("<command-message")?"⌘ slash command":t.startsWith("<local-command-stdout")?"⌘ command output":t.startsWith("<user-prompt-submit-hook")||t.startsWith("<session-")?"⚙ session hook":null}function GM(e,t,n=!1){const r=[];for(const s of e)switch(s.kind){case"text":{if(s.text&&s.text.length>0){const i=n?qM(s.text):null;r.push({type:"text",text:i??s.text})}break}case"thinking":{s.text&&s.text.trim().length>0&&r.push({type:"reasoning",text:s.text});break}case"tool_use":{const i=t.get(s.id),o=s.input&&typeof s.input=="object"?s.input:s.input!=null?{value:s.input}:{};r.push({type:"tool-call",toolCallId:s.id,toolName:s.name||"tool",args:{...o,[Tu]:s.inputSummary??""},argsText:s.inputSummary??"",result:i??void 0,isError:i?.isError});break}}return r}const YM="image/*,application/pdf,text/*,.md,.json,.csv,.log",Ff=" cockpit-path:";function QM(e){return Ff+e}const zl=new Map;function XM(e){return zl.get(e)??null}function JM(e){for(const t of e.content??[])if(t.type==="text"&&t.text.startsWith(Ff))return t.text.slice(Ff.length);return XM(e.id)}function ZM(e){return`${e.name}-${e.size}-${e.lastModified}`}function e2(e){return{accept:YM,async add({file:t}){const n=ZM(t),r=t.type.startsWith("image/"),s=t.type==="application/pdf",i={id:n,type:r?"image":s?"document":"file",name:t.name,contentType:t.type||"application/octet-stream",file:t};e(`Uploading ${t.name}…`);try{const o=await RM(t);return zl.set(n,o.path),e(`Attached ${o.name}`,"ok"),{...i,status:{type:"requires-action",reason:"composer-send"}}}catch(o){const a=o instanceof Error?o.message:String(o);return e(`Attach failed: ${a}`,"error"),{...i,status:{type:"incomplete",reason:"error"}}}},async send(t){const n=zl.get(t.id);if(!n)throw new Error(`attachment ${t.name} was not uploaded`);return{...t,status:{type:"complete"},content:[{type:"text",text:QM(n)}]}},async remove(t){zl.delete(t.id)}}}function mr(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ak(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}/*!
45
45
  * GSAP 3.15.0
46
46
  * https://gsap.com
47
47
  *
@@ -87,7 +87,7 @@ ${s.system}`:r.system=s.system),s.tools)for(const[o,a]of Object.entries(s.tools)
87
87
  `))+1))}const o="#".repeat(s),a=n.enter("headingAtx"),l=n.enter("phrasing");i.move(o+" ");let u=n.containerPhrasing(e,{before:"# ",after:`
88
88
  `,...i.current()});return/^[\t ]/.test(u)&&(u=Ea(u.charCodeAt(0))+u.slice(1)),u=u?o+" "+u:o,n.options.closeAtx&&(u+=" "+o),l(),a(),u}E1.peek=L4;function E1(e){return e.value||""}function L4(){return"<"}T1.peek=z4;function T1(e,t,n,r){const s=vm(n),i=s==='"'?"Quote":"Apostrophe",o=n.enter("image");let a=n.enter("label");const l=n.createTracker(r);let u=l.move("![");return u+=l.move(n.safe(e.alt,{before:u,after:"]",...l.current()})),u+=l.move("]("),a(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(a=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),a(),e.title&&(a=n.enter(`title${i}`),u+=l.move(" "+s),u+=l.move(n.safe(e.title,{before:u,after:s,...l.current()})),u+=l.move(s),a()),u+=l.move(")"),o(),u}function z4(){return"!"}I1.peek=F4;function I1(e,t,n,r){const s=e.referenceType,i=n.enter("imageReference");let o=n.enter("label");const a=n.createTracker(r);let l=a.move("![");const u=n.safe(e.alt,{before:l,after:"]",...a.current()});l+=a.move(u+"]["),o();const c=n.stack;n.stack=[],o=n.enter("reference");const f=n.safe(n.associationId(e),{before:l,after:"]",...a.current()});return o(),n.stack=c,i(),s==="full"||!u||u!==f?l+=a.move(f+"]"):s==="shortcut"?l=l.slice(0,-1):l+=a.move("]"),l}function F4(){return"!"}R1.peek=B4;function R1(e,t,n){let r=e.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(r);)s+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++i<n.unsafe.length;){const o=n.unsafe[i],a=n.compilePattern(o);let l;if(o.atBreak)for(;l=a.exec(r);){let u=l.index;r.charCodeAt(u)===10&&r.charCodeAt(u-1)===13&&u--,r=r.slice(0,u)+" "+r.slice(l.index+1)}}return s+r+s}function B4(){return"`"}function P1(e,t){const n=um(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}j1.peek=$4;function j1(e,t,n,r){const s=vm(n),i=s==='"'?"Quote":"Apostrophe",o=n.createTracker(r);let a,l;if(P1(e,n)){const c=n.stack;n.stack=[],a=n.enter("autolink");let f=o.move("<");return f+=o.move(n.containerPhrasing(e,{before:f,after:">",...o.current()})),f+=o.move(">"),a(),n.stack=c,f}a=n.enter("link"),l=n.enter("label");let u=o.move("[");return u+=o.move(n.containerPhrasing(e,{before:u,after:"](",...o.current()})),u+=o.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),u+=o.move("<"),u+=o.move(n.safe(e.url,{before:u,after:">",...o.current()})),u+=o.move(">")):(l=n.enter("destinationRaw"),u+=o.move(n.safe(e.url,{before:u,after:e.title?" ":")",...o.current()}))),l(),e.title&&(l=n.enter(`title${i}`),u+=o.move(" "+s),u+=o.move(n.safe(e.title,{before:u,after:s,...o.current()})),u+=o.move(s),l()),u+=o.move(")"),a(),u}function $4(e,t,n){return P1(e,n)?"<":"["}A1.peek=U4;function A1(e,t,n,r){const s=e.referenceType,i=n.enter("linkReference");let o=n.enter("label");const a=n.createTracker(r);let l=a.move("[");const u=n.containerPhrasing(e,{before:l,after:"]",...a.current()});l+=a.move(u+"]["),o();const c=n.stack;n.stack=[],o=n.enter("reference");const f=n.safe(n.associationId(e),{before:l,after:"]",...a.current()});return o(),n.stack=c,i(),s==="full"||!u||u!==f?l+=a.move(f+"]"):s==="shortcut"?l=l.slice(0,-1):l+=a.move("]"),l}function U4(){return"["}function xm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function V4(e){const t=xm(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function H4(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function N1(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function W4(e,t,n,r){const s=n.enter("list"),i=n.bulletCurrent;let o=e.ordered?H4(n):xm(n);const a=e.ordered?o==="."?")":".":V4(n);let l=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){const c=e.children?e.children[0]:void 0;if((o==="*"||o==="-")&&c&&(!c.children||!c.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(l=!0),N1(n)===o&&c){let f=-1;for(;++f<e.children.length;){const h=e.children[f];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(o=a),n.bulletCurrent=o;const u=n.containerFlow(e,r);return n.bulletLastUsed=o,n.bulletCurrent=i,s(),u}function K4(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function q4(e,t,n,r){const s=K4(n);let i=n.bulletCurrent||xm(n);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let o=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);const a=n.createTracker(r);a.move(i+" ".repeat(o-i.length)),a.shift(o);const l=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,a.current()),c);return l(),u;function c(f,h,p){return h?(p?"":" ".repeat(o))+f:(p?i:i+" ".repeat(o-i.length))+f}}function G4(e,t,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),o=n.containerPhrasing(e,r);return i(),s(),o}const Y4=xc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Q4(e,t,n,r){return(e.children.some(function(o){return Y4(o)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function X4(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}M1.peek=J4;function M1(e,t,n,r){const s=X4(n),i=n.enter("strong"),o=n.createTracker(r),a=o.move(s+s);let l=o.move(n.containerPhrasing(e,{after:s,before:a,...o.current()}));const u=l.charCodeAt(0),c=Fu(r.before.charCodeAt(r.before.length-1),u,s);c.inside&&(l=Ea(u)+l.slice(1));const f=l.charCodeAt(l.length-1),h=Fu(r.after.charCodeAt(0),f,s);h.inside&&(l=l.slice(0,-1)+Ea(f));const p=o.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:h.outside,before:c.outside},a+l+p}function J4(e,t,n){return n.options.strong||"*"}function Z4(e,t,n,r){return n.safe(e.value,r)}function e3(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function t3(e,t,n){const r=(N1(n)+(n.options.ruleSpaces?" ":"")).repeat(e3(n));return n.options.ruleSpaces?r.slice(0,-1):r}const D1={blockquote:S4,break:ix,code:P4,definition:A4,emphasis:C1,hardBreak:ix,heading:O4,html:E1,image:T1,imageReference:I1,inlineCode:R1,link:j1,linkReference:A1,list:W4,listItem:q4,paragraph:G4,root:Q4,strong:M1,text:Z4,thematicBreak:t3};function n3(){return{enter:{table:r3,tableData:ox,tableHeader:ox,tableRow:i3},exit:{codeText:o3,table:s3,tableData:Rd,tableHeader:Rd,tableRow:Rd}}}function r3(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function s3(e){this.exit(e),this.data.inTable=void 0}function i3(e){this.enter({type:"tableRow",children:[]},e)}function Rd(e){this.exit(e)}function ox(e){this.enter({type:"tableCell",children:[]},e)}function o3(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,a3));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function a3(e,t){return t==="|"?t:e}function l3(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,s=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
89
89
  `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:h,table:o,tableCell:l,tableRow:a}};function o(p,g,y,_){return u(c(p,y,_),p.align)}function a(p,g,y,_){const x=f(p,y,_),v=u([x]);return v.slice(0,v.indexOf(`
90
- `))}function l(p,g,y,_){const x=y.enter("tableCell"),v=y.enter("phrasing"),w=y.containerPhrasing(p,{..._,before:i,after:i});return v(),x(),w}function u(p,g){return b4(p,{align:g,alignDelimiters:r,padding:n,stringLength:s})}function c(p,g,y){const _=p.children;let x=-1;const v=[],w=g.enter("table");for(;++x<_.length;)v[x]=f(_[x],g,y);return w(),v}function f(p,g,y){const _=p.children;let x=-1;const v=[],w=g.enter("tableRow");for(;++x<_.length;)v[x]=l(_[x],p,g,y);return w(),v}function h(p,g,y){let _=D1.inlineCode(p,g,y);return y.stack.includes("tableCell")&&(_=_.replace(/\|/g,"\\$&")),_}}function u3(){return{exit:{taskListCheckValueChecked:ax,taskListCheckValueUnchecked:ax,paragraph:d3}}}function c3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:f3}}}function ax(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function d3(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const s=t.children;let i=-1,o;for(;++i<s.length;){const a=s[i];if(a.type==="paragraph"){o=a;break}}o===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function f3(e,t,n,r){const s=e.children[0],i=typeof e.checked=="boolean"&&s&&s.type==="paragraph",o="["+(e.checked?"x":" ")+"] ",a=n.createTracker(r);i&&a.move(o);let l=D1.listItem(e,t,n,{...r,...a.current()});return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(c){return c+o}}function h3(){return[WB(),f4(),g4(),n3(),u3()]}function p3(e){return{extensions:[KB(),h4(e),y4(),l3(e),c3()]}}const m3={tokenize:_3,partial:!0},O1={tokenize:b3,partial:!0},L1={tokenize:k3,partial:!0},z1={tokenize:S3,partial:!0},g3={tokenize:C3,partial:!0},F1={name:"wwwAutolink",tokenize:x3,previous:$1},B1={name:"protocolAutolink",tokenize:w3,previous:U1},Pr={name:"emailAutolink",tokenize:v3,previous:V1},dr={};function y3(){return{text:dr}}let xs=48;for(;xs<123;)dr[xs]=Pr,xs++,xs===58?xs=65:xs===91&&(xs=97);dr[43]=Pr;dr[45]=Pr;dr[46]=Pr;dr[95]=Pr;dr[72]=[Pr,B1];dr[104]=[Pr,B1];dr[87]=[Pr,F1];dr[119]=[Pr,F1];function v3(e,t,n){const r=this;let s,i;return o;function o(f){return!hh(f)||!V1.call(r,r.previous)||wm(r.events)?n(f):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),a(f))}function a(f){return hh(f)?(e.consume(f),a):f===64?(e.consume(f),l):n(f)}function l(f){return f===46?e.check(g3,c,u)(f):f===45||f===95||Et(f)?(i=!0,e.consume(f),l):c(f)}function u(f){return e.consume(f),s=!0,l}function c(f){return i&&s&&Nt(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(f)):n(f)}}function x3(e,t,n){const r=this;return s;function s(o){return o!==87&&o!==119||!$1.call(r,r.previous)||wm(r.events)?n(o):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(m3,e.attempt(O1,e.attempt(L1,i),n),n)(o))}function i(o){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(o)}}function w3(e,t,n){const r=this;let s="",i=!1;return o;function o(f){return(f===72||f===104)&&U1.call(r,r.previous)&&!wm(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(f),e.consume(f),a):n(f)}function a(f){if(Nt(f)&&s.length<5)return s+=String.fromCodePoint(f),e.consume(f),a;if(f===58){const h=s.toLowerCase();if(h==="http"||h==="https")return e.consume(f),l}return n(f)}function l(f){return f===47?(e.consume(f),i?u:(i=!0,l)):n(f)}function u(f){return f===null||Ou(f)||Re(f)||Vs(f)||gc(f)?n(f):e.attempt(O1,e.attempt(L1,c),n)(f)}function c(f){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(f)}}function _3(e,t,n){let r=0;return s;function s(o){return(o===87||o===119)&&r<3?(r++,e.consume(o),s):o===46&&r===3?(e.consume(o),i):n(o)}function i(o){return o===null?n(o):t(o)}}function b3(e,t,n){let r,s,i;return o;function o(u){return u===46||u===95?e.check(z1,l,a)(u):u===null||Re(u)||Vs(u)||u!==45&&gc(u)?l(u):(i=!0,e.consume(u),o)}function a(u){return u===95?r=!0:(s=r,r=void 0),e.consume(u),o}function l(u){return s||r||!i?n(u):t(u)}}function k3(e,t){let n=0,r=0;return s;function s(o){return o===40?(n++,e.consume(o),s):o===41&&r<n?i(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(z1,t,i)(o):o===null||Re(o)||Vs(o)?t(o):(e.consume(o),s)}function i(o){return o===41&&r++,e.consume(o),s}}function S3(e,t,n){return r;function r(a){return a===33||a===34||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===63||a===95||a===126?(e.consume(a),r):a===38?(e.consume(a),i):a===93?(e.consume(a),s):a===60||a===null||Re(a)||Vs(a)?t(a):n(a)}function s(a){return a===null||a===40||a===91||Re(a)||Vs(a)?t(a):r(a)}function i(a){return Nt(a)?o(a):n(a)}function o(a){return a===59?(e.consume(a),r):Nt(a)?(e.consume(a),o):n(a)}}function C3(e,t,n){return r;function r(i){return e.consume(i),s}function s(i){return Et(i)?n(i):t(i)}}function $1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Re(e)}function U1(e){return!Nt(e)}function V1(e){return!(e===47||hh(e))}function hh(e){return e===43||e===45||e===46||e===95||Et(e)}function wm(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const E3={tokenize:M3,partial:!0};function T3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:j3,continuation:{tokenize:A3},exit:N3}},text:{91:{name:"gfmFootnoteCall",tokenize:P3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:I3,resolveTo:R3}}}}function I3(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o;for(;s--;){const l=r.events[s][1];if(l.type==="labelImage"){o=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return a;function a(l){if(!o||!o._balanced)return n(l);const u=Un(r.sliceSerialize({start:o.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function R3(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},a=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",o,t],["exit",o,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function P3(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,o;return a;function a(f){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(f),e.exit("gfmFootnoteCallLabelMarker"),l}function l(f){return f!==94?n(f):(e.enter("gfmFootnoteCallMarker"),e.consume(f),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(f){if(i>999||f===93&&!o||f===null||f===91||Re(f))return n(f);if(f===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return s.includes(Un(r.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(f),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(f)}return Re(f)||(o=!0),i++,e.consume(f),f===92?c:u}function c(f){return f===91||f===92||f===93?(e.consume(f),i++,u):u(f)}}function j3(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,o=0,a;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(g)}function c(g){if(o>999||g===93&&!a||g===null||g===91||Re(g))return n(g);if(g===93){e.exit("chunkString");const y=e.exit("gfmFootnoteDefinitionLabelString");return i=Un(r.sliceSerialize(y)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return Re(g)||(a=!0),o++,e.consume(g),g===92?f:c}function f(g){return g===91||g===92||g===93?(e.consume(g),o++,c):c(g)}function h(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),s.includes(i)||s.push(i),_e(e,p,"gfmFootnoteDefinitionWhitespace")):n(g)}function p(g){return t(g)}}function A3(e,t,n){return e.check(za,t,e.attempt(E3,t,n))}function N3(e){e.exit("gfmFootnoteDefinition")}function M3(e,t,n){const r=this;return _e(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const o=r.events[r.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(i):n(i)}}function D3(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(o,a){let l=-1;for(;++l<o.length;)if(o[l][0]==="enter"&&o[l][1].type==="strikethroughSequenceTemporary"&&o[l][1]._close){let u=l;for(;u--;)if(o[u][0]==="exit"&&o[u][1].type==="strikethroughSequenceTemporary"&&o[u][1]._open&&o[l][1].end.offset-o[l][1].start.offset===o[u][1].end.offset-o[u][1].start.offset){o[l][1].type="strikethroughSequence",o[u][1].type="strikethroughSequence";const c={type:"strikethrough",start:Object.assign({},o[u][1].start),end:Object.assign({},o[l][1].end)},f={type:"strikethroughText",start:Object.assign({},o[u][1].end),end:Object.assign({},o[l][1].start)},h=[["enter",c,a],["enter",o[u][1],a],["exit",o[u][1],a],["enter",f,a]],p=a.parser.constructs.insideSpan.null;p&&un(h,h.length,0,yc(p,o.slice(u+1,l),a)),un(h,h.length,0,[["exit",f,a],["enter",o[l][1],a],["exit",o[l][1],a],["exit",c,a]]),un(o,u-1,l-u+3,h),l=u+h.length-2;break}}for(l=-1;++l<o.length;)o[l][1].type==="strikethroughSequenceTemporary"&&(o[l][1].type="data");return o}function i(o,a,l){const u=this.previous,c=this.events;let f=0;return h;function h(g){return u===126&&c[c.length-1][1].type!=="characterEscape"?l(g):(o.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const y=Xi(u);if(g===126)return f>1?l(g):(o.consume(g),f++,p);if(f<2&&!n)return l(g);const _=o.exit("strikethroughSequenceTemporary"),x=Xi(g);return _._open=!x||x===2&&!!y,_._close=!y||y===2&&!!x,a(g)}}}class O3{constructor(){this.map=[]}add(t,n,r){L3(this,t,n,r)}consume(t){if(this.map.sort(function(i,o){return i[0]-o[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const i of s)t.push(i);s=r.pop()}this.map.length=0}}function L3(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s<e.map.length;){if(e.map[s][0]===t){e.map[s][1]+=n,e.map[s][2].push(...r);return}s+=1}e.map.push([t,n,r])}}function z3(e,t){let n=!1;const r=[];for(;t<e.length;){const s=e[t];if(n){if(s[0]==="enter")s[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(s[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=r.length-1;r[i]=r[i]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function F3(){return{flow:{null:{name:"table",tokenize:B3,resolveAll:$3}}}}function B3(e,t,n){const r=this;let s=0,i=0,o;return a;function a(E){let M=r.events.length-1;for(;M>-1;){const Q=r.events[M][1].type;if(Q==="lineEnding"||Q==="linePrefix")M--;else break}const O=M>-1?r.events[M][1].type:null,W=O==="tableHead"||O==="tableRow"?k:l;return W===k&&r.parser.lazy[r.now().line]?n(E):W(E)}function l(E){return e.enter("tableHead"),e.enter("tableRow"),u(E)}function u(E){return E===124||(o=!0,i+=1),c(E)}function c(E){return E===null?n(E):se(E)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):n(E):me(E)?_e(e,c,"whitespace")(E):(i+=1,o&&(o=!1,s+=1),E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),o=!0,c):(e.enter("data"),f(E)))}function f(E){return E===null||E===124||Re(E)?(e.exit("data"),c(E)):(e.consume(E),E===92?h:f)}function h(E){return E===92||E===124?(e.consume(E),f):f(E)}function p(E){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(E):(e.enter("tableDelimiterRow"),o=!1,me(E)?_e(e,g,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):g(E))}function g(E){return E===45||E===58?_(E):E===124?(o=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),y):S(E)}function y(E){return me(E)?_e(e,_,"whitespace")(E):_(E)}function _(E){return E===58?(i+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),x):E===45?(i+=1,x(E)):E===null||se(E)?C(E):S(E)}function x(E){return E===45?(e.enter("tableDelimiterFiller"),v(E)):S(E)}function v(E){return E===45?(e.consume(E),v):E===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),w):(e.exit("tableDelimiterFiller"),w(E))}function w(E){return me(E)?_e(e,C,"whitespace")(E):C(E)}function C(E){return E===124?g(E):E===null||se(E)?!o||s!==i?S(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(E)):S(E)}function S(E){return n(E)}function k(E){return e.enter("tableRow"),T(E)}function T(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),T):E===null||se(E)?(e.exit("tableRow"),t(E)):me(E)?_e(e,T,"whitespace")(E):(e.enter("data"),R(E))}function R(E){return E===null||E===124||Re(E)?(e.exit("data"),T(E)):(e.consume(E),E===92?P:R)}function P(E){return E===92||E===124?(e.consume(E),R):R(E)}}function $3(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],o=[0,0,0,0],a=!1,l=0,u,c,f;const h=new O3;for(;++n<e.length;){const p=e[n],g=p[1];p[0]==="enter"?g.type==="tableHead"?(a=!1,l!==0&&(lx(h,t,l,u,c),c=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(n,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(r=!0,f=void 0,i=[0,0,0,0],o=[0,n+1,0,0],a&&(a=!1,c={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(n,0,[["enter",c,t]])),s=g.type==="tableDelimiterRow"?2:c?3:1):s&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(r=!1,o[2]===0&&(i[1]!==0&&(o[0]=o[1],f=wl(h,t,i,s,void 0,f),i=[0,0,0,0]),o[2]=n)):g.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(o[0]=o[1],f=wl(h,t,i,s,void 0,f)),i=o,o=[i[1],n,0,0])):g.type==="tableHead"?(a=!0,l=n):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=n,i[1]!==0?(o[0]=o[1],f=wl(h,t,i,s,n,f)):o[1]!==0&&(f=wl(h,t,o,s,n,f)),s=0):s&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(o[3]=n)}for(l!==0&&lx(h,t,l,u,c),h.consume(t.events),n=-1;++n<t.events.length;){const p=t.events[n];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=z3(t.events,n))}return e}function wl(e,t,n,r,s,i){const o=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",a="tableContent";n[0]!==0&&(i.end=Object.assign({},ui(t.events,n[0])),e.add(n[0],0,[["exit",i,t]]));const l=ui(t.events,n[1]);if(i={type:o,start:Object.assign({},l),end:Object.assign({},l)},e.add(n[1],0,[["enter",i,t]]),n[2]!==0){const u=ui(t.events,n[2]),c=ui(t.events,n[3]),f={type:a,start:Object.assign({},u),end:Object.assign({},c)};if(e.add(n[2],0,[["enter",f,t]]),r!==2){const h=t.events[n[2]],p=t.events[n[3]];if(h[1].end=Object.assign({},p[1].end),h[1].type="chunkText",h[1].contentType="text",n[3]>n[2]+1){const g=n[2]+1,y=n[3]-n[2]-1;e.add(g,y,[])}}e.add(n[3]+1,0,[["exit",f,t]])}return s!==void 0&&(i.end=Object.assign({},ui(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function lx(e,t,n,r,s){const i=[],o=ui(t.events,n);s&&(s.end=Object.assign({},o),i.push(["exit",s,t])),r.end=Object.assign({},o),i.push(["exit",r,t]),e.add(n+1,0,i)}function ui(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const U3={name:"tasklistCheck",tokenize:H3};function V3(){return{text:{91:U3}}}function H3(e,t,n){const r=this;return s;function s(l){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),i)}function i(l){return Re(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),o):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),o):n(l)}function o(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),a):n(l)}function a(l){return se(l)?t(l):me(l)?e.check({tokenize:W3},t,n)(l):n(l)}}function W3(e,t,n){return _e(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function K3(e){return JS([y3(),T3(),D3(e),F3(),V3()])}const q3={};function G3(e){const t=this,n=e||q3,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),o=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(K3(n)),i.push(h3()),o.push(p3(n))}const Y3="modulepreload",Q3=function(e,t){return new URL(e,t).href},ux={},Yn=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){const o=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=Promise.allSettled(n.map(u=>{if(u=Q3(u,r),u in ux)return;ux[u]=!0;const c=u.endsWith(".css"),f=c?'[rel="stylesheet"]':"";if(!!r)for(let g=o.length-1;g>=0;g--){const y=o[g];if(y.href===u&&(!c||y.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${u}"]${f}`))return;const p=document.createElement("link");if(p.rel=c?"stylesheet":Y3,c||(p.as="script"),p.crossOrigin="",p.href=u,l&&p.setAttribute("nonce",l),document.head.appendChild(p),c)return new Promise((g,y)=>{p.addEventListener("load",g),p.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})},X3={ts:"typescript",typescript:"typescript",tsx:"typescript",js:"javascript",javascript:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",json:"json",jsonc:"json",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",py:"python",python:"python",diff:"diff",patch:"diff",md:"markdown",markdown:"markdown",html:"xml",xml:"xml",css:"css"};function _m(e){return e?X3[e.trim().toLowerCase()]??null:null}let Pd=null;async function J3(){return Pd||(Pd=(async()=>{const{default:e}=await Yn(async()=>{const{default:c}=await import("./core-7jLm1R4l.js");return{default:c}},[],import.meta.url),[t,n,r,s,i,o,a,l,u]=await Promise.all([Yn(()=>import("./typescript-C2FFdlUC.js"),[],import.meta.url),Yn(()=>import("./javascript-BKRaQes9.js"),[],import.meta.url),Yn(()=>import("./json-DIYVocXf.js"),[],import.meta.url),Yn(()=>import("./bash-I8pq0VWm.js"),[],import.meta.url),Yn(()=>import("./python-sE43i1Pi.js"),[],import.meta.url),Yn(()=>import("./diff-DiTmLxSS.js"),[],import.meta.url),Yn(()=>import("./markdown-BrP960CR.js"),[],import.meta.url),Yn(()=>import("./xml-BXBhIUeX.js"),[],import.meta.url),Yn(()=>import("./css-DazXZka4.js"),[],import.meta.url)]);return e.registerLanguage("typescript",t.default),e.registerLanguage("javascript",n.default),e.registerLanguage("json",r.default),e.registerLanguage("bash",s.default),e.registerLanguage("python",i.default),e.registerLanguage("diff",o.default),e.registerLanguage("markdown",a.default),e.registerLanguage("xml",l.default),e.registerLanguage("css",u.default),e})()),Pd}async function H1(e,t){const n=_m(e);if(!n)return null;try{const r=await J3(),{value:s}=r.highlight(t,{language:n,ignoreIllegals:!0});return s}catch{return null}}function Z3(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n),t=t>>>0;return t.toString(36)}function e$(e,t){return"code-"+Z3((e??"")+`
90
+ `))}function l(p,g,y,_){const x=y.enter("tableCell"),v=y.enter("phrasing"),w=y.containerPhrasing(p,{..._,before:i,after:i});return v(),x(),w}function u(p,g){return b4(p,{align:g,alignDelimiters:r,padding:n,stringLength:s})}function c(p,g,y){const _=p.children;let x=-1;const v=[],w=g.enter("table");for(;++x<_.length;)v[x]=f(_[x],g,y);return w(),v}function f(p,g,y){const _=p.children;let x=-1;const v=[],w=g.enter("tableRow");for(;++x<_.length;)v[x]=l(_[x],p,g,y);return w(),v}function h(p,g,y){let _=D1.inlineCode(p,g,y);return y.stack.includes("tableCell")&&(_=_.replace(/\|/g,"\\$&")),_}}function u3(){return{exit:{taskListCheckValueChecked:ax,taskListCheckValueUnchecked:ax,paragraph:d3}}}function c3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:f3}}}function ax(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function d3(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const s=t.children;let i=-1,o;for(;++i<s.length;){const a=s[i];if(a.type==="paragraph"){o=a;break}}o===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function f3(e,t,n,r){const s=e.children[0],i=typeof e.checked=="boolean"&&s&&s.type==="paragraph",o="["+(e.checked?"x":" ")+"] ",a=n.createTracker(r);i&&a.move(o);let l=D1.listItem(e,t,n,{...r,...a.current()});return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(c){return c+o}}function h3(){return[WB(),f4(),g4(),n3(),u3()]}function p3(e){return{extensions:[KB(),h4(e),y4(),l3(e),c3()]}}const m3={tokenize:_3,partial:!0},O1={tokenize:b3,partial:!0},L1={tokenize:k3,partial:!0},z1={tokenize:S3,partial:!0},g3={tokenize:C3,partial:!0},F1={name:"wwwAutolink",tokenize:x3,previous:$1},B1={name:"protocolAutolink",tokenize:w3,previous:U1},Pr={name:"emailAutolink",tokenize:v3,previous:V1},dr={};function y3(){return{text:dr}}let xs=48;for(;xs<123;)dr[xs]=Pr,xs++,xs===58?xs=65:xs===91&&(xs=97);dr[43]=Pr;dr[45]=Pr;dr[46]=Pr;dr[95]=Pr;dr[72]=[Pr,B1];dr[104]=[Pr,B1];dr[87]=[Pr,F1];dr[119]=[Pr,F1];function v3(e,t,n){const r=this;let s,i;return o;function o(f){return!hh(f)||!V1.call(r,r.previous)||wm(r.events)?n(f):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),a(f))}function a(f){return hh(f)?(e.consume(f),a):f===64?(e.consume(f),l):n(f)}function l(f){return f===46?e.check(g3,c,u)(f):f===45||f===95||Et(f)?(i=!0,e.consume(f),l):c(f)}function u(f){return e.consume(f),s=!0,l}function c(f){return i&&s&&Nt(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(f)):n(f)}}function x3(e,t,n){const r=this;return s;function s(o){return o!==87&&o!==119||!$1.call(r,r.previous)||wm(r.events)?n(o):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(m3,e.attempt(O1,e.attempt(L1,i),n),n)(o))}function i(o){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(o)}}function w3(e,t,n){const r=this;let s="",i=!1;return o;function o(f){return(f===72||f===104)&&U1.call(r,r.previous)&&!wm(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(f),e.consume(f),a):n(f)}function a(f){if(Nt(f)&&s.length<5)return s+=String.fromCodePoint(f),e.consume(f),a;if(f===58){const h=s.toLowerCase();if(h==="http"||h==="https")return e.consume(f),l}return n(f)}function l(f){return f===47?(e.consume(f),i?u:(i=!0,l)):n(f)}function u(f){return f===null||Ou(f)||Re(f)||Vs(f)||gc(f)?n(f):e.attempt(O1,e.attempt(L1,c),n)(f)}function c(f){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(f)}}function _3(e,t,n){let r=0;return s;function s(o){return(o===87||o===119)&&r<3?(r++,e.consume(o),s):o===46&&r===3?(e.consume(o),i):n(o)}function i(o){return o===null?n(o):t(o)}}function b3(e,t,n){let r,s,i;return o;function o(u){return u===46||u===95?e.check(z1,l,a)(u):u===null||Re(u)||Vs(u)||u!==45&&gc(u)?l(u):(i=!0,e.consume(u),o)}function a(u){return u===95?r=!0:(s=r,r=void 0),e.consume(u),o}function l(u){return s||r||!i?n(u):t(u)}}function k3(e,t){let n=0,r=0;return s;function s(o){return o===40?(n++,e.consume(o),s):o===41&&r<n?i(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(z1,t,i)(o):o===null||Re(o)||Vs(o)?t(o):(e.consume(o),s)}function i(o){return o===41&&r++,e.consume(o),s}}function S3(e,t,n){return r;function r(a){return a===33||a===34||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===63||a===95||a===126?(e.consume(a),r):a===38?(e.consume(a),i):a===93?(e.consume(a),s):a===60||a===null||Re(a)||Vs(a)?t(a):n(a)}function s(a){return a===null||a===40||a===91||Re(a)||Vs(a)?t(a):r(a)}function i(a){return Nt(a)?o(a):n(a)}function o(a){return a===59?(e.consume(a),r):Nt(a)?(e.consume(a),o):n(a)}}function C3(e,t,n){return r;function r(i){return e.consume(i),s}function s(i){return Et(i)?n(i):t(i)}}function $1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Re(e)}function U1(e){return!Nt(e)}function V1(e){return!(e===47||hh(e))}function hh(e){return e===43||e===45||e===46||e===95||Et(e)}function wm(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const E3={tokenize:M3,partial:!0};function T3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:j3,continuation:{tokenize:A3},exit:N3}},text:{91:{name:"gfmFootnoteCall",tokenize:P3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:I3,resolveTo:R3}}}}function I3(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o;for(;s--;){const l=r.events[s][1];if(l.type==="labelImage"){o=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return a;function a(l){if(!o||!o._balanced)return n(l);const u=Un(r.sliceSerialize({start:o.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function R3(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},a=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",o,t],["exit",o,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function P3(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,o;return a;function a(f){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(f),e.exit("gfmFootnoteCallLabelMarker"),l}function l(f){return f!==94?n(f):(e.enter("gfmFootnoteCallMarker"),e.consume(f),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(f){if(i>999||f===93&&!o||f===null||f===91||Re(f))return n(f);if(f===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return s.includes(Un(r.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(f),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(f)}return Re(f)||(o=!0),i++,e.consume(f),f===92?c:u}function c(f){return f===91||f===92||f===93?(e.consume(f),i++,u):u(f)}}function j3(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,o=0,a;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(g)}function c(g){if(o>999||g===93&&!a||g===null||g===91||Re(g))return n(g);if(g===93){e.exit("chunkString");const y=e.exit("gfmFootnoteDefinitionLabelString");return i=Un(r.sliceSerialize(y)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return Re(g)||(a=!0),o++,e.consume(g),g===92?f:c}function f(g){return g===91||g===92||g===93?(e.consume(g),o++,c):c(g)}function h(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),s.includes(i)||s.push(i),_e(e,p,"gfmFootnoteDefinitionWhitespace")):n(g)}function p(g){return t(g)}}function A3(e,t,n){return e.check(za,t,e.attempt(E3,t,n))}function N3(e){e.exit("gfmFootnoteDefinition")}function M3(e,t,n){const r=this;return _e(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const o=r.events[r.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(i):n(i)}}function D3(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(o,a){let l=-1;for(;++l<o.length;)if(o[l][0]==="enter"&&o[l][1].type==="strikethroughSequenceTemporary"&&o[l][1]._close){let u=l;for(;u--;)if(o[u][0]==="exit"&&o[u][1].type==="strikethroughSequenceTemporary"&&o[u][1]._open&&o[l][1].end.offset-o[l][1].start.offset===o[u][1].end.offset-o[u][1].start.offset){o[l][1].type="strikethroughSequence",o[u][1].type="strikethroughSequence";const c={type:"strikethrough",start:Object.assign({},o[u][1].start),end:Object.assign({},o[l][1].end)},f={type:"strikethroughText",start:Object.assign({},o[u][1].end),end:Object.assign({},o[l][1].start)},h=[["enter",c,a],["enter",o[u][1],a],["exit",o[u][1],a],["enter",f,a]],p=a.parser.constructs.insideSpan.null;p&&un(h,h.length,0,yc(p,o.slice(u+1,l),a)),un(h,h.length,0,[["exit",f,a],["enter",o[l][1],a],["exit",o[l][1],a],["exit",c,a]]),un(o,u-1,l-u+3,h),l=u+h.length-2;break}}for(l=-1;++l<o.length;)o[l][1].type==="strikethroughSequenceTemporary"&&(o[l][1].type="data");return o}function i(o,a,l){const u=this.previous,c=this.events;let f=0;return h;function h(g){return u===126&&c[c.length-1][1].type!=="characterEscape"?l(g):(o.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const y=Xi(u);if(g===126)return f>1?l(g):(o.consume(g),f++,p);if(f<2&&!n)return l(g);const _=o.exit("strikethroughSequenceTemporary"),x=Xi(g);return _._open=!x||x===2&&!!y,_._close=!y||y===2&&!!x,a(g)}}}class O3{constructor(){this.map=[]}add(t,n,r){L3(this,t,n,r)}consume(t){if(this.map.sort(function(i,o){return i[0]-o[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const i of s)t.push(i);s=r.pop()}this.map.length=0}}function L3(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s<e.map.length;){if(e.map[s][0]===t){e.map[s][1]+=n,e.map[s][2].push(...r);return}s+=1}e.map.push([t,n,r])}}function z3(e,t){let n=!1;const r=[];for(;t<e.length;){const s=e[t];if(n){if(s[0]==="enter")s[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(s[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=r.length-1;r[i]=r[i]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function F3(){return{flow:{null:{name:"table",tokenize:B3,resolveAll:$3}}}}function B3(e,t,n){const r=this;let s=0,i=0,o;return a;function a(E){let M=r.events.length-1;for(;M>-1;){const Q=r.events[M][1].type;if(Q==="lineEnding"||Q==="linePrefix")M--;else break}const O=M>-1?r.events[M][1].type:null,W=O==="tableHead"||O==="tableRow"?k:l;return W===k&&r.parser.lazy[r.now().line]?n(E):W(E)}function l(E){return e.enter("tableHead"),e.enter("tableRow"),u(E)}function u(E){return E===124||(o=!0,i+=1),c(E)}function c(E){return E===null?n(E):se(E)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):n(E):me(E)?_e(e,c,"whitespace")(E):(i+=1,o&&(o=!1,s+=1),E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),o=!0,c):(e.enter("data"),f(E)))}function f(E){return E===null||E===124||Re(E)?(e.exit("data"),c(E)):(e.consume(E),E===92?h:f)}function h(E){return E===92||E===124?(e.consume(E),f):f(E)}function p(E){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(E):(e.enter("tableDelimiterRow"),o=!1,me(E)?_e(e,g,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):g(E))}function g(E){return E===45||E===58?_(E):E===124?(o=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),y):S(E)}function y(E){return me(E)?_e(e,_,"whitespace")(E):_(E)}function _(E){return E===58?(i+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),x):E===45?(i+=1,x(E)):E===null||se(E)?C(E):S(E)}function x(E){return E===45?(e.enter("tableDelimiterFiller"),v(E)):S(E)}function v(E){return E===45?(e.consume(E),v):E===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),w):(e.exit("tableDelimiterFiller"),w(E))}function w(E){return me(E)?_e(e,C,"whitespace")(E):C(E)}function C(E){return E===124?g(E):E===null||se(E)?!o||s!==i?S(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(E)):S(E)}function S(E){return n(E)}function k(E){return e.enter("tableRow"),T(E)}function T(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),T):E===null||se(E)?(e.exit("tableRow"),t(E)):me(E)?_e(e,T,"whitespace")(E):(e.enter("data"),R(E))}function R(E){return E===null||E===124||Re(E)?(e.exit("data"),T(E)):(e.consume(E),E===92?P:R)}function P(E){return E===92||E===124?(e.consume(E),R):R(E)}}function $3(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],o=[0,0,0,0],a=!1,l=0,u,c,f;const h=new O3;for(;++n<e.length;){const p=e[n],g=p[1];p[0]==="enter"?g.type==="tableHead"?(a=!1,l!==0&&(lx(h,t,l,u,c),c=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(n,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(r=!0,f=void 0,i=[0,0,0,0],o=[0,n+1,0,0],a&&(a=!1,c={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(n,0,[["enter",c,t]])),s=g.type==="tableDelimiterRow"?2:c?3:1):s&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(r=!1,o[2]===0&&(i[1]!==0&&(o[0]=o[1],f=wl(h,t,i,s,void 0,f),i=[0,0,0,0]),o[2]=n)):g.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(o[0]=o[1],f=wl(h,t,i,s,void 0,f)),i=o,o=[i[1],n,0,0])):g.type==="tableHead"?(a=!0,l=n):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=n,i[1]!==0?(o[0]=o[1],f=wl(h,t,i,s,n,f)):o[1]!==0&&(f=wl(h,t,o,s,n,f)),s=0):s&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(o[3]=n)}for(l!==0&&lx(h,t,l,u,c),h.consume(t.events),n=-1;++n<t.events.length;){const p=t.events[n];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=z3(t.events,n))}return e}function wl(e,t,n,r,s,i){const o=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",a="tableContent";n[0]!==0&&(i.end=Object.assign({},ui(t.events,n[0])),e.add(n[0],0,[["exit",i,t]]));const l=ui(t.events,n[1]);if(i={type:o,start:Object.assign({},l),end:Object.assign({},l)},e.add(n[1],0,[["enter",i,t]]),n[2]!==0){const u=ui(t.events,n[2]),c=ui(t.events,n[3]),f={type:a,start:Object.assign({},u),end:Object.assign({},c)};if(e.add(n[2],0,[["enter",f,t]]),r!==2){const h=t.events[n[2]],p=t.events[n[3]];if(h[1].end=Object.assign({},p[1].end),h[1].type="chunkText",h[1].contentType="text",n[3]>n[2]+1){const g=n[2]+1,y=n[3]-n[2]-1;e.add(g,y,[])}}e.add(n[3]+1,0,[["exit",f,t]])}return s!==void 0&&(i.end=Object.assign({},ui(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function lx(e,t,n,r,s){const i=[],o=ui(t.events,n);s&&(s.end=Object.assign({},o),i.push(["exit",s,t])),r.end=Object.assign({},o),i.push(["exit",r,t]),e.add(n+1,0,i)}function ui(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const U3={name:"tasklistCheck",tokenize:H3};function V3(){return{text:{91:U3}}}function H3(e,t,n){const r=this;return s;function s(l){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),i)}function i(l){return Re(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),o):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),o):n(l)}function o(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),a):n(l)}function a(l){return se(l)?t(l):me(l)?e.check({tokenize:W3},t,n)(l):n(l)}}function W3(e,t,n){return _e(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function K3(e){return JS([y3(),T3(),D3(e),F3(),V3()])}const q3={};function G3(e){const t=this,n=e||q3,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),o=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(K3(n)),i.push(h3()),o.push(p3(n))}const Y3="modulepreload",Q3=function(e,t){return new URL(e,t).href},ux={},Yn=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){const o=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=Promise.allSettled(n.map(u=>{if(u=Q3(u,r),u in ux)return;ux[u]=!0;const c=u.endsWith(".css"),f=c?'[rel="stylesheet"]':"";if(!!r)for(let g=o.length-1;g>=0;g--){const y=o[g];if(y.href===u&&(!c||y.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${u}"]${f}`))return;const p=document.createElement("link");if(p.rel=c?"stylesheet":Y3,c||(p.as="script"),p.crossOrigin="",p.href=u,l&&p.setAttribute("nonce",l),document.head.appendChild(p),c)return new Promise((g,y)=>{p.addEventListener("load",g),p.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})},X3={ts:"typescript",typescript:"typescript",tsx:"typescript",js:"javascript",javascript:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",json:"json",jsonc:"json",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",py:"python",python:"python",diff:"diff",patch:"diff",md:"markdown",markdown:"markdown",html:"xml",xml:"xml",css:"css"};function _m(e){return e?X3[e.trim().toLowerCase()]??null:null}let Pd=null;async function J3(){return Pd||(Pd=(async()=>{const{default:e}=await Yn(async()=>{const{default:c}=await import("./core-BA72pMy-.js");return{default:c}},[],import.meta.url),[t,n,r,s,i,o,a,l,u]=await Promise.all([Yn(()=>import("./typescript-C2FFdlUC.js"),[],import.meta.url),Yn(()=>import("./javascript-BKRaQes9.js"),[],import.meta.url),Yn(()=>import("./json-DIYVocXf.js"),[],import.meta.url),Yn(()=>import("./bash-I8pq0VWm.js"),[],import.meta.url),Yn(()=>import("./python-sE43i1Pi.js"),[],import.meta.url),Yn(()=>import("./diff-DiTmLxSS.js"),[],import.meta.url),Yn(()=>import("./markdown-BrP960CR.js"),[],import.meta.url),Yn(()=>import("./xml-BXBhIUeX.js"),[],import.meta.url),Yn(()=>import("./css-DazXZka4.js"),[],import.meta.url)]);return e.registerLanguage("typescript",t.default),e.registerLanguage("javascript",n.default),e.registerLanguage("json",r.default),e.registerLanguage("bash",s.default),e.registerLanguage("python",i.default),e.registerLanguage("diff",o.default),e.registerLanguage("markdown",a.default),e.registerLanguage("xml",l.default),e.registerLanguage("css",u.default),e})()),Pd}async function H1(e,t){const n=_m(e);if(!n)return null;try{const r=await J3(),{value:s}=r.highlight(t,{language:n,ignoreIllegals:!0});return s}catch{return null}}function Z3(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n),t=t>>>0;return t.toString(36)}function e$(e,t){return"code-"+Z3((e??"")+`
91
91
  `+t)}const cx=8,W1=m.createContext(null);function bm(){const e=m.useContext(W1);if(!e)throw new Error("useArtifactPanel must be used inside <ArtifactPanelProvider>");return e}function t$(e,t){const n=e.artifacts.findIndex(s=>s.id===t.id);if(n>=0)return{artifacts:[e.artifacts[n],...e.artifacts.filter((i,o)=>o!==n)],activeId:t.id};const r=[t,...e.artifacts];return{artifacts:r.length>cx?r.slice(0,cx):r,activeId:t.id}}function n$(e,t){const n=e.artifacts.findIndex(i=>i.id===t);if(n<0)return e;const r=e.artifacts.filter((i,o)=>o!==n);let s=e.activeId;if(e.activeId===t)if(r.length===0)s=null;else{const i=Math.min(n,r.length-1);s=r[i].id}return{artifacts:r,activeId:s}}function r$({children:e}){const[t,n]=m.useState({artifacts:[],activeId:null}),r=m.useCallback(a=>{n(l=>t$(l,a))},[]),s=m.useCallback(a=>{n(l=>({...l,activeId:a}))},[]),i=m.useCallback(a=>{n(l=>n$(l,a))},[]),o=m.useMemo(()=>({artifacts:t.artifacts,activeId:t.activeId,open:r,setActive:s,close:i}),[t,r,s,i]);return d.jsx(W1.Provider,{value:o,children:e})}const s$=({language:e,code:t})=>{const{open:n}=bm();if(!e)return null;const r=typeof t=="string"&&t.length>0,s=()=>{if(!r||typeof t!="string")return;const i=e||"code";n({id:e$(e,t),kind:"code",title:i,language:e,content:t})};return d.jsxs("div",{className:"aui-md-code-lang",children:[d.jsx("span",{className:"aui-md-code-lang-name",children:e}),r?d.jsx("button",{type:"button",className:"aui-md-code-open-btn",onClick:s,title:"Open in side panel","aria-label":`Open ${e} code in side panel`,children:"↗"}):null]})},i$=({components:e,language:t,code:n})=>{const{Pre:r,Code:s}=e,i=_m(t)!==null,[o,a]=m.useState(null);return m.useEffect(()=>{if(!i){a(null);return}let l=!0;return a(null),H1(t,n).then(u=>{l&&a(u)}).catch(()=>{l&&a(null)}),()=>{l=!1}},[i,t,n]),i&&o!=null?d.jsx(r,{children:d.jsx(s,{className:"hljs",dangerouslySetInnerHTML:{__html:o}})}):d.jsx(r,{children:d.jsx(s,{className:i?"hljs":void 0,children:n})})},o$=({node:e,...t})=>d.jsx("div",{className:"md-table-wrap",children:d.jsx("table",{...t})}),a$=()=>d.jsx(FB,{className:"aui-md",remarkPlugins:[G3],components:{CodeHeader:s$,SyntaxHighlighter:i$,table:o$}}),l$=m.memo(a$);function u$(e){const[t,n]=m.useState(null);return m.useEffect(()=>{let r=!1,s=null;return nt(CM(e)).then(i=>i.ok?i.blob():null).then(i=>{!i||r||(s=URL.createObjectURL(i),n(s))}).catch(()=>{}),()=>{r=!0,s&&URL.revokeObjectURL(s),n(null)}},[e]),t}const c$=new Set([".jpg",".jpeg",".png",".gif",".webp",".avif",".heic",".heif",".svg"]),dx=/(?:^|\s)(\/[^\s]*\/\.claude-control\/uploads\/([^\s]+))/g;function d$(e){const t=[],n=new Set;let r;for(dx.lastIndex=0;(r=dx.exec(e))!==null;){const s=r[1].trim();if(n.has(s))continue;n.add(s);const i=r[2],o=i.slice(i.lastIndexOf(".")).toLowerCase();t.push({fullPath:s,basename:i,isImage:c$.has(o)})}return t}function K1({src:e,alt:t,onClose:n}){const r=m.useRef(null);m.useEffect(()=>{r.current?.focus()},[]);const s=m.useCallback(i=>{i.key==="Escape"&&(i.preventDefault(),n())},[n]);return d.jsx("div",{className:"lightbox-backdrop",role:"dialog","aria-modal":"true","aria-label":`Preview: ${t}`,ref:r,tabIndex:-1,onClick:n,onKeyDown:s,children:d.jsx("img",{className:"lightbox-img",src:e,alt:t,onClick:i=>i.stopPropagation()})})}function f$({ref_:e}){const[t,n]=m.useState(!1),r=u$(e.basename);return e.isImage?d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"transcript-thumb-btn","aria-label":`Preview ${e.basename}`,title:e.basename,onClick:()=>n(!0),children:r?d.jsx("img",{className:"transcript-thumb",src:r,alt:e.basename,loading:"lazy"}):d.jsx("span",{className:"transcript-thumb transcript-thumb-loading","aria-hidden":"true"})}),t&&r?d.jsx(K1,{src:r,alt:e.basename,onClose:()=>n(!1)}):null]}):d.jsxs("a",{className:"transcript-file-chip",href:r??void 0,download:e.basename,"aria-label":`Download ${e.basename}`,title:e.basename,"aria-disabled":r?void 0:!0,children:[d.jsx("span",{className:"chip-icon","aria-hidden":"true",children:"📎"}),d.jsx("span",{className:"chip-name",children:e.basename})]})}function h$({text:e}){const t=d$(e);return t.length===0?null:d.jsx("div",{className:"transcript-attachments","aria-label":"Attachments",children:t.map(n=>d.jsx(f$,{ref_:n},n.fullPath))})}function p$(e){return e.trimStart().startsWith("Base directory for this skill:")}function m$(e){const n=e.trim().replace(/\/SKILL\.md$/i,"").split("/").filter(Boolean);return n[n.length-1]??"skill"}function g$(e){const t=e.split(`
92
92
  `);if(t[0]?.trim()!=="---")return{entries:[],rest:e};const n=[];let r=-1;for(let i=1;i<t.length;i++){if(t[i].trim()==="---"){r=i;break}const o=t[i].indexOf(":");if(o!==-1){const a=t[i].slice(0,o).trim(),l=t[i].slice(o+1).trim();a&&n.push({key:a,value:l})}}if(r===-1)return{entries:[],rest:e};const s=t.slice(r+1).join(`
93
93
  `);return{entries:n,rest:s}}function y$(e){const t=e.trimStart().split(`