@applica-software-guru/persona-sdk 0.1.44-preview5 → 0.1.44-preview7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,5 +2,5 @@ var personaSDK=function(I,C,y){"use strict";var Nn=Object.defineProperty;var Pn=
2
2
 
3
3
  ${r.system}`:s.system=r.system),r.tools)for(const[i,a]of Object.entries(r.tools)){const o=(n=s.tools)==null?void 0:n[i];if(o&&o!==a)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);s.tools||(s.tools={}),s.tools[i]=a}return r.config&&(s.config={...s.config,...r.config}),r.callSettings&&(s.callSettings={...s.callSettings,...r.callSettings}),s},{}),rr=class{constructor(){h(this,"_providers",new Set);h(this,"_subscribers",new Set)}getModelContext(){return sr(this._providers)}registerModelContextProvider(t){var s;this._providers.add(t);const e=(s=t.subscribe)==null?void 0:s.call(t,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(t),e==null||e(),this.notifySubscribers()}}notifySubscribers(){for(const t of this._subscribers)t()}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}},nr=class{constructor(){h(this,"_contextProvider",new rr)}registerModelContextProvider(t){return this._contextProvider.registerModelContextProvider(t)}},ir=class{constructor(){h(this,"_subscribers",new Set)}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}waitForUpdate(){return new Promise(t=>{const e=this.subscribe(()=>{e(),t()})})}_notifySubscribers(){const t=[];for(const e of this._subscribers)try{e()}catch(s){t.push(s)}if(t.length>0)throw t.length===1?t[0]:new AggregateError(t)}},ar=t=>t.status.type==="complete",Tt=class extends ir{constructor(){super(...arguments);h(this,"isEditing",!0);h(this,"_attachments",[]);h(this,"_text","");h(this,"_role","user");h(this,"_runConfig",{});h(this,"_eventSubscribers",new Map)}getAttachmentAccept(){var e;return((e=this.getAttachmentAdapter())==null?void 0:e.accept)??"*"}get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(e){this._text!==e&&(this._text=e,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(){const e=this.getAttachmentAdapter();e&&await Promise.all(this._attachments.map(s=>e.remove(s)))}async reset(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){const e=this._onClearAttachments();this.setAttachments([]),await e}async send(){const e=this.getAttachmentAdapter(),s=e&&this.attachments.length>0?await Promise.all(this.attachments.map(async n=>ar(n)?n:await e.send(n))):[],r={role:this.role,content:this.text?[{type:"text",text:this.text}]:[],attachments:s,runConfig:this.runConfig};this._emptyTextAndAttachments(),this.handleSend(r),this._notifyEventSubscribers("send")}cancel(){this.handleCancel()}async addAttachment(e){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");const r=i=>{const a=this._attachments.findIndex(o=>o.id===i.id);a!==-1?this._attachments=[...this._attachments.slice(0,a),i,...this._attachments.slice(a+1)]:(this._attachments=[...this._attachments,i],this._notifyEventSubscribers("attachment_add")),this._notifySubscribers()},n=s.add({file:e});if(Symbol.asyncIterator in n)for await(const i of n)r(i);else r(await n);this._notifyEventSubscribers("attachment_add"),this._notifySubscribers()}async removeAttachment(e){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");const r=this._attachments.findIndex(i=>i.id===e);if(r===-1)throw new Error("Attachment not found");const n=this._attachments[r];await s.remove(n),this._attachments=[...this._attachments.slice(0,r),...this._attachments.slice(r+1)],this._notifySubscribers()}_notifyEventSubscribers(e){const s=this._eventSubscribers.get(e);if(s)for(const r of s)r()}unstable_on(e,s){const r=this._eventSubscribers.get(e);return r?r.add(s):this._eventSubscribers.set(e,new Set([s])),()=>{const n=this._eventSubscribers.get(e);n&&n.delete(s)}}},or=class extends Tt{constructor(e){super();h(this,"_canCancel",!1);this.runtime=e,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}async handleSend(e){var s;this.runtime.append({...e,parentId:((s=this.runtime.messages.at(-1))==null?void 0:s.id)??null,sourceId:null})}async handleCancel(){this.runtime.cancelRun()}},Ie=((t,e=21)=>(s=e)=>{let r="",n=s|0;for(;n--;)r+=t[Math.random()*t.length|0];return r})("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),cr="__optimistic__",dr=()=>`${cr}${Ie()}`,ur=(t,{id:e=Ie(),status:s={type:"complete",reason:"unknown"},attachments:r=[]}={})=>{const n={id:e,createdAt:new Date},i=t.role;switch(i){case"assistant":return{...n,role:i,content:t.content.map(a=>a.type==="tool-call"?{...a,argsText:JSON.stringify(a.args)}:a),status:s,metadata:{unstable_annotations:[],unstable_data:[],steps:[],custom:{}}};case"user":return{...n,role:i,content:t.content,attachments:r,metadata:{custom:{}}};case"system":return{...n,role:i,content:t.content,metadata:{custom:{}}};default:{const a=i;throw new Error(`Unknown message role: ${a}`)}}},kt=Object.freeze({type:"running"}),Ct=Object.freeze({type:"complete",reason:"unknown"}),hr=t=>t===kt||t===Ct,Et=(t,e)=>t&&e?kt:Ct;function lr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var de={exports:{}};const fr=typeof Buffer<"u",It=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,At=/"(?: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 Rt(t,e,s){s==null&&e!==null&&typeof e=="object"&&(s=e,e=void 0),fr&&Buffer.isBuffer(t)&&(t=t.toString()),t&&t.charCodeAt(0)===65279&&(t=t.slice(1));const r=JSON.parse(t,e);if(r===null||typeof r!="object")return r;const n=s&&s.protoAction||"error",i=s&&s.constructorAction||"error";if(n==="ignore"&&i==="ignore")return r;if(n!=="ignore"&&i!=="ignore"){if(It.test(t)===!1&&At.test(t)===!1)return r}else if(n!=="ignore"&&i==="ignore"){if(It.test(t)===!1)return r}else if(At.test(t)===!1)return r;return Mt(r,{protoAction:n,constructorAction:i,safe:s&&s.safe})}function Mt(t,{protoAction:e="error",constructorAction:s="error",safe:r}={}){let n=[t];for(;n.length;){const i=n;n=[];for(const a of i){if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(a,"__proto__")){if(r===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete a.__proto__}if(s!=="ignore"&&Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype")){if(r===!0)return null;if(s==="error")throw new SyntaxError("Object contains forbidden prototype property");delete a.constructor}for(const o in a){const d=a[o];d&&typeof d=="object"&&n.push(d)}}}return t}function rt(t,e,s){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return Rt(t,e,s)}finally{Error.stackTraceLimit=r}}function pr(t,e){const{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return Rt(t,e,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=s}}de.exports=rt,de.exports.default=rt,de.exports.parse=rt,de.exports.safeParse=pr,de.exports.scan=Mt;var gr=de.exports;const Ot=lr(gr);function mr(t){const e=["ROOT"];let s=-1,r=null;function n(c,u,p){switch(c){case'"':{s=u,e.pop(),e.push(p),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{s=u,r=u,e.pop(),e.push(p),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{s=u,e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"{":{s=u,e.pop(),e.push(p),e.push("INSIDE_OBJECT_START");break}case"[":{s=u,e.pop(),e.push(p),e.push("INSIDE_ARRAY_START");break}}}function i(c,u){switch(c){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{s=u,e.pop();break}}}function a(c,u){switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{s=u,e.pop();break}}}for(let c=0;c<t.length;c++){const u=t[c];switch(e[e.length-1]){case"ROOT":n(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{s=c,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{e.pop(),s=c;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:s=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{s=c,e.pop();break}default:{s=c,n(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{s=c,e.pop();break}default:{s=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),s=c;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=c;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,c);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,c);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const x=t.substring(r,c+1);!"false".startsWith(x)&&!"true".startsWith(x)&&!"null".startsWith(x)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(u,c):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c)):s=c;break}}}let o=t.slice(0,s+1),d=0;for(let c=e.length-1;c>=0;c--)switch(e[c]){case"INSIDE_STRING":{o+='"',d++;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":{o+="}",d++;break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{o+="]",d++;break}case"INSIDE_LITERAL":{const p=t.substring(r,t.length);"true".startsWith(p)?o+="true".slice(p.length):"false".startsWith(p)?o+="false".slice(p.length):"null".startsWith(p)&&(o+="null".slice(p.length))}}return[o,d]}function Nt(t,e){function s(r){const n=y.useContext(t);if(!(r!=null&&r.optional)&&!n)throw new Error(`This component must be used within ${e}.`);return n}return s}function Pt(t,e){function s(n){const i=t(n);return i?i[e]:null}function r(n){let i=!1,a;typeof n=="function"?a=n:n&&typeof n=="object"&&(i=!!n.optional,a=n.selector);const o=s({optional:i});return o?a?o(a):o():null}return{[e]:r,[`${e}Store`]:s}}var Ae=t=>{var s;const e=t;e.__isBound||((s=e.__internal_bindMethods)==null||s.call(e),e.__isBound=!0)},Bt=y.createContext(null),_r=Nt(Bt,"AssistantRuntimeProvider"),{useToolUIs:zn,useToolUIsStore:Fn}=Pt(_r,"useToolUIs");const jt=t=>{let e;const s=new Set,r=(c,u)=>{const p=typeof c=="function"?c(e):c;if(!Object.is(p,e)){const x=e;e=u??(typeof p!="object"||p===null)?p:Object.assign({},e,p),s.forEach(E=>E(e,x))}},n=()=>e,o={setState:r,getState:n,getInitialState:()=>d,subscribe:c=>(s.add(c),()=>s.delete(c))},d=e=t(r,n,o);return o},br=t=>t?jt(t):jt,yr=t=>t;function vr(t,e=yr){const s=y.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return y.useDebugValue(s),s}const Zt=t=>{const e=br(t),s=r=>vr(e,r);return Object.assign(s,e),s},Re=t=>t?Zt(t):Zt;var Sr=()=>Re(t=>{const e=new Map;return Object.freeze({getToolUI:s=>{const r=e.get(s),n=r==null?void 0:r.at(-1);return n||null},setToolUI:(s,r)=>{let n=e.get(s);return n||(n=[],e.set(s,n)),n.push(r),t({}),()=>{const i=n.indexOf(r);i!==-1&&n.splice(i,1),i===n.length&&t({})}}})}),wr=y.createContext(null),$e=t=>t,xr=y.createContext(null),Tr=t=>{const[e]=y.useState(()=>Re(()=>t));return y.useEffect(()=>{Ae(t),$e(e).setState(t,!0)},[t,e]),e},kr=({runtime:t,children:e})=>{const s=Tr(t),[r]=y.useState(()=>({useThreadListItemRuntime:s}));return C.jsx(xr.Provider,{value:r,children:e})},Cr=()=>{const t=new Set;return Re(()=>({isAtBottom:!0,scrollToBottom:()=>{for(const e of t)e()},onScrollToBottom:e=>(t.add(e),()=>{t.delete(e)})}))},Dt=y.createContext(null),Er=Nt(Dt,"ThreadPrimitive.Viewport"),{useThreadViewport:Vn,useThreadViewportStore:Ir}=Pt(Er,"useThreadViewport"),Ar=()=>{const t=Ir({optional:!0}),[e]=y.useState(()=>Cr());return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{e.getState().scrollToBottom()}),[t,e]),y.useEffect(()=>{if(t)return e.subscribe(s=>{t.getState().isAtBottom!==s.isAtBottom&&$e(t).setState({isAtBottom:s.isAtBottom})})},[e,t]),e},Rr=({children:t})=>{const e=Ar(),[s]=y.useState(()=>({useThreadViewport:e}));return C.jsx(Dt.Provider,{value:s,children:t})},Mr=t=>{const[e]=y.useState(()=>Re(()=>t));return y.useEffect(()=>{Ae(t),Ae(t.composer),$e(e).setState(t,!0)},[t,e]),e},Or=({children:t,listItemRuntime:e,runtime:s})=>{const r=Mr(s),[n]=y.useState(()=>({useThreadRuntime:r}));return C.jsx(kr,{runtime:e,children:C.jsx(wr.Provider,{value:n,children:C.jsx(Rr,{children:t})})})},Nr=t=>{const[e]=y.useState(()=>Re(()=>t));return y.useEffect(()=>{Ae(t),Ae(t.threads),$e(e).setState(t,!0)},[t,e]),e},Pr=()=>y.useMemo(()=>Sr(),[]),Br=t=>{var e;return(e=t._core)==null?void 0:e.RenderComponent},jr=({children:t,runtime:e})=>{const s=Nr(e),r=Pr(),[n]=y.useState(()=>({useToolUIs:r,useAssistantRuntime:s})),i=Br(e);return C.jsxs(Bt.Provider,{value:n,children:[i&&C.jsx(i,{}),C.jsx(Or,{runtime:e.thread,listItemRuntime:e.threads.mainItem,children:t})]})},Zr=y.memo(jr),Lt=class{constructor(t,e,s){this.contentBinding=t,this.messageApi=e,this.threadApi=s}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(t){const e=this.contentBinding.getState();if(!e)throw new Error("Content part is not available");if(e.type!=="tool-call")throw new Error("Tried to add tool result to non-tool content part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const s=this.messageApi.getState();if(!s)throw new Error("Message is not available");const r=e.toolName,n=e.toolCallId;this.threadApi.getState().addToolResult({messageId:s.id,toolName:r,toolCallId:n,result:t})}subscribe(t){return this.contentBinding.subscribe(t)}},Dr=Symbol("partial-json-count"),Lr=t=>{try{return Ot.parse(t)}catch{try{const[e,s]=mr(t),r=Ot.parse(e);return r[Dr]=s,r}catch{return}}},$t=(t,e,s)=>{const{role:r,id:n,createdAt:i,attachments:a,status:o,metadata:d}=t,c={id:n??e,createdAt:i??new Date},u=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;if(r!=="user"&&a)throw new Error("attachments are only supported for user messages");if(r!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(r!=="assistant"&&(d!=null&&d.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(r){case"assistant":return{...c,role:r,content:u.map(p=>{const x=p.type;switch(x){case"text":case"reasoning":return p.text.trim().length===0?null:p;case"file":case"source":return p;case"tool-call":return p.args?{...p,toolCallId:p.toolCallId??"tool-"+Ie(),args:p.args,argsText:JSON.stringify(p.args)}:{...p,toolCallId:p.toolCallId??"tool-"+Ie(),args:p.args??Lr(p.argsText??"{}"),argsText:p.argsText??""};default:{const E=x;throw new Error(`Unsupported assistant content part type: ${E}`)}}}).filter(p=>!!p),status:o??s,metadata:{unstable_annotations:(d==null?void 0:d.unstable_annotations)??[],unstable_data:(d==null?void 0:d.unstable_data)??[],custom:(d==null?void 0:d.custom)??{},steps:(d==null?void 0:d.steps)??[]}};case"user":return{...c,role:r,content:u.map(p=>{const x=p.type;switch(x){case"text":case"image":case"audio":case"file":return p;default:{const E=x;throw new Error(`Unsupported user content part type: ${E}`)}}}),attachments:a??[],metadata:{custom:(d==null?void 0:d.custom)??{}}};case"system":if(u.length!==1||u[0].type!=="text")throw new Error("System messages must have exactly one text content part.");return{...c,role:r,content:u,metadata:{custom:(d==null?void 0:d.custom)??{}}};default:{const p=r;throw new Error(`Unknown message role: ${p}`)}}},$r={fromArray:t=>{const e=t.map(s=>$t(s,Ie(),Et(!1,!1)));return{messages:e.map((s,r)=>({parentId:r>0?e[r-1].id:null,message:s}))}}},ze=t=>t.next?ze(t.next):"current"in t?t:null,zr=class{constructor(t){h(this,"_value",null);this.func=t}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Fr=class{constructor(){h(this,"messages",new Map);h(this,"head",null);h(this,"root",{children:[],next:null});h(this,"_messages",new zr(()=>{var e;const t=new Array(((e=this.head)==null?void 0:e.level)??0);for(let s=this.head;s;s=s.prev)t[s.level]=s.current;return t}))}performOp(t,e,s){const r=e.prev??this.root,n=t??this.root;if(!(s==="relink"&&r===n)){if(s!=="link"&&(r.children=r.children.filter(i=>i!==e.current.id),r.next===e)){const i=r.children.at(-1),a=i?this.messages.get(i):null;if(a===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=a}if(s!=="cut"){for(let i=t;i;i=i.prev)if(i.current.id===e.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");n.children=[...n.children,e.current.id],(ze(e)===this.head||n.next===null)&&(n.next=e),e.prev=t}}}get headId(){var t;return((t=this.head)==null?void 0:t.current.id)??null}getMessages(){return this._messages.value}addOrUpdateMessage(t,e){const s=this.messages.get(e.id),r=t?this.messages.get(t):null;if(r===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(s){s.current=e,this.performOp(r,s,"relink"),this._messages.dirty();return}const n={prev:r,current:e,next:null,children:[],level:r?r.level+1:0};this.messages.set(e.id,n),this.performOp(r,n,"link"),this.head===r&&(this.head=n),this._messages.dirty()}getMessage(t){var s;const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:((s=e.prev)==null?void 0:s.current.id)??null,message:e.current}}appendOptimisticMessage(t,e){let s;do s=dr();while(this.messages.has(s));return this.addOrUpdateMessage(t,ur(e,{id:s,status:{type:"running"}})),s}deleteMessage(t,e){const s=this.messages.get(t);if(!s)throw new Error("MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui.");const r=e===void 0?s.prev:e===null?null:this.messages.get(e);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const n of s.children){const i=this.messages.get(n);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,i,"relink")}this.performOp(null,s,"cut"),this.messages.delete(t),this.head===s&&(this.head=ze(r??this.root)),this._messages.dirty()}getBranches(t){const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:s}=e.prev??this.root;return s}switchToBranch(t){const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const s=e.prev??this.root;s.next=e,this.head=ze(e),this._messages.dirty()}resetHead(t){if(t===null){this.head=null,this._messages.dirty();return}const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");this.head=e;for(let s=e;s;s=s.prev)s.prev&&(s.prev.next=s);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var e,s;const t=[];for(const[,r]of this.messages)t.push({message:r.current,parentId:((e=r.prev)==null?void 0:e.current.id)??null});return{headId:((s=this.head)==null?void 0:s.current.id)??null,messages:t}}import({headId:t,messages:e}){var s;for(const{message:r,parentId:n}of e)this.addOrUpdateMessage(n,r);this.resetHead(t??((s=e.at(-1))==null?void 0:s.message.id)??null)}},Fe=class{constructor(){h(this,"_subscriptions",new Set);h(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const t of this._subscriptions)t()}_updateConnection(){var t;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(t=this._connection)==null||t.call(this),this._connection=void 0}subscribe(t){return this._subscriptions.add(t),this._updateConnection(),()=>{this._subscriptions.delete(t),this._updateConnection()}}},j=Symbol("skip-update"),nt=class extends Fe{constructor(e){super();h(this,"_previousStateDirty",!0);h(this,"_previousState");h(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const e=this.binding.getState();e!==j&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=e}get path(){return this.binding.path}_connect(){const e=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(e)}},Ve=class{constructor(t,e){this._core=t,this._threadListBinding=e}get path(){return this._core.path}__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)}getState(){return this._core.getState()}switchTo(){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id)}rename(t){const e=this._core.getState();return this._threadListBinding.rename(e.id,t)}archive(){const t=this._core.getState();return this._threadListBinding.archive(t.id)}unarchive(){const t=this._core.getState();return this._threadListBinding.unarchive(t.id)}delete(){const t=this._core.getState();return this._threadListBinding.delete(t.id)}initialize(){const t=this._core.getState();return this._threadListBinding.initialize(t.id)}generateTitle(){const t=this._core.getState();return this._threadListBinding.generateTitle(t.id)}unstable_on(t,e){let s=this._core.getState().isMain;return this.subscribe(()=>{const r=this._core.getState().isMain;s!==r&&(s=r,!(t==="switched-to"&&!r)&&(t==="switched-away"&&r||e()))})}subscribe(t){return this._core.subscribe(t)}};function Vr(t,e){if(t===void 0&&e===void 0)return!0;if(t===void 0||e===void 0)return!1;for(const s of Object.keys(t)){const r=t[s],n=e[s];if(!Object.is(r,n))return!1}return!0}var Z=class extends Fe{constructor(e){super();h(this,"_previousState");h(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=e;const s=e.getState();if(s===j)throw new Error("Entry not available in the store");this._previousState=s}get path(){return this.binding.path}_syncState(){const e=this.binding.getState();return e===j||Vr(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){const e=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(e)}},ue=Symbol("innerMessage"),Ur=t=>t[ue],Me=t=>t.content.filter(s=>s.type==="text").map(s=>s.text).join(`
4
4
 
5
- `),zt=class{constructor(t){this._core=t}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(t){return this._core.subscribe(t)}},Ft=class extends zt{constructor(t,e){super(t),this._composerApi=e}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}},Jr=class extends Ft{get source(){return"thread-composer"}},Wr=class extends Ft{get source(){return"edit-composer"}},Yr=class extends zt{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}},Vt=class extends Fe{constructor(t){super(),this.config=t}getState(){return this.config.binding.getState()}outerSubscribe(t){return this.config.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let e=this.config.binding.getState(),s=e==null?void 0:e.unstable_on(this.config.event,t);const r=()=>{var a;const i=this.config.binding.getState();i!==e&&(e=i,s==null||s(),s=(a=this.config.binding.getState())==null?void 0:a.unstable_on(this.config.event,t))},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},Ut=Object.freeze([]),Jt=Object.freeze({}),qr=t=>Object.freeze({type:"thread",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,attachments:(t==null?void 0:t.attachments)??Ut,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",runConfig:(t==null?void 0:t.runConfig)??Jt,value:(t==null?void 0:t.text)??""}),Hr=t=>Object.freeze({type:"edit",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",attachments:(t==null?void 0:t.attachments)??Ut,runConfig:(t==null?void 0:t.runConfig)??Jt,value:(t==null?void 0:t.text)??""}),Wt=class{constructor(t){h(this,"_eventSubscriptionSubjects",new Map);this._core=t}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentAccept=this.getAttachmentAccept.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setText(t)}setRunConfig(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRunConfig(t)}addAttachment(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.addAttachment(t)}reset(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.reset()}clearAttachments(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.clearAttachments()}send(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.send()}cancel(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.cancel()}setRole(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRole(t)}subscribe(t){return this._core.subscribe(t)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new Vt({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}getAttachmentAccept(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.getAttachmentAccept()}},Kr=class extends Wt{constructor(e){const s=new nt({path:e.path,getState:()=>qr(e.getState()),subscribe:r=>e.subscribe(r)});super({path:e.path,getState:()=>e.getState(),subscribe:r=>s.subscribe(r)});h(this,"_getState");this._getState=s.getState.bind(s)}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(e){return new Jr(new Z({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"thread-composer"}:j},subscribe:s=>this._core.subscribe(s)}),this._core)}},Gr=class extends Wt{constructor(e,s){const r=new nt({path:e.path,getState:()=>Hr(e.getState()),subscribe:n=>e.subscribe(n)});super({path:e.path,getState:()=>e.getState(),subscribe:n=>r.subscribe(n)});h(this,"_getState");this._beginEdit=s,this._getState=r.getState.bind(r)}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new Wr(new Z({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"edit-composer"}:j},subscribe:s=>this._core.subscribe(s)}),this._core)}},Ue=class extends Fe{constructor(t){super(),this.binding=t}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let e=this.binding.getState(),s=e==null?void 0:e.subscribe(t);const r=()=>{var a;const i=this.binding.getState();i!==e&&(e=i,s==null||s(),s=(a=this.binding.getState())==null?void 0:a.subscribe(t),t())},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},Je=Object.freeze({type:"complete"}),Xr=(t,e,s)=>{if(t.role!=="assistant")return Je;if(s.type==="tool-call")return s.result?Je:t.status;const r=e===Math.max(0,t.content.length-1);return t.status.type==="requires-action"?Je:r?t.status:Je},Yt=(t,e)=>{const s=t.content[e];if(!s)return j;const r=Xr(t,e,s);return Object.freeze({...s,[ue]:s[ue],status:r})},Qr=class{constructor(t,e){h(this,"composer");h(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=t,this._threadBinding=e,this.composer=new Gr(new Ue({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:s=>this._threadBinding.subscribe(s)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id))}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getContentPartByIndex=this.getContentPartByIndex.bind(this),this.getContentPartByToolCallId=this.getContentPartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(t={}){const e=this._getEditComposerRuntimeCore(),s=e??this._threadBinding.getState().composer,r=e??s,{runConfig:n=r.runConfig}=t,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:n})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){var s;const t=this._core.getState();if(((s=this._threadBinding.getState().speech)==null?void 0:s.messageId)===t.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:t}){const e=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:e.id,type:t})}switchToBranch({position:t,branchId:e}){const s=this._core.getState();if(e&&t)throw new Error("May not specify both branchId and position");if(!e&&!t)throw new Error("Must specify either branchId or position");const n=this._threadBinding.getState().getBranches(s.id);let i=e;if(t==="previous"?i=n[s.branchNumber-2]:t==="next"&&(i=n[s.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return Me(this.getState())}subscribe(t){return this._core.subscribe(t)}getContentPartByIndex(t){if(t<0)throw new Error("Content part index must be >= 0");return new Lt(new Z({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[${t}]`,contentPartSelector:{type:"index",index:t}},getState:()=>Yt(this.getState(),t),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getContentPartByToolCallId(t){return new Lt(new Z({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(t)}]`,contentPartSelector:{type:"toolCallId",toolCallId:t}},getState:()=>{const e=this._core.getState(),s=e.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===t);return s===-1?j:Yt(e,s)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new Yr(new Z({path:{...this.path,ref:this.path.ref+`${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}},getState:()=>{const e=this.getState().attachments,s=e==null?void 0:e[t];return s?{...s,source:"message"}:j},subscribe:e=>this._core.subscribe(e)}))}},en=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{},stream:t.stream}),tn=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{}}),sn=(t,e)=>{var s,r;return typeof e=="string"?{parentId:((s=t.at(-1))==null?void 0:s.id)??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:e}],attachments:[]}:e.role&&e.parentId&&e.attachments?e:{...e,parentId:e.parentId??((r=t.at(-1))==null?void 0:r.id)??null,sourceId:e.sourceId??null,role:e.role??"user",attachments:e.attachments??[]}},rn=(t,e)=>{const s=t.messages.at(-1);return Object.freeze({threadId:e.id,metadata:e,capabilities:t.capabilities,isDisabled:t.isDisabled,isRunning:(s==null?void 0:s.role)!=="assistant"?!1:s.status.type==="running",messages:t.messages,suggestions:t.suggestions,extras:t.extras,speech:t.speech})},nn=class{constructor(t,e){h(this,"_threadBinding");h(this,"composer");h(this,"_eventSubscriptionSubjects",new Map);const s=new Z({path:t.path,getState:()=>rn(t.getState(),e.getState()),subscribe:r=>{const n=t.subscribe(r),i=e.subscribe(r);return()=>{n(),i()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>s.getState(),outerSubscribe:r=>t.outerSubscribe(r),subscribe:r=>t.subscribe(r)},this.composer=new Kr(new Ue({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)}))}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.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.getMesssageByIndex=this.getMesssageByIndex.bind(this),this.getMesssageById=this.getMesssageById.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)}getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(sn(this._threadBinding.getState().messages,t))}subscribe(t){return this._threadBinding.subscribe(t)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(t){const e=t===null||typeof t=="string"?{parentId:t}:t;return this._threadBinding.getState().startRun(tn(e))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(en(t))}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(t){this._threadBinding.getState().import(t)}getMesssageByIndex(t){if(t<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:this.path.ref+`${this.path.ref}.messages[${t}]`,messageSelector:{type:"index",index:t}},()=>{var r;const e=this._threadBinding.getState().messages,s=e[t];if(s)return{message:s,parentId:((r=e[t-1])==null?void 0:r.id)??null}})}getMesssageById(t){return this._getMessageRuntime({...this.path,ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(t)}]`,messageSelector:{type:"messageId",messageId:t}},()=>this._threadBinding.getState().getMessageById(t))}_getMessageRuntime(t,e){return new Qr(new Z({path:t,getState:()=>{var c;const{message:s,parentId:r}=e()??{},{messages:n,speech:i}=this._threadBinding.getState();if(!s||r===void 0)return j;const a=this._threadBinding.getState(),o=a.getBranches(s.id),d=a.getSubmittedFeedback(s.id);return{...s,[ue]:s[ue],isLast:((c=n.at(-1))==null?void 0:c.id)===s.id,parentId:r,branchNumber:o.indexOf(s.id)+1,branchCount:o.length,speech:(i==null?void 0:i.messageId)===s.id?i:void 0,submittedFeedback:d}},subscribe:s=>this._threadBinding.subscribe(s)}),this._threadBinding)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new Vt({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}},an=t=>({mainThreadId:t.mainThreadId,newThread:t.newThreadId,threads:t.threadIds,archivedThreads:t.archivedThreadIds}),We=(t,e)=>{if(e===void 0)return j;const s=t.getItemById(e);return s?{id:s.threadId,threadId:s.threadId,remoteId:s.remoteId,externalId:s.externalId,title:s.title,status:s.status,isMain:s.threadId===t.mainThreadId}:j},on=class{constructor(t,e=nn){h(this,"_getState");h(this,"_mainThreadListItemRuntime");h(this,"main");this._core=t,this._runtimeFactory=e;const s=new nt({path:{},getState:()=>an(t),subscribe:r=>t.subscribe(r)});this._getState=s.getState.bind(s),this._mainThreadListItemRuntime=new Ve(new Z({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>We(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new e(new Ue({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:r=>t.subscribe(r)}),this._mainThreadListItemRuntime)}__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(t){return this._core.switchToThread(t)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(t){return this._core.subscribe(t)}get mainItem(){return this._mainThreadListItemRuntime}getById(t){return new this._runtimeFactory(new Ue({path:{ref:"threads[threadId="+JSON.stringify(t)+"]",threadSelector:{type:"threadId",threadId:t}},getState:()=>this._core.getThreadRuntimeCore(t),subscribe:e=>this._core.subscribe(e)}),this.mainItem)}getItemByIndex(t){return new Ve(new Z({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>We(this._core,this._core.threadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(t){return new Ve(new Z({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>We(this._core,this._core.archivedThreadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(t){return new Ve(new Z({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>We(this._core,t),subscribe:e=>this._core.subscribe(e)}),this._core)}},se=Object.freeze([]),he="DEFAULT_THREAD_ID",cn=Object.freeze([he]),dn=Object.freeze({threadId:he,status:"regular"}),un=Promise.resolve(),hn=class{constructor(t={},e){h(this,"_mainThreadId",he);h(this,"_threads",cn);h(this,"_archivedThreads",se);h(this,"_mainThread");h(this,"_subscriptions",new Set);this.adapter=t,this.threadFactory=e,this._mainThread=this.threadFactory()}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}getLoadThreadsPromise(){return un}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(t){for(const e of this.adapter.threads??[])if(e.threadId===t)return e;for(const e of this.adapter.archivedThreads??[])if(e.threadId===t)return e;if(t===he)return dn}__internal_setAdapter(t){var d,c;const e=this.adapter;this.adapter=t;const s=t.threadId??he,r=t.threads??se,n=t.archivedThreads??se,i=e.threadId??he,a=e.threads??se,o=e.archivedThreads??se;i===s&&a===r&&o===n||(a!==r&&(this._threads=((d=this.adapter.threads)==null?void 0:d.map(u=>u.threadId))??se),o!==n&&(this._archivedThreads=((c=this.adapter.archivedThreads)==null?void 0:c.map(u=>u.threadId))??se),i!==s&&(this._mainThreadId=s,this._mainThread=this.threadFactory()),this._notifySubscribers())}async switchToThread(t){if(this._mainThreadId===t)return;const e=this.adapter.onSwitchToThread;if(!e)throw new Error("External store adapter does not support switching to thread");e(t)}async switchToNewThread(){const t=this.adapter.onSwitchToNewThread;if(!t)throw new Error("External store adapter does not support switching to new thread");t()}async rename(t,e){const s=this.adapter.onRename;if(!s)throw new Error("External store adapter does not support renaming");s(t,e)}async archive(t){const e=this.adapter.onArchive;if(!e)throw new Error("External store adapter does not support archiving");e(t)}async unarchive(t){const e=this.adapter.onUnarchive;if(!e)throw new Error("External store adapter does not support unarchiving");e(t)}async delete(t){const e=this.adapter.onDelete;if(!e)throw new Error("External store adapter does not support deleting");e(t)}initialize(){throw new Error("Method not implemented.")}generateTitle(){throw new Error("Method not implemented.")}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}_notifySubscribers(){for(const t of this._subscriptions)t()}},qt=class{constructor(){h(this,"cache",new WeakMap)}convertMessages(t,e){return t.map((s,r)=>{const n=this.cache.get(s),i=e(n,s,r);return this.cache.set(s,i),i})}},ln=class extends Tt{constructor(e,s,{parentId:r,message:n}){super();h(this,"_nonTextParts");h(this,"_previousText");h(this,"_parentId");h(this,"_sourceId");this.runtime=e,this.endEditCallback=s,this._parentId=r,this._sourceId=n.id,this._previousText=Me(n),this.setText(this._previousText),this.setRole(n.role),this.setAttachments(n.attachments??[]),this._nonTextParts=n.content.filter(i=>i.type!=="text"),this.setRunConfig({...e.composer.runConfig})}get canCancel(){return!0}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}async handleSend(e){Me(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()}},fn=class{constructor(t){h(this,"_subscriptions",new Set);h(this,"_isInitialized",!1);h(this,"repository",new Fr);h(this,"composer",new or(this));h(this,"_editComposers",new Map);h(this,"_submittedFeedback",{});h(this,"_stopSpeaking");h(this,"speech");h(this,"_eventSubscribers",new Map);this._contextProvider=t}get messages(){return this.repository.getMessages()}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(t){return this._editComposers.get(t)}beginEdit(t){if(this._editComposers.has(t))throw new Error("Edit already in progress");this._editComposers.set(t,new ln(this,()=>this._editComposers.delete(t),this.repository.getMessage(t))),this._notifySubscribers()}getMessageById(t){return this.repository.getMessage(t)}getBranches(t){return this.repository.getBranches(t)}switchToBranch(t){this.repository.switchToBranch(t),this._notifySubscribers()}_notifySubscribers(){for(const t of this._subscriptions)t()}_notifyEventSubscribers(t){const e=this._eventSubscribers.get(t);if(e)for(const s of e)s()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}getSubmittedFeedback(t){return this._submittedFeedback[t]}submitFeedback({messageId:t,type:e}){var n;const s=(n=this.adapters)==null?void 0:n.feedback;if(!s)throw new Error("Feedback adapter not configured");const{message:r}=this.repository.getMessage(t);s.submit({message:r,type:e}),this._submittedFeedback[t]={type:e},this._notifySubscribers()}speak(t){var i,a;const e=(i=this.adapters)==null?void 0:i.speech;if(!e)throw new Error("Speech adapter not configured");const{message:s}=this.repository.getMessage(t);(a=this._stopSpeaking)==null||a.call(this);const r=e.speak(Me(s)),n=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:t,status:r.status},this._notifySubscribers()});this.speech={messageId:t,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),n(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new 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(t){this.ensureInitialized(),this.repository.clear(),this.repository.import(t),this._notifySubscribers()}unstable_on(t,e){var r,n;if(t==="model-context-update")return((n=(r=this._contextProvider).subscribe)==null?void 0:n.call(r,e))??(()=>{});const s=this._eventSubscribers.get(t);return s?s.add(e):this._eventSubscribers.set(t,new Set([e])),()=>{this._eventSubscribers.get(t).delete(e)}}},pn=Object.freeze([]),gn=(t,e)=>{var s;return t&&((s=e[e.length-1])==null?void 0:s.role)!=="assistant"},mn=class extends fn{constructor(e,s){super(e);h(this,"assistantOptimisticId",null);h(this,"_capabilities",{switchToBranch:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1});h(this,"_messages");h(this,"isDisabled");h(this,"suggestions",[]);h(this,"extras");h(this,"_converter",new qt);h(this,"_store");h(this,"updateMessages",e=>{var r,n,i,a;this._store.convertMessage!==void 0?(n=(r=this._store).setMessages)==null||n.call(r,e.flatMap(Ur).filter(o=>o!=null)):(a=(i=this._store).setMessages)==null||a.call(i,e)});this.__internal_setAdapter(s)}get capabilities(){return this._capabilities}get messages(){return this._messages}get adapters(){return this._store.adapters}beginEdit(e){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(e)}__internal_setAdapter(e){var i,a,o,d,c,u;if(this._store===e)return;const s=e.isRunning??!1;this.isDisabled=e.isDisabled??!1;const r=this._store;if(this._store=e,this.extras=e.extras,this.suggestions=e.suggestions??pn,this._capabilities={switchToBranch:this._store.setMessages!==void 0,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:((i=this._store.adapters)==null?void 0:i.speech)!==void 0,unstable_copy:((a=this._store.unstable_capabilities)==null?void 0:a.copy)!==!1,attachments:!!((o=this._store.adapters)!=null&&o.attachments),feedback:!!((d=this._store.adapters)!=null&&d.feedback)},r){if(r.convertMessage!==e.convertMessage)this._converter=new qt;else if(r.isRunning===e.isRunning&&r.messages===e.messages){this._notifySubscribers();return}}const n=e.convertMessage?this._converter.convertMessages(e.messages,(p,x,E)=>{if(!e.convertMessage)return x;const qe=E===e.messages.length-1,K=Et(qe,s);if(p&&(p.role!=="assistant"||!hr(p.status)||p.status===K))return p;const dt=e.convertMessage(x,E),He=$t(dt,E.toString(),K);return He[ue]=x,He}):e.messages;n.length>0&&this.ensureInitialized(),((r==null?void 0:r.isRunning)??e.isRunning!==!1??!1)&&(e.isRunning?this._notifyEventSubscribers("run-start"):this._notifyEventSubscribers("run-end"));for(let p=0;p<n.length;p++){const x=n[p],E=n[p-1];this.repository.addOrUpdateMessage((E==null?void 0:E.id)??null,x)}this.assistantOptimisticId&&(this.repository.deleteMessage(this.assistantOptimisticId),this.assistantOptimisticId=null),gn(s,n)&&(this.assistantOptimisticId=this.repository.appendOptimisticMessage(((c=n.at(-1))==null?void 0:c.id)??null,{role:"assistant",content:[]})),this.repository.resetHead(this.assistantOptimisticId??((u=n.at(-1))==null?void 0:u.id)??null),this._messages=this.repository.getMessages(),this._notifySubscribers()}switchToBranch(e){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this.repository.switchToBranch(e),this.updateMessages(this.repository.getMessages())}async append(e){var s;if(e.parentId!==(((s=this.messages.at(-1))==null?void 0:s.id)??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(e)}else await this._store.onNew(e)}async startRun(e){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._store.onReload(e.parentId,e)}async resumeRun(){throw new Error("Runtime does not support resuming runs.")}cancelRun(){var r;if(!this._store.onCancel)throw new Error("Runtime does not support cancelling runs.");this._store.onCancel(),this.assistantOptimisticId&&(this.repository.deleteMessage(this.assistantOptimisticId),this.assistantOptimisticId=null);let e=this.repository.getMessages();const s=e[e.length-1];(s==null?void 0:s.role)==="user"&&s.id===((r=e.at(-1))==null?void 0:r.id)?(this.repository.deleteMessage(s.id),this.composer.text.trim()||this.composer.setText(Me(s)),e=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(e)},0)}addToolResult(e){if(!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult(e)}},Ht=t=>{var e;return((e=t.adapters)==null?void 0:e.threadList)??{}},_n=class extends nr{constructor(e){super();h(this,"threads");this.threads=new hn(Ht(e),()=>new mn(this._contextProvider,e))}setAdapter(e){this.threads.__internal_setAdapter(Ht(e)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(e)}},bn=y.createContext(null),yn=()=>y.useContext(bn),vn=t=>{const[e]=y.useState(()=>new _n(t));y.useEffect(()=>{e.setAdapter(t)});const{modelContext:s}=yn()??{};return y.useEffect(()=>{if(s)return e.registerModelContextProvider(s)},[s,e]),y.useMemo(()=>new Sn(e),[e])},Sn=class{constructor(t){h(this,"threads");h(this,"_thread");this._core=t,this.threads=new on(t.threads),this._thread=this.threads.main}get threadList(){return this.threads}__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(t){return this._core.threads.switchToThread(t)}registerModelContextProvider(t){return this._core.registerModelContextProvider(t)}registerModelConfigProvider(t){return this.registerModelContextProvider(t)}reset({initialMessages:t}={}){return this._core.threads.getMainThreadRuntimeCore().import($r.fromArray(t??[]))}};function wn(t){return t.filter(e=>{var s;return e.finishReason==="stop"?e.text!==null&&((s=e.text)==null?void 0:s.trim())!=="":!0})}function xn(t){const e=[];let s=null;for(const r of t)r.type==="reasoning"?(s!=null&&(e.push(s),s=null),e.push(r)):r.functionCalls?(s&&e.push(s),e.push(r),s=null):r.functionResponse?e[e.length-1]={...e[e.length-1],functionResponse:r.functionResponse}:s&&r.protocol===s.protocol&&(s.role===r.role||r.finishReason==="stop")?s.text+=r.text:(s&&e.push(s),s={...r});return s&&e.push(s),wn(e)}function Tn(t){var e;return t.role==="function"?{id:t.id,role:"assistant",status:(t==null?void 0:t.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((e=t.functionCalls)==null?void 0:e.map(s=>{var r;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(r=t.functionResponse)==null?void 0:r.result}}))??[]}:{id:t.id,role:t.role,content:t.type==="reasoning"?[{type:"reasoning",text:t.text}]:[{type:"text",text:t.text}]}}class Ye{constructor(){h(this,"statusChangeCallbacks",[]);h(this,"messageCallbacks",[])}addStatusChangeListener(e){this.statusChangeCallbacks.push(e)}addMessageListener(e){this.messageCallbacks.push(e)}async syncSession(e){this.session=e}async notifyMessage(e){this.messageCallbacks.forEach(s=>s(e))}async notifyMessages(e){e.forEach(s=>{this.messageCallbacks.forEach(r=>r(s))})}async setSession(e){this.session=e}async setStatus(e){const s=this.status!==e;this.status=e,s&&this.statusChangeCallbacks.forEach(r=>r(e))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class it extends Ye{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"notify",!0);this.config=s,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(s){return this.setStatus("connected"),s}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(s){this.session=s}async send(s){const{apiUrl:r,apiKey:n,agentId:i}=this.config,a=this.session??"new",o=s,c=await(await fetch(`${r}/agents/${i}/sessions/${a}/messages`,{body:JSON.stringify({userMessage:o}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":n,"x-persona-apikey":n}})).json();this.notifyMessages(c.response.messages)}}class at extends Ye{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"webSocket");this.config=s,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(s){var r;(r=this.config.logger)==null||r.debug("Syncing session with WebSocket protocol:",s),this.session=s,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(s))}connect(s){var o;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const r=s||this.session||"new";(o=this.config.logger)==null||o.debug("Connecting to WebSocket with sessionId:",r);const n=encodeURIComponent(this.config.apiKey),i=this.config.agentId,a=`${this.config.webSocketUrl}?sessionCode=${r}&agentId=${i}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(a),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",d=>{const c=JSON.parse(d.data);if(c.type!=="message")return;const u=c.payload;this.notifyMessage(u!=null&&u.thought?{role:"assistant",type:"reasoning",text:u.thought}:u)}),this.webSocket.addEventListener("close",()=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",d=>{var c;this.setStatus("disconnected"),this.webSocket=null,(c=this.config.logger)==null||c.error("WebSocket error",d)}),Promise.resolve(r)}disconnect(){var s;return(s=this.config.logger)==null||s.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(s){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:s})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class kn{constructor(e){h(this,"config");h(this,"pc",null);h(this,"ws",null);h(this,"localStream",null);h(this,"remoteStream",new MediaStream);h(this,"audioCtx",null);h(this,"localAnalyser",null);h(this,"remoteAnalyser",null);h(this,"analyzerFrame",null);h(this,"dataChannel",null);h(this,"isConnected",!1);h(this,"visualizerCallbacks",[]);h(this,"messageCallbacks",[]);this.config=e}async connect(e){var s;if(!this.isConnected){this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(r){(s=this.config.logger)==null||s.error("Error accessing microphone:",r);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(r=>{this.pc.addTrack(r,this.localStream)}),this.pc.ontrack=r=>{r.streams[0].getTracks().forEach(i=>{this.remoteStream.addTrack(i)}),this.audioCtx||this._startAnalyzers();const n=new Audio;n.srcObject=this.remoteStream,n.play().catch(i=>{var a;(a=this.config.logger)==null||a.error("Error playing remote audio:",i)})},this.pc.onicecandidate=r=>{var n;r.candidate&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:r.candidate}}))},this.pc.ondatachannel=r=>{const n=r.channel;n.onmessage=i=>{this.messageCallbacks.forEach(a=>{a(i)})}},this.ws=new WebSocket(this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc"),this.ws.onopen=async()=>{var a,o;const r=await this.pc.createOffer();await this.pc.setLocalDescription(r);const n={agentId:this.config.agentId,sessionCode:e};(a=this.config.logger)==null||a.debug("Opening connection to WebRTC server: ",n);const i={type:"OFFER",src:((o=crypto.randomUUID)==null?void 0:o.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:r.sdp,type:r.type},connectionId:(Date.now()%1e6).toString(),metadata:n}};this.ws.send(JSON.stringify(i))},this.ws.onmessage=async r=>{var i;const n=JSON.parse(r.data);if(n.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(n.payload.sdp));else if(n.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(n.payload.candidate))}catch(a){(i=this.config.logger)==null||i.error("Error adding ICE candidate:",a)}},this.ws.onclose=()=>{this._stopAnalyzers()}}}async disconnect(){var e;this.isConnected&&(this.isConnected=!1,((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(s=>s.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(e){this.visualizerCallbacks.push(e)}addMessageCallback(e){this.messageCallbacks.push(e)}createDataChannel(e="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(e),this.dataChannel.onopen=()=>{var s;return(s=this.config.logger)==null?void 0:s.info("Data channel opened")},this.dataChannel.onmessage=s=>{this.messageCallbacks.forEach(r=>{r(s)})})}sendMessage(e){var s,r;if(!this.dataChannel){(s=this.config.logger)==null||s.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(e),(r=this.config.logger)==null||r.info("Sent message:",e)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const e=this.audioCtx.createMediaStreamSource(this.localStream),s=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,e.connect(this.localAnalyser),s.connect(this.remoteAnalyser);const r=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(i);const a=n.reduce((d,c)=>d+c,0)/n.length,o=i.reduce((d,c)=>d+c,0)/i.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(d=>{d({localAmplitude:a,remoteAmplitude:o})}),this.analyzerFrame=requestAnimationFrame(r)};this.analyzerFrame=requestAnimationFrame(r)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class ot extends Ye{constructor(s){super();h(this,"status");h(this,"session");h(this,"autostart");h(this,"config");h(this,"webRTCClient");this.config=s,this.status="disconnected",this.session=null,this.autostart=(s==null?void 0:s.autostart)??!1,this.webRTCClient=new kn(s),this.webRTCClient.addMessageCallback(r=>{var i;(i=s.logger)==null||i.debug("Received data message:",r.data);const n=JSON.parse(r.data);n.type==="message"&&this.notifyMessage(n.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(s){super.syncSession(s),this.status==="connected"&&(await this.disconnect(),await this.connect(s))}async connect(s){var r;return this.status==="connected"?Promise.resolve(this.session):(this.session=s||this.session||"new",this.setStatus("connecting"),(r=this.config.logger)==null||r.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var s,r,n;if(this.status==="disconnected")return(s=this.config.logger)==null||s.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(r=this.config)==null?void 0:r.logger)==null||n.debug("Disconnected from WebRTC")}send(s){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(s),Promise.resolve())}}const ct=y.createContext(void 0);function Cn({dev:t=!1,protocols:e,logger:s,children:r,session:n="new",...i}){const[a,o]=y.useState(!1),[d,c]=y.useState([]),[u,p]=y.useState(n),[x,E]=y.useState(new Map),qe=y.useRef(!1),K=y.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const k=t?"localhost:8000":"persona.applica.guru/api",J=t?"http":"https",G=t?"ws":"wss";return Object.keys(e).map(D=>{switch(D){case"rest":const Ke=e[D];return Ke===!0?new it({apiUrl:`${J}://${k}`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new it(Ke);case"webrtc":const Gt=e[D];return Gt===!0?new ot({webrtcUrl:`${G}://${k}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new ot(Gt);case"websocket":const Xt=e[D];return Xt===!0?new at({webSocketUrl:`${G}://${k}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new at(Xt);default:throw new Error(`Unknown protocol: ${D}`)}})}throw new Error("Invalid protocols configuration")},[]);y.useEffect(()=>{qe.current||(qe.current=!0,s==null||s.debug("Initializing protocols: ",K.map(k=>k.getName())),K.forEach(k=>{k.setSession(u),k.clearListeners(),k.addStatusChangeListener(J=>{s==null||s.debug(`${k.getName()} has notified new status: ${J}`),x.set(k.getName(),J),E(new Map(x))}),k.addMessageListener(J=>{c(G=>xn([...G,{...J,protocol:k.getName()}]))}),k.autostart&&k.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${k.getName()}`),k.connect(u))}))},[u,K,s,x]);const dt=async k=>{var ut;if(((ut=k.content[0])==null?void 0:ut.type)!=="text")throw new Error("Only text messages are supported");const J=k.content[0].text;c(D=>[...D,{role:"user",type:"text",text:J}]),o(!0);const G=K.sort((D,Ke)=>Ke.getPriority()-D.getPriority()).find(D=>D.status==="connected");await(G==null?void 0:G.send(J)),o(!1)},He=y.useCallback(()=>(o(!1),c([]),p("new"),Promise.resolve()),[]),Mn=y.useCallback(()=>Promise.resolve(),[]),On=vn({isRunning:a,messages:d,convertMessage:Tn,onNew:dt,onCancel:He,onReload:Mn});return C.jsx(ct.Provider,{value:{protocols:K,protocolsStatus:x},children:C.jsx(Zr,{runtime:On,children:r})})}function En({children:t,...e}){return C.jsx(Cn,{...e,children:t})}function In(){const t=y.useContext(ct);if(!t)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return t}function Kt(t){const e=y.useContext(ct);if(!e)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const s=e.protocols.find(n=>n.getName()===t);if(!s)return null;const r=e.protocolsStatus.get(s.getName());return{...s,connect:s.connect.bind(s),disconnect:s.disconnect.bind(s),send:s.send.bind(s),setSession:s.setSession.bind(s),addStatusChangeListener:s.addStatusChangeListener.bind(s),addMessageListener:s.addMessageListener.bind(s),getName:s.getName.bind(s),getPriority:s.getPriority.bind(s),status:r||s.status}}function An(){return Kt("webrtc")}class Rn{constructor(){h(this,"prefix","[Persona]")}log(e,...s){console.log(`${this.prefix} - ${e}`,...s)}info(e,...s){console.info(`${this.prefix} - ${e}`,...s)}warn(e,...s){console.warn(`${this.prefix} - ${e}`,...s)}error(e,...s){console.error(`${this.prefix} - ${e}`,...s)}debug(e,...s){console.debug(`${this.prefix} - ${e}`,...s)}}return I.PersonaConsoleLogger=Rn,I.PersonaProtocolBase=Ye,I.PersonaRESTProtocol=it,I.PersonaRuntimeProvider=En,I.PersonaWebRTCProtocol=ot,I.PersonaWebSocketProtocol=at,I.usePersonaRuntime=In,I.usePersonaRuntimeProtocol=Kt,I.usePersonaRuntimeWebRTCProtocol=An,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"}),I}({},jsxRuntime,React);
5
+ `),zt=class{constructor(t){this._core=t}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(t){return this._core.subscribe(t)}},Ft=class extends zt{constructor(t,e){super(t),this._composerApi=e}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}},Jr=class extends Ft{get source(){return"thread-composer"}},Wr=class extends Ft{get source(){return"edit-composer"}},Yr=class extends zt{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}},Vt=class extends Fe{constructor(t){super(),this.config=t}getState(){return this.config.binding.getState()}outerSubscribe(t){return this.config.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let e=this.config.binding.getState(),s=e==null?void 0:e.unstable_on(this.config.event,t);const r=()=>{var a;const i=this.config.binding.getState();i!==e&&(e=i,s==null||s(),s=(a=this.config.binding.getState())==null?void 0:a.unstable_on(this.config.event,t))},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},Ut=Object.freeze([]),Jt=Object.freeze({}),qr=t=>Object.freeze({type:"thread",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,attachments:(t==null?void 0:t.attachments)??Ut,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",runConfig:(t==null?void 0:t.runConfig)??Jt,value:(t==null?void 0:t.text)??""}),Hr=t=>Object.freeze({type:"edit",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",attachments:(t==null?void 0:t.attachments)??Ut,runConfig:(t==null?void 0:t.runConfig)??Jt,value:(t==null?void 0:t.text)??""}),Wt=class{constructor(t){h(this,"_eventSubscriptionSubjects",new Map);this._core=t}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentAccept=this.getAttachmentAccept.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setText(t)}setRunConfig(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRunConfig(t)}addAttachment(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.addAttachment(t)}reset(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.reset()}clearAttachments(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.clearAttachments()}send(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.send()}cancel(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.cancel()}setRole(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRole(t)}subscribe(t){return this._core.subscribe(t)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new Vt({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}getAttachmentAccept(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.getAttachmentAccept()}},Kr=class extends Wt{constructor(e){const s=new nt({path:e.path,getState:()=>qr(e.getState()),subscribe:r=>e.subscribe(r)});super({path:e.path,getState:()=>e.getState(),subscribe:r=>s.subscribe(r)});h(this,"_getState");this._getState=s.getState.bind(s)}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(e){return new Jr(new Z({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"thread-composer"}:j},subscribe:s=>this._core.subscribe(s)}),this._core)}},Gr=class extends Wt{constructor(e,s){const r=new nt({path:e.path,getState:()=>Hr(e.getState()),subscribe:n=>e.subscribe(n)});super({path:e.path,getState:()=>e.getState(),subscribe:n=>r.subscribe(n)});h(this,"_getState");this._beginEdit=s,this._getState=r.getState.bind(r)}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new Wr(new Z({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"edit-composer"}:j},subscribe:s=>this._core.subscribe(s)}),this._core)}},Ue=class extends Fe{constructor(t){super(),this.binding=t}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let e=this.binding.getState(),s=e==null?void 0:e.subscribe(t);const r=()=>{var a;const i=this.binding.getState();i!==e&&(e=i,s==null||s(),s=(a=this.binding.getState())==null?void 0:a.subscribe(t),t())},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},Je=Object.freeze({type:"complete"}),Xr=(t,e,s)=>{if(t.role!=="assistant")return Je;if(s.type==="tool-call")return s.result?Je:t.status;const r=e===Math.max(0,t.content.length-1);return t.status.type==="requires-action"?Je:r?t.status:Je},Yt=(t,e)=>{const s=t.content[e];if(!s)return j;const r=Xr(t,e,s);return Object.freeze({...s,[ue]:s[ue],status:r})},Qr=class{constructor(t,e){h(this,"composer");h(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=t,this._threadBinding=e,this.composer=new Gr(new Ue({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:s=>this._threadBinding.subscribe(s)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id))}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getContentPartByIndex=this.getContentPartByIndex.bind(this),this.getContentPartByToolCallId=this.getContentPartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(t={}){const e=this._getEditComposerRuntimeCore(),s=e??this._threadBinding.getState().composer,r=e??s,{runConfig:n=r.runConfig}=t,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:n})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){var s;const t=this._core.getState();if(((s=this._threadBinding.getState().speech)==null?void 0:s.messageId)===t.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:t}){const e=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:e.id,type:t})}switchToBranch({position:t,branchId:e}){const s=this._core.getState();if(e&&t)throw new Error("May not specify both branchId and position");if(!e&&!t)throw new Error("Must specify either branchId or position");const n=this._threadBinding.getState().getBranches(s.id);let i=e;if(t==="previous"?i=n[s.branchNumber-2]:t==="next"&&(i=n[s.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return Me(this.getState())}subscribe(t){return this._core.subscribe(t)}getContentPartByIndex(t){if(t<0)throw new Error("Content part index must be >= 0");return new Lt(new Z({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[${t}]`,contentPartSelector:{type:"index",index:t}},getState:()=>Yt(this.getState(),t),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getContentPartByToolCallId(t){return new Lt(new Z({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(t)}]`,contentPartSelector:{type:"toolCallId",toolCallId:t}},getState:()=>{const e=this._core.getState(),s=e.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===t);return s===-1?j:Yt(e,s)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new Yr(new Z({path:{...this.path,ref:this.path.ref+`${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}},getState:()=>{const e=this.getState().attachments,s=e==null?void 0:e[t];return s?{...s,source:"message"}:j},subscribe:e=>this._core.subscribe(e)}))}},en=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{},stream:t.stream}),tn=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{}}),sn=(t,e)=>{var s,r;return typeof e=="string"?{parentId:((s=t.at(-1))==null?void 0:s.id)??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:e}],attachments:[]}:e.role&&e.parentId&&e.attachments?e:{...e,parentId:e.parentId??((r=t.at(-1))==null?void 0:r.id)??null,sourceId:e.sourceId??null,role:e.role??"user",attachments:e.attachments??[]}},rn=(t,e)=>{const s=t.messages.at(-1);return Object.freeze({threadId:e.id,metadata:e,capabilities:t.capabilities,isDisabled:t.isDisabled,isRunning:(s==null?void 0:s.role)!=="assistant"?!1:s.status.type==="running",messages:t.messages,suggestions:t.suggestions,extras:t.extras,speech:t.speech})},nn=class{constructor(t,e){h(this,"_threadBinding");h(this,"composer");h(this,"_eventSubscriptionSubjects",new Map);const s=new Z({path:t.path,getState:()=>rn(t.getState(),e.getState()),subscribe:r=>{const n=t.subscribe(r),i=e.subscribe(r);return()=>{n(),i()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>s.getState(),outerSubscribe:r=>t.outerSubscribe(r),subscribe:r=>t.subscribe(r)},this.composer=new Kr(new Ue({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)}))}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.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.getMesssageByIndex=this.getMesssageByIndex.bind(this),this.getMesssageById=this.getMesssageById.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)}getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(sn(this._threadBinding.getState().messages,t))}subscribe(t){return this._threadBinding.subscribe(t)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(t){const e=t===null||typeof t=="string"?{parentId:t}:t;return this._threadBinding.getState().startRun(tn(e))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(en(t))}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(t){this._threadBinding.getState().import(t)}getMesssageByIndex(t){if(t<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:this.path.ref+`${this.path.ref}.messages[${t}]`,messageSelector:{type:"index",index:t}},()=>{var r;const e=this._threadBinding.getState().messages,s=e[t];if(s)return{message:s,parentId:((r=e[t-1])==null?void 0:r.id)??null}})}getMesssageById(t){return this._getMessageRuntime({...this.path,ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(t)}]`,messageSelector:{type:"messageId",messageId:t}},()=>this._threadBinding.getState().getMessageById(t))}_getMessageRuntime(t,e){return new Qr(new Z({path:t,getState:()=>{var c;const{message:s,parentId:r}=e()??{},{messages:n,speech:i}=this._threadBinding.getState();if(!s||r===void 0)return j;const a=this._threadBinding.getState(),o=a.getBranches(s.id),d=a.getSubmittedFeedback(s.id);return{...s,[ue]:s[ue],isLast:((c=n.at(-1))==null?void 0:c.id)===s.id,parentId:r,branchNumber:o.indexOf(s.id)+1,branchCount:o.length,speech:(i==null?void 0:i.messageId)===s.id?i:void 0,submittedFeedback:d}},subscribe:s=>this._threadBinding.subscribe(s)}),this._threadBinding)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new Vt({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}},an=t=>({mainThreadId:t.mainThreadId,newThread:t.newThreadId,threads:t.threadIds,archivedThreads:t.archivedThreadIds}),We=(t,e)=>{if(e===void 0)return j;const s=t.getItemById(e);return s?{id:s.threadId,threadId:s.threadId,remoteId:s.remoteId,externalId:s.externalId,title:s.title,status:s.status,isMain:s.threadId===t.mainThreadId}:j},on=class{constructor(t,e=nn){h(this,"_getState");h(this,"_mainThreadListItemRuntime");h(this,"main");this._core=t,this._runtimeFactory=e;const s=new nt({path:{},getState:()=>an(t),subscribe:r=>t.subscribe(r)});this._getState=s.getState.bind(s),this._mainThreadListItemRuntime=new Ve(new Z({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>We(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new e(new Ue({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:r=>t.subscribe(r)}),this._mainThreadListItemRuntime)}__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(t){return this._core.switchToThread(t)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(t){return this._core.subscribe(t)}get mainItem(){return this._mainThreadListItemRuntime}getById(t){return new this._runtimeFactory(new Ue({path:{ref:"threads[threadId="+JSON.stringify(t)+"]",threadSelector:{type:"threadId",threadId:t}},getState:()=>this._core.getThreadRuntimeCore(t),subscribe:e=>this._core.subscribe(e)}),this.mainItem)}getItemByIndex(t){return new Ve(new Z({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>We(this._core,this._core.threadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(t){return new Ve(new Z({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>We(this._core,this._core.archivedThreadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(t){return new Ve(new Z({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>We(this._core,t),subscribe:e=>this._core.subscribe(e)}),this._core)}},se=Object.freeze([]),he="DEFAULT_THREAD_ID",cn=Object.freeze([he]),dn=Object.freeze({threadId:he,status:"regular"}),un=Promise.resolve(),hn=class{constructor(t={},e){h(this,"_mainThreadId",he);h(this,"_threads",cn);h(this,"_archivedThreads",se);h(this,"_mainThread");h(this,"_subscriptions",new Set);this.adapter=t,this.threadFactory=e,this._mainThread=this.threadFactory()}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}getLoadThreadsPromise(){return un}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(t){for(const e of this.adapter.threads??[])if(e.threadId===t)return e;for(const e of this.adapter.archivedThreads??[])if(e.threadId===t)return e;if(t===he)return dn}__internal_setAdapter(t){var d,c;const e=this.adapter;this.adapter=t;const s=t.threadId??he,r=t.threads??se,n=t.archivedThreads??se,i=e.threadId??he,a=e.threads??se,o=e.archivedThreads??se;i===s&&a===r&&o===n||(a!==r&&(this._threads=((d=this.adapter.threads)==null?void 0:d.map(u=>u.threadId))??se),o!==n&&(this._archivedThreads=((c=this.adapter.archivedThreads)==null?void 0:c.map(u=>u.threadId))??se),i!==s&&(this._mainThreadId=s,this._mainThread=this.threadFactory()),this._notifySubscribers())}async switchToThread(t){if(this._mainThreadId===t)return;const e=this.adapter.onSwitchToThread;if(!e)throw new Error("External store adapter does not support switching to thread");e(t)}async switchToNewThread(){const t=this.adapter.onSwitchToNewThread;if(!t)throw new Error("External store adapter does not support switching to new thread");t()}async rename(t,e){const s=this.adapter.onRename;if(!s)throw new Error("External store adapter does not support renaming");s(t,e)}async archive(t){const e=this.adapter.onArchive;if(!e)throw new Error("External store adapter does not support archiving");e(t)}async unarchive(t){const e=this.adapter.onUnarchive;if(!e)throw new Error("External store adapter does not support unarchiving");e(t)}async delete(t){const e=this.adapter.onDelete;if(!e)throw new Error("External store adapter does not support deleting");e(t)}initialize(){throw new Error("Method not implemented.")}generateTitle(){throw new Error("Method not implemented.")}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}_notifySubscribers(){for(const t of this._subscriptions)t()}},qt=class{constructor(){h(this,"cache",new WeakMap)}convertMessages(t,e){return t.map((s,r)=>{const n=this.cache.get(s),i=e(n,s,r);return this.cache.set(s,i),i})}},ln=class extends Tt{constructor(e,s,{parentId:r,message:n}){super();h(this,"_nonTextParts");h(this,"_previousText");h(this,"_parentId");h(this,"_sourceId");this.runtime=e,this.endEditCallback=s,this._parentId=r,this._sourceId=n.id,this._previousText=Me(n),this.setText(this._previousText),this.setRole(n.role),this.setAttachments(n.attachments??[]),this._nonTextParts=n.content.filter(i=>i.type!=="text"),this.setRunConfig({...e.composer.runConfig})}get canCancel(){return!0}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}async handleSend(e){Me(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()}},fn=class{constructor(t){h(this,"_subscriptions",new Set);h(this,"_isInitialized",!1);h(this,"repository",new Fr);h(this,"composer",new or(this));h(this,"_editComposers",new Map);h(this,"_submittedFeedback",{});h(this,"_stopSpeaking");h(this,"speech");h(this,"_eventSubscribers",new Map);this._contextProvider=t}get messages(){return this.repository.getMessages()}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(t){return this._editComposers.get(t)}beginEdit(t){if(this._editComposers.has(t))throw new Error("Edit already in progress");this._editComposers.set(t,new ln(this,()=>this._editComposers.delete(t),this.repository.getMessage(t))),this._notifySubscribers()}getMessageById(t){return this.repository.getMessage(t)}getBranches(t){return this.repository.getBranches(t)}switchToBranch(t){this.repository.switchToBranch(t),this._notifySubscribers()}_notifySubscribers(){for(const t of this._subscriptions)t()}_notifyEventSubscribers(t){const e=this._eventSubscribers.get(t);if(e)for(const s of e)s()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}getSubmittedFeedback(t){return this._submittedFeedback[t]}submitFeedback({messageId:t,type:e}){var n;const s=(n=this.adapters)==null?void 0:n.feedback;if(!s)throw new Error("Feedback adapter not configured");const{message:r}=this.repository.getMessage(t);s.submit({message:r,type:e}),this._submittedFeedback[t]={type:e},this._notifySubscribers()}speak(t){var i,a;const e=(i=this.adapters)==null?void 0:i.speech;if(!e)throw new Error("Speech adapter not configured");const{message:s}=this.repository.getMessage(t);(a=this._stopSpeaking)==null||a.call(this);const r=e.speak(Me(s)),n=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:t,status:r.status},this._notifySubscribers()});this.speech={messageId:t,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),n(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new 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(t){this.ensureInitialized(),this.repository.clear(),this.repository.import(t),this._notifySubscribers()}unstable_on(t,e){var r,n;if(t==="model-context-update")return((n=(r=this._contextProvider).subscribe)==null?void 0:n.call(r,e))??(()=>{});const s=this._eventSubscribers.get(t);return s?s.add(e):this._eventSubscribers.set(t,new Set([e])),()=>{this._eventSubscribers.get(t).delete(e)}}},pn=Object.freeze([]),gn=(t,e)=>{var s;return t&&((s=e[e.length-1])==null?void 0:s.role)!=="assistant"},mn=class extends fn{constructor(e,s){super(e);h(this,"assistantOptimisticId",null);h(this,"_capabilities",{switchToBranch:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1});h(this,"_messages");h(this,"isDisabled");h(this,"suggestions",[]);h(this,"extras");h(this,"_converter",new qt);h(this,"_store");h(this,"updateMessages",e=>{var r,n,i,a;this._store.convertMessage!==void 0?(n=(r=this._store).setMessages)==null||n.call(r,e.flatMap(Ur).filter(o=>o!=null)):(a=(i=this._store).setMessages)==null||a.call(i,e)});this.__internal_setAdapter(s)}get capabilities(){return this._capabilities}get messages(){return this._messages}get adapters(){return this._store.adapters}beginEdit(e){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(e)}__internal_setAdapter(e){var i,a,o,d,c,u;if(this._store===e)return;const s=e.isRunning??!1;this.isDisabled=e.isDisabled??!1;const r=this._store;if(this._store=e,this.extras=e.extras,this.suggestions=e.suggestions??pn,this._capabilities={switchToBranch:this._store.setMessages!==void 0,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:((i=this._store.adapters)==null?void 0:i.speech)!==void 0,unstable_copy:((a=this._store.unstable_capabilities)==null?void 0:a.copy)!==!1,attachments:!!((o=this._store.adapters)!=null&&o.attachments),feedback:!!((d=this._store.adapters)!=null&&d.feedback)},r){if(r.convertMessage!==e.convertMessage)this._converter=new qt;else if(r.isRunning===e.isRunning&&r.messages===e.messages){this._notifySubscribers();return}}const n=e.convertMessage?this._converter.convertMessages(e.messages,(p,x,E)=>{if(!e.convertMessage)return x;const qe=E===e.messages.length-1,K=Et(qe,s);if(p&&(p.role!=="assistant"||!hr(p.status)||p.status===K))return p;const dt=e.convertMessage(x,E),He=$t(dt,E.toString(),K);return He[ue]=x,He}):e.messages;n.length>0&&this.ensureInitialized(),((r==null?void 0:r.isRunning)??e.isRunning!==!1??!1)&&(e.isRunning?this._notifyEventSubscribers("run-start"):this._notifyEventSubscribers("run-end"));for(let p=0;p<n.length;p++){const x=n[p],E=n[p-1];this.repository.addOrUpdateMessage((E==null?void 0:E.id)??null,x)}this.assistantOptimisticId&&(this.repository.deleteMessage(this.assistantOptimisticId),this.assistantOptimisticId=null),gn(s,n)&&(this.assistantOptimisticId=this.repository.appendOptimisticMessage(((c=n.at(-1))==null?void 0:c.id)??null,{role:"assistant",content:[]})),this.repository.resetHead(this.assistantOptimisticId??((u=n.at(-1))==null?void 0:u.id)??null),this._messages=this.repository.getMessages(),this._notifySubscribers()}switchToBranch(e){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this.repository.switchToBranch(e),this.updateMessages(this.repository.getMessages())}async append(e){var s;if(e.parentId!==(((s=this.messages.at(-1))==null?void 0:s.id)??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(e)}else await this._store.onNew(e)}async startRun(e){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._store.onReload(e.parentId,e)}async resumeRun(){throw new Error("Runtime does not support resuming runs.")}cancelRun(){var r;if(!this._store.onCancel)throw new Error("Runtime does not support cancelling runs.");this._store.onCancel(),this.assistantOptimisticId&&(this.repository.deleteMessage(this.assistantOptimisticId),this.assistantOptimisticId=null);let e=this.repository.getMessages();const s=e[e.length-1];(s==null?void 0:s.role)==="user"&&s.id===((r=e.at(-1))==null?void 0:r.id)?(this.repository.deleteMessage(s.id),this.composer.text.trim()||this.composer.setText(Me(s)),e=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(e)},0)}addToolResult(e){if(!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult(e)}},Ht=t=>{var e;return((e=t.adapters)==null?void 0:e.threadList)??{}},_n=class extends nr{constructor(e){super();h(this,"threads");this.threads=new hn(Ht(e),()=>new mn(this._contextProvider,e))}setAdapter(e){this.threads.__internal_setAdapter(Ht(e)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(e)}},bn=y.createContext(null),yn=()=>y.useContext(bn),vn=t=>{const[e]=y.useState(()=>new _n(t));y.useEffect(()=>{e.setAdapter(t)});const{modelContext:s}=yn()??{};return y.useEffect(()=>{if(s)return e.registerModelContextProvider(s)},[s,e]),y.useMemo(()=>new Sn(e),[e])},Sn=class{constructor(t){h(this,"threads");h(this,"_thread");this._core=t,this.threads=new on(t.threads),this._thread=this.threads.main}get threadList(){return this.threads}__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(t){return this._core.threads.switchToThread(t)}registerModelContextProvider(t){return this._core.registerModelContextProvider(t)}registerModelConfigProvider(t){return this.registerModelContextProvider(t)}reset({initialMessages:t}={}){return this._core.threads.getMainThreadRuntimeCore().import($r.fromArray(t??[]))}};function wn(t){return t.filter(e=>{var s;return e.finishReason==="stop"?e.text!==null&&((s=e.text)==null?void 0:s.trim())!=="":!0})}function xn(t){const e=[];let s=null;for(const r of t)r.type==="reasoning"?(s!=null&&(e.push(s),s=null),e.push(r)):r.functionCalls?(s&&e.push(s),e.push(r),s=null):r.functionResponse?e[e.length-1]={...e[e.length-1],functionResponse:r.functionResponse}:s&&r.protocol===s.protocol&&(s.role===r.role||r.finishReason==="stop")?s.text+=r.text:(s&&e.push(s),s={...r});return s&&e.push(s),wn(e)}function Tn(t){var e;return t.role==="function"?{id:t.id,role:"assistant",status:(t==null?void 0:t.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((e=t.functionCalls)==null?void 0:e.map(s=>{var r;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(r=t.functionResponse)==null?void 0:r.result}}))??[]}:{id:t.id,role:t.role,content:t.type==="reasoning"?[{type:"reasoning",text:t.text}]:[{type:"text",text:t.text}]}}class Ye{constructor(){h(this,"statusChangeCallbacks",[]);h(this,"messageCallbacks",[])}addStatusChangeListener(e){this.statusChangeCallbacks.push(e)}addMessageListener(e){this.messageCallbacks.push(e)}async syncSession(e){this.session=e}async notifyMessage(e){this.messageCallbacks.forEach(s=>s(e))}async notifyMessages(e){e.forEach(s=>{this.messageCallbacks.forEach(r=>r(s))})}async setSession(e){this.session=e}async setStatus(e){const s=this.status!==e;this.status=e,s&&this.statusChangeCallbacks.forEach(r=>r(e))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class it extends Ye{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"notify",!0);this.config=s,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(s){return this.setStatus("connected"),s}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(s){this.session=s}async send(s){const{apiUrl:r,apiKey:n,agentId:i}=this.config,a=this.session??"new",o=s,c=await(await fetch(`${r}/agents/${i}/sessions/${a}/messages`,{body:JSON.stringify({userMessage:o}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":n,"x-persona-apikey":n}})).json();this.notifyMessages(c.response.messages)}}class at extends Ye{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"webSocket");this.config=s,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(s){var r;(r=this.config.logger)==null||r.debug("Syncing session with WebSocket protocol:",s),this.session=s,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(s))}connect(s){var o;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const r=s||this.session||"new";(o=this.config.logger)==null||o.debug("Connecting to WebSocket with sessionId:",r);const n=encodeURIComponent(this.config.apiKey),i=this.config.agentId,a=`${this.config.webSocketUrl}?sessionCode=${r}&agentId=${i}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(a),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",d=>{const c=JSON.parse(d.data);if(c.type!=="message")return;const u=c.payload;this.notifyMessage(u!=null&&u.thought?{role:"assistant",type:"reasoning",text:u.thought}:u)}),this.webSocket.addEventListener("close",()=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",d=>{var c;this.setStatus("disconnected"),this.webSocket=null,(c=this.config.logger)==null||c.error("WebSocket error",d)}),Promise.resolve(r)}disconnect(){var s;return(s=this.config.logger)==null||s.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(s){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:s})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class kn{constructor(e){h(this,"config");h(this,"pc",null);h(this,"ws",null);h(this,"localStream",null);h(this,"remoteStream",new MediaStream);h(this,"audioCtx",null);h(this,"localAnalyser",null);h(this,"remoteAnalyser",null);h(this,"analyzerFrame",null);h(this,"dataChannel",null);h(this,"isConnected",!1);h(this,"visualizerCallbacks",[]);h(this,"messageCallbacks",[]);this.config=e}async connect(e){var s;if(!this.isConnected){this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(r){(s=this.config.logger)==null||s.error("Error accessing microphone:",r);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(r=>{this.pc.addTrack(r,this.localStream)}),this.pc.ontrack=r=>{r.streams[0].getTracks().forEach(i=>{this.remoteStream.addTrack(i)}),this.audioCtx||this._startAnalyzers();const n=new Audio;n.srcObject=this.remoteStream,n.play().catch(i=>{var a;(a=this.config.logger)==null||a.error("Error playing remote audio:",i)})},this.pc.onicecandidate=r=>{var n;r.candidate&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:r.candidate}}))},this.pc.ondatachannel=r=>{const n=r.channel;n.onmessage=i=>{this.messageCallbacks.forEach(a=>{a(i)})}},this.ws=new WebSocket(this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc"),this.ws.onopen=async()=>{var a,o;const r=await this.pc.createOffer();await this.pc.setLocalDescription(r);const n={agentId:this.config.agentId,sessionCode:e};(a=this.config.logger)==null||a.debug("Opening connection to WebRTC server: ",n);const i={type:"OFFER",src:((o=crypto.randomUUID)==null?void 0:o.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:r.sdp,type:r.type},connectionId:(Date.now()%1e6).toString(),metadata:n}};this.ws.send(JSON.stringify(i))},this.ws.onmessage=async r=>{var i;const n=JSON.parse(r.data);if(n.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(n.payload.sdp));else if(n.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(n.payload.candidate))}catch(a){(i=this.config.logger)==null||i.error("Error adding ICE candidate:",a)}},this.ws.onclose=()=>{this._stopAnalyzers()}}}async disconnect(){var e;this.isConnected&&(this.isConnected=!1,((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(s=>s.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(e){this.visualizerCallbacks.push(e)}addMessageCallback(e){this.messageCallbacks.push(e)}createDataChannel(e="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(e),this.dataChannel.onopen=()=>{var s;return(s=this.config.logger)==null?void 0:s.info("Data channel opened")},this.dataChannel.onmessage=s=>{this.messageCallbacks.forEach(r=>{r(s)})})}sendMessage(e){var s,r;if(!this.dataChannel){(s=this.config.logger)==null||s.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(e),(r=this.config.logger)==null||r.info("Sent message:",e)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const e=this.audioCtx.createMediaStreamSource(this.localStream),s=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,e.connect(this.localAnalyser),s.connect(this.remoteAnalyser);const r=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(i);const a=n.reduce((d,c)=>d+c,0)/n.length,o=i.reduce((d,c)=>d+c,0)/i.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(d=>{d({localAmplitude:a,remoteAmplitude:o})}),this.analyzerFrame=requestAnimationFrame(r)};this.analyzerFrame=requestAnimationFrame(r)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class ot extends Ye{constructor(s){super();h(this,"status");h(this,"session");h(this,"autostart");h(this,"config");h(this,"webRTCClient");this.config=s,this.status="disconnected",this.session=null,this.autostart=(s==null?void 0:s.autostart)??!1,this.webRTCClient=new kn(s),this.webRTCClient.addMessageCallback(r=>{var i;(i=s.logger)==null||i.debug("Received data message:",r.data);const n=JSON.parse(r.data);n.type==="message"&&this.notifyMessage(n.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(s){super.syncSession(s),this.status==="connected"&&(await this.disconnect(),await this.connect(s))}async connect(s){var r;return this.status==="connected"?Promise.resolve(this.session):(this.session=s||this.session||"new",this.setStatus("connecting"),(r=this.config.logger)==null||r.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var s,r,n;if(this.status==="disconnected")return(s=this.config.logger)==null||s.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(r=this.config)==null?void 0:r.logger)==null||n.debug("Disconnected from WebRTC")}send(s){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(s),Promise.resolve())}}const ct=y.createContext(void 0);function Cn({dev:t=!1,protocols:e,logger:s,children:r,session:n="new",...i}){const[a,o]=y.useState(!1),[d,c]=y.useState([]),[u,p]=y.useState(n),[x,E]=y.useState(new Map),qe=y.useRef(!1),K=y.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const k=t?"localhost:8000":"persona.applica.guru/api",J=t?"http":"https",G=t?"ws":"wss";return Object.keys(e).map(D=>{switch(D){case"rest":const Ke=e[D];return Ke===!0?new it({apiUrl:`${J}://${k}`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new it(Ke);case"webrtc":const Gt=e[D];return Gt===!0?new ot({webrtcUrl:`${G}://${k}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new ot(Gt);case"websocket":const Xt=e[D];return Xt===!0?new at({webSocketUrl:`${G}://${k}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new at(Xt);default:throw new Error(`Unknown protocol: ${D}`)}})}throw new Error("Invalid protocols configuration")},[]);y.useEffect(()=>{qe.current||(qe.current=!0,s==null||s.debug("Initializing protocols: ",K.map(k=>k.getName())),K.forEach(k=>{k.setSession(u),k.clearListeners(),k.addStatusChangeListener(J=>{s==null||s.debug(`${k.getName()} has notified new status: ${J}`),x.set(k.getName(),J),E(new Map(x))}),k.addMessageListener(J=>{c(G=>xn([...G,{...J,protocol:k.getName()}]))}),k.autostart&&k.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${k.getName()}`),k.connect(u))}))},[u,K,s,x]);const dt=async k=>{var ut;if(((ut=k.content[0])==null?void 0:ut.type)!=="text")throw new Error("Only text messages are supported");const J=k.content[0].text;c(D=>[...D,{role:"user",type:"text",text:J}]),o(!0);const G=K.sort((D,Ke)=>Ke.getPriority()-D.getPriority()).find(D=>D.status==="connected");await(G==null?void 0:G.send(J)),o(!1)},He=y.useCallback(()=>(o(!1),c([]),p("new"),Promise.resolve()),[]),Mn=y.useCallback(()=>Promise.resolve(),[]),On=vn({isRunning:a,messages:d,convertMessage:Tn,onNew:dt,onCancel:He,onReload:Mn});return C.jsx(ct.Provider,{value:{protocols:K,protocolsStatus:x},children:C.jsx(Zr,{runtime:On,children:r})})}function En({children:t,...e}){return C.jsx(Cn,{...e,children:t})}function In(){const t=y.useContext(ct);if(!t)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return t}function Kt(t){const e=y.useContext(ct);if(!e)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const s=e.protocols.find(n=>n.getName()===t);if(!s)return null;const r=e.protocolsStatus.get(s.getName());return{...s,connect:s.connect.bind(s),disconnect:s.disconnect.bind(s),send:s.send.bind(s),setSession:s.setSession.bind(s),addStatusChangeListener:s.addStatusChangeListener.bind(s),addMessageListener:s.addMessageListener.bind(s),getName:s.getName.bind(s),getPriority:s.getPriority.bind(s),status:r||s.status}}function An(){return Kt("webrtc")}class Rn{constructor(){h(this,"prefix","[Persona]")}log(e,...s){console.log(`${this.prefix} - ${e}`,...s)}info(e,...s){console.info(`${this.prefix} - ${e}`,...s)}warn(e,...s){console.warn(`${this.prefix} - ${e}`,...s)}error(e,...s){console.error(`${this.prefix} - ${e}`,...s)}debug(e,...s){console.debug(`${this.prefix} - ${e}`,...s)}}return I.PersonaConsoleLogger=Rn,I.PersonaProtocolBase=Ye,I.PersonaRESTProtocol=it,I.PersonaRuntimeProvider=En,I.PersonaWebRTCProtocol=ot,I.PersonaWebSocketProtocol=at,I.usePersonaRuntime=In,I.usePersonaRuntimeProtocol=Kt,I.usePersonaRuntimeWebRTCProtocol=An,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"}),I}({},React,React);
6
6
  //# sourceMappingURL=bundle.iife.js.map