1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,878598,(e,t,r)=>{"use strict";var s=e.i(65453);let i=void 0!==s.Buffer,a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,n=/"(?: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 o(e,t,r){null==r&&null!==t&&"object"==typeof t&&(r=t,t=void 0),i&&s.Buffer.isBuffer(e)&&(e=e.toString()),e&&65279===e.charCodeAt(0)&&(e=e.slice(1));let o=JSON.parse(e,t);if(null===o||"object"!=typeof o)return o;let d=r&&r.protoAction||"error",u=r&&r.constructorAction||"error";if("ignore"===d&&"ignore"===u)return o;if("ignore"!==d&&"ignore"!==u){if(!1===a.test(e)&&!1===n.test(e))return o}else if("ignore"!==d&&"ignore"===u){if(!1===a.test(e))return o}else if(!1===n.test(e))return o;return l(o,{protoAction:d,constructorAction:u,safe:r&&r.safe})}function l(e,{protoAction:t="error",constructorAction:r="error",safe:s}={}){let i=[e];for(;i.length;){let e=i;for(let a of(i=[],e)){if("ignore"!==t&&Object.prototype.hasOwnProperty.call(a,"__proto__")){if(!0===s)return null;if("error"===t)throw SyntaxError("Object contains forbidden prototype property");delete a.__proto__}if("ignore"!==r&&Object.prototype.hasOwnProperty.call(a,"constructor")&&null!==a.constructor&&"object"==typeof a.constructor&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype")){if(!0===s)return null;if("error"===r)throw SyntaxError("Object contains forbidden prototype property");delete a.constructor}for(let e in a){let t=a[e];t&&"object"==typeof t&&i.push(t)}}}return e}function d(e,t,r){let{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return o(e,t,r)}finally{Error.stackTraceLimit=s}}t.exports=d,t.exports.default=d,t.exports.parse=d,t.exports.safeParse=function(e,t){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return o(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=r}},t.exports.scan=l},699672,e=>{"use strict";var t,r,s=e.i(391610),i=e.i(138415),a=e.i(638437),n=e.i(925916);function o(e){let t=[];for(let r of e.effectTasks)try{r()}catch(e){t.push(e)}if(t.length>0)if(1===t.length)throw t[0];else{for(let e of t)console.error(e);throw AggregateError(t,"Errors during commit")}}function l(e){let t=[];for(let r of e.cells)if(r?.type==="effect"&&(r.deps=null,r.cleanup))try{r.cleanup?.()}catch(e){t.push(e)}finally{r.cleanup=void 0}if(t.length>0)if(1===t.length)throw t[0];else{for(let e of t)console.error(e);throw AggregateError(t,"Errors during cleanup")}}let d=void 0!==n.default&&!1,u=null;function c(){if(!u)throw Error("No resource fiber available");return u}let h=Symbol("fnSymbol");function p(e,t,r,s=function(e){return d?u?.devStrictMode?u.isFirstRender?"child":"root":e?"root":null:null}(!1)){return{type:e,root:t,markDirty:r,devStrictMode:s,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function g(e){if(!e.isMounted)throw Error("Tried to unmount a fiber that is already unmounted");e.isMounted=!1,l(e)}function m(e,t){let r={effectTasks:[],props:t,output:void 0};e.currentIndex=0;let s=u;u=e;try{if((()=>{e.renderContext=r;try{r.output=function(e,t){let r=e[h];if(!r)throw Error("ResourceElement.type is not a valid Resource");return r(t)}(e.type,t)}finally{e.renderContext=void 0}})(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{u=s}return r}function f(e,t){e.isMounted=!0,d&&e.isNeverMounted&&"root"===e.devStrictMode&&(e.isNeverMounted=!1,o(t),l(e)),e.isNeverMounted=!1,o(t)}let b=e=>({version:0,committedVersion:0,dispatchUpdate:e,changelog:[],dirtyCells:[]}),_=e=>{for(let t of e.dirtyCells)t.dirty=!1,t.queue.clear(),t.current=t.workInProgress;e.committedVersion=e.version,e.changelog.length=0,e.dirtyCells.length=0},y=(e,t)=>{let r=e.version>t;if(e.version=t,r){for(let t of e.dirtyCells)t.dirty=!1,t.queue.clear(),t.workInProgress=t.current;if(e.dirtyCells.length=0,t===e.committedVersion)e.changelog.length=0;else{if(e.committedVersion>t)throw Error("Version is less than committed version");for(;e.committedVersion+e.changelog.length>t;)e.changelog.pop();
1e.changelog.forEach(e=>e()),_(e)}}},w=(e,t)=>{t.dirty||(t.dirty=!0,e.markDirty?.(),e.root.dirtyCells.push(t))};function x(e){let t=e=>({type:t,props:e});return t[h]=e,t}let v=(e,t)=>{let r=c(),s=r.currentIndex++;if(!r.isFirstRender&&s>=r.cells.length)throw Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");let i=r.cells[s];if(i||(i=t(),r.cells[s]=i),i.type!==e)throw Error("Hook order changed between renders");return i};function S(e,t,r,s){let i=v("reducer",()=>{let t=c(),a=s?s(r):r;return d&&t.devStrictMode&&s&&s(r),{type:"reducer",queue:new Set,dirty:!1,workInProgress:a,current:a,reducer:e,dispatch:r=>{let s={action:r,hasEagerState:!1,eagerState:void 0};if(t.renderContext)throw Error("Resource updated during render");if(t.isNeverMounted)throw Error("Resource updated before mount");t.root.dispatchUpdate(()=>{let a=0===t.root.dirtyCells.length&&!s.hasEagerState&&(s.eagerState=e(i.workInProgress,r),s.hasEagerState=!0,Object.is(i.current,s.eagerState))?null:()=>{w(t,i),i.queue.add(s)};return!!a&&(a(),t.root.changelog.push(a),!0)})}}}),a=c(),n=e===i.reducer;for(let t of(i.reducer=e,i.queue))t.hasEagerState&&n||(t.eagerState=e(i.workInProgress,t.action),t.hasEagerState=!0),d&&a.devStrictMode&&e(i.workInProgress,t.action),i.workInProgress=t.eagerState;if(i.queue.clear(),t){let e=t(i.workInProgress);Object.is(e,i.workInProgress)||(w(a,i),i.workInProgress=e)}return[i.workInProgress,i.dispatch]}let T=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0},I=()=>{throw Error("Memo reducer should not be called")},E=(e,t)=>{let r=c(),[s]=S(I,s=>{if(s&&T(s.deps,t))return s;let i=e();return d&&r.devStrictMode&&e(),{value:i,deps:t}},null,void 0);return s.value},C=()=>({type:"effect",cleanup:void 0,deps:null});function k(e,t){let r=v("effect",C);if(!(t&&r.deps&&T(r.deps,t))){if(null!==r.deps&&!!t!=!!r.deps)throw Error("tapEffect called with and without dependencies across re-renders");c().renderContext.effectTasks.push(()=>{let s=[];try{r.cleanup?.()}catch(e){s.push(e)}finally{r.cleanup=void 0}try{let t=e();if(void 0!==t&&"function"!=typeof t)throw Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof t}`);r.cleanup=t}catch(e){s.push(e)}if(r.deps=t,s.length>0)if(1===s.length)throw s[0];else{for(let e of s)console.error(e);throw AggregateError(s,"Errors during commit")}})}}let R=(e,t)=>E(()=>e,t),A=(e,t)=>
1"function"==typeof t?t(e):t,N=e=>"function"==typeof e?e():e;function M(e){return S(A,void 0,e,N)}function j(e,t){let[r]=M(e);return r}function P(e){let[t]=M(()=>({current:e}));return t}function B(e,t){let r=P(0),s=r.current,i=j(c,[]),a=j(()=>()=>{r.current++,i.markDirty?.()},[]),n=j(()=>new Map,[]),o=t?R(e,t):e,l=E(()=>{let e=o(),t=new Set,r=[],s=0;for(let o=0;o<e.length;o++){let l=e[o],d=l.key;if(void 0===d)throw Error(`tapResources did not provide a key for array at index ${o}`);if(t.has(d))throw Error(`Duplicate key ${d} in tapResources`);t.add(d);let u=n.get(d);if(u)if(u.fiber.type!==l.type){let e=p(l.type,i.root,a),t=m(e,l.props);u.next=[e,t],r.push(t.output)}else u.next=m(u.fiber,l.props),r.push(u.next.output);else{let e=p(l.type,i.root,a),t=m(e,l.props);u={fiber:e,next:t},s++,n.set(d,u),r.push(t.output)}}if(n.size>r.length-s)for(let e of n.keys())t.has(e)||(n.get(e).next="delete");return r},[o,s]);return k(()=>()=>{for(let e of n.keys())g(n.get(e).fiber)},[]),k(()=>{for(let[e,t]of n.entries())"delete"===t.next?(t.fiber.isMounted&&g(t.fiber),n.delete(e)):Array.isArray(t.next)?(g(t.fiber),t.fiber=t.next[0],f(t.fiber,t.next[1])):f(t.fiber,t.next)},[l]),l}function D(e){let t=P(e);if(k(()=>{t.current=e}),d){let e=c();return R((...r)=>{if(e.renderContext)throw Error("tapEffectEvent cannot be called during render");return t.current(...r)},[e])}return t.current}function O(e,t){let r=c(),s=P(0),i=E(()=>(e.key,p(e.type,r.root,()=>{s.current++,r.markDirty?.()})),[e.type,e.key,r]),a=t?E(()=>m(i,e.props),[i,...t,s.current]):m(i,e.props);return k(()=>()=>g(i),[i]),k(()=>{f(i,a)},[i,a]),a.output}function L(e,t){return{...t,key:e}}let F={schedulers:new Set([]),isScheduled:!1};class U{_task;_isDirty=!1;constructor(e){this._task=e}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,F.schedulers.add(this),$()}runTask(){this._isDirty=!1,this._task()}}let $=()=>{F.isScheduled||(F.isScheduled=!0,q())},z=()=>{try{let e=[],t=0;for(let r of F.schedulers)if(F.schedulers.delete(r),r.isDirty){if(++t>50)throw Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");try{r.runTask()}catch(t){e.push(t)}}if(e.length>0)if(1===e.length)throw e[0];else{for(let t of e)console.error(t);throw AggregateError(e,"Errors occurred during flushSync")}}finally{F.schedulers.clear(),F.isScheduled=!1}},q=(()=>{if("undefined"!=typeof MessageChannel){let e=new MessageChannel;return e.port1.onmessage=z,()=>e.port2.postMessage(null)}return()=>setTimeout(z,0)})(),V=e=>"string"==typeof e?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},H=Symbol("tap.Context"),J=e=>({[H]:e}),W=(e,t,r)=>{let s=e[H];e[H]=t;try{return r()}finally{e[H]=s}},G=e=>e[H],K=Symbol("assistant-ui.store.clientIndex"),Y=J([]),Q=new Set(["$$typeof","nodeType","then"]),Z=(e,t)=>e===Symbol.toStringTag?t:"symbol"==typeof e?void 0:"toJSON"===e?()=>t:!!Q.has(e)&&void 0;class X{getOwnPropertyDescriptor(e,t){let r=this.get(e,t);if(void 0!==r)return{value:r,writable:!1,enumerable:!0,configurable:!1}}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}}let ee=e=>{let t=x(e);return e=>{let r=t(e);return void 0===e.key?r:L(e.key,r)}},et=Symbol("assistant-ui.store.getValue"),er=new Map;class es extends X{outputRef;index;boundFns;cachedReceiver;constructor(e,t){super(),this.outputRef=e,this.index=t}get(e,t,r){if(t===et)return this.outputRef.current;if(t===K)return this.index;let s=Z(t,"ClientProxy");if(!1!==s)return s;let i=this.outputRef.current[t];if("function"==typeof i){this.cachedReceiver!==r&&(this.boundFns=new Map,this.cachedReceiver=r);let e=this.boundFns.get(t);if(!e){let s;e=(!(s=er.get(t))&&(s=function(...e){if(!this||"object"!=typeof this)throw Error(`Method "${String(t)}" called without proper context. This may indicate the function was called incorrectly.`);let r=this[et];if(!r)throw Error(`Method "${String(t)}" called on invalid client proxy. Ensure you are calling this method on a valid client instance.`);let s=r[t];if(!s)throw Error(`Method "${String(t)}" is not implemented.`);if("function"!=typeof s)throw Error(`"${String(t)}" is not a function.`);return s(...e)},er.set(t,s)),s).bind(r),this.boundFns.set(t,e)}return e}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(e,t){return t===et||t===K||t in this.outputRef.current}}let ei=ee(e=>{var t;let r,s=P(null),i=G(Y).length,a=E(()=>new Proxy({},new es(s,i)),[i]),n=(t=()=>O(e),r=G(Y),W(Y,E(()=>[...r,a],[r,a]),t));return s.current||(s.current=n),k(()=>{s.current=n}),{methods:a,state:n.getState?.(),key:e.key}}),ea=x(()=>j(()=>{let e=new Map,t=new Set,r=new Set;return{on(r,s){if("*"===r)return t.add(s),()=>t.delete(s);let i=e.get(r);
1return i||(i=new Set,e.set(r,i)),i.add(s),()=>{i.delete(s),0===i.size&&e.delete(r)}},emit(r,s,i){let a=e.get(r);(a||0!==t.size)&&queueMicrotask(()=>{let e=[];if(a)for(let t of a)try{t(s,i)}catch(t){e.push(t)}if(t.size>0){let a={event:r,payload:s};for(let r of t)try{r(a,i)}catch(t){e.push(t)}}if(e.length>0)if(1===e.length)throw e[0];else{for(let t of e)console.error(t);throw AggregateError(e,"Errors occurred during event emission")}})},subscribe:e=>(r.add(e),()=>r.delete(e)),notifySubscribers(){for(let e of r)try{e()}catch(e){console.error("NotificationManager: subscriber callback error",e)}}}},[])),en=J(null),eo=()=>{let e=G(en);if(!e)throw Error("AssistantTapContext is not available");return e},el=()=>{let{emit:e}=eo(),t=G(Y);return D((r,s)=>{e(r,s,t)})},ed=Symbol("assistant-ui.store.proxiedAssistantState"),eu=e=>"on"===e||"subscribe"===e||"symbol"==typeof e,ec=e=>new Proxy({},new class extends X{get(t,r){let s=Z(r,"AssistantState");if(!1!==s)return s;if(!eu(r)){let t=e[r]()[et];if(!t)throw 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?.()}}ownKeys(){return Object.keys(e).filter(e=>!eu(e))}has(t,r){return!eu(r)&&r in e}}),eh=x(e=>null),ep=Symbol("assistant-ui.transform-scopes");function eg(e,t){if(e[ep])throw Error("transformScopes is already attached to this resource");e[ep]=t}let em=e=>E(()=>e,[...Object.entries(e).flat()]),ef=()=>()=>{},eb=e=>{let t=()=>{throw Error(e)};return t.source=null,t.query=null,t},e_=new Proxy({},new class extends X{get(e,t){if("subscribe"===t||"on"===t)return ef;if(t===ed)return ey;let r=Z(t,"DefaultAssistantClient");return!1!==r?r:eb("You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.")}ownKeys(){return["subscribe","on",ed]}has(e,t){return"subscribe"===t||"on"===t||t===ed}}),ey=ec(e_),ew=(0,i.createContext)(e_),ex=({value:e,children:t})=>(0,s.jsx)(ew.Provider,{value:e,children:t}),ev=e=>E(()=>e,e),eS=x(({element:e,emit:t,clientRef:r})=>{let{methods:s,state:i}=W(en,{clientRef:r,emit:t},()=>O(ei(e)));return E(()=>({state:i,methods:s}),[s,i])}),eT=x(({element:e,notifications:t,clientRef:r,name:s})=>{var i;let a,n,o,l,u,c,h,w,x,v=(i=eS({element:e,emit:t.emit,clientRef:r}),a=j(()=>new U(()=>x(null)),[]),n=j(()=>[],[]),y((o=E(()=>(i.key,p(i.type,b(e=>{(a.isDirty||e())&&(n.push(e),a.markDirty())}))),[i.type,i.key])).root,o.root.committedVersion),l=m(o,i.props),u=P(!1),c=P(i.props),h=P(l.output),w=j(()=>new Set,[]),x=D(e=>{if(null===e&&(y(o.root,2),y(o.root,1),n.forEach(e=>{d&&o.devStrictMode&&e(),e()}),d&&o.devStrictMode&&m(o,c.current),e=m(o,c.current)),a.isDirty)throw Error("Scheduler is dirty, this should never happen");_(o.root),n.length=0,u.current&&f(o,e),a.isDirty||h.current===e.output||(h.current=e.output,w.forEach(e=>e()))}),k(()=>(u.current=!0,()=>{u.current=!1,g(o)}),[o]),k(()=>{c.current=l.props,_(o.root),f(o,l),a.isDirty||h.current===l.output||(h.current=l.output,w.forEach(e=>e()))}),E(()=>({getValue:()=>h.current,subscribe:e=>(w.add(e),()=>w.delete(e))}),[]));return k(()=>v.subscribe(t.notifySubscribers),[v,t]),E(()=>{let e=()=>v.getValue().methods;return Object.defineProperties(e,{source:{value:"root",writable:!1},query:{value:{},writable:!1},name:{value:s,configurable:!0}}),e},[v,s])}),eI=x(()=>E(()=>({clients:[],subscribe:void 0,on:void 0}),[])),eE=x(({clients:e,clientRef:t})=>{let r=O(ea());k(()=>t.parent.subscribe(r.notifySubscribers),[t,r]);let s=ev(B(()=>Object.keys(e).map(s=>L(s,eT({element:e[s],notifications:r,clientRef:t,name:s}))),[e,r,t]));return E(()=>({clients:s,subscribe:r.subscribe,on:function(e,s){if(!this)throw Error("const { on } = useAui() is not supported. Use aui.on() instead.");let{scope:i,event:a}=V(e);if("*"!==i&&null===this[i].source)throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);let n=r.on(a,(e,t)=>{if("*"===i)return void s(e);let r=this[i](),a=r[K];r===t[a]&&s(e)});if("*"!==i&&null===t.parent[i].source)return n;let o=t.parent.on(e,s);return()=>{n(),o()}}}),[s,r,t])}),eC=(e,t,r)=>{if("source"in e&&"query"in e)return e;if(r.dep===e)return r.meta;let s=e.getMeta(t.current);return r.meta=s,r.dep=e,s},ek=x(({element:e,clientRef:t,name:r})=>{let s=D(()=>e.props);return E(()=>{let e=()=>s().get(t.current),i={};return Object.defineProperties(e,{source:{get:()=>eC(s(),t,i).source},query:{get:()=>eC(s(),t,i).query},name:{value:r,configurable:!0}}),e},[t,r])}),eR=x(({clients:e,clientRef:t})=>ev(B(()=>Object.keys(e).map(r=>L(r,ek({element:e[r],clientRef:t,name:r}))),[e,t]))),eA=x(({parent:e,clients:t})=>{let{rootClients:r,derivedClients:s}=((e,t)=>{let{rootClients:r,derivedClients:s}=function(e,t){let r={...e},s=new Set,i=!0;for(;i;
1)for(let e of(i=!1,Object.values(r))){if(e.type===eh||s.has(e.type))continue;s.add(e.type);let a=e.type[ep];if(a){r=a(r,t),i=!0;break}}let a={},n={};for(let[e,t]of Object.entries(r))t.type===eh?n[e]=t:a[e]=t;return{rootClients:a,derivedClients:n}}(e,t);return{rootClients:em(r),derivedClients:em(s)}})(t,e),i=P({parent:e,current:null}).current;k(()=>{i.current=o});let a=O(Object.keys(r).length>0?eE({clients:r,clientRef:i}):eI()),n=O(eR({clients:s,clientRef:i})),o=E(()=>{let t=Object.create(e===e_?new Proxy({},{get(e,t){let r=Z(t,"AssistantClient");return!1!==r?r:eb(`The current scope does not have a "${String(t)}" property.`)}}):e);for(let r of(Object.assign(t,{subscribe:a.subscribe??e.subscribe,on:a.on??e.on,[ed]:ec(t)}),a.clients))t[r.name]=r;for(let e of n)t[e.name]=e;return t},[e,a,n]);return null===i.current&&(i.current=o),o});function eN(e,{parent:t}={parent:(0,i.useContext)(ew)}){if(e)return function(e){let t=(0,i.useMemo)(()=>b(e=>s(e)),[]),[r,s]=(0,i.useReducer)((e,r)=>(y(t,e),e+ +!!r()),0);y(t,r);let a=(()=>{if(!d)return null;let e=(0,i.useRef)(0),t=0===e.current;return((0,i.useState)(()=>e.current++),2!==e.current)?null:t?"child":"root"})(),n=(0,i.useMemo)(()=>(e.key,p(e.type,t,void 0,a)),[e.type,e.key,t,a]),o=m(n,e.props);return(0,i.useLayoutEffect)(()=>()=>g(n),[n]),(0,i.useLayoutEffect)(()=>{_(t),f(n,o)}),o.output}(eA({parent:t??e_,clients:e}));if(null===t)throw Error("received null parent, this usage is not allowed");return t}let eM=ee(e=>{if(void 0===e.key)throw Error("tapClientResource: Element has no key");return O(ei(e))});function ej(e,t){let r=B(()=>e().map(e=>eM(e)),t),s=E(()=>Object.keys(r),[r]),i=E(()=>r.reduce((e,t,r)=>(e[t.key]=r,e),{}),[r]);return{state:E(()=>r.map(e=>e.state),[r]),get:e=>{if("index"in e){if(e.index<0||e.index>=s.length)throw Error(`tapClientLookup: Index ${e.index} out of bounds (length: ${s.length})`);return r[e.index].methods}let t=i[e.key];if(void 0===t)throw Error(`tapClientLookup: Key "${e.key}" not found`);return r[t].methods}}}let eP=e=>{let[,t]=M(e.getState);return k(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},eB=x(({runtime:e})=>{let t=eP(e),r=el();return k(()=>{let t=[];for(let s of["switchedTo","switchedAway"]){let i=e.unstable_on(s,()=>{r(`threadListItem.${s}`,{threadId:e.getState().id})});t.push(i)}return()=>{for(let e of t)e()}},[e,r]),{getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e}}),eD=x(({runtime:e})=>{let t=eP(e);return{getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e}}),eO=x(({runtime:e,index:t})=>O(eD({runtime:E(()=>e.getAttachmentByIndex(t),[e,t])}))),eL=x(({threadIdRef:e,messageIdRef:t,runtime:r})=>{let s=eP(r),i=el();k(()=>{let s=[];for(let a of["send","attachmentAdd"]){let n=r.unstable_on(a,()=>{i(`composer.${a}`,{threadId:e.current,...t&&{messageId:t.current}})});s.push(n)}return()=>{for(let e of s)e()}},[r,i,e,t]);let a=ej(()=>s.attachments.map((e,t)=>L(e.id,eO({runtime:r,index:t}))),[s.attachments,r]),n=E(()=>({text:s.text,role:s.role,attachments:a.state,runConfig:s.runConfig,isEditing:s.isEditing,canCancel:s.canCancel,attachmentAccept:s.attachmentAccept,isEmpty:s.isEmpty,type:s.type??"thread",dictation:s.dictation,quote:s.quote}),[s,a.state]);return{getState:()=>n,setText:r.setText,setRole:r.setRole,setRunConfig:r.setRunConfig,addAttachment:r.addAttachment,reset:r.reset,clearAttachments:r.clearAttachments,send:r.send,cancel:r.cancel,beginEdit:r.beginEdit??(()=>{throw Error("beginEdit is not supported in this runtime")}),startDictation:r.startDictation,stopDictation:r.stopDictation,setQuote:r.setQuote,attachment:e=>"id"in e?a.get({key:e.id}):a.get(e),__internal_getRuntime:()=>r}}),eF=x(({runtime:e})=>{let t=eP(e);return{getState:()=>t,addToolResult:t=>e.addToolResult(t),resumeToolCall:t=>e.resumeToolCall(t),__internal_getRuntime:()=>e}}),eU=x(({runtime:e,index:t})=>O(eD({runtime:E(()=>e.getAttachmentByIndex(t),[e,t])}))),e$=x(({runtime:e,index:t})=>O(eF({runtime:E(()=>e.getMessagePartByIndex(t),[e,t])}))),ez=x(({runtime:e,threadIdRef:t})=>{let r=eP(e),[s,i]=M(!1),[a,n]=M(!1),o=E(()=>({get current(){return e.getState().id}}),[e]),l=O(ei(eL({runtime:e.composer,threadIdRef:t,messageIdRef:o}))),d=ej(()=>r.content.map((t,r)=>L("toolCallId"in t&&null!=t.toolCallId?`toolCallId-${t.toolCallId}`:`index-${r}`,e$({runtime:e,index:r}))),[r.content,e]),u=ej(()=>(r.attachments??[]).map((t,r)=>L(t.id,eU({runtime:e,index:r}))),[r.attachments,e]),c=E(()=>({...r,parts:d.state,composer:l.state,isCopied:s,isHovering:a}),[r,d.state,l.state,s,a]);return{getState:()=>c,composer:()=>l.methods,reload:t=>e.reload(t),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:t=>e.submitFeedback(t),switchToBranch:t=>e.switchToBranch(t),getCopyText:()=>e.unstable_getCopyText(),part:e=>"index"in e?d.get({index:e.index}):d.get({key:`toolCallId-${e.toolCallId}`}),attachment:e=>"id"in e?u.get({key:e.id}):u.get(e),setIsCopied:i,setIsHovering:n,__internal_getRuntime:()=>e}}),eq=x(({runtime:e,id:t,threadIdRef:r})=>O(ez({runtime:E(()=>e.getMessageById(t),[e,t]),threadIdRef:r}))),eV=x(({runtime:e})=>{let t=eP(e),r=el();k(()=>{let t=[];for(let s of["runStart","runEnd","initialize","modelContextUpdate"]){let i=e.unstable_on(s,()=>{r(`thread.${s}`,{threadId:e.getState()?.threadId||"unknown"})});t.push(i)}return()=>{for(let e of t)e()}},[e,r]);let s=E(()=>({get current(){return e.getState().threadId}}),[e]),i=O(ei(eL({runtime:e.composer,threadIdRef:s}
1))),a=ej(()=>t.messages.map(t=>L(t.id,eq({runtime:e,id:t.id,threadIdRef:s}))),[t.messages,e,s]),n=E(()=>({isEmpty:0===a.state.length&&!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,composer:i.state,messages:a.state}),[t,a,i.state]);return{getState:()=>n,composer:()=>i.methods,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:async()=>{throw Error("startVoice is not supported in this runtime")},stopVoice:async()=>{throw Error("stopVoice is not supported in this runtime")},message:e=>"id"in e?a.get({key:e.id}):a.get(e),__internal_getRuntime:()=>e}}),eH=x(({runtime:e,id:t})=>O(eB({runtime:E(()=>e.getItemById(t),[e,t])}))),eJ=x(({runtime:e,__internal_assistantRuntime:t})=>{let r=eP(e),s=O(ei(eV({runtime:e.main}))),i=ej(()=>Object.keys(r.threadItems).map(t=>L(t,eH({runtime:e,id:t}))),[r.threadItems,e]),a=E(()=>({mainThreadId:r.mainThreadId,newThreadId:r.newThreadId??null,isLoading:r.isLoading,threadIds:r.threadIds,archivedThreadIds:r.archivedThreadIds,threadItems:i.state,main:s.state}),[r,i.state,s.state]);return{getState:()=>a,thread:()=>s.methods,item:e=>{if("main"===e)return i.get({key:a.mainThreadId});if("id"in e)return i.get({key:e.id});let{index:t,archived:r=!1}=e,s=r?a.archivedThreadIds[t]:a.threadIds[t];return i.get({key:s})},switchToThread:async t=>{await e.switchToThread(t)},switchToNewThread:async()=>{await e.switchToNewThread()},__internal_getAssistantRuntime:()=>t}});class eW{_providers=new Set;getModelContext(){return Array.from(this._providers).map(e=>e.getModelContext()).sort((e,t)=>(t.priority??0)-(e.priority??0)).reduce((e,t)=>{if(t.system&&(e.system?e.system+=` 2 3${t.system}`:e.system=t.system),t.tools)for(let[r,s]of Object.entries(t.tools)){let t=e.tools?.[r];if(t&&t!==s)throw Error(`You tried to define a tool with the name ${r}, but it already exists.`);e.tools||(e.tools={}),e.tools[r]=s}return t.config&&(e.config={...e.config,...t.config}),t.callSettings&&(e.callSettings={...e.callSettings,...t.callSettings}),e},{})}registerModelContextProvider(e){this._providers.add(e);let t=e.subscribe?.(()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t?.(),this.notifySubscribers()}}_subscribers=new Set;notifySubscribers(){for(let e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}}let eG=x(()=>{let[e]=M(()=>({version:2})),t=E(()=>new eW,[]);return{getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:e=>t.subscribe(e),register:e=>t.registerModelContextProvider(e)}}),eK=x(({toolkit:e})=>{let[t,r]=M(()=>({tools:{}})),s=eo().clientRef,i=R((e,t)=>(r(r=>({...r,tools:{...r.tools,[e]:[...r.tools[e]??[],t]}})),()=>{r(r=>({...r,tools:{...r.tools,[e]:r.tools[e]?.filter(e=>e!==t)??[]}}))}),[]);return k(()=>{if(!e)return;let t=[];for(let[r,s]of Object.entries(e))s.render&&t.push(i(r,s.render));let r=Object.entries(e).reduce((e,[t,r])=>{let{render:s,...i}=r;return e[t]=i,e},{});return t.push(s.current.modelContext().register({getModelContext:()=>({tools:r})})),()=>{t.forEach(e=>e())}},[e,i,s]),{getState:()=>t,setToolUI:i}});eg(eK,(e,t)=>({...e,...e.modelContext||null!==t.modelContext.source?{}:{modelContext:eG()}}));let eY=x(e=>({getState:()=>e})),eQ=x(e=>{let[t]=M(()=>({suggestions:(e??[]).map(e=>"string"==typeof e?{title:e,label:"",prompt:e}:{title:e.title,label:e.label,prompt:e.prompt})})),r=ej(()=>t.suggestions.map((e,t)=>L(t,eY(e))),[t.suggestions]);return{getState:()=>t,suggestion:({index:e})=>r.get({index:e})}}),eZ=x(e=>{let t=eo().clientRef;return k(()=>e.registerModelContextProvider(t.current.modelContext()),[e,t]),O(eJ({runtime:e.threads,__internal_assistantRuntime:e}))});eg(eZ,(e,t)=>{let r={...e,thread:e.thread??eh({source:"threads",query:{type:"main"},get:e=>e.threads().thread("main")}),threadListItem:e.threadListItem??eh({source:"threads",query:{type:"main"},get:e=>e.threads().item("main")}),composer:e.composer??eh({source:"thread",query:{},get:e=>e.threads().thread("main").composer()})};return r.modelContext||null!==t.modelContext.source||(r.modelContext=eG()),r.tools||null!==t.tools.source||(r.tools=eK({})),r.suggestions||null!==t.suggestions.source||(r.suggestions=eQ()),r});let eX=e=>{let t,r=new Set,s=(e,s)=>{let i="function"==typeof e?e(t):e;if(!Object.is(i,t)){let e=t;t=(null!=s?s:"object"!=typeof i||null===i)?i:Object.assign({},t,i),r.forEach(r=>r(t,e))}},i=()=>t,a={setState:s,getState:i,getInitialState:()=>n,subscribe:e=>(r.add(e),()=>r.delete(e))},n=t=e(s,i,a);return a},e0=e=>{let t=e?eX(e):eX,r=e=>(function(e,t=e=>e){let r=i.default.useSyncExternalStore(e.subscribe,i.default.useCallback(()=>t(e.getState()),[e,t]),i.default.useCallback(()=>t(e.getInitialState()),[e,t]));return i.default.useDebugValue(r),r})(t,e);return Object.assign(r,t),r},e1=e=>e?e0(e):e0,e5=e=>{let t=new Map,r=()=>{let r=0;for(let e of t.values())r+=e;e(r)};return{register:()=>{let e=Symbol();return t.set(e,0),{setHeight:s=>{t.get(e)!==s&&(t.set(e,s),r())},unregister:()=>{t.delete(e),r()}}}}},e2=(0,i.createContext)(null),{useThreadViewport:e6,useThreadViewportStore:e3}=function(e,t){function r(r){let s=e(r);return s?s[t]:null}return{[t]:function(e){let t,s=!1;"function"==typeof e?t=e:e&&"object"==typeof e&&(s=!!e.optional,t=e.selector);let i=r({optional:s});return i?t?i(t):i():null},[`${t}Store`]:r}}(function(e){let t=(0,i.useContext)(e2);if(!e?.optional&&!t)throw Error("This component must be used within ThreadPrimitive.Viewport.");return t},"useThreadViewport"),e4=({children:e,options:t={}})=>{let r=(e=>{let t=e3({optional:!0}),[r]=(0,i.useState)(()=>((e={})=>{let t=new Set,r=e5(e=>{a.setState({height:{...a.getState().height,viewport:e}})}),s=e5(e=>{a.setState({height:{...a.getState().height,inset:e}})}),i=e5(e=>{a.setState({height:{...a.getState().height,userMessage:e}})}),a=e1(()=>({isAtBottom:!0,scrollToBottom:({behavior:e="auto"}={})=>{for(let r of t)r({behavior:e})},onScrollToBottom:e=>(t.add(e),()=>{t.delete(e)}),turnAnchor:e.turnAnchor??"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:r.register,registerContentInset:s.register,registerUserMessageHeight:i.register}));return a})(e));return(0,i.useEffect)(()=>t?.getState().onScrollToBottom(()=>{r.getState().scrollToBottom()}),[t,r]),(0,i.useEffect)(()=>
3{if(t)return r.subscribe(e=>{t.getState().isAtBottom!==e.isAtBottom&&t.setState({isAtBottom:e.isAtBottom})})},[r,t]),(0,i.useEffect)(()=>{let t={turnAnchor:e.turnAnchor??"bottom"};r.getState().turnAnchor!==t.turnAnchor&&r.setState(t)},[r,e.turnAnchor]),r})(t),[a]=(0,i.useState)(()=>({useThreadViewport:r}));return(0,s.jsx)(e2.Provider,{value:a,children:e})},e7=(0,i.memo)(({children:e,aui:t=null,runtime:r})=>{let a=eN({threads:eZ(r)},{parent:t});(0,i.useEffect)(()=>{},[a]);let n=r._core?.RenderComponent;return(0,s.jsxs)(ex,{value:a,children:[n&&(0,s.jsx)(n,{}),(0,s.jsx)(e4,{children:e})]})});e.s([],580006),e.i(580006);var e8=e.i(291967),e9=e.i(879789);let te=(e,t,r=[])=>{let a=(0,i.forwardRef)((e,i)=>{let a={},n={};Object.keys(e).forEach(t=>{r.includes(t)?a[t]=e[t]:n[t]=e[t]});let o=t(a)??void 0;return(0,s.jsx)(e9.Primitive.button,{type:"button",...n,ref:i,disabled:n.disabled||!o,onClick:(0,e8.composeEventHandlers)(n.onClick,o)})});return a.displayName=e,a},tt=e=>{let t=eN(),r=t[ed],s=(0,i.useSyncExternalStore)(t.subscribe,()=>e(r),()=>e(r));if(s===r)throw Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return(0,i.useDebugValue)(s),s},tr=()=>{let e=eN(),t=tt(e=>e.thread.isRunning||!e.composer.isEditing||e.composer.isEmpty),r=(0,i.useCallback)(()=>{e.composer().send()},[e]);return t?null:r},ts=te("ComposerPrimitive.Send",tr),ti=(0,i.forwardRef)(({onSubmit:e,...t},r)=>{let i=tr();return(0,s.jsx)(e9.Primitive.form,{...t,ref:r,onSubmit:(0,e8.composeEventHandlers)(e,e=>{e.preventDefault(),i&&i()})})});ti.displayName="ComposerPrimitive.Root";var ta=e.i(789268),tn=e.i(92024);function to(){return(to=Object.assign.bind()).apply(null,arguments)}var tl=i.useLayoutEffect,td=function(e){var t=i.default.useRef(e);return tl(function(){t.current=e}),t},tu=function(e,t){"function"==typeof e?e(t):e.current=t},tc=function(e,t){var r=i.default.useRef();return i.default.useCallback(function(s){e.current=s,r.current&&tu(r.current,null),r.current=t,t&&tu(t,s)},[t])},th={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},tp=function(e){Object.keys(th).forEach(function(t){e.style.setProperty(t,th[t],"important")})},tg=null,tm=function(e,t){var r=e.scrollHeight;return"border-box"===t.sizingStyle.boxSizing?r+t.borderSize:r-t.paddingSize},tf=function(){},tb=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],t_=!!document.documentElement.currentStyle,ty=function(e){var t=window.getComputedStyle(e);if(null===t)return null;var r=tb.reduce(function(e,r){return e[r]=t[r],e},{}),s=r.boxSizing;if(""===s)return null;t_&&"border-box"===s&&(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),a=parseFloat(r.borderBottomWidth)+parseFloat(r.borderTopWidth);return{sizingStyle:r,paddingSize:i,borderSize:a}};function tw(e,t,r){var s=td(r);i.useLayoutEffect(function(){var r=function(e){return s.current(e)};if(e)return e.addEventListener(t,r),function(){return e.removeEventListener(t,r)}},[])}var tx=function(e,t){tw(document.body,"reset",function(r){e.current.form===r.target&&t(r)})},tv=function(e){tw(window,"resize",e)},tS=function(e){tw(document.fonts,"loadingdone",e)},tT=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],tI=i.forwardRef(function(e,t){var r=e.cacheMeasurements,s=e.maxRows,a=e.minRows,n=e.onChange,o=void 0===n?tf:n,l=e.onHeightChange,d=void 0===l?tf:l,u=function(e,t){if(null==e)return{};var r={};for(var s in e)if(({}).hasOwnProperty.call(e,s)){if(-1!==t.indexOf(s))continue;r[s]=e[s]}return r}(e,tT),c=void 0!==u.value,h=i.useRef(null),p=tc(h,t),g=i.useRef(0),m=i.useRef(),f=function(){var e=h.current,t=r&&m.current?m.current:ty(e);if(t){m.current=t;var i,n,o,l,u,c,p,f,b,_,y,w=(i=e.value||e.placeholder||"x",void 0===(n=a)&&(n=1),void 0===(o=s)&&(o=1/0),tg||((tg=document.createElement("textarea")).setAttribute("tabindex","-1"),tg.setAttribute("aria-hidden","true"),tp(tg)),null===tg.parentNode&&document.body.appendChild(tg),l=t.paddingSize,u=t.borderSize,p=(c=t.sizingStyle).boxSizing,Object.keys(c).forEac
3h(function(e){tg.style[e]=c[e]}),tp(tg),tg.value=i,f=tm(tg,t),tg.value=i,f=tm(tg,t),tg.value="x",_=(b=tg.scrollHeight-l)*n,"border-box"===p&&(_=_+l+u),f=Math.max(_,f),y=b*o,"border-box"===p&&(y=y+l+u),[f=Math.min(y,f),b]),x=w[0],v=w[1];g.current!==x&&(g.current=x,e.style.setProperty("height",x+"px","important"),d(x,{rowHeight:v}))}};return i.useLayoutEffect(f),tx(h,function(){if(!c){var e=h.current.value;requestAnimationFrame(function(){var t=h.current;t&&e!==t.value&&f()})}}),tv(f),tS(f),i.createElement("textarea",to({},u,{onChange:function(e){c||f(),o(e)},ref:p}))}),tE=e.i(519937),tC=e.i(767768);let tk=e=>{let t=(0,tC.useCallbackRef)(e),r=e6(e=>e.onScrollToBottom);(0,i.useEffect)(()=>r(t),[r,t])},tR=(0,i.forwardRef)(({autoFocus:e=!1,asChild:t,disabled:r,onChange:a,onKeyDown:n,onPaste:o,submitOnEnter:l,submitMode:d,cancelOnEscape:u=!0,unstable_focusOnRunStart:c=!0,unstable_focusOnScrollToBottom:h=!0,unstable_focusOnThreadSwitched:p=!0,addAttachmentOnPaste:g=!0,...m},f)=>{let b=eN(),_=d??(!1===l?"none":"enter"),y=tt(e=>e.composer.isEditing?e.composer.text:""),w=t?tn.Slot:tI,x=tt(e=>e.thread.isDisabled||e.composer.dictation?.inputDisabled)||r,v=(0,i.useRef)(null),S=(0,ta.useComposedRefs)(f,v);(0,tE.useEscapeKeydown)(e=>{if(!u||!v.current?.contains(e.target))return;let t=b.composer();t.getState().canCancel&&(t.cancel(),e.preventDefault())});let T=async e=>{if(!g)return;let t=b.thread().getState().capabilities,r=Array.from(e.clipboardData?.files||[]);if(t.attachments&&r.length>0)try{e.preventDefault(),await Promise.all(r.map(e=>b.composer().addAttachment(e)))}catch(e){console.error("Error adding attachment:",e)}},I=e&&!x,E=(0,i.useCallback)(()=>{let e=v.current;e&&I&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[I]);return(0,i.useEffect)(()=>E(),[E]),tk(()=>{"thread"===b.composer().getState().type&&h&&E()}),(0,i.useEffect)(()=>{if("thread"===b.composer().getState().type&&c)return b.on("thread.runStart",E)},[c,E,b]),(0,i.useEffect)(()=>{if("thread"===b.composer().getState().type&&p)return b.on("threadListItem.switchedTo",E)},[p,E,b]),(0,s.jsx)(w,{name:"input",value:y,...m,ref:S,disabled:x,onChange:(0,e8.composeEventHandlers)(a,e=>{b.composer().getState().isEditing&&(e=>{let t=F;F={schedulers:new Set([]),isScheduled:!0};try{let t=e();return z(),t}finally{F=t}})(()=>{b.composer().setText(e.target.value)})}),onKeyDown:(0,e8.composeEventHandlers)(n,e=>{if(!x&&!e.nativeEvent.isComposing&&"Enter"===e.key&&!e.shiftKey){if(b.thread().getState().isRunning)return;let t=!1;"ctrlEnter"===_?t=e.ctrlKey||e.metaKey:"enter"===_&&(t=!0),t&&(e.preventDefault(),v.current?.closest("form")?.requestSubmit())}}),onPaste:(0,e8.composeEventHandlers)(o,T)})});tR.displayName="ComposerPrimitive.Input";let tA=te("ComposerPrimitive.Cancel",()=>{let e=eN(),t=tt(e=>!e.composer.canCancel),r=(0,i.useCallback)(()=>{e.composer().cancel()},[e]);return t?null:r}),tN=te("ComposerPrimitive.AddAttachment",({multiple:e=!0}={})=>{let t=tt(e=>!e.composer.isEditing),r=eN(),s=(0,i.useCallback)(()=>{let t=document.createElement("input");t.type="file",t.multiple=e,t.hidden=!0;let s=r.composer().getState().attachmentAccept;"*"!==s&&(t.accept=s),document.body.appendChild(t),t.onchange=e=>{let s=e.target.files;if(s){for(let e of s)r.composer().addAttachment(e);document.body.removeChild(t)}},t.oncancel=()=>{t.files&&0!==t.files.length||document.body.removeChild(t)},t.click()},[r,e]);return t?null:s},["multiple"]),tM=({index:e,children:t})=>{let r=eN({attachment:eh({source:"composer",query:{type:"index",index:e},get:t=>t.composer().attachment({index:e})})});return(0,s.jsx)(ex,{value:r,children:t})},tj=({components:e})=>{let t=tt(e=>e.attachment);if(!t)return null;let r=((e,t)=>{let r=t.type;switch(r){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:throw Error(`Unknown attachment type: ${r}`)}})(e,t);return r?(0,s.jsx)(r,{}):null},tP=(0,i.memo)(({index:e,components:t})=>(0,s.jsx)(tM,{index:e,children:(0,s.jsx)(tj,{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);tP.displayName="ComposerPrimitive.AttachmentByIndex";let tB=({components:e})=>{let t=tt(e=>e.composer.attachments.length);return(0,i.useMemo)(()=>Array.from({length:t},(t,r)=>(0,s.jsx)(tP,{index:r,components:e},r)),[t,e])};tB.displayName="ComposerPrimitive.Attachments";let tD=(0,i.forwardRef)(({disabled:e,asChild:t=!1,children:r,...a},n)=>{let[o,l]=(0,i.useState)(!1),d=eN(),u=(0,i.useCallback)(t=>{e||(t.preventDefault(),l(!0))},[e]),c=(0,i.useCallback)(t=>{!e&&(t.preventDefault(),o||l(!0))},[e,o]),h=(0,i.useCallback)(t=>{if(e)return;t.preventDefault();let r=t.relatedTarget;r&&t.currentTarget.contains(r)||l(!1)},[e]),p=(0,i.useCallback)(async t=>{if(!e)for(let e of(t.preventDefault(),l(!1),t.dataTransfer.files))try{await d.composer().addAttachment(e)}catch(e){console.error("Failed to add attachment:",e)}},[e,d]),g=t?tn.Slot:"div";return(0,s.jsx)(g,{...o?{"data-dragging":"true"}:null,ref:n,onDragEnterCapture:u,onDragOverCapture:c,onDragLeaveCapture:h,onDropCapture:p,...a,children:r})});tD.displayName="ComposerPrimitive.AttachmentDropzone";let tO=te("ComposerPrimitive.Dictate",()=>{let e=eN(),t=tt(e=>null!=e.composer.dictation||!e.thread.capabilities.dictation||!e.composer.isEditing),r=(0,i.useCallback)(()=>{e.composer().startDictation()},[e]);return t?null:r}),tL=te("ComposerPrimitive.StopDictation",()=>{let e=eN(),t=tt(e=>null!=e.composer.dictation),r=(0,i.useCallback)(()=>{e.composer().stopDictation()},[e]);return t?r:null}),tF=(0,i.forwardRef)(({children:e,...t},r)=>{let i=tt(e=>e.composer.dictation?.transcript);return i?(0,s.jsx)(e9.Primitive.span,{...t,ref:r,children:e??i}):null});tF.displayName="ComposerPrimitive.DictationTranscript";let tU=({children:e,...t})=>tt(e=>{if(!0===t.editing&&!e.composer.isEditing||!1===t.editing&&e.composer.isEditing)return!1;let r=null!=e.composer.dictation;return(!0!==t.dictation||!!r)&&(!1!==t.dictation||!r)})?e:null;tU.displayName="ComposerPrimitive.If";let t$=(0,i.forwardRef)((e,t)=>tt(e=>e.composer.quote)?(0,s.jsx)(e9.Primitive.div,{...e,ref:t}):null);t$.displayName="ComposerPrimitive.Quote";let tz=(0,i.forwardRef)(({children:e,...t},r)=>{let i=tt(e=>e.composer.quote?.text);return i?(0,s.jsx)(e9.Primitive.span,{...t,ref:r,children:e??i}):null});tz.displayName="ComposerPrimitive.QuoteText";let tq=(0,i.forwardRef)(({onClick:e,...t},r)=>{let a=eN(),n=(0,i.useCallback)(()=>{a.composer().setQuote(void 0)},[a]);return(0,s.jsx)(e9.Primitive.button,{type:"button",...t,ref:r,onClick:(0,e8.composeEventHandlers)(e,n)})});tq.displayName="ComposerPrimitive.QuoteDismiss",e.s(["AddAttachment",0,tN,"AttachmentByIndex",0,tP,"AttachmentDropzone",0,tD,"Attachments",0,tB,"Cancel",0,tA,"Dictate",0,tO,"DictationTranscript",0,tF,"If",0,tU,"Input",0,tR,"Quote",0,t$,"QuoteDismiss",0,tq,"QuoteText",0,tz,"Root",0,ti,"Send",0,ts,"StopDictation",0,tL],312654);var tV=e.i(312654),tV=tV;e.s([],310508),e.i(310508);let tH=(0,i.forwardRef)((e,t)=>(0,s.jsx)(e9.Primitive.div,{...e,ref:t}));tH.displayName="ThreadPrimitive.Root";let tJ=({children:e})=>tt(e=>0===e.thread.messages.length&&!e.thread.isLoading)?e:null;tJ.displayName="ThreadPrimitive.Empty";let tW=({children:e,...t})=>tt(e=>(!0!==t.empty||!!e.thread.isEmpty)&&(!1!==t.empty||!e.thread.isEmpty)&&(!0!==t.running||!!e.thread.isRunning)&&(!1!==t.running||!e.thread.isRunning)&&(!0!==t.disabled||!!e.thread.isDisabled)&&(!1!==t.disabled||!e.thread.isDisabled)&&!0)?e:null;tW.displayName="ThreadPrimitive.If";let tG=i.default.createContext(!0);function tK(){throw Error("A function wrapped in useEffectEvent can't be called during rendering.")}let tY="use"in i.default?()=>{try{return i.default.use(tG)}catch{return!1}}:()=>!1,tQ=(e,t)=>{let r,s=eN(),a=(r=i.default.useRef(tK),i.default.useInsertionEffect(()=>{r.current=t},[t]),(...e)=>
3(tY()&&tK(),(0,r.current)(...e))),{scope:n,event:o}=V(e);(0,i.useEffect)(()=>s.on({scope:n,event:o},a),[s,n,o,a])},tZ=e=>{let t=(0,i.useRef)(void 0);return(0,i.useCallback)(r=>{t.current&&t.current(),r&&(t.current=e(r))},[e])},tX=(e,t)=>tZ((0,i.useCallback)(r=>{if(!e)return;let s=e(),i=()=>{let e=t?t(r):r.offsetHeight;s.setHeight(e)},a=new ResizeObserver(i);return a.observe(r),i(),()=>{a.disconnect(),s.unregister()}},[e,t])),t0=(0,i.forwardRef)(({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:a,children:n,...o},l)=>{let d=(({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:s=!0})=>{var a;let n,o=(0,i.useRef)(null),l=e3();void 0===e&&(e="top"!==l.getState().turnAnchor);let d=(0,i.useRef)(0),u=(0,i.useRef)(null),c=(0,i.useCallback)(e=>{let t=o.current;t&&(u.current=e,t.scrollTo({top:t.scrollHeight,behavior:e}))},[]),h=()=>{let e=o.current;if(!e)return;let t=l.getState().isAtBottom,r=1>Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)||e.scrollHeight<=e.clientHeight;!r&&d.current<e.scrollTop||(r&&(u.current=null),(r||null===u.current)&&r!==t&&l.setState({isAtBottom:r})),d.current=e.scrollTop},p=(a=()=>{let t=u.current;t?c(t):e&&l.getState().isAtBottom&&c("instant"),h()},n=(0,tC.useCallbackRef)(a),tZ((0,i.useCallback)(e=>{let t=new ResizeObserver(()=>{n()}),r=new MutationObserver(e=>{e.some(e=>"attributes"!==e.type||"style"!==e.attributeName)&&n()});return t.observe(e),r.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{t.disconnect(),r.disconnect()}},[n]))),g=tZ(e=>(e.addEventListener("scroll",h),()=>{e.removeEventListener("scroll",h)}));return tk(({behavior:e})=>{c(e)}),tQ("thread.runStart",()=>{t&&(u.current="auto",requestAnimationFrame(()=>{c("auto")}))}),tQ("thread.initialize",()=>{r&&(u.current="instant",requestAnimationFrame(()=>{c("instant")}))}),tQ("threadListItem.switchedTo",()=>{s&&(u.current="instant",requestAnimationFrame(()=>{c("instant")}))}),(0,ta.useComposedRefs)(p,g,o)})({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:a}),u=tX(e6(e=>e.registerViewport),(0,i.useCallback)(e=>e.clientHeight,[])),c=(0,ta.useComposedRefs)(l,d,u);return(0,s.jsx)(e9.Primitive.div,{...o,ref:c,children:n})});t0.displayName="ThreadPrimitive.ViewportScrollable";let t1=(0,i.forwardRef)(({turnAnchor:e,...t},r)=>(0,s.jsx)(e4,{options:{turnAnchor:e},children:(0,s.jsx)(t0,{...t,ref:r})}));t1.displayName="ThreadPrimitive.Viewport";let t5=(0,i.forwardRef)((e,t)=>{let r=tX(e6(e=>e.registerContentInset),(0,i.useCallback)(e=>{let t=parseFloat(getComputedStyle(e).marginTop)||0;return e.offsetHeight+t},[])),a=(0,ta.useComposedRefs)(t,r);return(0,s.jsx)(e9.Primitive.div,{...e,ref:a})});t5.displayName="ThreadPrimitive.ViewportFooter";let t2=(0,i.createContext)(!1),t6=(e,t)=>{let r=e.match(/^([\d.]+)(em|px|rem)$/);if(!r)return 0;let s=parseFloat(r[1]),i=r[2];return"px"===i?s:"em"===i?s*(parseFloat(getComputedStyle(t).fontSize)||16):"rem"===i?s*(parseFloat(getComputedStyle(document.documentElement).fontSize)||16):0},t3=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{let a=tt(e=>e.message.isLast&&"assistant"===e.message.role&&e.message.index>=1&&e.thread.messages.at(e.message.index-1)?.role==="user"),n=e3({optional:!0}),o=(0,i.useContext)(t2),l=tZ((0,i.useCallback)(e=>{if(!n||o)return;let s=()=>{let s=n.getState();if("top"===s.turnAnchor&&a){let{viewport:i,inset:a,userMessage:n}=s.height,o=t6(t,e),l=t6(r,e),d=Math.max(0,i-a-(n<=o?n:l));e.style.minHeight=`${d}px`,e.style.flexShrink="0",e.style.transition="min-height 0s"}else e.style.minHeight="",e.style.flexShrink="",e.style.transition=""};return s(),n.subscribe(s)},[n,a,o,t,r]));return(0,s.jsx)(t2.Provider,{value:!0,children:(0,s.jsx)(tn.Slot,{ref:l,children:e})})};t3.displayName="ThreadPrimitive.ViewportSlack";let t4=({index:e,children:t})=>{let r=eN({message:eh({source:"thread",query:{type:"index",index:e},get:t=>t.thread().message({index:e})}),composer:eh({source:"message",query:{},get:t=>t.thread().message({index:e}).composer()})});return(0,s.jsx)(ex,{value:r,children:t})},t7=(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,t8=()=>null,t9=({components:e})=>{let t=((e,t,r)=>{switch(t){case"user":if(r)return e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message;return e.UserMessage??e.Message;case"assistant":if(r)return e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message;return e.AssistantMessage??e.Message;case"system":if(r)return e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message;return e.SystemMessage??t8;default:throw Error(`Unknown message role: ${t}`)}})(e,tt(e=>e.message.role),tt(e=>e.message.composer.isEditing));return(0,s.jsx)(t,{})},re=(0,i.memo)(({index:e,components:t})=>(0,s.jsx)(t4,{index:e,children:(0,s.jsx)(t9,{components:t})}),(e,t)=>e.index===t.index&&t7(e.components,t.components));re.displayName="ThreadPrimitive.MessageByIndex";let rt=({components:e})=>{let t=tt(e=>e.thread.messages.length);return(0,i.useMemo)(()=>0===t?null:Array.from({length:t},(t,r)=>(0,s.jsx)(re,{index:r,components:e},r)),[t,e])};rt.displayName="ThreadPrimitive.Messages";let rr=(0,i.memo)(rt,(e,t)=>t7(e.components,t.components)),rs=te("ThreadPrimitive.ScrollToBottom",({behavior:e}={})=>{let t=e6(e=>e.isAtBottom),r=e3(),s=(0,i.useCallback)(()=>{r.getState().scrollToBottom({behavior:e})},[r,e]);return t?null:s},["behavior"]),ri=te("ThreadPrimitive.Suggestion",({prompt:e,send:t,clearComposer:r=!0,autoSend:s,method:a})=>{let n=eN(),o=tt(e=>e.thread.isDisabled),l=t??s??!1,d=(0,i.useCallback)(()=>{let t=n.thread().getState().isRunning;if(l&&!t)n.thread().append({content:[{type:"text",text:e}],runConfig:n.composer().getState().runConfig}),r&&n.composer().setText("");else if(r)n.composer().setText(e);else{let t=n.composer().getState().text;n.composer().setText(t.trim()?`${t} ${e}`:e)}},[n,l,r,e]);return o?null:d},["prompt","send","clearComposer","autoSend","method"]),ra=({index:e,children:t})=>{let r=eN({suggestion:eh({source:"suggestions",query:{index:e},get:t=>t.suggestions().suggestion({index:e})})});return(0,s.jsx)(ex,{value:r,children:t})},rn=({components:e})=>{let t=e.Suggestion;return(0,s.jsx)(t,{})},ro=(0,i.memo)(({index:e,components:t})=>(0,s.jsx)(ra,{index:e,children:(0,s.jsx)(rn,{components:t})}),(e,t)=>e.index===t.index&&e.components.Suggestion===t.components.Suggestion);ro.displayName="ThreadPrimitive.SuggestionByIndex";let rl=({components:e})=>{let t=tt(e=>e.suggestions.suggestions.length);return(0,i.useMemo)(()=>0===t?null:Array.from({length:t},(t,r)=>(0,s.jsx)(ro,{index:r,components:e},r)),[t,e])};rl.displayName="ThreadPrimitive.Suggestions";let rd=(0,i.memo)(rl,(e,t)=>e.components.Suggestion===t.components.Suggestion);e.s(["Empty",0,tJ,"If",0,tW,"MessageByIndex",0,re,"Messages",0,rr,"Root",0,tH,"ScrollToBottom",0,rs,"Suggestion",0,ri,"SuggestionByIndex",0,ro,"Suggestions",0,rd,"Viewport",0,t1,"ViewportFooter",0,t5,"ViewportProvider",0,e4,"ViewportSlack",0,t3],68167);var ru=e.i(68167),ru=ru;class rc{_contextProvider=new eW;registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}}var rh=e.i(878598);let rp=Symbol("aui.parse-partial-json-object.meta"),rg=e=>{if(0===e.length)return{[rp]:{state:"partial",partialPath:[]}};try{let t=rh.default.parse(e);if("object"!=typeof t||null===t)throw Error("argsText is expected to be an object");return t[rp]={state:"complete",partialPath:[]},t}catch{try{let[t,r]=function(e){let t,r=["ROOT"],s=-1,i=null,a=[];function n(){void 0!==t&&(a.push(JSON.parse(`"${t}"`)),t=void 0)}function o(e,t,a){switch(e){case'"':s=t,r.pop(),r.push(a),r.push("INSIDE_STRING"),n();break;case"f":case"t":case"n":s=t,i=t,r.pop(),r.push(a),r.push("INSIDE_LITERAL");break;case"-":r.pop(),r.push(a),r.push("INSIDE_NUMBER"),n();break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":s=t,r.pop(),r.push(a),r.push("INSIDE_NUMBER"),n();break;case"{":s=t,r.pop(),r.push(a),r.push("INSIDE_OBJECT_START"),n();break;case"[":s=t,r.pop(),r.push(a),r.push("INSIDE_ARRAY_START"),n()}}function l(e,i){switch(e){case",":r.pop(),r.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":s=i,r.pop(),t=a.pop()}}function d(e,i){switch(e){case",":r.pop(),r.push("INSIDE_ARRAY_AFTER_COMMA"),t=(Number(t)+1).toString();break;case"]":s=i,r.pop(),t=a.pop()}}for(let n=0;n<e.length;n++){let u=e[n];switch(r[r.length-1]){case"ROOT":o(u,n,"FINISH");break;case"INSIDE_OBJECT_START":switch(u){case'"':r.pop(),r.push("INSIDE_OBJECT_KEY"),t="";break;case"}":s=n,r.pop(),t=a.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":'"'===u&&(r.pop(),r.push("INSIDE_OBJECT_KEY"),t="");break;case"INSIDE_OBJECT_KEY":switch(u){case'"':r.pop(),r.push("INSIDE_OBJECT_AFTER_KEY");break;case"\\":r.push("INSIDE_STRING_ESCAPE"),t+=u;break;default:t+=u}break;case"INSIDE_OBJECT_AFTER_KEY":":"===u&&(r.pop(),r.push("INSIDE_OBJECT_BEFORE_VALUE"));break;case"INSIDE_OBJECT_BEFORE_VALUE":o(u,n,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":l(u,n);break;case"INSIDE_STRING":switch(u){case'"':r.pop(),s=n,t=a.pop();break;case"\\":r.push("INSIDE_STRING_ESCAPE");break;default:s=n}break;case"INSIDE_ARRAY_START":"]"===u?(s=n,r.pop(),t=a.pop()):(s=n,t="0",o(u,n,"INSIDE_ARRAY_AFTER_VALUE"));break;case"INSIDE_ARRAY_AFTER_VALUE":switch(u){case",":r.pop(),r.push("INSIDE_ARRAY_AFTER_COMMA"),t=(Number(t)+1).toString();break;case"]":s=n,r.pop(),t=a.pop();break;default:s=n}break;case"INSIDE_ARRAY_AFTER_COMMA":o(u,n,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":r.pop(),"INSIDE_STRING"===r[r.length-1]?s=n:"INSIDE_OBJECT_KEY"===r[r.length-1]&&(t+=u);break;case"INSIDE_NUMBER":switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":s=n;break;case"e":case"E":case"-":case".":break;case",":r.pop(),t=a.pop(),"INSIDE_ARRAY_AFTER_VALUE"===r[r.length-1]&&d(u,n
3),"INSIDE_OBJECT_AFTER_VALUE"===r[r.length-1]&&l(u,n);break;case"}":r.pop(),t=a.pop(),"INSIDE_OBJECT_AFTER_VALUE"===r[r.length-1]&&l(u,n);break;case"]":r.pop(),t=a.pop(),"INSIDE_ARRAY_AFTER_VALUE"===r[r.length-1]&&d(u,n);break;default:r.pop(),t=a.pop()}break;case"INSIDE_LITERAL":{let t=e.substring(i,n+1);"false".startsWith(t)||"true".startsWith(t)||"null".startsWith(t)?s=n:(r.pop(),"INSIDE_OBJECT_AFTER_VALUE"===r[r.length-1]?l(u,n):"INSIDE_ARRAY_AFTER_VALUE"===r[r.length-1]&&d(u,n))}}}let u=e.slice(0,s+1);for(let t=r.length-1;t>=0;t--)switch(r[t]){case"INSIDE_STRING":u+='"';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":u+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":u+="]";break;case"INSIDE_LITERAL":{let t=e.substring(i,e.length);"true".startsWith(t)?u+="true".slice(t.length):"false".startsWith(t)?u+="false".slice(t.length):"null".startsWith(t)&&(u+="null".slice(t.length))}}return[u,a]}(e),s=rh.default.parse(t);if("object"!=typeof s||null===s)throw Error("argsText is expected to be an object");return s[rp]={state:"partial",partialPath:r},s}catch{return}}},rm=(e,t=21)=>(r=t)=>{let s="",i=0|r;for(;i--;)s+=e[Math.random()*e.length|0];return s},rf=rm("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),rb=()=>`__optimistic__${rf()}`,r_=(e,t,r)=>{let{role:s,id:i,createdAt:a,attachments:n,status:o,metadata:l}=e,d={id:i??t,createdAt:a??new Date},u="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;if("user"!==s&&n?.length)throw Error("attachments are only supported for user messages");if("assistant"!==s&&o)throw Error("status is only supported for assistant messages");if("assistant"!==s&&l?.steps)throw Error("metadata.steps is only supported for assistant messages");switch(s){case"assistant":return{...d,role:s,content:u.map(e=>{let t=e.type;switch(t){case"text":case"reasoning":if(0===e.text.trim().length)return null;return e;case"file":case"source":case"data":return e;case"image":return(({image:e,...t})=>e.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?{...t,image:e}:(console.warn("Invalid image data format detected"),null))(e);case"tool-call":{let{parentId:t,messages:r,...s}=e,i={...s,toolCallId:e.toolCallId??`tool-${rf()}`,...void 0!==t&&{parentId:t},...void 0!==r&&{messages:r}};if(e.args)return{...i,args:e.args,argsText:e.argsText??JSON.stringify(e.args)};return{...i,args:rg(e.argsText??"")??{},argsText:e.argsText??""}}default:throw Error(`Unsupported assistant message part type: ${t}`)}}).filter(e=>!!e),status:o??r,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}}};case"user":return{...d,role:s,content:u.map(e=>{let t=e.type;switch(t){case"text":case"image":case"audio":case"file":case"data":return e;default:throw Error(`Unsupported user message part type: ${t}`)}}),attachments:n??[],metadata:{custom:l?.custom??{}}};case"system":if(1!==u.length||"text"!==u[0].type)throw Error("System messages must have exactly one text message part.");return{...d,role:s,content:u,metadata:{custom:l?.custom??{}}};default:throw Error(`Unknown message role: ${s}`)}},ry=(e,t)=>void 0===t?e.status?.type==="requires-action"&&"tool-calls"===e.status.reason&&e.content.every(e=>"tool-call"!==e.type||!!e.result):e.status?.type==="requires-action"&&"tool-calls"===e.status.reason&&e.content.every(e=>"tool-call"!==e.type||!!e.result||!t.includes(e.toolName)),rw=e=>e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n"),rx=Symbol("autoStatus"),rv=Object.freeze(Object.assign({type:"running"},{[rx]:!0})),rS=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[rx]:!0})),rT=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[rx]:!0})),rI=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[rx]:!0})),rE=e=>{let t=e.map(e=>r_(e,rf(),rS));return{messages:t.map((e,r)=>({parentId:r>0?t[r-1].id:null,message:e}))}},rC=e=>e.next?rC(e.next):"current"in e?e:null;class rk{func;_value=null;constructor(e){this.func=e}get value(){return null===this._value&&(this._value=this.func()),this._value}dirty(){this._value=null}}class rR{messages=new Map;head=null;root={children:[],next:null};updateLevels(e,t){for(let r of(e.level=t,e.children)){let e=this.messages.get(r);e&&this.updateLevels(e,t+1)}}performOp(e,t,r){let s=t.prev??this.root,i=e??this.root;if("relink"!==r||s!==i){if("link"!==r&&(s.children=s.children.filter(e=>e!==t.current.id),s.next===t)){let e=s.children.at(-1),t=e?this.messages.get(e):null;if(void 0===t)throw Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");s.next=t}if("cut"!==r){for(let r=e;r;r=r.prev)if(r.current.id===t.current.id)throw 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.");i.children=[...i.children,t.current.id],(rC(t)===this.head||null===i.next)&&(i.next=t),t.prev=e;
3let r=e?e.level+1:0;this.updateLevels(t,r)}}}_messages=new rk(()=>{let e=Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e});get headId(){return this.head?.current.id??null}getMessages(e){if(void 0===e||e===this.head?.current.id)return this._messages.value;let t=this.messages.get(e);if(!t)throw Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");let r=Array(t.level+1);for(let e=t;e;e=e.prev)r[e.level]=e.current;return r}addOrUpdateMessage(e,t){let r=this.messages.get(t.id),s=e?this.messages.get(e):null;if(void 0===s)throw Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(r){r.current=t,this.performOp(s,r,"relink"),this._messages.dirty();return}let i={prev:s,current:t,next:null,children:[],level:s?s.level+1:0};this.messages.set(t.id,i),this.performOp(s,i,"link"),this.head===s&&(this.head=i),this._messages.dirty()}getMessage(e){let t=this.messages.get(e);if(!t)throw 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}}appendOptimisticMessage(e,t){let r;do r=rb();while(this.messages.has(r))return this.addOrUpdateMessage(e,r_(t,r,{type:"running"})),r}deleteMessage(e,t){let r=this.messages.get(e);if(!r)throw Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");let s=void 0===t?r.prev:null===t?null:this.messages.get(t);if(void 0===s)throw Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(let e of r.children){let t=this.messages.get(e);if(!t)throw Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(s,t,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=rC(s??this.root)),this._messages.dirty()}getBranches(e){let t=this.messages.get(e);if(!t)throw Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");let{children:r}=t.prev??this.root;return r}switchToBranch(e){let t=this.messages.get(e);if(!t)throw Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");(t.prev??this.root).next=t,this.head=rC(t),this._messages.dirty()}resetHead(e){if(null===e)return void this.clear();let t=this.messages.get(e);if(!t)throw Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(t.children.length>0){let e=t=>{for(let r of t.children){let t=this.messages.get(r);t&&(e(t),this.messages.delete(r))}};e(t),t.children=[],t.next=null}this.head=t;for(let e=t;e;e=e.prev)e.prev?e.prev.next=e:this.root.next=e;this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){let e=[];for(let[,t]of this.messages)e.push({message:t.current,parentId:t.prev?.current.id??null});return{headId:this.head?.current.id??null,messages:e}}import({headId:e,messages:t}){for(let{message:e,parentId:r}of t)this.addOrUpdateMessage(r,e);this.resetHead(e??t.at(-1)?.message.id??null)}}let rA=Symbol("skip-update");class rN{_subscribers=new Set;subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{let t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){let e=[];for(let t of this._subscribers)try{t()}catch(t){e.push(t)}if(e.length>0)if(1===e.length)throw e[0];else{for(let t of e)console.error(t);throw AggregateError(e)}}}class rM{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(){for(let e of this._subscriptions)e()}_updateConnection(){this._subscriptions.size>0?this._connection||(this._connection=this._connect()):(this._connection?.(),this._connection=void 0)}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}}class rj extends rM{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e;const t=e.getState();if(t===rA)throw Error("Entry not available in the store");this._previousState=t}_previousState;getState=()=>(this.isConnected||this._syncState(),this._previousState);_syncState(){let e=this.binding.getState();return!(e===rA||function(e,t){if(void 0===e&&void 0===t)return!0;
3if(void 0===e||void 0===t)return!1;for(let r of Object.keys(e))if(!Object.is(e[r],t[r]))return!1;return!0}(e,this._previousState))&&(this._previousState=e,!0)}_connect(){let e=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(e)}}class rP extends rM{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e}_previousStateDirty=!0;_previousState;getState=()=>{if(!this.isConnected||this._previousStateDirty){let e=this.binding.getState();e!==rA&&(this._previousState=e),this._previousStateDirty=!1}if(void 0===this._previousState)throw Error("Entry not available in the store");return this._previousState};_connect(){let e=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(e)}}class rB extends rM{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){let e=()=>{this.notifySubscribers()},t=this.binding.getState(),r=t?.subscribe(e),s=()=>{let s=this.binding.getState();s!==t&&(t=s,r?.(),r=s?.subscribe(e),e())},i=this.outerSubscribe(s);return()=>{i?.(),r?.()}}}class rD extends rM{config;constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){let e=()=>{this.notifySubscribers()},t=this.config.binding.getState(),r=t?.unstable_on(this.config.event,e),s=()=>{let s=this.config.binding.getState();s!==t&&(t=s,r?.(),r=s?.unstable_on(this.config.event,e))},i=this.outerSubscribe(s);return()=>{i?.(),r?.()}}}class rO extends rN{isEditing=!0;get attachmentAccept(){return this.getAttachmentAdapter()?.accept??"*"}_attachments=[];get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}_text="";get text(){return this._text}_role="user";get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}_quote=void 0;get quote(){return this._quote}setQuote(e){this._quote!==e&&(this._quote=e,this._notifySubscribers())}setText(e){if(this._text!==e){if(this._text=e,this._dictation){this._dictationBaseText=e,this._currentInterimText="";let{status:t,inputDisabled:r}=this._dictation;this._dictation=r?{status:t,inputDisabled:r}:{status:t}}this._notifySubscribers()}}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){let e=this.getAttachmentAdapter();e&&await Promise.all(this._attachments.map(t=>e.remove(t)))}async reset(){if(0===this._attachments.length&&""===this._text&&"user"===this._role&&0===Object.keys(this._runConfig).length&&void 0===this._quote)return;this._role="user",this._runConfig={},this._quote=void 0;let e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){let e=this._onClearAttachments();this.setAttachments([]),await e}async send(){this._dictationSession&&(this._dictationSession.cancel(),this._cleanupDictation());let e=this.getAttachmentAdapter(),t=e&&this.attachments.length>0?Promise.all(this.attachments.map(async t=>"complete"===t.status.type?t:await e.send(t))):[],r=this.text,s=this._quote;this._quote=void 0,this._emptyTextAndAttachments();let i={createdAt:new Date,role:this.role,content:r?[{type:"text",text:r}]:[],attachments:await t,runConfig:this.runConfig,metadata:{custom:{...s?{quote:s}:{}}}};this.handleSend(i),this._notifyEventSubscribers("send")}cancel(){this.handleCancel()}async addAttachment(e){let t=this.getAttachmentAdapter();if(!t)throw Error("Attachments are not supported");let r=e=>{let t=this._attachments.findIndex(t=>t.id===e.id);-1!==t?this._attachments=[...this._attachments.slice(0,t),e,...this._attachments.slice(t+1)]:this._attachments=[...this._attachments,e],this._notifySubscribers()},s=t.add({file:e});if(Symbol.asyncIterator in s)for await(let e of s)r(e);else r(await s);this._notifyEventSubscribers("attachmentAdd"),this._notifySubscribers()}async removeAttachment(e){let t=this.getAttachmentAdapter();if(!t)throw Error("Attachments are not supported");let r=this._attachments.findIndex(t=>t.id===e);if(-1===r)throw Error("Attachment not found");let s=this._attachments[r];await t.remove(s),this._attachments=this._attachments.filter(t=>t.id!==e),this._notifySubscribers()}_dictation;_dictationSession;_dictationUnsubscribes=[];_dictationBaseText="";_currentInterimText="";_dictationSessionIdCounter=0;_activeDictationSessionId;_isCleaningDictation=!1;get dictation(){return this._dictation}_isActiveSession(e,t){return this._activeDictationSessionId===e&&this._dictationSession===t}startDictation(){let e=this.getDictationAdapter();if(!e)throw Error("Dictation adapter not configured");if(this._dictationSession){for(let e of this._dictationUnsubscribes)e();this._dictationUnsubscribes=[],this._dictationSession.stop().catch(()=>{}),this._dictationSession=void 0}let t=e.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText="";let r=e.listen();this._dictationSession=r;let s=++this._dictationSessionIdCounter;this._activeDictationSessionId=s,this._dictation={status:r.status,inputDisabled:t},this._notifySubscribers();let i=r.onSpeech(e=>{if(!this._isActiveSession(s,r))return;let t=!1!==e.isFinal,i=this._dictationBaseText&&!this._dictationBaseText.endsWith(" ")&&e.transcript?" ":"";if(t){if(this._dictationBaseText=this._dictationBaseText+i+e.transcript,this._currentInterimText="",this._text=this._dictationBaseText,this._dictation){let{transcript:e,...t}=this._dictation;this._dictation=t}this._notifySubscribers()}else this._currentInterimText=i+e.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&(this._dictation={...this._dictation,transcript:e.transcript}),this._notifySubscribers()});this._dictationUnsubscribes.push(i);let a=r.onSpeechStart(()=>{this._isActiveSession(s,r)&&(this._dictation={status:{type:"running"},inputDisabled:t,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())});this._dictationUnsubscribes.push(a);let n=r.onSpeechEnd(()=>{this._cleanupDictation({sessionId:s})});this._dictationUnsubscribes.push(n);let o=setInterval(()=>{this._isActiveSession(s,r)&&"ended"===r.status.type&&this._cleanupDictation({sessionId:s})},100);this._dictationUnsubscribes.push(()=>clearInterval(o))}stopDictation(){if(!this._dictationSession)return;let e=this._dictationSession,t=this._activeDictationSessionId;e.stop().finally(()=>{this._cleanupDictation({sessionId:t})})}_cleanupDictation(e){if((e?.sessionId===void 0||e.sessionId===this._activeDictationSessionId)&&!this._isCleaningDictation){this._isCleaningDictation=!0;try{for(let e of this._dictationUnsubscribes)e();this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText="",this._currentInterimText="",this._notifySubscribers()}finally{this._isCleaningDictation=!1}}}_eventSubscribers=new Map;_notifyEventSubscribers(e){let t=this._eventSubscribers.get(e);if(t)for(let e of t)e()}unstable_on(e,t){let r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{let r=this._eventSubscribers.get(e);r&&r.delete(t)}}}class rL extends rO{runtime;_canCancel=!1;get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}constructor(e){super(),this.runtime=e,this.connect()}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}async handleSend(e){this.runtime.append({...e,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null})}async handleCancel(){this.runtime.cancelRun()}}class rF extends rO{runtime;endEditCallback;get canCancel(){return!0}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}_nonTextParts;_previousText;_parentId;_sourceId;constructor(e,t,{parentId:r,message:s}){super(),this.runtime=e,this.endEditCallback=t,this._parentId=r,this._sourceId=s.id,this._previousText=rw(s),this.setText(this._previousText),this.setRole(s.role),this.setAttachments(s.attachments??[]),this._nonTextParts=s.content.filter(e=>"text"!==e.type),this.setRunConfig({...e.composer.runConfig})}async handleSend(e){rw(e)!==this._previousText&&this.runtime.append({...e,content:[...e.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId}),this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}}class rU{_contextProvider;_subscriptions=new Set;_isInitialized=!1;repository=new rR;get messages(){return this.repository.getMessages()}get state(){let e;for(let t of this.messages)"assistant"===t.role&&(e=t);return e?.metadata.unstable_state??null}composer=new rL(this);constructor(e){this._contextProvider=e}getModelContext(){return this._contextProvider.getModelContext()}_editComposers=new Map;getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw Error("Edit already in progress");this._editComposers.set(e,new rF(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{return}}getBranches(e){return this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(let e of this._subscriptions)e()}_notifyEventSubscribers(e){let t=this._eventSubscribers.get(e);if(t)for(let e of t)e()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){let r=this.adapters?.feedback;if(!r)throw Error("Feedback adapter not configured");let{message:s,parentId:i}=this.repository.getMessage(e);if(r.submit({message:s,type:t}),"assistant"===s.role){let e={...s,metadata:{...s.metadata,submittedFeedback:{type:t}}};this.repository.addOrUpdateMessage(i,e)}this._notifySubscribers()}_stopSpeaking;speech;speak(e){let t=this.adapters?.speech;if(!t)throw Error("Speech adapter not configured");let{message:r}=this.repository.getMessage(e);this._stopSpeaking?.();let s=t.speak(rw(r)),i=s.subscribe(()=>{"ended"===s.status.type?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:s.status},this._notifySubscribers()});this.speech={messageId:e,status:s.status},this._notifySubscribers(),this._stopSpeaking=()=>{s.cancel(),i(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw Error("No message is being spoken");this._stopSpeaking(),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(rE(e??[]))}_eventSubscribers=new Map;unstable_on(e,t){if("modelContextUpdate"===e)return this._contextProvider.subscribe?.(t)??(()=>{});let r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}}
3class r$ extends Error{name="AbortError";detach;constructor(e,t){super(t),this.detach=e}}class rz extends rU{capabilities={switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,dictation:!1,attachments:!1,feedback:!1};abortController=null;isDisabled=!1;_isLoading=!1;get isLoading(){return this._isLoading}_suggestions=[];_suggestionsController=null;get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}constructor(e,t){super(e),this.__internal_setOptions(t)}_options;_lastRunConfig={};_getThreadId;__internal_setGetThreadId(e){this._getThreadId=e}_getInitializePromise;__internal_setGetInitializePromise(e){this._getInitializePromise=e}get extras(){}__internal_setOptions(e){if(this._options===e)return;this._options=e;let t=!1,r=e.adapters?.speech!==void 0;this.capabilities.speech!==r&&(this.capabilities.speech=r,t=!0);let s=e.adapters?.dictation!==void 0;this.capabilities.dictation!==s&&(this.capabilities.dictation=s,t=!0);let i=e.adapters?.attachments!==void 0;this.capabilities.attachments!==i&&(this.capabilities.attachments=i,t=!0);let a=e.adapters?.feedback!==void 0;this.capabilities.feedback!==a&&(this.capabilities.feedback=a,t=!0),t&&this._notifySubscribers()}_loadPromise;__internal_load(){if(this._loadPromise)return this._loadPromise;let e=this.adapters.history?.load()??Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=e.then(e=>{if(!e)return;this.repository.import(e),e.messages.length>0&&this.ensureInitialized(),this._notifySubscribers();let t=this.adapters.history?.resume?.bind(this.adapters.history);e.unstable_resume&&t&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},t).catch(()=>{})}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}async append(e){this.ensureInitialized();let t=this._getInitializePromise?.();t&&await t;let r=r_(e,rf(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(e.parentId,r),this._options.adapters.history?.append({parentId:e.parentId,message:r,...void 0!==e.runConfig&&{runConfig:e.runConfig}}),e.startRun??"user"===e.role?await this.startRun({parentId:r.id,sourceId:e.sourceId,runConfig:e.runConfig??{}}):(this.repository.resetHead(r.id),this._notifySubscribers())}resumeRun({stream:e,...t}){if(!e)throw Error("You must pass a stream parameter to resume runs.");return this.startRun(t,e)}exportExternalState(){throw Error("Runtime does not support exporting external states.")}importExternalState(){throw Error("Runtime does not support importing external states.")}unstable_loadExternalState(){throw Error("Runtime does not support importing external states.")}async startRun({parentId:e,runConfig:t},r){this.ensureInitialized();let s={id:rf(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("runStart");try{this._suggestions=[],this._suggestionsController?.abort(),this._suggestionsController=null,this._notifySubscribers();do s=await this.performRoundtrip(e,s,t,r),r=void 0;while(ry(s,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("runEnd")}this._suggestionsController=new AbortController;let i=this._suggestionsController.signal;if(this.adapters.suggestion&&s.status?.type!=="requires-action"){let e=this.adapters.suggestion?.generate({messages:this.messages});if(Symbol.asyncIterator in e)for await(let t of e){if(i.aborted)break;this._suggestions=t,this._notifySubscribers()}else{let t=await e;if(i.aborted)return;this._suggestions=t,this._notifySubscribers()}}}async performRoundtrip(e,t,r,s){let i=e?this.repository.getMessages(e):[];this.abortController?.abort(),this.abortController=new AbortController;let a=t.content,n=t.metadata?.unstable_annotations,o=t.metadata?.unstable_data,l=t.metadata?.steps,d=t.metadata?.custom,u=r=>{let s=r.metadata?.steps,i=s?[...l??[],...s]:void 0,u=r.metadata?.unstable_annotations,c=r.metadata?.unstable_data,h=u?[...n??[],...u]:void 0,p=c?[...o??[],...c]:void 0;t={...t,...r.content?{content:[...a,...r.content??[]]}:void 0,status:r.status??t.status,...r.metadata?{metadata:{...t.metadata,...r.metadata.unstable_state?{unstable_state:r.metadata.unstable_state}:void 0,...h?{unstable_annotations:h}:void 0,...p?{unstable_data:p}:void 0,...i?{steps:i}:void 0,...r.metadata?.timing?{timing:r.metadata.timing}:void 0,...r.metadata?.custom?{custom:{...d??{},...r.metadata.custom}}:void 0}}:void 0},this.repository.addOrUpdateMessage(e,t),this._notifySubscribers()},c=this._options.maxSteps??2;if((t.metadata?.steps?.length??0)>=c)return u({status:{type:"incomplete",reason:"tool-calls"}}),t;u({status:{type:"running"}}),this.repository.resetHead(t.id),this._notifySubscribers();try{this._lastRunConfig=r??{};let a=this.getModelContext();s=s??this.adapters.chatModel.run.bind(this.adapters.chatModel);let n=this.abortController.signal,o=this._getThreadId?.(),l=s({messages:i,runConfig:this._lastRunConfig,abortSignal:n,context:a,c
3onfig:a,unstable_assistantMessageId:t.id,unstable_threadId:o,unstable_parentId:e,unstable_getMessage:()=>t});if(Symbol.asyncIterator in l)for await(let e of l){if(n.aborted){u({status:{type:"incomplete",reason:"cancelled"}});break}u(e)}else u(await l);"running"===t.status.type&&u({status:{type:"complete",reason:"unknown"}})}catch(e){if(e instanceof r$)u({status:{type:"incomplete",reason:"cancelled"}});else if(e instanceof Error&&"AbortError"===e.name)u({status:{type:"incomplete",reason:"cancelled"}});else throw u({status:{type:"incomplete",reason:"error",error:e instanceof Error?e.message:`[${typeof e}] ${new String(e).toString()}`}}),e}finally{this.abortController=null,("complete"===t.status.type||"incomplete"===t.status.type)&&await this._options.adapters.history?.append({parentId:e,message:t,runConfig:this._lastRunConfig})}return t}detach(){let e=new r$(!0);this.abortController?.abort(e),this.abortController=null}cancelRun(){let e=new r$(!1);this.abortController?.abort(e),this.abortController=null}addToolResult({messageId:e,toolCallId:t,result:r,isError:s,artifact:i}){let a=this.repository.getMessage(e),{parentId:n}=a,{message:o}=a;if("assistant"!==o.role)throw Error("Tried to add tool result to non-assistant message");let l=!1,d=!1,u=o.content.map(e=>"tool-call"!==e.type||e.toolCallId!==t?e:(d=!0,e.result||(l=!0),{...e,result:r,artifact:i,isError:s}));if(!d)throw Error("Tried to add tool result to non-existing tool call");o={...o,content:u},this.repository.addOrUpdateMessage(n,o),l&&ry(o,this._options.unstable_humanToolNames)&&this.performRoundtrip(n,o,this._lastRunConfig).catch(()=>{})}resumeToolCall(e){throw Error("Local runtime does not support resuming tool calls.")}}let rq=Object.freeze([]),rV="__DEFAULT_ID__",rH=Object.freeze({[rV]:{id:rV,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}});class rJ extends rN{_mainThread;constructor(e){super(),this._mainThread=e()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){}get threadIds(){return rq}get archivedThreadIds(){return rq}get mainThreadId(){return rV}get threadItems(){return rH}getThreadRuntimeCore(){throw Error("Method not implemented.")}getLoadThreadsPromise(){return Promise.resolve()}getItemById(e){if(e===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw Error("Method not implemented")}async switchToThread(){throw Error("Method not implemented.")}switchToNewThread(){throw Error("Method not implemented.")}rename(){throw Error("Method not implemented.")}archive(){throw Error("Method not implemented.")}detach(){throw Error("Method not implemented.")}unarchive(){throw Error("Method not implemented.")}delete(){throw Error("Method not implemented.")}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){throw Error("Method not implemented.")}}class rW extends rc{threads;Provider=void 0;_options;constructor(e,t){super(),this._options=e,this.threads=new rJ(()=>new rz(this._contextProvider,this._options)),t&&this.threads.getMainThreadRuntimeCore().import(rE(t))}}let rG=(0,i.createContext)(null),rK=({adapters:e,children:t})=>{let r=(0,i.useContext)(rG);return(0,s.jsx)(rG.Provider,{value:{...r,...e},children:t})};class rY{_core;_threadListBinding;get path(){return this._core.path}constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.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(){let e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){let t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){let e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){let e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){let e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){let e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){let e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let r=this._core.getState().isMain,s=this._core.getState().id;return this.subscribe(()=>{let i=this._core.getState(),a=i.isMain,n=i.id;r===a&&s===n||(r=a,s=n,"switchedTo"===e&&!a||"switchedAway"===e&&a||t())})}subscribe(e){return this._core.subscribe(e)}detach(){let e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}}let rQ=Symbol("innerMessage");Symbol("innerMessages");class rZ{_core;get path(){return this._core.path}constructor(e){this._core=e,this.__internal_bindMethods()}
3__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)}}class rX extends rZ{_composerApi;constructor(e,t){super(e),this._composerApi=t}remove(){let e=this._composerApi.getState();if(!e)throw Error("Composer is not available");return e.removeAttachment(this.getState().id)}}class r0 extends rX{get source(){return"thread-composer"}}class r1 extends rX{get source(){return"edit-composer"}}class r5 extends rZ{get source(){return"message"}constructor(e){super(e)}remove(){throw Error("Message attachments cannot be removed")}}let r2=Object.freeze([]),r6=Object.freeze({});class r3{_core;get path(){return this._core.path}constructor(e){this._core=e}__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){let t=this._core.getState();if(!t)throw Error("Composer is not available");t.setText(e)}setRunConfig(e){let t=this._core.getState();if(!t)throw Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){let t=this._core.getState();if(!t)throw Error("Composer is not available");return t.addAttachment(e)}reset(){let e=this._core.getState();if(!e)throw Error("Composer is not available");return e.reset()}clearAttachments(){let e=this._core.getState();if(!e)throw Error("Composer is not available");return e.clearAttachments()}send(){let e=this._core.getState();if(!e)throw Error("Composer is not available");e.send()}cancel(){let e=this._core.getState();if(!e)throw Error("Composer is not available");e.cancel()}setRole(e){let t=this._core.getState();if(!t)throw Error("Composer is not available");t.setRole(e)}startDictation(){let e=this._core.getState();if(!e)throw Error("Composer is not available");e.startDictation()}stopDictation(){let e=this._core.getState();if(!e)throw Error("Composer is not available");e.stopDictation()}setQuote(e){let t=this._core.getState();if(!t)throw Error("Composer is not available");t.setQuote(e)}subscribe(e){return this._core.subscribe(e)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new rD({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}}class r4 extends r3{get path(){return this._core.path}get type(){return"thread"}_getState;constructor(e){const t=new rP({path:e.path,getState:()=>{let t;return t=e.getState(),Object.freeze({type:"thread",isEditing:t?.isEditing??!1,canCancel:t?.canCancel??!1,isEmpty:t?.isEmpty??!0,attachments:t?.attachments??r2,text:t?.text??"",role:t?.role??"user",runConfig:t?.runConfig??r6,attachmentAccept:t?.attachmentAccept??"",dictation:t?.dictation,quote:t?.quote,value:t?.text??""})},subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>t.subscribe(e)}),this._getState=t.getState.bind(t),this.__internal_bindMethods()}getState(){return this._getState()}getAttachmentByIndex(e){return new r0(new rj({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:"thread-composer"}:rA},subscribe:e=>this._core.subscribe(e)}),this._core)}}class r7 extends r3{_beginEdit;get path(){return this._core.path}get type(){return"edit"}_getState;constructor(e,t){const r=new rP({path:e.path,getState:()=>{let t;return t=e.getState(),Object.freeze({type:"edit",isEditing:t?.isEditing??!1,canCancel:t?.canCancel??!1,isEmpty:t?.isEmpty??!0,text:t?.text??"",role:t?.role??"user",attachments:t?.attachments??r2,runConfig:t?.runConfig??r6,attachmentAccept:t?.attachmentAccept??"",dictation:t?.dictation,quote:t?.quote,value:t?.text??""})},subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>r.subscribe(e)}),this._beginEdit=t,this._getState=r.getState.bind(r),this.__internal_bindMethods()}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new r1(new rj({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:e},ref:`${this.path.ref}.attachments[${e}]`}
3,getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:"edit-composer"}:rA},subscribe:e=>this._core.subscribe(e)}),this._core)}}let r8=Symbol.for("aui.tool-response");class r9{get[r8](){return!0}artifact;result;isError;constructor(e){void 0!==e.artifact&&(this.artifact=e.artifact),this.result=e.result,this.isError=e.isError??!1}static[Symbol.hasInstance](e){return"object"==typeof e&&null!==e&&r8 in e}static toResponse(e){return e instanceof r9?e:new r9({result:void 0===e?"<no result>":e})}}class se{contentBinding;messageApi;threadApi;get path(){return this.contentBinding.path}constructor(e,t,r){this.contentBinding=e,this.messageApi=t,this.threadApi=r,this.__internal_bindMethods()}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){let t=this.contentBinding.getState();if(!t)throw Error("Message part is not available");if("tool-call"!==t.type)throw Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw Error("Thread API is not available");let r=this.messageApi.getState();if(!r)throw Error("Message is not available");let s=t.toolName,i=t.toolCallId,a=r9.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:s,toolCallId:i,result:a.result,artifact:a.artifact,isError:a.isError})}resumeToolCall(e){let t=this.contentBinding.getState();if(!t)throw Error("Message part is not available");if("tool-call"!==t.type)throw Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw Error("Thread API is not available");let r=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}}let st=Object.freeze({type:"complete"}),sr=(e,t)=>{let r=e.content[t];if(!r)return rA;let s=((e,t,r)=>{if("assistant"!==e.role)return st;if("tool-call"===r.type)if(!r.result)return e.status;else return st;let s=t===Math.max(0,e.content.length-1);return"requires-action"===e.status.type?st:s?e.status:st})(e,t,r);return Object.freeze({...r,...{[rQ]:r[rQ]},status:s})};class ss{_core;_threadBinding;get path(){return this._core.path}constructor(e,t){this._core=e,this._threadBinding=t,this.composer=new r7(new rB({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:e=>this._threadBinding.subscribe(e)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}__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)}composer;_getEditComposerRuntimeCore=()=>this._threadBinding.getState().getEditComposer(this._core.getState().id);getState(){return this._core.getState()}reload(e={}){let t=this._getEditComposerRuntimeCore(),r=t??this._threadBinding.getState().composer,{runConfig:s=(t??r).runConfig}=e,i=this._core.getState();if("assistant"!==i.role)throw Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:s})}speak(){let e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){let e=this._core.getState(),t=this._threadBinding.getState();if(t.speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw Error("Message is not being spoken")}submitFeedback({type:e}){let t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){let r=this._core.getState();if(t&&e)throw Error("May not specify both branchId and position");
3if(!t&&!e)throw Error("Must specify either branchId or position");let s=this._threadBinding.getState().getBranches(r.id),i=t;if("previous"===e?i=s[r.branchNumber-2]:"next"===e&&(i=s[r.branchNumber]),!i)throw Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return rw(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw Error("Message part index must be >= 0");return new se(new rj({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}},getState:()=>sr(this.getState(),e),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new se(new rj({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}},getState:()=>{let t=this._core.getState(),r=t.content.findIndex(t=>"tool-call"===t.type&&t.toolCallId===e);return -1===r?rA:sr(t,r)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new r5(new rj({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}},getState:()=>{let t=this.getState().attachments,r=t?.[e];return r?{...r,source:"message"}:rA},subscribe:e=>this._core.subscribe(e)}))}}class si{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;constructor(e,t){const r=new rj({path:e.path,getState:()=>{var r,s;let i;return r=e.getState(),s=t.getState(),i=r.messages.at(-1),Object.freeze({threadId:s.id,metadata:s,capabilities:r.capabilities,isDisabled:r.isDisabled,isLoading:r.isLoading,isRunning:i?.role==="assistant"&&"running"===i.status.type,messages:r.messages,state:r.state,suggestions:r.suggestions,extras:r.extras,speech:r.speech})},subscribe:r=>{let s=e.subscribe(r),i=t.subscribe(r);return()=>{s(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:t=>e.outerSubscribe(t),subscribe:t=>e.subscribe(t)},this.composer=new r4(new rB({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:e=>this._threadBinding.subscribe(e)})),this.__internal_bindMethods()}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.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.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.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(e){var t;this._threadBinding.getState().append((t=this._threadBinding.getState().messages,"string"==typeof e?{createdAt:new Date,parentId:t.at(-1)?.id??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:e}],attachments:[],metadata:{custom:{}}}:{createdAt:e.createdAt??new Date,parentId:e.parentId??t.at(-1)?.id??null,sourceId:e.sourceId??null,role:e.role??"user",content:e.content,attachments:e.attachments??[],metadata:e.metadata??{custom:{}},runConfig:e.runConfig??{},startRun:e.startRun}))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(e){let t;return this._threadBinding.getState().startRun({parentId:(t=null===e||"string"==typeof e?{parentId:e}:e).parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{}})}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}})}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}unstable_loadExternalState(e){this._threadBinding.getState().unstable_loadExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}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 Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}},()=>{let t=this._threadBinding.getState().messages,r=t[e];if(r)return{message:r,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 ss(new rj({path:e,getState:()=>{let{message:e,parentId:r,index:s}=t()??{},{messages:i,speech:a}=this._threadBinding.getState();if(!e||void 0===r||void 0===s)return rA;let n=this._threadBinding.getState().getBranches(e.id),o=e.metadata.submittedFeedback;return{...e,...{[rQ]:e[rQ]},index:s,isLast:i.at(-1)?.id===e.id,parentId:r,branchNumber:n.indexOf(e.id)+1,branchCount:n.length,speech:a?.messageId===e.id?a:void 0,submittedFeedback:o}},subscribe:e=>this._threadBinding.subscribe(e)}),this._threadBinding)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new rD({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}}let sa=(e,t)=>{if(void 0===t)return rA;let r=e.getItemById(t);return r?{id:r.id,remoteId:r.remoteId,externalId:r.externalId,title:r.title,status:r.status,isMain:r.id===e.mainThreadId}:rA};class sn{_core;_runtimeFactory;
3_getState;constructor(e,t=si){this._core=e,this._runtimeFactory=t;const r=new rP({path:{},getState:()=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadItems}),subscribe:t=>e.subscribe(t)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new rY(new rj({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>sa(this._core,this._core.mainThreadId),subscribe:e=>this._core.subscribe(e)}),this._core),this.main=new t(new rB({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:t=>e.subscribe(t)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.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){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}_mainThreadListItemRuntime;main;get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new rB({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:e=>this._core.subscribe(e)}),this.mainItem)}getItemByIndex(e){return new rY(new rj({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>sa(this._core,this._core.threadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(e){return new rY(new rj({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>sa(this._core,this._core.archivedThreadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(e){return new rY(new rj({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>sa(this._core,e),subscribe:e=>this._core.subscribe(e)}),this._core)}}class so{_core;threads;get threadList(){return this.threads}_thread;constructor(e){this._core=e,this.threads=new sn(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(e){return this._core.threads.switchToThread(e)}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}registerModelConfigProvider(e){return this.registerModelContextProvider(e)}reset({initialMessages:e}={}){return this._core.threads.getMainThreadRuntimeCore().import(rE(e??[]))}}let sl=(e,t,r)=>r.reduce((e,r)=>r?.(e,t)??e,e);class sd extends rN{_pendingTransforms=[];_baseValue;_cachedValue;constructor(e){super(),this._baseValue=e,this._cachedValue=e}_updateState(){this._cachedValue=this._pendingTransforms.reduce((e,t)=>sl(e,t.task,[t.loading,t.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(e){this._baseValue=e,this._updateState()}async optimisticUpdate(e){let t=e.execute(),r={...e,task:t};try{this._pendingTransforms.push(r),this._updateState();let s=await t;return this._baseValue=sl(this._baseValue,s,[e.optimistic,e.then]),s}finally{let e=this._pendingTransforms.indexOf(r);e>-1&&this._pendingTransforms.splice(e,1),this._updateState()}}}let su=Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),sc={getMessageById(){},getBranches:()=>[],switchToBranch(){throw su},append(){throw su},startRun(){throw su},resumeRun(){throw su},cancelRun(){throw su},addToolResult(){throw su},resumeToolCall(){throw su},speak(){throw su},stopSpeaking(){throw su},submitFeedback(){throw su},getModelContext:()=>({}),exportExternalState(){throw su},importExternalState(){throw su},unstable_loadExternalState(){throw su},composer:{attachments:[],attachmentAccept:"*",async addAttachment(){throw su},async removeAttachment(){throw su},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw su},role:"user",setRole(){throw su},runConfig:{},setRunConfig(){throw su},async reset(){},async clearAttachments(){},send(){throw su},cancel(){},dictation:void 0,startDictation(){throw su},stopDictation(){},quote:void 0,setQuote(){throw su},subscribe:()=>()=>{},unstable_on:()=>()=>{}},getEditComposer(){},beginEdit(){throw su},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe:()=>()=>{},import(){throw su},export:()=>({messages:[]}),reset(){throw su},unstable_on:()=>()=>{}},sh=(e,t)=>{let r=e.threadIdMap[t];if(void 0!==r)return e.threadData[r]},sp=(e,t,r)=>{let s=sh(e,t);if(!s)return e;let{id:i,remoteId:a,status:n}=s;if(n===r)return e;let o={...e};switch(n){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(e=>e!==i);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(e=>e!==i);break;default:throw Error(`Unsupported state: ${n}`)}switch(r){case"regular":o.threadIds=[i,...o.threadIds];break;case"archived":o.archivedThreadIds=[i,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([e])=>e!==i)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([e])=>e!==i&&e!==a));break;default:throw Error(`Unsupported state: ${r}`)}return"deleted"!==r&&(o.threadData={...o.threadData,[i]:{...s,status:r}}),o},sg=({runtime:e,children:t})=>{let r=eN({threadListItem:eB({runtime:e})});return(0,s.jsx)(ex,{value:r,children:t})};class sm extends rN{useRuntimeHook;instances=new Map;useAliveThreadsKeysChanged=e1(()=>({}));parent;constructor(e,t){super(),this.parent=t,this.useRuntimeHook=e1(()=>({useRuntime:e}))}startThreadRuntime(e){return this.instances.has(e)||(this.instances.set(e,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((t,r)=>{let s=()=>{let s=this.instances.get(e);if(s){if(!s.runtime)return;i(),t(s.runtime)}else i(),r(Error("Thread was deleted before runtime was started"))},i=this.subscribe(s);s()})}getThreadRuntimeCore(e){let t=this.instances.get(e);if(t)return t.runtime}stopThreadRuntime(e){this.instances.delete(e),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(e){this.useRuntimeHook.getState().useRuntime!==e&&this.useRuntimeHook.setState({useRuntime:e},!0)}_InnerActiveThreadProvider=({threadId:e})=>{let{useRuntime:t}=this.useRuntimeHook(),r=t(),s=r.thread.__internal_threadBinding,a=(0,i.useCallback)(()=>{let t=this.instances.get(e);if(!t)throw Error("Thread not found. This is a bug in assistant-ui.");t.runtime=s.getState(),this._notifySubscribers()},[e,s]),n=(0,i.useRef)(!1);n.current||a(),(0,i.useEffect)(()=>(n.current=!0,a(),s.outerSubscribe(a)),[s,a]);let o=eN(),l=(0,i.useRef)(void 0);return(0,i.useEffect)(()=>{let e=s.getState(),t=e.__internal_setGetInitializePromise;"function"==typeof t&&t.call(e,()=>l.current)},[s]),(0,i.useEffect)(()=>r.threads.main.unstable_on("initialize",()=>{if("new"===o.threadListItem().getState().status){l.current=o.threadListItem().initialize();let e=r.thread.unstable_on("runEnd",()=>{e(),o.threadListItem().generateTitle()})}}),[r,o]),null};_OuterActiveThreadProvider=(0,i.memo)(({threadId:e,provider:t})=>{let r=(0,i.useMemo)(()=>new sn(this.parent).getItemById(e),[e]);return(0,s.jsx)(sg,{runtime:r,children:(0,s.jsx)(t,{children:(0,s.jsx)(this._InnerActiveThreadProvider,{threadId:e})})})});__internal_RenderThreadRuntimes=({provider:e})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(t=>(0,s.jsx)(this._OuterActiveThreadProvider,{threadId:t,provider:e},t)))}let sf=rm("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);class sb{_state;constructor(e=null){this._state=e}get state(){return this._state}append(e){this._state=e.reduce((e,t)=>
3sb.apply(e,t),this._state)}static apply(e,t){let r=t.type;switch(r){case"set":return sb.updatePath(e,t.path,()=>t.value);case"append-text":return sb.updatePath(e,t.path,e=>{if("string"!=typeof e)throw Error(`Expected string at path [${t.path.join(", ")}]`);return e+t.value});default:throw Error(`Invalid operation type: ${r}`)}}static updatePath(e,t,r){if(0===t.length)return r(e);if("object"!=typeof(e??={}))throw Error(`Invalid path: [${t.join(", ")}]`);let[s,...i]=t;if(Array.isArray(e)){let a=Number(s);if(Number.isNaN(a))throw Error(`Expected array index at [${t.join(", ")}]`);if(a>e.length||a<0)throw Error("Insert array index out of bounds");let n=[...e];return n[a]=this.updatePath(n[a],i,r),n}let a={...e};return a[s]=this.updatePath(a[s],i,r),a}}class s_{_streamStartTime;_firstTokenTime;_totalChunks=0;_toolCallIds=new Set;constructor(){this._streamStartTime=Date.now()}recordChunk(){this._totalChunks++}recordFirstToken(){void 0===this._firstTokenTime&&(this._firstTokenTime=Date.now())}recordToolCallStart(e){this._toolCallIds.add(e)}getTiming(e,t){let r=Date.now()-this._streamStartTime,s=e&&e>0?e:t?Math.ceil(t.length/4):void 0,i=s&&r>0?s/r*1e3:void 0;return{streamStartTime:this._streamStartTime,...void 0!==this._firstTokenTime?{firstTokenTime:this._firstTokenTime-this._streamStartTime}:void 0,totalStreamTime:r,...void 0!==s?{tokenCount:s}:void 0,...void 0!==i?{tokensPerSecond:i}:void 0,totalChunks:this._totalChunks,toolCallCount:this._toolCallIds.size}}}let sy=(e,t,r)=>{if(0===e.parts.length)throw Error("No parts available to update.");if(1!==t.path.length)throw Error("Nested paths are not supported yet.");let s=t.path[0],i=r(e.parts[s]);return{...e,parts:[...e.parts.slice(0,s),i,...e.parts.slice(s+1)],get content(){return this.parts}}},sw=(e,t)=>{if(e.status?.type==="incomplete"&&e.status?.reason==="error")return e;let r=sx(t);return{...e,status:r}},sx=e=>"tool-calls"===e.finishReason?{type:"requires-action",reason:"tool-calls"}:"stop"===e.finishReason||"unknown"===e.finishReason?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},sv=(e,t)=>{let r=0;for(let e of t.metadata.steps)"finished"===e.state&&e.usage&&(r+=e.usage.outputTokens);let s="";for(let e of t.parts)("text"===e.type||"reasoning"===e.type)&&(s+=e.text);return e.getTiming(r>0?r:void 0,s||void 0)};class sS extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let s,i=e??(({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}))();const a=new s_,n=t?(e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}})(()=>{s?.enqueue(i)}):()=>{s?.enqueue(i)};super({start(e){s=e},transform(e){var t,s;a.recordChunk();let o=e.type;switch(o){case"part-start":i=((e,t)=>{let r=t.part;if("text"===r.type||"reasoning"===r.type){let t={type:r.type,text:"",status:{type:"running"},...r.parentId&&{parentId:r.parentId}};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}if("tool-call"===r.type){let t={type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:"",args:{},...r.parentId&&{parentId:r.parentId}};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}if("source"===r.type){let t={type:"source",sourceType:r.sourceType,id:r.id,url:r.url,...r.title?{title:r.title}:void 0,...r.parentId&&{parentId:r.parentId}};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}if("file"===r.type){let t={type:"file",mimeType:r.mimeType,data:r.data};return{...e,parts:[...e.parts,t],get content(){return this.parts}}}throw Error(`Unsupported part type: ${r.type}`)})(i,e),"tool-call"===e.part.type&&a.recordToolCallStart(e.part.toolCallId);break;case"tool-call-args-text-finish":i=sy(i,e,e=>{if("tool-call"!==e.type)throw Error("Last is not a tool call");return"partial-call"!==e.state?e:{...e,state:"call"}});break;case"part-finish":i=sy(i,e,e=>({...e,status:{type:"complete",reason:"unknown"}}));break;case"text-delta":i=sy(i,e,t=>{if("text"===t.type||"reasoning"===t.type)return{...t,text:t.text+e.textDelta};if("tool-call"===t.type){let r=t.argsText+e.textDelta,s=rg(r)??t.args;return{...t,argsText:r,args:s}}throw Error("text-delta received but part is neither text nor tool-call")}
3),a.recordFirstToken();break;case"result":i=sy(i,e,t=>{if("tool-call"===t.type)return{...t,state:"result",...void 0!==e.artifact?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1,status:{type:"complete",reason:"stop"}};throw Error("Result chunk received but part is not a tool-call")});break;case"message-finish":i=sw(i,e);break;case"annotations":let l;i={...l=i,metadata:{...l.metadata,unstable_annotations:[...l.metadata.unstable_annotations,...e.annotations]}};break;case"data":let d;i={...d=i,metadata:{...d.metadata,unstable_data:[...d.metadata.unstable_data,...e.data]}};break;case"step-start":let u;i={...u=i,metadata:{...u.metadata,steps:[...u.metadata.steps,{state:"started",messageId:e.messageId}]}};break;case"step-finish":let c,h;h=(c=(t=i).metadata.steps.slice()).length-1,c.length>0&&c[h]?.state==="started"?c[h]={...c[h],state:"finished",finishReason:e.finishReason,usage:e.usage,isContinued:e.isContinued}:c.push({state:"finished",messageId:sf(),finishReason:e.finishReason,usage:e.usage,isContinued:e.isContinued}),i={...t,metadata:{...t.metadata,steps:c}};break;case"error":i={...i,status:{type:"incomplete",reason:"error",error:e.error}},r?.(e.error);break;case"update-state":let p;(p=new sb((s=i).metadata.unstable_state)).append(e.operations),i={...s,metadata:{...s.metadata,unstable_state:p.state}};break;default:throw Error(`Unsupported chunk type: ${o}`)}"running"!==i.status.type&&(i={...i,metadata:{...i.metadata,timing:sv(a,i)}}),n()},flush(e){if(i.status?.type==="running"){let t=i.parts?.some(e=>"tool-call"===e.type&&("call"===e.state||"partial-call"===e.state)&&void 0===e.result)??!1;i={...i=sw(i,{type:"message-finish",path:[],finishReason:t?"tool-calls":"unknown",usage:{inputTokens:0,outputTokens:0}}),metadata:{...i.metadata,timing:sv(a,i)}},e.enqueue(i)}}})}}class sT{readable;constructor(e){this.readable=e,this.readable=e}static fromAssistantStream(e){return new sT(e.pipeThrough(new sS))}async unstable_result(){let e;for await(let t of this)e=t;return e||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}}[Symbol.asyncIterator](){let e=this.readable.getReader();return{async next(){let{done:t,value:r}=await e.read();return t?{done:!0,value:void 0}:{done:!1,value:r}}}}tee(){let[e,t]=this.readable.tee();return[new sT(e),new sT(t)]}}class sI extends rN{contextProvider;_options;_hookManager;_loadThreadsPromise;_mainThreadId;_state=new sd({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}});get threadItems(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:e=>({...e,isLoading:!0}),then:(e,t)=>{let r=[],s=[],i={},a={};for(let e of t.threads){switch(e.status){case"regular":r.push(e.remoteId);break;case"archived":s.push(e.remoteId);break;default:{let t=e.status;throw Error(`Unsupported state: ${t}`)}}let t=e.remoteId;i[e.remoteId]=t,a[t]={id:e.remoteId,remoteId:e.remoteId,externalId:e.externalId,status:e.status,title:e.title,initializeTask:Promise.resolve({remoteId:e.remoteId,externalId:e.externalId})}}return{...e,threadIds:r,archivedThreadIds:s,threadIdMap:{...e.threadIdMap,...i},threadData:{...e.threadData,...a}}}}).then(()=>{})),this._loadThreadsPromise}constructor(e,t){super(),this.contextProvider=t,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new sm(e.runtimeHook,this),this.useProvider=e1(()=>({Provider:e.adapter.unstable_Provider??i.Fragment})),this.__internal_setOptions(e),this.switchToNewThread()}useProvider;__internal_setOptions(e){if(this._options===e)return;this._options=e;let t=e.adapter.unstable_Provider??i.Fragment;t!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:t},!0),this._hookManager.setRuntimeHook(e.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){let e=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return e||sc}getThreadRuntimeCore(e){let t=this.getItemById(e);if(!t)throw Error("Thread not found");let r=this._hookManager.getThreadRuntimeCore(t.id);if(!r)throw Error("Thread not found");return r}getItemById(e){return sh(this._state.value,e)}async switchToThread(e){let t=this.getItemById(e);if(!t){let r=await this._options.adapter.fetch(e),s=this._state.value,i=r.remoteId,a={...s.threadData,[i]:{id:i,initializeTask:Prom
3ise.resolve({remoteId:r.remoteId,externalId:r.externalId}),remoteId:r.remoteId,externalId:r.externalId,status:r.status,title:r.title}},n={...s.threadIdMap,[r.remoteId]:i},o="regular"===r.status?[...s.threadIds,r.remoteId]:s.threadIds,l="archived"===r.status?[...s.archivedThreadIds,r.remoteId]:s.archivedThreadIds;this._state.update({...s,threadIds:o,archivedThreadIds:l,threadIdMap:n,threadData:a}),t=this.getItemById(e)}if(!t)throw Error("Thread not found");if(this._mainThreadId===t.id)return;let r=this._hookManager.startThreadRuntime(t.id);void 0!==this.mainThreadId?await r:r.then(()=>this._notifySubscribers()),"archived"===t.status&&await this.unarchive(t.id),this._mainThreadId=t.id,this._notifySubscribers()}async switchToNewThread(){for(;void 0!==this._state.baseValue.newThreadId&&void 0===this._state.value.newThreadId;)await this._state.waitForUpdate();let e=this._state.value,t=this._state.value.newThreadId;if(void 0===t){do t=`__LOCALID_${rf()}`;while(e.threadIdMap[t])let r=t;this._state.update({...e,newThreadId:t,threadIdMap:{...e.threadIdMap,[t]:r},threadData:{...e.threadData,[r]:{status:"new",id:t,remoteId:void 0,externalId:void 0,title:void 0}}})}return this.switchToThread(t)}initialize=async e=>{if(this._state.value.newThreadId!==e){let t=this.getItemById(e);if(!t)throw Error("Thread not found");if("new"===t.status)throw Error("Unexpected new state");return t.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(e),optimistic:t=>sp(t,e,"regular"),loading:(t,r)=>({...t,threadData:{...t.threadData,[e]:{...t.threadData[e],initializeTask:r}}}),then:(t,{remoteId:r,externalId:s})=>{let i=sh(t,e);return i?{...t,threadIdMap:{...t.threadIdMap,[r]:e},threadData:{...t.threadData,[e]:{...i,initializeTask:Promise.resolve({remoteId:r,externalId:s}),remoteId:r,externalId:s}}}:t}})};generateTitle=async e=>{let t=this.getItemById(e);if(!t)throw Error("Thread not found");if("new"===t.status)throw Error("Thread is not yet initialized");let{remoteId:r}=await t.initializeTask,s=this._hookManager.getThreadRuntimeCore(t.id);if(!s)return;let i=s.messages,a=await this._options.adapter.generateTitle(r,i);for await(let e of sT.fromAssistantStream(a)){let r=e.parts.filter(e=>"text"===e.type)[0]?.text,s=this._state.baseValue,i=sh(s,t.id);i&&this._state.update({...s,threadData:{...s.threadData,[i.id]:{...i,title:r}}})}};rename(e,t){let r=this.getItemById(e);if(!r)throw Error("Thread not found");if("new"===r.status)throw Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await r.initializeTask;return this._options.adapter.rename(e,t)},optimistic:r=>{let s=sh(r,e);return s?{...r,threadData:{...r.threadData,[s.id]:{...s,title:t}}}:r}})}async _ensureThreadIsNotMain(e){if(e===this.newThreadId)throw Error("Cannot ensure new thread is not main");e===this._mainThreadId&&await this.switchToNewThread()}async archive(e){let t=this.getItemById(e);if(!t)throw Error("Thread not found");if("regular"!==t.status)throw Error("Thread is not yet initialized or already archived");return await this._ensureThreadIsNotMain(t.id),this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await t.initializeTask;return this._options.adapter.archive(e)},optimistic:e=>sp(e,t.id,"archived")})}unarchive(e){let t=this.getItemById(e);if(!t)throw Error("Thread not found");if("archived"!==t.status)throw Error("Thread is not archived");return this._state.optimisticUpdate({execute:async()=>{try{let{remoteId:e}=await t.initializeTask;return await this._options.adapter.unarchive(e)}catch(e){throw await this._ensureThreadIsNotMain(t.id),e}},optimistic:e=>sp(e,t.id,"regular")})}async delete(e){let t=this.getItemById(e);if(!t)throw Error("Thread not found");if("regular"!==t.status&&"archived"!==t.status)throw Error("Thread is not yet initialized");return await this._ensureThreadIsNotMain(t.id),this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await t.initializeTask;return await this._options.adapter.delete(e)},optimistic:e=>sp(e,t.id,"deleted")})}async detach(e){let t=this.getItemById(e);if(!t)throw Error("Thread not found");if("regular"!==t.status&&"archived"!==t.status)throw Error("Thread is not yet initialized");await this._ensureThreadIsNotMain(t.id),this._hookManager.stopThreadRuntime(t.id)}useBoundIds=e1(()=>[]);__internal_RenderComponent=()=>{let e=(0,i.useId)();(0,i.useEffect)(()=>(this.useBoundIds.setState(t=>[...t,e],!0),()=>{this.useBoundIds.setState(t=>t.filter(t=>t!==e),!0)}),[e]);let t=this.useBoundIds(),{Provider:r}=this.useProvider(),a={modelContext:this.contextProvider};return(0===t.length||t[0]===e)&&(0,s.jsx)(rK,{adapters:a,children:(0,s.jsx)(this._hookManager.__internal_RenderThreadRuntimes,{provider:r})})}}class sE extends rc{threads;constructor(e){super(),this.threads=new sI(e,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}}
3let sC=e=>{try{let t=e.split(".")[1];if(!t)throw Error("Invalid JWT format");let r=t.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4!=0;)r+="=";let s=atob(r),i=JSON.parse(s).exp;if(!i||"number"!=typeof i)throw Error('JWT does not contain a valid "exp" field');return 1e3*i}catch(e){throw Error(`Unable to determine the token expiry: ${e}`)}};class sk{strategy="jwt";cachedToken=null;tokenExpiry=null;#e;constructor(e){this.#e=e}async getAuthHeaders(){let e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>3e4)return{Authorization:`Bearer ${this.cachedToken}`};let t=await this.#e();return!!t&&(this.cachedToken=t,this.tokenExpiry=sC(t),{Authorization:`Bearer ${t}`})}readAuthHeaders(e){let t=e.get("Authorization");if(!t)return;let[r,s]=t.split(" ");if("Bearer"!==r||!s)throw Error("Invalid auth header received");this.cachedToken=s,this.tokenExpiry=sC(s)}}class sR{strategy="api-key";#t;#r;#s;constructor(e,t,r){this.#t=e,this.#r=t,this.#s=r}async getAuthHeaders(){return{Authorization:`Bearer ${this.#t}`,"Aui-User-Id":this.#r,"Aui-Workspace-Id":this.#s}}readAuthHeaders(){}}let sA="aui:refresh_token";class sN{strategy="anon";baseUrl;jwtStrategy;constructor(e){this.baseUrl=e,this.jwtStrategy=new sk(async()=>{let e=Date.now(),t=localStorage.getItem(sA),r=t?JSON.parse(t):void 0;if(r)if(new Date(r.expires_at).getTime()-e>3e4){let e=await fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:r.token})});if(e.ok){let{access_token:t,refresh_token:r}=await e.json();return r&&localStorage.setItem(sA,JSON.stringify(r)),t}}else localStorage.removeItem(sA);let s=await fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!s.ok)return null;let{access_token:i,refresh_token:a}=await s.json();return i&&a?(localStorage.setItem(sA,JSON.stringify(a)),i):null})}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}}class sM extends Error{constructor(e){super(e),this.name="APIError"}}class sj{_auth;_baseUrl;constructor(e){if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new sk(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new sR(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new sN(e.baseUrl);else throw Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}async initializeAuth(){return!!this._auth.getAuthHeaders()}async makeRawRequest(e,t={}){let r=await this._auth.getAuthHeaders();if(!r)throw Error("Authorization failed");let s={...r,...t.headers,"Content-Type":"application/json"},i=new URLSearchParams;if(t.query)for(let[e,r]of Object.entries(t.query))!1!==r&&(!0===r?i.set(e,"true"):i.set(e,r.toString()));let a=new URL(`${this._baseUrl}/v1${e}`);a.search=i.toString();let n=await fetch(a,{method:t.method??"GET",headers:s,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(n.headers),!n.ok){let e=await n.text();try{let t=JSON.parse(e);throw new sM(t.message)}catch(t){if(t instanceof sM)throw t;throw Error(`Request failed with status ${n.status}, ${e}`)}}return n}async makeRequest(e,t={}){return(await this.makeRawRequest(e,t)).json()}}class sP{cloud;constructor(e){this.cloud=e}async create(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})}}let sB={toResponse:(e,t)=>new Response(sB.toByteStream(e,t),{headers:t.headers??{}}),fromResponse:(e,t)=>sB.fromByteStream(e.body,t),toByteStream:(e,t)=>e.pipeThrough(t),fromByteStream:(e,t)=>e.pipeThrough(t)},sD=function(){let e,t,r=new Promise((r,s)=>{e=r,t=s});if(!e||!t)throw Error("Failed to create promise");return{promise:r,resolve:e,reject:t}};class sO{_controller;_isClosed=!1;constructor(e){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())}}let sL=e=>new ReadableStream({start:t=>e.start?.(new sO(t)),pull:t=>e.pull?.(new sO(t)),cancel:t=>e.cancel?.(t)}),sF=()=>{let e;return[sL({start(t){e=t}}),e]};class sU{_controller;_isClosed=!1;_mergeTask;constructor(e){this._controller=e;const t=sL({start:e=>{this._argsTextController=e}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:e=>{switch(e.type){case"text-delta":r=!0,this._controller.enqueue(e);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw Error(`Unexpected chunk type: ${e.type}`)}}}))}get argsText(){return this._argsTextController}_argsTextController;async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...void 0!==e.artifact?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}}class s${value=-1;up(){return++this.value}}class sz extends TransformStream{constructor(e){super({transform(t,r){r.enqueue({...t,path:[e,...t.path]})}})}}TransformStream;class sq extends TransformStream{constructor(e){const t=new s$,r=new Map;super({transform(s,i){"part-start"===s.type&&0===s.path.length&&r.set(t.up(),e.up());let[a,...n]=s.path;if(void 0===a)return void i.enqueue(s);let o=r.get(a);if(void 0===o)throw Error("Path not found");i.enqueue({...s,path:[o,...n]})}})}}class sV extends TransformStream{constructor(e){super(),Object.defineProperty(this,"readable",{value:e(super.readable),writable:!1})}}(t=r||(r={})).TextDelta="0",t.Data="2",t.Error="3",t.Annotation="8",t.ToolCall="9",t.ToolCallResult="a",t.StartToolCall="b",t.ToolCallArgsTextDelta="c",t.Finis
3hMessage="d",t.FinishStep="e",t.StartStep="f",t.ReasoningDelta="g",t.Source="h",t.RedactedReasoning="i",t.ReasoningSignature="j",t.File="k",t.AuiUpdateStateOperations="aui-state",t.AuiTextDelta="aui-text-delta",t.AuiReasoningDelta="aui-reasoning-delta",TransformStream,TransformStream,TransformStream,TransformStream,r.StartToolCall,r.ToolCall,r.TextDelta,r.ReasoningDelta,r.Source,r.Error,r.FinishStep,r.FinishMessage,r.AuiTextDelta,r.AuiReasoningDelta;class sH{_state;_parentId;constructor(e){this._state=e||{merger:(()=>{let e,t,r=[],s=!1,i=i=>{i.promise||(i.promise=i.reader.read().then(({done:a,value:n})=>{i.promise=void 0,a?(r.splice(r.indexOf(i),1),s&&0===r.length&&e.close()):e.enqueue(n),t?.resolve(),t=void 0}).catch(s=>{console.error(s),r.forEach(e=>{e.reader.cancel()}),r.length=0,e.error(s),t?.reject(s),t=void 0}))};return{readable:new ReadableStream({start(t){e=t},pull:()=>(t=sD(),r.forEach(e=>{i(e)}),t.promise),cancel(){r.forEach(e=>{e.reader.cancel()}),r.length=0}}),isSealed:()=>s,seal(){s=!0,0===r.length&&e.close()},addStream(e){if(s)throw Error("Cannot add streams after the run callback has settled.");let t={reader:e.getReader()};r.push(t),i(t)},enqueue(e){this.addStream(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}}})(),contentCounter:new s$}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(e){this._state.closeSubscriber=e}_addPart(e,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:e,path:[]}),this._state.merger.addStream(t.pipeThrough(new sz(this._state.contentCounter.value)))}merge(e){this._state.merger.addStream(e.pipeThrough(new sq(this._state.contentCounter)))}appendText(e){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(e)}addTextPart(){let[e,t]=sF();return this._addPart({type:"text"},e),t}addReasoningPart(){let[e,t]=sF();return this._addPart({type:"reasoning"},e),t}addToolCallPart(e){let t,r,s="string"==typeof e?{toolName:e}:e,i=s.toolName,a=s.toolCallId??sf(),[n,o]=[(r={start(e){t=e}},new ReadableStream({start:e=>r.start?.(new sU(e)),pull:e=>r.pull?.(new sU(e)),cancel:e=>r.cancel?.(e)})),t];return this._addPart({type:"tool-call",toolName:i,toolCallId:a,...this._parentId&&{parentId:this._parentId}},n),void 0!==s.argsText&&(o.argsText.append(s.argsText),o.argsText.close()),void 0!==s.args&&(o.argsText.append(JSON.stringify(s.args)),o.argsText.close()),void 0!==s.response&&o.setResponse(s.response),o}appendSource(e){this._addPart({...e,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(e){e.enqueue({type:"part-finish",path:[]}),e.close()}}))}appendFile(e){this._addPart(e,new ReadableStream({start(e){e.enqueue({type:"part-finish",path:[]}),e.close()}}))}enqueue(e){this._state.merger.enqueue(e),"part-start"===e.type&&0===e.path.length&&this._state.contentCounter.up()}withParentId(e){let t=new sH(this._state);return t._parentId=e,t}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}}class sJ extends TransformStream{constructor(e,t,r){let s;const[i,a]=function(){var e;let t,r,{resolve:s,promise:i}=sD();return[(e=e=>((t=e).__internal_subscribeToClose(s),i),r=new sH,(async()=>{try{await e(r)}catch(e){throw r.__internal_isClosed||r.enqueue({type:"error",path:[],error:String(e)}),e}finally{r.__internal_isClosed||r.close()}})(),r.__internal_getReadable()),t]}();super({start:t=>(s=i.pipeTo(new WritableStream({write(e){t.enqueue(e)},abort(e){t.error(e)},close(){t.terminate()}})).catch(e=>{t.error(e)}),e.start?.(a)),transform:t=>e.transform?.(t,a),async flush(){await e.flush?.(a),a.close(),await s}},t,r)}}class sW extends sV{constructor(){super(e=>{let t=new sJ({transform(e,t){t.appendText(e)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}}class sG{cloud;constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:async()=>{let e=await this.cloud._auth.getAuthHeaders();if(!e)throw Error("Authorization failed");return{...e,Accept:"text/plain"}},body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}async stream(e){let t=await this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return sB.fromResponse(t,new sW)}
3async report(e){return this.cloud.makeRequest("/runs",{method:"POST",body:e})}}class sK{cloud;constructor(e){this.cloud=e}async list(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})}async create(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})}async update(e,t,r){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}`,{method:"PUT",body:r})}}class sY{cloud;messages;constructor(e){this.cloud=e,this.messages=new sK(e)}async list(e){return this.cloud.makeRequest("/threads",{query:e})}async get(e){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)}async create(e){return this.cloud.makeRequest("/threads",{method:"POST",body:e})}async update(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})}async delete(e){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})}}class sQ{cloud;constructor(e){this.cloud=e}async pdfToImages(e){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})}async generatePresignedUploadUrl(e){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})}}class sZ{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(Error("Thread not found"))}}class sX{cloud;idMapping={};constructor(e){this.cloud=e}async append(e,t,r,s,i){let a=r?await this.idMapping[r]??r:null,n=this.cloud.threads.messages.create(e,{parent_id:a,format:s,content:i}).then(({message_id:e})=>(this.idMapping[t]=e,e)).catch(e=>{throw this.idMapping[t]===n&&delete this.idMapping[t],e});return this.idMapping[t]=n,n.then(()=>{})}async update(e,t,r,s){let i=await this.getRemoteId(t);i&&await this.cloud.threads.messages.update(e,i,{content:s})}isPersisted(e){return e in this.idMapping}async getRemoteId(e){let t=this.idMapping[e];if(t)return t}async load(e,t){let{messages:r}=await this.cloud.threads.messages.list(e,t?{format:t}:void 0);for(let e of r)this.idMapping[e.id]=e.id;return r}reset(){this.idMapping={}}}function s0(e){let t=e.content,r=r_({id:e.id,createdAt:e.created_at,...t},e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}}let s1=new WeakMap;class s5{cloudRef;aui;constructor(e,t){this.cloudRef=e,this.aui=t}get _persistence(){let e=this.aui.threadListItem();return s1.has(e)||s1.set(e,new sX(this.cloudRef.current)),s1.get(e)}withFormat(e){let t,r=this,s=(t=this._persistence,{append:async(r,s)=>{let i=e.getId(s.message),a=e.encode(s);return t.append(r,i,s.parentId,e.format,a)},update:t.update?async(r,s,i)=>{let a=e.encode(s);return t.update(r,i,e.format,a)}:void 0,load:async r=>({messages:(await t.load(r,e.format)).filter(t=>t.format===e.format).map(t=>e.decode({id:t.id,parent_id:t.parent_id,format:t.format,content:t.content})).reverse()}),isPersisted:e=>t.isPersisted(e)});return{async append(e){let{remoteId:t}=await r.aui.threadListItem().initialize();await s.append(t,e)},async update(e,t){let i=r.aui.threadListItem().getState().remoteId;i&&await s.update?.(i,e,t)},reportTelemetry(t,s){let i=t.map(t=>e.encode(t));r._reportBatchTelemetry(e.format,i,s)},async load(){let e=r.aui.threadListItem().getState().remoteId;return e?s.load(e):{messages:[]}}}}async append({parentId:e,message:t}){let r,{remoteId:s}=await this.aui.threadListItem().initialize(),i=(r=t.status?.type==="running"?{type:"incomplete",reason:"cancelled"}:t.status,{role:t.role,content:t.content.map(e=>{let t=e.type;switch(t){case"text":return{type:"text",text:e.text};case"reasoning":return{type:"reasoning",text:e.text};case"source":return{type:"source",sourceType:e.sourceType,id:e.id,url:e.url,...e.title?{title:e.title}:void 0};case"tool-call":return!function e(t,r=0){return!(r>100)&&(null===t||"string"==typeof t||"boolean"==typeof t||("number"==typeof t?!Number.isNaN(t)&&Number.isFinite(t):Array.isArray(t)?t.every(t=>e(t,r+1)):"object"==typeof t&&Object.entries(t).every(([t,s])=>"string"==typeof t&&e(s,r+1))))}(e.result)&&console.warn(`tool-call result is not JSON! ${JSON.stringify(e)}`),{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,...JSON.stringify(e.args)===e.argsText?{args:e.args}:{argsText:e.argsText},...e.result?{result:e.result}:void 0,...e.isError?{isError:!0}:void 0};case"image":return{type:"image",image:e.image};case"file":return{type:"file",data:e.data,mimeType:e.mimeType,...e.filename?{filename:e.filename}:void 0};default:throw Error(`Message part type not supported by aui/v0: ${t}`)}}),metadata:t.metadata,...r?{status:r}:void 0});await this._persistence.append(s,t.id,e,"aui/v0",i),this.cloudRef.current.telemetry.enabled&&this._maybeReportRun(s,"aui
3/v0",i)}async load(){let e=this.aui.threadListItem().getState().remoteId;return e?{messages:(await this._persistence.load(e,"aui/v0")).filter(e=>"aui/v0"===e.format).map(s0).reverse()}:{messages:[]}}_reportBatchTelemetry(e,t,r){if(!this.cloudRef.current.telemetry.enabled)return;let s=this.aui.threadListItem().getState().remoteId;if(!s)return;let i=function(e,t){if("ai-sdk/v6"===e)return function(e){let t,r,s=[],i=[],a=[],n=!1;for(let o of e){if("assistant"!==o.role)continue;n=!0;let{textParts:e,toolCalls:l,stepsData:d}=s9(o.parts??[]);s.push(...e),i.push(...l),a.push(...d),o.metadata&&(t=o.metadata);let u=ir(o.metadata);u&&(r||(r={inputTokens:0,outputTokens:0}),r.inputTokens+=u.inputTokens??0,r.outputTokens+=u.outputTokens??0)}return n?ie(s,i,a.length,t,a,r):null}(t);for(let r=t.length-1;r>=0;r--){let s=s7(e,t[r]);if(s)return s}return null}(e,t);i&&this._sendReport(s,i,r?.durationMs,r?.stepTimestamps)}_maybeReportRun(e,t,r){let s=s7(t,r);s&&this._sendReport(e,s)}_sendReport(e,t,r,s){let i=function(e,t){if(!t)return e;if(!e)return t.map(e=>({...e}));let r=Math.min(e.length,t.length);return e.map((e,s)=>({...e,...s<r?t[s]:void 0}))}(t.steps,s),a={thread_id:e,status:t.status,...null!=t.totalSteps?{total_steps:t.totalSteps}:void 0,...t.toolCalls?{tool_calls:t.toolCalls}:void 0,...i?{steps:i}:void 0,...null!=t.inputTokens?{input_tokens:t.inputTokens}:void 0,...null!=t.outputTokens?{output_tokens:t.outputTokens}:void 0,...null!=r?{duration_ms:r}:void 0,...null!=t.outputText?{output_text:t.outputText}:void 0,...t.metadata?{metadata:t.metadata}:void 0,...t.modelId?{model_id:t.modelId}:void 0},{beforeReport:n}=this.cloudRef.current.telemetry,o=n?n(a):a;o&&this.cloudRef.current.runs.report(o).catch(()=>{})}}function s2(e){return e.length<=5e4?e:e.slice(0,5e4)}function s6(e){if(null!=e)try{return s2(JSON.stringify(e))}catch{return}}let s3=/^[A-Za-z0-9+/]{100,}={0,2}$/;function s4(e,t,r,s,i,a){let n={tool_name:e,tool_call_id:t},o=i??s6(r);void 0!==o&&(n.tool_args=o);let l="mcp"===a?function(e){if(null!=e){try{let t="string"==typeof e?JSON.parse(e):e;if(Array.isArray(t)){let e=t.map(e=>{if(e&&"object"==typeof e&&e.type&&("image"===e.type||"audio"===e.type)&&"string"==typeof e.data&&s3.test(e.data.slice(0,200))){let t=(3*e.data.length/4/1024).toFixed(1);return{...e,data:`[${e.type}: ${t}KB]`}}return e});return s2(JSON.stringify(e))}}catch{}return s6(e)}}(s):s6(s);return void 0!==l&&(n.tool_result=l),a&&(n.tool_source=a),n}function s7(e,t){switch(e){case"aui/v0":return function(e){let t,r;if("assistant"!==e.role)return null;let s=e.content?.filter(e=>"tool-call"===e.type&&e.toolName&&e.toolCallId).map(e=>s4(e.toolName,e.toolCallId,e.args,e.result,e.argsText)),i=e.content?.filter(e=>"text"===e.type&&e.text),a=i&&i.length>0?s2(i.map(e=>e.text).join("")):void 0,n=e.metadata?.steps;if(n&&n.length>0)for(let e of(t=0,r=0,n))t+=e.usage?.inputTokens??0,r+=e.usage?.outputTokens??0;let o=e.status?.type,l=o&&s8[o]||"completed",d=e.metadata?.custom,u=e.metadata?.modelId??("string"==typeof e.metadata?.custom?.modelId?e.metadata.custom.modelId:void 0),c=n&&n.length>1?n.map(e=>({...e.usage?.inputTokens!=null?{input_tokens:e.usage.inputTokens}:void 0,...e.usage?.outputTokens!=null?{output_tokens:e.usage.outputTokens}:void 0})):void 0;return{status:l,...s&&s.length>0?{toolCalls:s}:void 0,...n?.length?{totalSteps:n.length}:void 0,...null!=t?{inputTokens:t}:void 0,...null!=r?{outputTokens:r}:void 0,...null!=a?{outputText:a}:void 0,...d?{metadata:d}:void 0,...c?{steps:c}:void 0,...u?{modelId:u}:void 0}}(t);case"ai-sdk/v6":return function(e){if("assistant"!==e.role)return null;let{textParts:t,toolCalls:r,stepsData:s}=s9(e.parts??[]);return ie(t,r,s.length,e.metadata,s,ir(e.metadata))}(t);default:return null}}let s8={error:"error",incomplete:"incomplete"};function s9(e){let t=[],r=[],s=[],i=null;for(let a of e)if("step-start"===a.type)null!==i&&s.push({tool_calls:i}),i=[];else if("text"===a.type&&a.text)t.push(a.text);else if(a.toolCallId&&("tool-call"===a.type||"dynamic-tool"===a.type?!!a.toolName:a.type.startsWith("tool-")||a.type.startsWith("dynamic-tool-"))){let e=function(e){let t="dynamic-tool"===e.type||e.type.startsWith("dynamic-tool-")?"mcp":void 0;return s4(e.toolName??e.type.slice(5),e.toolCallId,e.args??e.input,e.result??e.output,void 0,t)}(a);r.push(e),null!==i&&i.push(e)}return null!==i&&s.push({tool_calls:i}),{textParts:t,toolCalls:r,stepsData:s}}function ie(e,t,r,s,i,a){let n=e.length>0,o=n?s2(e.join("")):void 0,l=function(e){if(!e)return;if("string"==typeof e.modelId)return e.modelId;let t=e.custom;if("string"==typeof t?.modelId)return t.modelId}(s),d=i&&i.length>1?i.map(e=>({...e.tool_calls.length>0?{tool_calls:e.tool_calls}:void 0})):void 0;return{status:n?"completed":"incomplete",...t.length>0?{toolCalls:t}:void 0,...r>0?{totalSteps:r}:void 0,...a?.inputTokens!=null?{inputTokens:a.inputTokens}:void 0,...a?.outputTokens!=null?{outputTokens:a.outputTokens}:void 0,...null!=o?{outputText:o}:void 0,...s?{metadata:s}:void 0,...d?{steps:d}:void 0,...l?{modelId:l}:void 0}}function it(e){let t=e.inputTokens??e.promptTokens,r=e.outputTokens??e.completionTokens;if(null!=t||null!=r)return{inputTokens:t??0,outputTokens:r??0}}function ir(e){let t=e?.usage;if(t){let e=it(t);if(e)return e}let r=e?.steps;if(r&&r.length>0){let e=0,t=0,s=!1;for(let i of r){if(!i.usage)continue;let r=it(i.usage);r&&(e+=r.inputTokens,t+=r.outputTokens,s=!0)}if(s)return{inputTokens:e,outputTokens:t}}}class is{cloud;accept="*";constructor(e){this.cloud=e}uploadedUrls=new Map;async *add({file:e}){var t;let r=crypto.randomUUID(),s={id:r,type:(t=e.type).startsWith("image/")?"image":t.startsWith("text/")?"document":"file",name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield s;try{let{signedUrl:t,publicUrl:i}=await this.cloud.files.generatePresignedUploadUrl({filename:e.name});await fetch(t,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"}),this.uploadedUrls.set(r,i),s={...s,status:{type:"requires-action",reason:"composer-send"}},yield s}catch{s={...s,status:{type:"incomplete",reason:"error"}},yield s}}async remove(e){this.uploadedUrls.delete(e.id)}async send(e){let t,r=this.uploadedUrls.get(e.id);if(!r)throw Error("Attachment not uploaded");return this.uploadedUrls.delete(e.id),t="image"===e.type?[{type:"image",image:r,filename:e.name}]:[{type:"file",data:r,mimeType:e.contentType,filename:e.name}],{...e,status:{type:"complete"},content:t}}}let ii=void 0!==n.default&&n.default?.env?.NEXT_PUBLIC_ASSISTANT_BASE_URL,ia=ii?new class{threads;auth;runs;files;telemetry;constructor(e){const t=new sj(e);this.threads=new sY(t),this.auth={tokens:new sP(t)},this.runs=new sG(t),this.files=new sQ(t);const r=e.telemetry;this.telemetry=!1===r?{enabled:!1}:!0===r||void 0===r?{enabled:!0}:{enabled:!1!==r.enabled,...r}}}({baseUrl:ii,anonymous:!0}):void 0;function io(e){return function(t){let r,s=!1;"function"==typeof t?r=t:t&&(s=!!t.optional,r=t.selector);
3let a=e({optional:s});return a?function(e,t=e=>e){e.__isBound||(e.__internal_bindMethods?.(),e.__isBound=!0);let r=(0,i.useSyncExternalStore)(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return(0,i.useDebugValue)(r),r}(a,r):null}}function il(e){let t=eN(),r=tt(()=>t.message.source?t.message().__internal_getRuntime?.()??null:null);if(!r&&!e?.optional)throw Error("MessageRuntime is not available");return r}let id=io(il);function iu(e){let t=eN(),r=tt(()=>t.thread.source?t.thread().__internal_getRuntime?.()??null:null);if(!r&&!e?.optional)throw Error("ThreadRuntime is not available");return r}io(e=>il(e)?.composer??null);let ic=io(iu);io(e=>iu(e)?.composer??null);var ih=e.i(954937),ip=e.i(412256),ig=e.i(999269),im=e.i(827764),ib=e.i(459021),i_=e.i(739351);e.i(577630);var iy=e.i(455852),iw=e.i(914460);e.i(389820);var ix=e.i(156561),iv=e.i(502916),iS=e.i(7205),iT=e.i(875487),iI=e.i(687123);e.i(53759);var iE=e.i(541048),iC=e.i(932647),ik=e.i(453620),iR=e.i(137180),iA=e.i(706048),iN=e.i(421080),iM=e.i(554662),ij=e.i(85280),iP=e.i(548566),iB=e.i(525393),iD=e.i(22154),iO=e.i(304986),iL=e.i(71345),iF=e.i(511356),iU=e.i(675917),i$=e.i(812878);let iz={...iU.defaultSchema,tagNames:[...iU.defaultSchema.tagNames??[],"details","summary"],attributes:{...iU.defaultSchema.attributes,span:[...iU.defaultSchema.attributes?.span??[],"style","className","class"],details:["className","class"],summary:["className","class"]}},iq={pre:({children:e})=>(0,s.jsx)("pre",{className:"bg-muted overflow-x-auto rounded-md p-3 text-xs",children:e}),code:({children:e,className:t})=>t?.startsWith("language-")?(0,s.jsx)("code",{className:t,children:e}):(0,s.jsx)("code",{className:"bg-muted rounded px-1 py-0.5 text-xs",children:e}),a:function({href:e,children:t}){let r=e&&/^(https?:\/\/|mailto:)/i.test(e),i=e&&/^\/api\/export\//i.test(e),a=e&&(/^\/viewer\//.test(e)||/^\/home\/[^/]+\/drawings\/[^/]+/.test(e)),n=r||i||a?e:void 0;return n?(0,s.jsx)("a",{href:n,...i?{download:""}:{target:"_blank",rel:"noopener noreferrer"},className:"text-primary break-all underline",children:t}):(0,s.jsx)(s.Fragment,{children:t})},table:function({children:e}){let t=(0,i.useRef)(null),[r,a]=(0,i.useState)(!1),n=(0,i.useCallback)(()=>{let e=t.current;if(!e)return;let r=Array.from(e.querySelectorAll("tr")).map(e=>Array.from(e.querySelectorAll("th, td")).map(e=>(e.textContent??"").replace(/\t/g," ").replace(/\n/g," ").trim()).join(" ")).join("\n");if(!r)return;let s=e.outerHTML,i=()=>{a(!0),setTimeout(()=>a(!1),3e3)};navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([s],{type:"text/html"}),"text/plain":new Blob([r],{type:"text/plain"})})]).then(i).catch(()=>{navigator.clipboard.writeText(r).then(i)})},[]);return(0,s.jsxs)("div",{className:"group/table relative overflow-x-auto",children:[(0,s.jsx)("button",{type:"button",onClick:n,"aria-label":r?"Copied":"Copy table",className:"border-border/60 bg-card text-muted-foreground hover:text-foreground absolute top-1 right-1 z-10 flex h-7 w-7 items-center justify-center rounded-md border opacity-0 shadow-sm transition-opacity group-hover/table:opacity-100",children:r?(0,s.jsx)(iB.Check,{className:"h-3.5 w-3.5"}):(0,s.jsx)(iD.Copy,{className:"h-3.5 w-3.5"})}),(0,s.jsx)("table",{ref:t,className:"border-border w-full border-collapse border text-xs",children:e})]})},th:({children:e})=>(0,s.jsx)("th",{className:"bg-muted border-border border px-2 py-1 text-left font-medium",children:e}),td:({children:e})=>(0,s.jsx)("td",{className:"border-border border px-2 py-1 align-middle",children:e})},iV=(0,i.memo)(function({text:e}){return(0,s.jsx)(iO.default,{remarkPlugins:[i$.default],rehypePlugins:[iL.default,[iF.default,iz]],components:iq,children:e})}),iH="__onboarding_init__";function iJ(e,t){let r={};try{r=JSON.parse(e.argsText||"{}")}catch{return null}switch(e.toolName){case"navigate":if("string"==typeof r.path)return t.onNavigate(r.path),"first_file";break;case"highlight":"string"==typeof r.selector&&t.onHighlight(r.selector,"string"==typeof r.label?r.label:void 0);break;case"connect_integration":"string"==typeof r.provider&&t.onConnectIntegration(r.provider);break;case"open_viewer":"string"==typeof r.drawingId&&"string"==typeof r.accountId&&t.onOpenViewer(r.drawingId,r.accountId);break;case"update_profile":{let e={};
3if("string"==typeof r.displayName&&(e.displayName=r.displayName),"string"==typeof r.role&&(e.role=r.role),"string"==typeof r.language&&(e.language=r.language),t.onUpdateProfile(e),e.role)return"cloud_storage";if(e.displayName)return"role";break}case"wait_for_event":"string"==typeof r.event&&t.onWaitForEvent(r.event,"string"==typeof r.message?r.message:void 0);break;case"open_panel":"string"==typeof r.tab&&t.onOpenPanel(r.tab);break;case"complete_onboarding":return"__complete__";case"show_answer_cards":break;case"trigger_file_action":"string"==typeof r.action&&t.onTriggerFileAction(r.action);break;case"skip_step":{let e=t.getOnboardingState().currentStep,r=iR.STEP_ORDER.indexOf(e),s=iR.STEP_ORDER[r+1];if(s)return s;return"__complete__"}}return null}var iW=e.i(629162),iG=e.i(990311),iK=e.i(765343),iY=e.i(928231),iQ=e.i(638511),iZ=e.i(316909),iX=e.i(607655);let i0=(0,iX.default)("compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),i1=(0,iX.default)("hammer",[["path",{d:"m15 12-9.373 9.373a1 1 0 0 1-3.001-3L12 9",key:"1hayfq"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172v-.344a2 2 0 0 0-.586-1.414l-1.657-1.657A6 6 0 0 0 12.516 3H9l1.243 1.243A6 6 0 0 1 12 8.485V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"15ts47"}]]),i5=(0,iX.default)("palette",[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]]);var i2=e.i(728387);let i6=(0,iX.default)("trees",[["path",{d:"M10 10v.2A3 3 0 0 1 8.9 16H5a3 3 0 0 1-1-5.8V10a3 3 0 0 1 6 0Z",key:"1l6gj6"}],["path",{d:"M7 16v6",key:"1a82de"}],["path",{d:"M13 19v3",key:"13sx9i"}],["path",{d:"M12 19h8.3a1 1 0 0 0 .7-1.7L18 14h.3a1 1 0 0 0 .7-1.7L16 9h.2a1 1 0 0 0 .8-1.7L13 3l-1.4 1.5",key:"1sj9kv"}]]);var i3=e.i(290126);let i4={architect:(0,s.jsx)(i0,{className:"h-5 w-5"}),interior_designer:(0,s.jsx)(i5,{className:"h-5 w-5"}),builder:(0,s.jsx)(i1,{className:"h-5 w-5"}),civil_engineer:(0,s.jsx)(iQ.Building2,{className:"h-5 w-5"}),structural_engineer:(0,s.jsx)(iY.Building,{className:"h-5 w-5"}),project_manager:(0,s.jsx)(iZ.ClipboardList,{className:"h-5 w-5"}),landscape_architect:(0,s.jsx)(i6,{className:"h-5 w-5"}),other:(0,s.jsx)(i3.User,{className:"h-5 w-5"}),google_drive:(0,s.jsx)(iM.ProviderIcon,{provider:"google_drive",className:"h-5 w-5"}),dropbox:(0,s.jsx)(iM.ProviderIcon,{provider:"dropbox",className:"h-5 w-5"}),neither:(0,s.jsx)(ip.ArrowRight,{className:"h-5 w-5"})};function i7({options:e,onSelect:t,onUploadFile:r,disabled:a,selectedId:n}){let{t:o}=(0,iy.useTranslation)("drawings"),[l,d]=(0,i.useState)(!1),[u,c]=(0,i.useState)(""),{state:h}=(0,iW.useOnboarding)(),p=e.some(e=>"other"===e.id),g=e.filter(e=>"other"!==e.id),m=()=>{let e=u.trim();e&&t(e.toLowerCase().replace(/\s+/g,"_"),e)};if(l)return(0,s.jsxs)("div",{className:"my-3 flex items-center gap-2",children:[(0,s.jsx)("input",{type:"text",autoFocus:!0,value:u,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&m()},placeholder:o("onboardingToolRenderers.typeYourRole"),className:"border-border bg-background flex-1 rounded-full border px-4 py-2 text-sm outline-none focus:ring-2 focus:ring-offset-2"}),(0,s.jsx)(iS.Button,{size:"icon",className:"h-9 w-9 shrink-0 rounded-full",disabled:!u.trim(),onClick:m,children:(0,s.jsx)(ig.ArrowUp,{className:"h-4 w-4"})})]});let f=e.some(e=>"import_integration"===e.id||e.id.startsWith("import_"));return(0,s.jsxs)("div",{className:"my-3",children:[(0,s.jsxs)("div",{className:"flex flex-wrap justify-center gap-2",children:[g.map(e=>{let i=n===e.id;return(0,s.jsxs)(iS.Button,{variant:i?"default":"outline",size:"sm",disabled:a,onClick:()=>{var s,i;return s=e.id,i=e.label,void("other"===s?d(!0):("upload_file"===s||"sample_file"===s||"import_integration"===s||s.startsWith("import_"))&&r?r(s):t(s,i))},className:(0,iE.cn)("gap-2 rounded-full px-4 py-2 transition-all",i&&"ring-primary ring-2 ring-offset-2"),children:[i4[e.id]??i4[e.icon??""],e.label]},e.id)}),p&&(0,s.jsx)(iS.Button,{variant:"outline",size:"sm",disabled:a,onClick:()=>d(!0),className:"gap-1 rounded-full px-4 py-2",children:(0,s.jsx)(i2.Plus,{className:"h-4 w-4"})})]}),f&&"google_drive"!==h.integrationProvider&&(0,s.jsx)("p",{className:"text-foreground mt-3 text-center text-base",children:(0,s.jsx)(iI.Trans,{i18nKey:"drawings:onboardingToolRenderers.askToFindFile"})})]})}function i8({message:e}){let{t}=(0,iy.useTranslation)("drawings");return(0,s.jsxs)("div",{className:"my-3 flex items-center gap-2 rounded-lg border border-dashed p-3",children:[(0,s.jsx)(im.Loader2,{className:"text-muted-foreground h-4 w-4 animate-spin"}),(0,s.jsx)("span",{className:"text-muted-foreground text-sm",children:e??t("onboardingToolRenderers.waitingForYou")})]})}function i9({path:e}){return(0,s.jsxs)("div",{className:"text-muted-foreground my-1 flex items-center gap-1.5 text-xs",children:[(0,s.jsx)(ip.ArrowRight,{className:"h-3 w-3"}),(0,s.jsx)("span",{children:(0,s.jsx)(iI.Trans,{i18nKey:"drawings:onboardingToolRenderers.navigating"})})]})}function ae({provider:e}){let{t}=(0,iy.useTranslation)("drawings"),{state:r}=(0,iW.useOnboarding)(),i=r.integrationConnected,a=!i&&r.integrationProvider!==e,n=(0,iM.getProviderLabel)(e);return(0,s.jsxs)("div",{className:"bg-muted/50 my-2 flex items-center gap-3 rounded-lg border p-3",children:[(0,s.jsx)(iM.ProviderIcon,{provider:e,className:"h-5 w-5"}),(0,s.jsxs)("div",{className:"flex-1",children:[(0,s.jsx)("p",{className:"text-sm font-medium",children:t(i?"onboardingToolRenderers.providerConnected":a?"onboardingToolRenderers.providerNotConnected":"onboardingToolRenderers.connectProvider",{label:n})}),(0,s.jsx)("p",{className:"text-muted-foreground text-xs",children:i?t("onboardingToolRenderers.lookingForFiles"):a?t("onboardingToolRenderers.connectionFailed"):t("onboardingToolRenderers.openingAuthorization",{label:n})})]}),!i&&!a&&(0,s.jsx)(im.Loader2,{className:"h-4 w-4 animate-spin"})]})}function at({call:e,onSendMessage:t,onDirectAdvance:r,onUploadFile:i}){let a=e.args??{},n=void 0!==e.result;
3switch(e.toolName){case"show_answer_cards":{let e=a.options??[];return(0,s.jsx)(i7,{options:e,onUploadFile:i,onSelect:(e,s)=>{"neither"===e&&r?r():t&&t(s)}})}case"wait_for_event":if(n)return null;return(0,s.jsx)(i8,{message:a.message});case"navigate":return(0,s.jsx)(i9,{path:a.path});case"connect_integration":return(0,s.jsx)(ae,{provider:a.provider});default:return null}}let ar=(0,i.memo)(function({onSendMessage:e,onDirectAdvance:t,onUploadFile:r}){let i=id().content;return(0,s.jsx)(s.Fragment,{children:i.map((i,a)=>{if("text"===i.type){let e=i.text??"";return e?(0,s.jsx)(iV,{text:e},a):null}return"tool-call"===i.type?(0,s.jsx)(at,{call:i,onSendMessage:e,onDirectAdvance:t,onUploadFile:r},`${i.toolCallId}-${a}`):null})})}),as="/api/ai/onboarding/step",ai=new Set(["viewer","sharing"]),aa=[{text:"I will walk you through the viewer. It will take about a minute."},{text:"This bottom bar helps you move around the drawing.",selector:'[data-onboarding="viewer-controls"]'},{text:"Per-page scale",selector:'[data-onboarding="nav-scale"]'},{text:"Zoom controls",selector:'[data-onboarding="nav-zoom"]'},{text:"On the left are your annotation tools.",selector:'[data-onboarding="floating-toolbox"]'},{text:"Revision cloud",selector:'[data-onboarding="tool-cloud"]'},{text:"Freehand",selector:'[data-onboarding="tool-freehand"]'},{text:"Measurements",selector:'[data-onboarding="tool-measurement"]'},{text:"Now try it. Tap anywhere on the drawing to place a comment.",selector:'[data-onboarding="tool-comment"]',selectTool:"comment",waitForEvent:"onboarding:comment-placed"},{text:"Your comment appears in the Markups panel.",selector:'[data-onboarding="right-panel"]',openPanel:"markups"},{text:"These tabs help you manage the file.",selector:'[data-onboarding="right-panel"]'},{text:"Page thumbnails",selector:'[data-onboarding="tab-pages"]',openPanel:"pages"},{text:"Version history",selector:'[data-onboarding="tab-versions"]',openPanel:"versions"},{text:"And this is the AI chat â use it to find, manage, and compose your files.",selector:'[data-onboarding="tab-chat"]',openPanel:"chat"}],an=[{text:"Drawings in a workspace are already shared with everyone on that workspace team.",selector:'[data-onboarding="share-button"]'},{text:"Use Share when you want to target specific people.",selector:'[data-onboarding="share-user-section"]',openShareDialog:!0},{text:"Or create a link when you want to share by URL.",selector:'[data-onboarding="share-link-section"]',openShareDialog:!0}],ao=[{text:"Use Share when you want to target specific people.",selector:'[data-onboarding="share-user-section"]',openShareDialog:!0},{text:"You can also add this file to a workspace so that team can access it there.",selector:'[data-onboarding="share-workspace-section"]',openShareDialog:!0},{text:"Or create a link when you want to share by URL.",selector:'[data-onboarding="share-link-section"]',openShareDialog:!0}];function al(){let e=(0,iW.useOnboarding)(),{currentStep:t}=e.state,r=iR.BROWSER_ONBOARDING_STEPS.includes(t)?iR.BROWSER_ONBOARDING_STEPS:iR.VIEWER_ONBOARDING_STEPS,a=r.indexOf(t),[n,o]=(0,i.useState)(null),l=(0,i.useCallback)(()=>{(0,iK.clearSpotlight)(),window.dispatchEvent(new Event(iG.ONBOARDING_CLOSE_SHARE_DIALOG_EVENT)),e.skip()},[e]),d=(0,i.useCallback)(()=>{(0,iK.clearSpotlight)(),window.dispatchEvent(new Event(iG.ONBOARDING_CLOSE_SHARE_DIALOG_EVENT)),e.goForward()},[e]),u=(0,i.useCallback)(()=>{(0,iK.clearSpotlight)(),window.dispatchEvent(new Event(iG.ONBOARDING_CLOSE_SHARE_DIALOG_EVENT)),e.goBack()},[e]),c=ai.has(t);return(0,s.jsxs)("div",{className:(0,iE.cn)("flex flex-col overflow-hidden",!c&&"flex-1"),children:[c&&(0,s.jsx)("div",{className:"absolute top-2 right-2 z-10",children:(0,s.jsx)(iS.Button,{variant:"ghost",size:"icon",onClick:l,className:"text-muted-foreground h-6 w-6 opacity-0 transition-opacity group-hover:opacity-100",children:(0,s.jsx)(i_.X,{className:"h-3 w-3"})})}),(0,s.jsx)(au,{holdoverMessage:n,onCaptureLastMessage:o,navigation:c?null:(0,s.jsx)(ad,{currentStep:t,progressSteps:r,stepNumber:a>=0?a+1:1,canGoBack:a>0,onGoBack:u,onGoForward:d,onSkip:l})},t)]})}function ad({currentStep:e,progressSteps:t,stepNumber:r,canGoBack:i,onGoBack:a,onGoForward:n,onSkip:o}){return(0,s.jsx)("div",{className:"mx-auto w-full max-w-2xl shrink-0 px-4 pt-4 pb-3",children:(0,s.jsxs)("div",{className:"border-border/50 flex items-center justify-between rounded-2xl border bg-white/10 px-3 py-2 dark:bg-white/5",children:[(0,s.jsx)("div",{className:"w-20",children:i&&(0,s.jsxs)(iS.Button,{variant:"ghost",size:"sm",onClick:a,className:"text-muted-foreground gap-1 text-xs",children:[(0,s.jsx)(ih.ArrowLeft,{className:"h-3 w-3"}),(0,s.jsx)(iI.Trans,{i18nKey:"drawings:onboardingChat.back"})]})}),(0,s.jsxs)("div",{className:"flex flex-col items-center gap-1",children:[(0,s.jsx)("span",{className:"text-muted-foreground text-xs font-medium",children:(0,s.jsx)(iI.Trans,{i18nKey:"drawings:onboardingChat.stepProgress",values:{current:r,total:t.length}})}),(0,s.jsx)("div",{className:"flex gap-1",children:t.map((e,t)=>(0,s.jsx)("div",{className:(0,iE.cn)("h-1 w-6 rounded-full transition-colors",t<r?"bg-primary":"bg-muted-foreground
3/20")},e))}),(0,s.jsx)("span",{className:"text-muted-foreground text-[10px]",children:(0,s.jsx)(iI.Trans,{i18nKey:iW.STEP_LABELS[e]})})]}),(0,s.jsxs)("div",{className:"flex w-20 justify-end gap-1",children:[(0,s.jsxs)(iS.Button,{variant:"ghost",size:"sm",onClick:n,className:"text-muted-foreground gap-1 text-xs",children:[(0,s.jsx)(iI.Trans,{i18nKey:"drawings:onboardingChat.next"}),(0,s.jsx)(ip.ArrowRight,{className:"h-3 w-3"})]}),(0,s.jsx)(iS.Button,{variant:"ghost",size:"sm",onClick:o,className:"text-muted-foreground gap-1 text-xs",children:(0,s.jsx)(i_.X,{className:"h-3 w-3"})})]})]})})}function au({holdoverMessage:e,onCaptureLastMessage:t,navigation:r}){let{t:n,i18n:o}=(0,iy.useTranslation)("drawings"),l=(0,iv.useSupabase)(),d=(0,a.useRouter)(),u=(0,iW.useOnboarding)(),c=(0,iw.useRevalidatePersonalAccountDataQuery)(),h=(0,i.useRef)(null),p=(0,i.useRef)(null),g=(0,i.useRef)(null),m=(0,i.useRef)(null);(0,i.useEffect)(()=>()=>{m.current?.()},[]);let[f,b]=(0,i.useState)(!1),[_,y]=(0,i.useState)(!1),w=u.state.currentStep,x=u.state.drawingSource,v=u.state.integrationProvider,S=u.state.integrationId,T=ai.has(w),I=(0,i.useMemo)(()=>(function(e,t,r){switch(e){case"viewer":let s;return"external"===t?(s="google_drive"===r||"dropbox"===r?(0,iM.getProviderLabel)(r):"your drive",[{text:"I will walk you through the viewer. It will take about a minute."},{text:"This bottom bar helps you move around the drawing.",selector:'[data-onboarding="viewer-controls"]'},{text:"Per-page scale",selector:'[data-onboarding="nav-scale"]'},{text:"Zoom controls",selector:'[data-onboarding="nav-zoom"]'},{text:"On the left are your annotation tools.",selector:'[data-onboarding="floating-toolbox"]'},{text:"Revision cloud",selector:'[data-onboarding="tool-cloud"]'},{text:"Freehand",selector:'[data-onboarding="tool-freehand"]'},{text:"Measurements",selector:'[data-onboarding="tool-measurement"]'},{text:"Now try it. Tap anywhere on the drawing to place a comment.",selector:'[data-onboarding="tool-comment"]',selectTool:"comment",waitForEvent:"onboarding:comment-placed"},{text:`Because this file is synced with ${s}, a branch with your annotation was created automatically.`,selector:'[data-onboarding="version-current-branch"]',openPanel:"versions"},{text:`When this file updates in ${s}, the latest synced main state appears here.`,selector:'[data-onboarding="version-main-state"]',openPanel:"versions"},{text:`You can save changes back to ${s} at any time, but your work is already preserved here in real time.`,selector:'[data-onboarding="external-save-button"]'},{text:"This sidebar helps you manage the file.",selector:'[data-onboarding="right-panel"]',openPanel:"pages"},{text:"Page thumbnails",selector:'[data-onboarding="tab-pages"]',openPanel:"pages"},{text:"Your comments and markups appear here.",selector:'[data-onboarding="tab-markups"]',openPanel:"markups"},{text:"And this is the AI chat â use it to find, manage, and compose your files.",selector:'[data-onboarding="tab-chat"]',openPanel:"chat"}]):aa;case"sharing":return"workspace"===t?an:ao;default:return null}})(w,x,v),[w,x,v]),[E,C]=(0,i.useState)(0),[k,R]=(0,i.useState)(null),A=`${w}:${x??"unknown"}:${E}`,N=k===A;(0,i.useEffect)(()=>{C(0),(0,iK.clearSpotlight)()},[w,x,v]),(0,i.useEffect)(()=>{if(!I||0===E)return;let e=I[E-1]?.selector,t=I[E]?.selector;e&&t&&e===t||(0,iK.clearSpotlight)()},[I,E]);let M=(0,i.useRef)(u.state);(0,i.useEffect)(()=>{M.current=u.state});let j=(0,i.useRef)(o.language);(0,i.useEffect)(()=>{j.current=o.language});let P=(0,i.useCallback)(()=>{(0,iK.clearSpotlight)(),window.dispatchEvent(new Event(iG.ONBOARDING_CLOSE_COMMENT_EVENT)),window.dispatchEvent(new Event(iG.ONBOARDING_CLOSE_PANEL_EVENT)),window.dispatchEvent(new Event(iG.ONBOARDING_CLOSE_SHARE_DIALOG_EVENT)),setTimeout(()=>{u.setStep("sharing")},1500)},[u]),B=(0,i.useCallback)(()=>{(0,iK.clearSpotlight)(),window.dispatchEvent(new Event(iG.ONBOARDING_CLOSE_SHARE_DIALOG_EVENT)),setTimeout(()=>{iT.notify.success(n("onboardingChat.allSet")),u.complete()},1500)},[u,n]),D=(0,i.useMemo)(()=>({getAccessToken:async()=>{let{data:{session:e}}=await l.auth.getSession();return e?.access_token??null},getOnboardingState:()=>({currentStep:M.current.currentStep,displayName:M.current.displayName,role:M.current.role,language:M.current.language??(j.current&&"en"!==j.current?j.current:null),integrationProvider:M.current.integrationProvider,integrationId:M.current.integrationId,hasFile:M.current.hasFile}),onNavigate:e=>d.push(e),onHighlight:(e,t)=>
3{setTimeout(()=>(0,iK.setSpotlight)(e,t),400)},onClearHighlight:()=>(0,iK.clearSpotlight)(),onConnectIntegration:e=>{m.current?.(),u.setIntegrationId(null),u.setIntegrationProvider(e);let t=navigator.userAgent.includes("DetaDesktop/"),r=window.open("google_drive"===e?"/google-drive/connect?returnUrl=/oauth-callback":"/dropbox/connect?returnUrl=/oauth-callback","_blank","width=600,height=700");if(!r&&!t){u.setIntegrationProvider(null),h.current?.("The connection was not completed.");return}let s=!1,i=new BroadcastChannel("oauth-result"),a=()=>{s=!0,i.close(),window.removeEventListener("message",o)},n=e=>{"oauth-result"!==e.type||s||(a(),e.success?(e.integrationId&&u.setIntegrationId(e.integrationId),u.setIntegrationConnected(!0),d.refresh(),setTimeout(()=>u.goForward(),1500)):(u.setIntegrationProvider(null),u.setIntegrationId(null),h.current?.("The connection was not completed.")))};i.onmessage=e=>n(e.data);let o=e=>{e.origin===window.location.origin&&n(e.data)};window.addEventListener("message",o);let l=r?window.setInterval(()=>{r.closed&&!s&&(window.clearInterval(l),a(),u.setIntegrationProvider(null),u.setIntegrationId(null),h.current?.("The connection was not completed."))},500):void 0,c=r?void 0:window.setTimeout(()=>{s||(a(),u.setIntegrationProvider(null),u.setIntegrationId(null),h.current?.("The connection was not completed."))},6e5);m.current=()=>{l&&window.clearInterval(l),c&&window.clearTimeout(c),a()}},onOpenViewer:(e,t)=>d.push(`/home/${t}/drawings/${e}`),onUpdateProfile:e=>{e.displayName&&u.setDisplayName(e.displayName),e.role&&u.setRole(e.role),e.language&&u.setLanguage(e.language),l.auth.getUser().then(({data:{user:e}})=>{e&&c(e.id),d.refresh()})},onCompleteOnboarding:()=>{(0,iK.clearSpotlight)(),u.complete()},onStepChange:e=>{(0,iK.clearSpotlight)(),u.setStep(e)},onWaitForEvent:()=>{},onOpenPanel:e=>{window.dispatchEvent(new CustomEvent("onboarding:open-panel",{detail:{tab:e}}))},onTriggerFileAction:e=>p.current?.(e),onStreamComplete:()=>{},onCaptureLastMessage:t}),[l,d,u,c,t]),O=((e,{cloud:t,...r}={})=>{var a={runtimeHook:function(){return((e,{initialMessages:t,...r})=>{let{modelContext:s,...a}=(0,i.useContext)(rG)??{},n={...r,adapters:{...a,...r.adapters,chatModel:e}},[o]=(0,i.useState)(()=>new rW(n,t)),l=(0,i.useRef)(void 0);return l.current=tt(e=>e.threadListItem.remoteId),(0,i.useEffect)(()=>{o.threads.getMainThreadRuntimeCore().__internal_setGetThreadId(()=>l.current)},[o]),(0,i.useEffect)(()=>()=>{o.threads.getMainThreadRuntimeCore().detach()},[o]),(0,i.useEffect)(()=>{o.threads.getMainThreadRuntimeCore().__internal_setOptions(n),o.threads.getMainThreadRuntimeCore().__internal_load()}),(0,i.useEffect)(()=>{if(s)return o.registerModelContextProvider(s)},[s,o]),(0,i.useMemo)(()=>new so(o),[o])})(e,r)},adapter:(e=>{let t=(0,i.useRef)(e);(0,i.useEffect)(()=>{t.current=e},[e]);let r=(0,i.useCallback)(function({children:e}){let r=function(e){let t=eN(),[r]=(0,i.useState)(()=>new s5(e,t));return r}({get current(){return t.current.cloud??ia}}),a=t.current.cloud??ia,n=(0,i.useMemo)(()=>new is(a),[a]),o=(0,i.useMemo)(()=>({history:r,attachments:n}),[r,n]);return(0,s.jsx)(rK,{adapters:o,children:e})},[]),a=e.cloud??ia;if(!a){let e=new sZ;return e.initialize=async e=>{let r=await t.current.create?.();return{remoteId:e,externalId:r?.externalId}},e}return{list:async()=>{let{threads:e}=await a.threads.list();return{threads:e.map(e=>({status:e.is_archived?"archived":"regular",remoteId:e.id,title:e.title,externalId:e.external_id??void 0}))}},initialize:async()=>{let t=e.create?.()??Promise.resolve(),r=await t,s=r?r.externalId:void 0,{thread_id:i}=await a.threads.create({last_message_at:new Date,external_id:s});return{externalId:s,remoteId:i}},rename:async(e,t)=>a.threads.update(e,{title:t}),archive:async e=>a.threads.update(e,{is_archived:!0}),unarchive:async e=>a.threads.update(e,{is_archived:!1}),delete:async t=>(await e.delete?.(t),a.threads.delete(t)),generateTitle:async(e,t)=>{let r=t.map(e=>({...e,content:e.content.filter(e=>"text"===e.type||"tool-call"===e.type)}));return a.runs.stream({thread_id:e,assistant_id:"system/thread_title",messages:r})},fetch:async e=>{let t=await a.threads.get(e);return{status:t.is_archived?"archived":"regular",remoteId:t.id,title:t.title,externalId:t.external_id??void 0}},unstable_Provider:r}})({cloud:t}),allowNesting:!0};if(null!==eN().threadListItem.source){if(!a.allowNesting)throw Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return a.runtimeHook()}return(e=>{let[t]=(0,i.useState)(()=>new sE(e));return(0,i.useEffect)(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),(0,i.useMemo)(()=>new so(t),[t])})(a)})((0,i.useMemo)(()=>({async *run({messages:e,abortSignal:t}){let r,s=await D.getAccessToken();if(!s)return void(yield{content:[{type:"text",text:"Session expired. Please refresh the page."}]});let i=[],a=[];for(let t of e.slice(0,-1))if("user"===t.role){let e=t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),r=e===iH?"start onboarding":e;if(a.length>0){let e=[...a,{type:"text",text:r}];i.push({role:"user",content:e}),a=[]}else i.push({role:"user",content:r})}
3else if("assistant"===t.role){let e=new Set(["show_answer_cards","wait_for_event"]),r=[];for(let s of t.content)"text"===s.type&&"text"in s?r.push({type:"text",text:s.text}):"tool-call"===s.type&&e.has(s.toolName)&&r.push({type:"tool_use",id:s.toolCallId,name:s.toolName,input:s.args??{}});for(let s of(r.length>0&&i.push({role:"assistant",content:r}),t.content))"tool-call"===s.type&&void 0!==s.result&&e.has(s.toolName)&&a.push({type:"tool_result",tool_use_id:s.toolCallId,content:"string"==typeof s.result?s.result:JSON.stringify(s.result??"ok")})}let n=e[e.length-1];if(!n||"user"!==n.role)return;let o=n.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),l=o===iH?"start onboarding":o,d=D.getOnboardingState();l.startsWith("viewer:")&&(r=l.slice(7).trim());let u=await fetch("/api/ai/onboarding",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({message:l||"continue",step:d.currentStep??"name",subStep:r,history:i,pendingToolResults:a.length>0?a:void 0,onboardingState:d}),signal:t});if(!u.ok)return void(yield{content:[{type:"text",text:"Something went wrong. Please try again."}]});let c=u.body?.getReader();if(!c)return;let h=new TextDecoder,p="",g=[],m=null,f=!1;function b(){let e=g[g.length-1];if(e?.kind==="text")return e;let t={kind:"text",text:""};return g.push(t),t}try{for(;;){let{done:e,value:t}=await c.read();if(e)break;p+=h.decode(t,{stream:!0});let r=function(e){let t=[],r=e.split("\n"),s="",i="";for(let e of r)e.startsWith("event: ")?s=e.slice(7):e.startsWith("data: ")?i=e.slice(6):""===e&&s&&(t.push({event:s,data:i}),s="",i="");return t}(p),s=p.lastIndexOf("\n\n");for(let e of(s>=0&&(p=p.slice(s+2)),r))try{let t=JSON.parse(e.data);switch(e.event){case"text-delta":b().text+=t.text;break;case"tool-call-start":g.push({kind:"tool-call",key:t.index,toolCallId:t.id,toolName:t.name,argsText:""});break;case"tool-call-delta":{let e=g.find(e=>"tool-call"===e.kind&&e.key===t.index);e&&(e.argsText+=t.partialJson);break}case"tool-call-complete":{let e=g.find(e=>"tool-call"===e.kind&&e.toolCallId===t.id);if(e)if(!1===t.ok)e.result={status:"error",message:"string"==typeof t.error?t.error:"Tool execution failed"};else{let t=iJ(e,D);"__complete__"===t?f=!0:t&&(m=t),e.result={status:"ok"}}break}case"done":for(let e of g)if("tool-call"===e.kind&&void 0===e.result){let t=iJ(e,D);"__complete__"===t?f=!0:t&&(m=t),e.result={status:"ok"}}if(m){let e=g.filter(e=>"text"===e.kind).map(e=>e.text).join("").trim();e&&D.onCaptureLastMessage(e);let t=m;setTimeout(()=>D.onStepChange(t),600)}f&&setTimeout(()=>D.onCompleteOnboarding(),2500),D.onStreamComplete();break;case"error":b().text+=` 4 5Error: ${t.message}`}}catch{}let i=[];for(let e of g)if("text"===e.kind)i.push({type:"text",text:e.text});else{let t={};try{t=JSON.parse(e.argsText||"{}")}catch{}i.push({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,argsText:e.argsText,args:t,result:e.result})}i.length>0&&(yield{content:i})}}finally{c.releaseLock()}}}),[D]));h.current=e=>{O.thread.composer.setText(e),O.thread.composer.send()};let L=(0,i.useCallback)(e=>{h.current?.(e)},[]),F=(0,i.useCallback)(async e=>{y(!0);let{data:t,error:r}=await l.from("accounts").select("id").eq("is_personal_account",!1).limit(1).single();if(r||!t)throw Error(n("onboardingChat.noWorkspace"));let s=Date.now(),i=`${t.id}/temp/${s}/${e.name}`,a=await (0,iP.uploadWithProgress)(l,"drawings",i,e,()=>{});if(a.error)throw a.error;let o=await (0,ij.importLocalPdfAction)({tempFilePath:i,fileName:e.name,accountId:t.id});if(!o.success)throw Error(o.errors.join(", ")||n("onboardingChat.importFailed"));iT.notify.success(n("onboardingChat.drawingSetUploaded")),await fetch(as,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({step:"viewer"})}),await new Promise(e=>setTimeout(e,500)),d.push(`/home/${t.id}/drawings/${o.drawingSetId}`)},[l,d,n]),U=(0,i.useCallback)(async(e,t)=>{y(!0),await fetch(as,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({step:"viewer"})}),await new Promise(e=>setTimeout(e,500));let r=t??M.current.integrationId;r?d.push(`/home/external/${r}/${e}`):d.push(`/home/external-file/${e}`)},[d]),$=(0,i.useCallback)(async e=>{if("sample_file"===e){y(!0);try{let{data:e}=l.storage.from("samples").getPublicUrl("sample-1.pdf"),t=await fetch(e.publicUrl);if(!t.ok)throw Error(n("onboardingChat.fetchSampleFailed"));let r=await t.blob(),s=new File([r],"Sample Drawing Set.pdf",{type:"application/pdf"});await F(s)}catch(e){y(!1),iT.notify.error(e,{fallback:n("onboardingChat.loadSampleFailed")})}return}if("import_integration"===e)return void(S?b(!0):iT.notify.error(n("onboardingChat.noIntegration")));if(e.startsWith("import_")&&"import_integration"!==e){let t=e.slice(7);if(!t)return;y(!0);try{let e="google_drive"===v?ik.importFromGoogleDriveAction:iC.importFromDropboxAction,r=await e({fileId:t,integrationId:S??void 0});r.success?(iT.notify.success(n("onboardingChat.fileImported")),await U(r.drawingId,r.integrationId)):(y(!1),iT.notify.error((0,ix.classifyError)(r.error).message,{fallback:n("onboardingChat.importFileFailed")}))}catch(e){y(!1),iT.notify.error(e,{fallback:n("onboardingChat.importFileFailed")})}return}g.current?.click()},[l,F,S,v,U,n]);p.current=$;let z=(0,i.useCallback)(e=>{b(e),e||_||h.current?.("I closed the file browser. What else can I do?")},[_]),q=(0,i.useCallback)(async e=>{let t=e.target.files?.[0];if(!t||"application/pdf"!==t.type){t&&iT.notify.error(n("onboardingChat.selectPdf")),e.target.value="";return}e.target.value="";try{await F(t)}catch(e){y(!1),iT.notify.error(e,{fallback:n("onboardingChat.uploadPdfFailed")})}},[F,n]),V=(0,i.useRef)(O);return V.current=O,(0,i.useEffect)(()=>
5{if(!I)return;let e=I[E];if(!e)return void("viewer"===w?P():"sharing"===w&&B());let t=!1,r=null,s=()=>{let s=e.selector;s&&(r=setTimeout(()=>{(async()=>{for(;!t;){if(document.querySelector(s))return void(0,iK.setSpotlight)(s);await new Promise(e=>setTimeout(e,100))}})()},150))};if(!N&&e.openPanel&&window.dispatchEvent(new CustomEvent("onboarding:open-panel",{detail:{tab:e.openPanel}})),!N&&e.selectTool&&window.dispatchEvent(new CustomEvent("onboarding:select-tool",{detail:{tool:e.selectTool}})),!N&&e.openShareDialog&&window.dispatchEvent(new Event(iG.ONBOARDING_OPEN_SHARE_DIALOG_EVENT)),e.chatPrompt){if(!N)return()=>{t=!0};s();let i=e.chatPrompt,a="undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`onboarding-${Date.now()}-${Math.random().toString(36).slice(2)}`,n=null,o=e=>{let t=e.detail;t?.requestId===a&&(0,iK.clearSpotlight)()},l=e=>{let t=e.detail;t?.requestId===a&&(n=setTimeout(()=>{P()},2e3))};window.addEventListener(iG.ONBOARDING_CHAT_SENT_EVENT,o),window.addEventListener(iG.ONBOARDING_CHAT_COMPLETE_EVENT,l);let d=setTimeout(()=>{(async()=>{for(;!t;){if(document.querySelector('[data-ai-chat-root="true"]'))return void window.dispatchEvent(new CustomEvent(iG.ONBOARDING_SEND_CHAT_EVENT,{detail:{requestId:a,text:i}}));await new Promise(e=>setTimeout(e,100))}})()},600);return()=>{t=!0,n&&clearTimeout(n),r&&clearTimeout(r),clearTimeout(d),window.removeEventListener(iG.ONBOARDING_CHAT_SENT_EVENT,o),window.removeEventListener(iG.ONBOARDING_CHAT_COMPLETE_EVENT,l)}}if(e.waitForEvent){let i=()=>{C(e=>e+1)};return window.addEventListener(e.waitForEvent,i),N&&s(),()=>{t=!0,r&&clearTimeout(r),window.removeEventListener(e.waitForEvent,i)}}if(!N)return()=>{t=!0};s();let i=setTimeout(()=>{C(e=>e+1)},Math.max(1500,50*e.text.length));return()=>{t=!0,r&&clearTimeout(r),clearTimeout(i)}},[I,E,w,N,P,B]),(0,i.useEffect)(()=>{if(T)return;let e=setTimeout(()=>{V.current.thread.composer.setText("__onboarding_init__"),V.current.thread.composer.send()},300);return()=>clearTimeout(e)},[T]),(0,s.jsxs)(e7,{runtime:O,children:[(0,s.jsx)(ac,{step:w,isStaticOnboardingStep:T,staticSteps:I,staticStepIndex:E,holdoverMessage:e,onSendMessage:L,onDirectAdvance:u.goForward,onUploadFile:$,hideComposer:T,onStaticTextComplete:()=>R(A),navigation:r,isImporting:_}),(0,s.jsx)("input",{ref:g,type:"file",accept:".pdf,application/pdf",onChange:q,className:"hidden"}),S&&"dropbox"===v&&(0,s.jsx)(iA.DropboxFilePicker,{integrationId:S,trigger:(0,s.jsx)("span",{}),open:f,onOpenChange:z,onImportSuccess:U}),S&&"google_drive"===v&&(0,s.jsx)(iN.GoogleDriveImportPicker,{integrationId:S,trigger:(0,s.jsx)("span",{}),open:f,onOpenChange:z,onImportSuccess:U})]})}
5function ac({step:e,isStaticOnboardingStep:t,staticSteps:r,staticStepIndex:i,holdoverMessage:a,onSendMessage:n,onDirectAdvance:o,onUploadFile:l,hideComposer:d,onStaticTextComplete:u,navigation:c,isImporting:h}){let p=t&&r?r[Math.min(i,r.length-1)]?.text??null:null;return(0,s.jsx)(ah,{step:e,holdoverMessage:a,onSendMessage:n,onDirectAdvance:o,onUploadFile:l,hideComposer:d,staticText:p,onStaticTextComplete:u,navigation:c,isImporting:h})}function ah({step:e,holdoverMessage:t,onSendMessage:r,onDirectAdvance:i,onUploadFile:a,hideComposer:n,staticText:o,onStaticTextComplete:l,navigation:d,isImporting:u}){let{t:c}=(0,iy.useTranslation)("drawings"),h=ic(e=>e.isRunning),p=!ic(e=>e.messages).some(e=>"assistant"===e.role),g=p&&!!t;return u?(0,s.jsxs)("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 px-6 py-6",children:[(0,s.jsx)(im.Loader2,{className:"text-primary h-8 w-8 animate-spin"}),(0,s.jsx)("p",{className:"text-muted-foreground text-center text-lg font-medium",children:(0,s.jsx)(iI.Trans,{i18nKey:"drawings:onboardingChat.preparingDrawing"})})]}):o?(0,s.jsx)("div",{className:"flex flex-1 items-center justify-center px-6 py-6",children:(0,s.jsx)("p",{className:"text-foreground text-center text-lg leading-relaxed font-medium tracking-tight",children:(0,s.jsx)(am,{text:o,speed:30,onComplete:l})})}):(0,s.jsxs)(ru.Root,{className:"flex flex-1 flex-col overflow-hidden",children:[(0,s.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto px-4",children:(0,s.jsx)("div",{className:"w-full max-w-2xl",children:!p||h||"name"!==e||t?g?(0,s.jsx)("div",{className:(0,iE.cn)("text-foreground mx-auto max-w-xl rounded-2xl px-6 py-5 text-center text-lg leading-relaxed font-medium tracking-tight transition-opacity duration-300",h?"opacity-40":"opacity-100"),children:(0,s.jsx)(iV,{text:t})}):p?(0,s.jsx)("div",{className:"flex justify-center py-8",children:(0,s.jsx)(im.Loader2,{className:"text-muted-foreground h-5 w-5 animate-spin"})}):(0,s.jsx)(ru.Messages,{components:{UserMessage:ap,AssistantMessage:function(){return(0,s.jsx)(ag,{onSendMessage:r,onDirectAdvance:i,onUploadFile:a})}}}):(0,s.jsxs)("div",{className:"text-center",children:[(0,s.jsx)("h1",{className:"text-foreground text-4xl font-semibold tracking-tight",children:(0,s.jsx)(iI.Trans,{i18nKey:"drawings:onboardingChat.welcome"})}),(0,s.jsx)("p",{className:"text-muted-foreground mt-2 text-lg",children:(0,s.jsx)(iI.Trans,{i18nKey:"drawings:onboardingChat.getSetup"})})]})})}),d,!n&&(0,s.jsx)("div",{className:"mx-auto w-full max-w-2xl shrink-0 px-4 pb-4",children:(0,s.jsx)("div",{className:"border-border/50 rounded-2xl border bg-white/10 backdrop-blur-sm dark:bg-white/5",children:(0,s.jsxs)(tV.Root,{className:"flex flex-col px-4 py-2",children:[(0,s.jsx)(tV.Input,{placeholder:c("onboardingChat.composerPlaceholder"),rows:1,className:"placeholder:text-muted-foreground max-h-[200px] resize-none overflow-y-auto bg-transparent py-2 text-sm outline-none",autoFocus:!0}),(0,s.jsx)("div",{className:"flex items-center justify-end pt-1",children:(0,s.jsxs)("div",{children:[(0,s.jsx)(ru.If,{running:!0,children:(0,s.jsx)(tV.Cancel,{asChild:!0,children:(0,s.jsx)(iS.Button,{size:"icon",variant:"outline",className:"h-8 w-8 shrink-0 rounded-full",children:(0,s.jsx)(ib.Square,{className:"h-3.5 w-3.5 fill-current"})})})}
5),(0,s.jsx)(ru.If,{running:!1,children:(0,s.jsx)(tV.Send,{asChild:!0,children:(0,s.jsx)(iS.Button,{size:"icon",className:"h-8 w-8 shrink-0 rounded-full",children:(0,s.jsx)(ig.ArrowUp,{className:"h-4 w-4"})})})})]})})]})})})]})}function ap(){return null}function ag({onSendMessage:e,onDirectAdvance:t,onUploadFile:r}){let i=id(),a=ic(e=>e.messages),n=null;for(let e=a.length-1;e>=0;e--)if("assistant"===a[e].role){n=a[e].id;break}return i.id!==n?null:(0,s.jsx)("div",{className:"text-foreground mx-auto max-w-xl rounded-2xl px-6 py-5 text-center text-lg leading-relaxed font-medium tracking-tight",children:(0,s.jsx)(ar,{onSendMessage:e,onDirectAdvance:t,onUploadFile:r})})}function am({text:e,speed:t=30,onComplete:r}){let[a,n]=(0,i.useState)(""),o=(0,i.useRef)(null),[l,d]=(0,i.useState)(e);return e!==l&&(d(e),n("")),(0,i.useEffect)(()=>{o.current=null},[e]),(0,i.useEffect)(()=>{if(a.length>=e.length)return;let r=setTimeout(()=>{n(e.slice(0,a.length+1))},t+Math.random()*t*.6-.2*t);return()=>clearTimeout(r)},[a,e,t]),(0,i.useEffect)(()=>{r&&a.length===e.length&&o.current!==e&&(o.current=e,r())},[a,e,r]),(0,s.jsxs)("span",{children:[a,a.length<e.length&&(0,s.jsx)("span",{className:"ml-0.5 inline-block h-[1.1em] w-[2px] animate-pulse bg-current align-text-bottom"})]})}e.s(["OnboardingChat",()=>al],699672)}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.