@cuadra-ai/uikit 0.1.10 → 0.1.13

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.
@@ -12,7 +12,7 @@ ${i.system}`:a.system=i.system),i.tools)for(const[o,c]of Object.entries(i.tools)
12
12
 
13
13
  `),Ch=class{constructor(t){this._core=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(t){return this._core.subscribe(t)}},Ah=class extends Ch{constructor(t,n){super(t),this._composerApi=n}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}},f0=class extends Ah{get source(){return"thread-composer"}},d0=class extends Ah{get source(){return"edit-composer"}},h0=class extends Ch{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}},kh=class extends ts{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 n=this.config.binding.getState(),a=n==null?void 0:n.unstable_on(this.config.event,t);const i=()=>{var c;const o=this.config.binding.getState();o!==n&&(n=o,a==null||a(),a=(c=this.config.binding.getState())==null?void 0:c.unstable_on(this.config.event,t))},u=this.outerSubscribe(i);return()=>{u==null||u(),a==null||a()}}},Rh=Object.freeze([]),Mh=Object.freeze({}),p0=t=>{var n,a,i,u,o,c,d,h,m;return Object.freeze({type:"thread",isEditing:(n=t==null?void 0:t.isEditing)!=null?n:!1,canCancel:(a=t==null?void 0:t.canCancel)!=null?a:!1,isEmpty:(i=t==null?void 0:t.isEmpty)!=null?i:!0,attachments:(u=t==null?void 0:t.attachments)!=null?u:Rh,text:(o=t==null?void 0:t.text)!=null?o:"",role:(c=t==null?void 0:t.role)!=null?c:"user",runConfig:(d=t==null?void 0:t.runConfig)!=null?d:Mh,attachmentAccept:(h=t==null?void 0:t.attachmentAccept)!=null?h:"",value:(m=t==null?void 0:t.text)!=null?m:""})},m0=t=>{var n,a,i,u,o,c,d,h,m;return Object.freeze({type:"edit",isEditing:(n=t==null?void 0:t.isEditing)!=null?n:!1,canCancel:(a=t==null?void 0:t.canCancel)!=null?a:!1,isEmpty:(i=t==null?void 0:t.isEmpty)!=null?i:!0,text:(u=t==null?void 0:t.text)!=null?u:"",role:(o=t==null?void 0:t.role)!=null?o:"user",attachments:(c=t==null?void 0:t.attachments)!=null?c:Rh,runConfig:(d=t==null?void 0:t.runConfig)!=null?d:Mh,attachmentAccept:(h=t==null?void 0:t.attachmentAccept)!=null?h:"",value:(m=t==null?void 0:t.text)!=null?m:""})},zh=class{constructor(t){V(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.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setText(t)}setRunConfig(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setRunConfig(t)}addAttachment(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");return n.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 n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setRole(t)}subscribe(t){return this._core.subscribe(t)}unstable_on(t,n){let a=this._eventSubscriptionSubjects.get(t);return a||(a=new kh({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,a)),a.subscribe(n)}},g0=class extends zh{constructor(n){const a=new ho({path:n.path,getState:()=>p0(n.getState()),subscribe:i=>n.subscribe(i)});super({path:n.path,getState:()=>n.getState(),subscribe:i=>a.subscribe(i)});V(this,"_getState");this._getState=a.getState.bind(a),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(n){return new f0(new Mn({path:G(_({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:n},ref:`${this.path.ref}${this.path.ref}.attachments[${n}]`}),getState:()=>{const i=this.getState().attachments[n];return i?G(_({},i),{source:"thread-composer"}):Rn},subscribe:a=>this._core.subscribe(a)}),this._core)}},y0=class extends zh{constructor(n,a){const i=new ho({path:n.path,getState:()=>m0(n.getState()),subscribe:u=>n.subscribe(u)});super({path:n.path,getState:()=>n.getState(),subscribe:u=>i.subscribe(u)});V(this,"_getState");this._beginEdit=a,this._getState=i.getState.bind(i),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(n){return new d0(new Mn({path:G(_({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:n},ref:`${this.path.ref}${this.path.ref}.attachments[${n}]`}),getState:()=>{const i=this.getState().attachments[n];return i?G(_({},i),{source:"edit-composer"}):Rn},subscribe:a=>this._core.subscribe(a)}),this._core)}},b0=class $u{constructor(n=null){V(this,"_state");this._state=n}get state(){return this._state}append(n){this._state=n.reduce((a,i)=>$u.apply(a,i),this._state)}static apply(n,a){const i=a.type;switch(i){case"set":return $u.updatePath(n,a.path,()=>a.value);case"append-text":return $u.updatePath(n,a.path,u=>{if(typeof u!="string")throw new Error(`Expected string at path [${a.path.join(", ")}]`);return u+a.value});default:{const u=i;throw new Error(`Invalid operation type: ${u}`)}}}static updatePath(n,a,i){if(a.length===0)return i(n);if(n!=null||(n={}),typeof n!="object")throw new Error(`Invalid path: [${a.join(", ")}]`);const[u,...o]=a;if(Array.isArray(n)){const d=Number(u);if(isNaN(d))throw new Error(`Expected array index at [${a.join(", ")}]`);if(d>n.length||d<0)throw new Error("Insert array index out of bounds");const h=[...n];return h[d]=this.updatePath(h[d],o,i),h}const c=_({},n);return c[u]=this.updatePath(c[u],o,i),c}},v0=({unstable_state:t=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:t,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),as=(t,n,a)=>{if(t.parts.length===0)throw new Error("No parts available to update.");if(n.path.length!==1)throw new Error("Nested paths are not supported yet.");const i=n.path[0],u=a(t.parts[i]);return G(_({},t),{parts:[...t.parts.slice(0,i),u,...t.parts.slice(i+1)],get content(){return this.parts}})},x0=(t,n)=>{const a=n.part;if(a.type==="text"||a.type==="reasoning"){const i=_({type:a.type,text:"",status:{type:"running"}},a.parentId&&{parentId:a.parentId});return G(_({},t),{parts:[...t.parts,i],get content(){return this.parts}})}else if(a.type==="tool-call"){const i=_({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:a.toolCallId,toolName:a.toolName,argsText:"",args:{}},a.parentId&&{parentId:a.parentId});return G(_({},t),{parts:[...t.parts,i],get content(){return this.parts}})}else if(a.type==="source"){const i=_(_({type:"source",sourceType:a.sourceType,id:a.id,url:a.url},a.title?{title:a.title}:void 0),a.parentId&&{parentId:a.parentId});return G(_({},t),{parts:[...t.parts,i],get content(){return this.parts}})}else if(a.type==="file"){const i={type:"file",mimeType:a.mimeType,data:a.data};return G(_({},t),{parts:[...t.parts,i],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${a.type}`)},S0=(t,n)=>as(t,n,a=>{if(a.type!=="tool-call")throw new Error("Last is not a tool call");return a.state!=="partial-call"?a:G(_({},a),{state:"call"})}),w0=(t,n)=>as(t,n,a=>G(_({},a),{status:{type:"complete",reason:"unknown"}})),_0=(t,n)=>as(t,n,a=>{var i;if(a.type==="text"||a.type==="reasoning")return G(_({},a),{text:a.text+n.textDelta});if(a.type==="tool-call"){const u=a.argsText+n.textDelta,o=(i=$l(u))!=null?i:a.args;return G(_({},a),{argsText:u,args:o})}else throw new Error("text-delta received but part is neither text nor tool-call")}),T0=(t,n)=>as(t,n,a=>{var i;if(a.type==="tool-call")return G(_(G(_({},a),{state:"result"}),n.artifact!==void 0?{artifact:n.artifact}:{}),{result:n.result,isError:(i=n.isError)!=null?i:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),Oh=(t,n)=>{var i,u;if(((i=t.status)==null?void 0:i.type)==="incomplete"&&((u=t.status)==null?void 0:u.reason)==="error")return t;const a=E0(n);return G(_({},t),{status:a})},E0=t=>t.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:t.finishReason==="stop"||t.finishReason==="unknown"?{type:"complete",reason:t.finishReason}:{type:"incomplete",reason:t.finishReason},C0=(t,n)=>G(_({},t),{metadata:G(_({},t.metadata),{unstable_annotations:[...t.metadata.unstable_annotations,...n.annotations]})}),A0=(t,n)=>G(_({},t),{metadata:G(_({},t.metadata),{unstable_data:[...t.metadata.unstable_data,...n.data]})}),k0=(t,n)=>G(_({},t),{metadata:G(_({},t.metadata),{steps:[...t.metadata.steps,{state:"started",messageId:n.messageId}]})}),R0=(t,n)=>{var u;const a=t.metadata.steps.slice(),i=a.length-1;return a.length>0&&((u=a[i])==null?void 0:u.state)==="started"?a[i]=G(_({},a[i]),{state:"finished",finishReason:n.finishReason,usage:n.usage,isContinued:n.isContinued}):a.push({state:"finished",messageId:_h(),finishReason:n.finishReason,usage:n.usage,isContinued:n.isContinued}),G(_({},t),{metadata:G(_({},t.metadata),{steps:a})})},M0=(t,n)=>G(_({},t),{status:{type:"incomplete",reason:"error",error:n.error}}),z0=(t,n)=>{const a=new b0(t.metadata.unstable_state);return a.append(n.operations),G(_({},t),{metadata:G(_({},t.metadata),{unstable_state:a.state})})},O0=t=>{let n=!1;return()=>{n||(n=!0,queueMicrotask(()=>{n=!1,t()}))}},D0=class extends TransformStream{constructor({initialMessage:t,throttle:n,onError:a}={}){let i=t!=null?t:v0(),u;const o=n?O0(()=>{u==null||u.enqueue(i)}):()=>{u==null||u.enqueue(i)};super({start(c){u=c},transform(c){const d=c.type;switch(d){case"part-start":i=x0(i,c);break;case"tool-call-args-text-finish":i=S0(i,c);break;case"part-finish":i=w0(i,c);break;case"text-delta":i=_0(i,c);break;case"result":i=T0(i,c);break;case"message-finish":i=Oh(i,c);break;case"annotations":i=C0(i,c);break;case"data":i=A0(i,c);break;case"step-start":i=k0(i,c);break;case"step-finish":i=R0(i,c);break;case"error":i=M0(i,c),a==null||a(c.error);break;case"update-state":i=z0(i,c);break;default:{const h=d;throw new Error(`Unsupported chunk type: ${h}`)}}o()},flush(c){var d,h,m;if(((d=i.status)==null?void 0:d.type)==="running"){const g=(m=(h=i.parts)==null?void 0:h.some(y=>y.type==="tool-call"&&(y.state==="call"||y.state==="partial-call")&&y.result===void 0))!=null?m:!1;i=Oh(i,{finishReason:g?"tool-calls":"unknown"}),c.enqueue(i)}}})}},N0=class extends Sh{constructor(){super(t=>{const n=new u0({transform(a,i){i.appendText(a)}});return t.pipeThrough(new TextDecoderStream).pipeThrough(n)})}},I0=class Wu{constructor(n){this.readable=n,this.readable=n}static fromAssistantStream(n){return new Wu(n.pipeThrough(new D0))}unstable_result(){return $(this,null,function*(){let n;try{for(var a=xa(this),i,u,o;i=!(u=yield a.next()).done;i=!1){const c=u.value;n=c}}catch(u){o=[u]}finally{try{i&&(u=a.return)&&(yield u.call(a))}finally{if(o)throw o[0]}}return n||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}})}[Symbol.asyncIterator](){const n=this.readable.getReader();return{next(){return $(this,null,function*(){const{done:i,value:u}=yield n.read();return i?{done:!0,value:void 0}:{done:!1,value:u}})}}}tee(){const[n,a]=this.readable.tee();return[new Wu(n),new Wu(a)]}},Dh=Symbol.for("aui.tool-response"),_a=class Jd{constructor(n){V(this,"artifact");V(this,"result");V(this,"isError");var a;n.artifact!==void 0&&(this.artifact=n.artifact),this.result=n.result,this.isError=(a=n.isError)!=null?a:!1}get[Dh](){return!0}static[Symbol.hasInstance](n){return typeof n=="object"&&n!==null&&Dh in n}static toResponse(n){return n instanceof Jd?n:new Jd({result:n===void 0?"<no result>":n})}};function j0(t,n,a){try{const i=t();if(typeof i=="object"&&i!==null&&"then"in i)return i.then(n,a);n(i)}catch(i){a(i)}}function Ni(t,n){let a=t;for(const i of n){if(a==null)return;a=a[i]}return a}var L0=class{constructor(t,n,a){V(this,"resolve");V(this,"reject");V(this,"disposed",!1);V(this,"fieldPath");this.resolve=t,this.reject=n,this.fieldPath=a}update(t){if(!this.disposed)try{if(wa(t,this.fieldPath)==="complete"){const n=Ni(t,this.fieldPath);n!==void 0&&(this.resolve(n),this.dispose())}}catch(n){this.reject(n),this.dispose()}}dispose(){this.disposed=!0}},Nh=class{constructor(t,n){V(this,"controller");V(this,"disposed",!1);V(this,"fieldPath");this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=Ni(t,this.fieldPath);n!==void 0&&this.controller.enqueue(n),wa(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}},Ih=class{constructor(t,n){V(this,"controller");V(this,"disposed",!1);V(this,"fieldPath");V(this,"lastValue");this.controller=t,this.fieldPath=n}update(t){var n;if(!this.disposed)try{const a=Ni(t,this.fieldPath);if(a!==void 0&&typeof a=="string"){const i=a.substring(((n=this.lastValue)==null?void 0:n.length)||0);this.lastValue=a,this.controller.enqueue(i)}wa(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(a){this.controller.error(a),this.dispose()}}dispose(){this.disposed=!0}},jh=class{constructor(t,n){V(this,"controller");V(this,"disposed",!1);V(this,"fieldPath");V(this,"processedIndexes",new Set);this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=Ni(t,this.fieldPath);if(!Array.isArray(n))return;for(let a=0;a<n.length;a++)if(!this.processedIndexes.has(a)){const i=[...this.fieldPath,a];wa(t,i)==="complete"&&(this.controller.enqueue(n[a]),this.processedIndexes.add(a))}wa(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}},B0=class{constructor(t){V(this,"argTextDeltas");V(this,"handles",new Set);V(this,"args",$l(""));this.argTextDeltas=t,this.processStream()}processStream(){return $(this,null,function*(){try{let t="";const n=this.argTextDeltas.getReader();for(;;){const{value:a,done:i}=yield n.read();if(i)break;t+=a;const u=$l(t);if(u!==void 0){this.args=u;for(const o of this.handles)o.update(u)}}}catch(t){console.error("Error processing argument stream:",t);for(const n of this.handles)n.dispose()}})}get(...t){return new Promise((n,a)=>{const i=new L0(n,a,t);if(this.args&&wa(this.args,t)==="complete"){const u=Ni(this.args,t);if(u!==void 0){n(u);return}}this.handles.add(i),i.update(this.args)})}streamValues(...t){const n=t,a=new ReadableStream({start:i=>{const u=new Nh(i,n);this.handles.add(u),u.update(this.args)},cancel:()=>{for(const i of this.handles)if(i instanceof Nh){i.dispose(),this.handles.delete(i);break}}});return uo(a)}streamText(...t){const n=t,a=new ReadableStream({start:i=>{const u=new Ih(i,n);this.handles.add(u),u.update(this.args)},cancel:()=>{for(const i of this.handles)if(i instanceof Ih){i.dispose(),this.handles.delete(i);break}}});return uo(a)}forEach(...t){const n=t,a=new ReadableStream({start:i=>{const u=new jh(i,n);this.handles.add(u),u.update(this.args)},cancel:()=>{for(const i of this.handles)if(i instanceof jh){i.dispose(),this.handles.delete(i);break}}});return uo(a)}},U0=class{constructor(t){this.promise=t}get(){return this.promise}},H0=class{constructor(){V(this,"args");V(this,"response");V(this,"writable");V(this,"resolve");V(this,"argsText","");V(this,"result",{get:()=>$(this,null,function*(){return(yield this.response.get()).result})});const t=new TransformStream;this.writable=t.writable,this.args=new B0(t.readable);const{promise:n,resolve:a}=co();this.resolve=a,this.response=new U0(n)}appendArgsTextDelta(t){return $(this,null,function*(){const n=this.writable.getWriter();try{yield n.write(t)}catch(a){console.warn(a)}finally{n.releaseLock()}this.argsText+=t})}setResponse(t){this.resolve(t)}},q0=class extends Sh{constructor(t){const n=new Map,a=new Map;super(i=>{const u=new TransformStream({transform(c,d){switch((c.type!=="part-finish"||c.meta.type!=="tool-call")&&d.enqueue(c),c.type){case"part-start":if(c.part.type==="tool-call"){const m=new H0;a.set(c.part.toolCallId,m),t.streamCall({reader:m,toolCallId:c.part.toolCallId,toolName:c.part.toolName})}break;case"text-delta":{if(c.meta.type==="tool-call"){const m=c.meta.toolCallId,g=a.get(m);if(!g)throw new Error("No controller found for tool call");g.appendArgsTextDelta(c.textDelta)}break}case"result":{if(c.meta.type!=="tool-call")break;const{toolCallId:m}=c.meta,g=a.get(m);if(!g)throw new Error("No controller found for tool call");g.setResponse(new _a({result:c.result,artifact:c.artifact,isError:c.isError}));break}case"tool-call-args-text-finish":{if(c.meta.type!=="tool-call")break;const{toolCallId:m,toolName:g}=c.meta,y=a.get(m);if(!y)throw new Error("No controller found for tool call");const v=j0(()=>{let x;try{x=so.parse(y.argsText)}catch(w){throw new Error(`Function parameter parsing failed. ${JSON.stringify(w.message)}`)}return t.execute({toolCallId:m,toolName:g,args:x})},x=>{if(x===void 0)return;const w=new _a({artifact:x.artifact,result:x.result,isError:x.isError});y.setResponse(w),d.enqueue(_({type:"result",path:c.path},w))},x=>{const w=new _a({result:String(x),isError:!0});y.setResponse(w),d.enqueue(_({type:"result",path:c.path},w))});v&&n.set(m,v);break}case"part-finish":{if(c.meta.type!=="tool-call")break;const{toolCallId:m}=c.meta,g=n.get(m);g?g.then(()=>{n.delete(m),a.delete(m),d.enqueue(c)}):d.enqueue(c)}}},flush(){return $(this,null,function*(){yield Promise.all(n.values())})}});return i.pipeThrough(new wh).pipeThrough(u)})}},V0=t=>typeof t=="object"&&t!==null&&"~standard"in t&&t["~standard"].version===1;function Y0(t,n,a,i){const u=t==null?void 0:t[a.toolName];return!u||!u.execute?void 0:(c=>$(null,null,function*(){var m;let d=c;if(V0(u.parameters)){let g=u.parameters["~standard"].validate(a.args);g instanceof Promise&&(g=yield g),g.issues&&(d=(m=u.experimental_onSchemaValidationError)!=null?m:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(g.issues)}`)}))}const h=yield d(a.args,{toolCallId:a.toolCallId,abortSignal:n,human:g=>i(a.toolCallId,g)});return _a.toResponse(h)}))(u.execute)}function F0(t,n,a,i,u){var o,c;(c=(o=t==null?void 0:t[i.toolName])==null?void 0:o.streamCall)==null||c.call(o,a,{toolCallId:i.toolCallId,abortSignal:n,human:d=>u(i.toolCallId,d)})}function G0(t,n,a){const i=typeof t=="function"?t:()=>t,u=typeof n=="function"?n:()=>n;return new q0({execute:o=>Y0(i(),u(),o,a),streamCall:d=>{var h=d,{reader:o}=h,c=gt(h,["reader"]);return F0(i(),u(),o,c,a)}})}var Lh=class{constructor(t,n,a){this.contentBinding=t,this.messageApi=n,this.threadApi=a,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(t){const n=this.contentBinding.getState();if(!n)throw new Error("Message part is not available");if(n.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const a=this.messageApi.getState();if(!a)throw new Error("Message is not available");const i=n.toolName,u=n.toolCallId,o=_a.toResponse(t);this.threadApi.getState().addToolResult({messageId:a.id,toolName:i,toolCallId:u,result:o.result,artifact:o.artifact,isError:o.isError})}resumeToolCall(t){const n=this.contentBinding.getState();if(!n)throw new Error("Message part is not available");if(n.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const a=n.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:a,payload:t})}subscribe(t){return this.contentBinding.subscribe(t)}},is=class extends ts{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 n=this.binding.getState(),a=n==null?void 0:n.subscribe(t);const i=()=>{var c;const o=this.binding.getState();o!==n&&(n=o,a==null||a(),a=(c=this.binding.getState())==null?void 0:c.subscribe(t),t())},u=this.outerSubscribe(i);return()=>{u==null||u(),a==null||a()}}},ls=Object.freeze({type:"complete"}),P0=(t,n,a)=>{if(t.role!=="assistant")return ls;if(a.type==="tool-call")return a.result?ls:t.status;const i=n===Math.max(0,t.content.length-1);return t.status.type==="requires-action"?ls:i?t.status:ls},Bh=(t,n)=>{const a=t.content[n];if(!a)return Rn;const i=P0(t,n,a);return Object.freeze(G(_({},a),{[ns]:a[ns],status:i}))},X0=class{constructor(t,n){V(this,"composer");V(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=t,this._threadBinding=n,this.composer=new y0(new is({path:G(_({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:a=>this._threadBinding.subscribe(a)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(t={}){const n=this._getEditComposerRuntimeCore(),a=n!=null?n:this._threadBinding.getState().composer,i=n!=null?n:a,{runConfig:u=i.runConfig}=t,o=this._core.getState();if(o.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:o.parentId,sourceId:o.id,runConfig:u})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){var a;const t=this._core.getState();if(((a=this._threadBinding.getState().speech)==null?void 0:a.messageId)===t.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:t}){const n=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:n.id,type:t})}switchToBranch({position:t,branchId:n}){const a=this._core.getState();if(n&&t)throw new Error("May not specify both branchId and position");if(!n&&!t)throw new Error("Must specify either branchId or position");const u=this._threadBinding.getState().getBranches(a.id);let o=n;if(t==="previous"?o=u[a.branchNumber-2]:t==="next"&&(o=u[a.branchNumber]),!o)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(o)}unstable_getCopyText(){return rs(this.getState())}subscribe(t){return this._core.subscribe(t)}getMessagePartByIndex(t){if(t<0)throw new Error("Message part index must be >= 0");return new Lh(new Mn({path:G(_({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${t}]`,messagePartSelector:{type:"index",index:t}}),getState:()=>Bh(this.getState(),t),subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getMessagePartByToolCallId(t){return new Lh(new Mn({path:G(_({},this.path),{ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(t)}]`,messagePartSelector:{type:"toolCallId",toolCallId:t}}),getState:()=>{const n=this._core.getState(),a=n.content.findIndex(i=>i.type==="tool-call"&&i.toolCallId===t);return a===-1?Rn:Bh(n,a)},subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new h0(new Mn({path:G(_({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}}),getState:()=>{const n=this.getState().attachments,a=n==null?void 0:n[t];return a?G(_({},a),{source:"message"}):Rn},subscribe:n=>this._core.subscribe(n)}))}},Q0=t=>{var n,a,i;return _({parentId:(n=t.parentId)!=null?n:null,sourceId:(a=t.sourceId)!=null?a:null,runConfig:(i=t.runConfig)!=null?i:{}},t.stream?{stream:t.stream}:{})},Z0=t=>{var n,a,i;return{parentId:(n=t.parentId)!=null?n:null,sourceId:(a=t.sourceId)!=null?a:null,runConfig:(i=t.runConfig)!=null?i:{}}},K0=(t,n)=>{var a,i,u,o,c,d,h,m,g,y,v;return typeof n=="string"?{createdAt:new Date,parentId:(i=(a=t.at(-1))==null?void 0:a.id)!=null?i:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:n}],attachments:[],metadata:{custom:{}}}:{createdAt:(u=n.createdAt)!=null?u:new Date,parentId:(d=(c=n.parentId)!=null?c:(o=t.at(-1))==null?void 0:o.id)!=null?d:null,sourceId:(h=n.sourceId)!=null?h:null,role:(m=n.role)!=null?m:"user",content:n.content,attachments:(g=n.attachments)!=null?g:[],metadata:(y=n.metadata)!=null?y:{custom:{}},runConfig:(v=n.runConfig)!=null?v:{},startRun:n.startRun}},J0=(t,n)=>{const a=t.messages.at(-1);return Object.freeze({threadId:n.id,metadata:n,capabilities:t.capabilities,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:(a==null?void 0:a.role)!=="assistant"?!1:a.status.type==="running",messages:t.messages,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech})},Uh=class{constructor(t,n){V(this,"_threadBinding");V(this,"composer");V(this,"_eventSubscriptionSubjects",new Map);const a=new Mn({path:t.path,getState:()=>J0(t.getState(),n.getState()),subscribe:i=>{const u=t.subscribe(i),o=n.subscribe(i);return()=>{u(),o()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>a.getState(),outerSubscribe:i=>t.outerSubscribe(i),subscribe:i=>t.subscribe(i)},this.composer=new g0(new is({path:G(_({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:i=>this._threadBinding.subscribe(i)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(K0(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 n=t===null||typeof t=="string"?{parentId:t}:t;return this._threadBinding.getState().startRun(Z0(n))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(Q0(t))}unstable_loadExternalState(t){this._threadBinding.getState().unstable_loadExternalState(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)}reset(t){this._threadBinding.getState().reset(t)}getMessageByIndex(t){if(t<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime(G(_({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${t}]`,messageSelector:{type:"index",index:t}}),()=>{var i,u;const n=this._threadBinding.getState().messages,a=n[t];if(a)return{message:a,parentId:(u=(i=n[t-1])==null?void 0:i.id)!=null?u:null,index:t}})}getMessageById(t){return this._getMessageRuntime(G(_({},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,n){return new X0(new Mn({path:t,getState:()=>{var g,y;const{message:a,parentId:i,index:u}=(g=n())!=null?g:{},{messages:o,speech:c}=this._threadBinding.getState();if(!a||i===void 0||u===void 0)return Rn;const h=this._threadBinding.getState().getBranches(a.id),m=a.metadata.submittedFeedback;return G(_({},a),{[ns]:a[ns],index:u,isLast:((y=o.at(-1))==null?void 0:y.id)===a.id,parentId:i,branchNumber:h.indexOf(a.id)+1,branchCount:h.length,speech:(c==null?void 0:c.messageId)===a.id?c:void 0,submittedFeedback:m})},subscribe:a=>this._threadBinding.subscribe(a)}),this._threadBinding)}unstable_on(t,n){let a=this._eventSubscriptionSubjects.get(t);return a||(a=new kh({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,a)),a.subscribe(n)}},$0=t=>({mainThreadId:t.mainThreadId,newThread:t.newThreadId,threads:t.threadIds,archivedThreads:t.archivedThreadIds,isLoading:t.isLoading,threadItems:t.threadData}),ss=(t,n)=>{if(n===void 0)return Rn;const a=t.getItemById(n);return a?{id:a.id,threadId:a.id,remoteId:a.remoteId,externalId:a.externalId,title:a.title,status:a.status,isMain:a.id===t.mainThreadId}:Rn},W0=class{constructor(t,n=Uh){V(this,"_getState");V(this,"_mainThreadListItemRuntime");V(this,"main");this._core=t,this._runtimeFactory=n;const a=new ho({path:{},getState:()=>$0(t),subscribe:i=>t.subscribe(i)});this._getState=a.getState.bind(a),this._mainThreadListItemRuntime=new es(new Mn({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>ss(this._core,this._core.mainThreadId),subscribe:i=>this._core.subscribe(i)}),this._core),this.main=new n(new is({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:i=>t.subscribe(i)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(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 is({path:{ref:`threads[threadId=${JSON.stringify(t)}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>this._core.getThreadRuntimeCore(t),subscribe:n=>this._core.subscribe(n)}),this.mainItem)}getItemByIndex(t){return new es(new Mn({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>ss(this._core,this._core.threadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getArchivedItemByIndex(t){return new es(new Mn({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>ss(this._core,this._core.archivedThreadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getItemById(t){return new es(new Mn({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>ss(this._core,t),subscribe:n=>this._core.subscribe(n)}),this._core)}},t1=t=>t.startsWith("image/")?"image":t.startsWith("text/")?"document":"file",e1=class{constructor(t){V(this,"accept","*");V(this,"uploadedUrls",new Map);this.cloud=t}add(n){return Kl(this,arguments,function*({file:t}){const a=crypto.randomUUID(),i=t1(t.type);let u={id:a,type:i,name:t.name,contentType:t.type,file:t,status:{type:"running",reason:"uploading",progress:0}};yield u;try{const{signedUrl:o,publicUrl:c}=yield new gr(this.cloud.files.generatePresignedUploadUrl({filename:t.name}));yield new gr(fetch(o,{method:"PUT",body:t,headers:{"Content-Type":t.type},mode:"cors"})),this.uploadedUrls.set(a,c),u=G(_({},u),{status:{type:"requires-action",reason:"composer-send"}}),yield u}catch(o){u=G(_({},u),{status:{type:"incomplete",reason:"error"}}),yield u}})}remove(t){return $(this,null,function*(){this.uploadedUrls.delete(t.id)})}send(t){return $(this,null,function*(){const n=this.uploadedUrls.get(t.id);if(!n)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(t.id);let a;return t.type==="image"?a=[{type:"image",image:n,filename:t.name}]:a=[{type:"file",data:n,mimeType:t.contentType,filename:t.name}],G(_({},t),{status:{type:"complete"},content:a})})}},po=M.createContext(null),Hh=({adapters:t,children:n})=>{const a=M.useContext(po);return E.jsx(po.Provider,{value:_(_({},a),t),children:n})},n1=()=>M.useContext(po),r1=class extends ch{constructor(n,a,{parentId:i,message:u}){var o;super();V(this,"_nonTextParts");V(this,"_previousText");V(this,"_parentId");V(this,"_sourceId");this.runtime=n,this.endEditCallback=a,this._parentId=i,this._sourceId=u.id,this._previousText=rs(u),this.setText(this._previousText),this.setRole(u.role),this.setAttachments((o=u.attachments)!=null?o:[]),this._nonTextParts=u.content.filter(c=>c.type!=="text"),this.setRunConfig(_({},n.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var n;return(n=this.runtime.adapters)==null?void 0:n.attachments}handleSend(n){return $(this,null,function*(){rs(n)!==this._previousText&&this.runtime.append(G(_({},n),{content:[...n.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},a1=class{constructor(t){V(this,"_subscriptions",new Set);V(this,"_isInitialized",!1);V(this,"repository",new Eh);V(this,"composer",new fh(this));V(this,"_editComposers",new Map);V(this,"_stopSpeaking");V(this,"speech");V(this,"_eventSubscribers",new Map);this._contextProvider=t}get messages(){return this.repository.getMessages()}get state(){var n;let t;for(const a of this.messages)if(a.role==="assistant"){t=a;break}return(n=t==null?void 0:t.metadata.unstable_state)!=null?n:null}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 r1(this,()=>this._editComposers.delete(t),this.repository.getMessage(t))),this._notifySubscribers()}getMessageById(t){try{return this.repository.getMessage(t)}catch(n){return}}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 n=this._eventSubscribers.get(t);if(n)for(const a of n)a()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}submitFeedback({messageId:t,type:n}){var o;const a=(o=this.adapters)==null?void 0:o.feedback;if(!a)throw new Error("Feedback adapter not configured");const{message:i,parentId:u}=this.repository.getMessage(t);if(a.submit({message:i,type:n}),i.role==="assistant"){const c=G(_({},i),{metadata:G(_({},i.metadata),{submittedFeedback:{type:n}})});this.repository.addOrUpdateMessage(u,c)}this._notifySubscribers()}speak(t){var o,c;const n=(o=this.adapters)==null?void 0:o.speech;if(!n)throw new Error("Speech adapter not configured");const{message:a}=this.repository.getMessage(t);(c=this._stopSpeaking)==null||c.call(this);const i=n.speak(rs(a)),u=i.subscribe(()=>{i.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:t,status:i.status},this._notifySubscribers()});this.speech={messageId:t,status:i.status},this._notifySubscribers(),this._stopSpeaking=()=>{i.cancel(),u(),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()}reset(t){this.import(fo.fromArray(t!=null?t:[]))}unstable_on(t,n){var i,u,o;if(t==="model-context-update")return(o=(u=(i=this._contextProvider).subscribe)==null?void 0:u.call(i,n))!=null?o:(()=>{});const a=this._eventSubscribers.get(t);return a?a.add(n):this._eventSubscribers.set(t,new Set([n])),()=>{this._eventSubscribers.get(t).delete(n)}}},i1=t=>{try{return JSON.parse(t),!0}catch(n){return!1}};function l1({state:t,getTools:n,onResult:a,setToolStatuses:i}){const u=M.useRef({}),o=M.useRef(new Map),c=M.useRef(new AbortController),[d]=M.useState(()=>{const[y,v]=Th(),x=G0(n,()=>{var w,R;return(R=(w=c.current)==null?void 0:w.signal)!=null?R:new AbortController().signal},(w,R)=>new Promise((N,z)=>{const Y=o.current.get(w);Y&&Y.reject(new Error("Human input request was superseded by a new request")),o.current.set(w,{resolve:N,reject:z}),i(I=>G(_({},I),{[w]:{type:"interrupt",payload:{type:"human",payload:R}}}))}));return y.pipeThrough(x).pipeThrough(new wh).pipeTo(new WritableStream({write(w){var R;if(w.type==="result"){if((R=u.current[w.meta.toolCallId])!=null&&R.hasResult)return;a(_({type:"add-tool-result",toolCallId:w.meta.toolCallId,toolName:w.meta.toolName,result:w.result,isError:w.isError},w.artifact&&{artifact:w.artifact})),i(N=>{const z=_({},N);return delete z[w.meta.toolCallId],z})}}})),v}),h=M.useRef(new Set),m=M.useRef(!0);M.useEffect(()=>{const y=v=>{v.forEach(x=>{x.content.forEach(w=>{if(w.type==="tool-call"){if(m.current)h.current.add(w.toolCallId);else{if(h.current.has(w.toolCallId))return;let R=u.current[w.toolCallId];if(R||(R={argsText:"",hasResult:!1,argsComplete:!1,controller:d.addToolCallPart({toolName:w.toolName,toolCallId:w.toolCallId})},u.current[w.toolCallId]=R),w.argsText!==R.argsText)if(R.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:R.argsText,next:w.argsText});else{if(!w.argsText.startsWith(R.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${w.argsText} does not start with ${R.argsText}`);const N=w.argsText.slice(R.argsText.length);R.controller.argsText.append(N);const z=i1(w.argsText);z&&R.controller.argsText.close(),u.current[w.toolCallId]={argsText:w.argsText,hasResult:R.hasResult,argsComplete:z,controller:R.controller}}w.result!==void 0&&!R.hasResult&&(R.controller.setResponse(new _a({result:w.result,artifact:w.artifact,isError:w.isError})),R.controller.close(),u.current[w.toolCallId]={hasResult:!0,argsComplete:!0,argsText:R.argsText,controller:R.controller})}w.messages&&y(w.messages)}})})};y(t.messages),m.current&&(m.current=!1)},[t,d,a]);const g=()=>{o.current.forEach(({reject:y})=>{y(new Error("Tool execution aborted"))}),o.current.clear(),i({}),c.current.abort(),c.current=new AbortController};return{reset:()=>{g(),m.current=!0},abort:g,resume:(y,v)=>{const x=o.current.get(y);if(x)o.current.delete(y),i(w=>{const R=_({},w);return delete R[y],R}),x.resolve(v);else throw new Error(`Tool call ${y} is not waiting for human input`)}}}var s1=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(t){return Promise.reject(new Error("Thread not found"))}};function u1(t,n){t.commitTasks.forEach(a=>{const i=a.cellIndex,u=n.cells[i];if(u.type!=="effect")throw new Error("Cannot find effect cell");let o=!0;if(u.deps!==void 0&&a.deps!==void 0&&(o=u.deps.length!==a.deps.length||u.deps.some((c,d)=>!Object.is(c,a.deps[d]))),o){if(u.mounted){if(typeof u.deps!=typeof a.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{u.mounted&&u.cleanup&&u.cleanup()}finally{u.mounted=!1}}try{const c=a.effect();if(c!==void 0&&typeof c!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof c}`);u.mounted=!0,u.cleanup=typeof c=="function"?c:void 0,u.deps=a.deps}catch(c){throw c}}})}function o1(t){let n=null;for(let a=t.cells.length-1;a>=0;a--){const i=t.cells[a];if((i==null?void 0:i.type)==="effect"&&i.mounted&&i.cleanup)try{i.cleanup()}catch(u){n==null&&(n=u)}finally{i.mounted=!1}}if(n!=null)throw n}var Ii=null;function c1(t,n){t.currentIndex=0;const a=Ii;Ii=t;try{if(n(),t.isFirstRender=!1,t.cells.length!==t.currentIndex)throw new Error(`Rendered ${t.currentIndex} hooks but expected ${t.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{Ii=a}}function mo(){if(!Ii)throw new Error("No resource fiber available");return Ii}function qh(t,n){const a=t[Vh];if(!a)throw new Error("ResourceElement.type is not a valid Resource");return a(n)}var Vh=Symbol("fnSymbol");function us(t,n){return{resource:t,scheduleRerender:n,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function Ta(t){t.isMounted=!1,o1(t)}function ji(t,n){const a={commitTasks:[],props:n,state:void 0};return c1(t,()=>{t.renderContext=a;try{a.state=qh(t.resource,n)}finally{t.renderContext=void 0}}),a}function Ea(t,n){t.isMounted=!0,t.isNeverMounted=!1,u1(n,t)}var f1=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,Yh=f1?M.useEffect:M.useLayoutEffect;function go(t){const[,n]=M.useState({}),a=M.useMemo(()=>us(t.type,()=>n({})),[t.type,n]),i=ji(a,t.props);return Yh(()=>()=>Ta(a),[]),Yh(()=>{Ea(a,i)}),i.state}var Ca=t=>typeof t=="string"?{scope:t.split(".")[0],event:t}:{scope:t.scope,event:t.event},Qr=(t,n,a)=>n===t,Aa,yo=()=>{if(Aa)return Aa;const t=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return Aa=t(),Aa;const n=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(n)return Aa=n,n;const a=t();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=a,Aa=a,a},d1=(Nn=class{static register(n){var d,h;const a=yo();for(const m of a.apis.values())if(m.api===n)return()=>{};const i=a.nextId++,u={api:n,logs:[]},o=(d=n.on)==null?void 0:d.call(n,"*",m=>{const g=a.apis.get(i);g&&(g.logs.push({time:new Date,event:m.event,data:m.payload}),g.logs.length>Nn.MAX_EVENT_LOGS_PER_API&&(g.logs=g.logs.slice(-200)),Nn.notifyListeners(i))}),c=(h=n.subscribe)==null?void 0:h.call(n,()=>{Nn.notifyListeners(i)});return a.apis.set(i,u),Nn.notifyListeners(i),()=>{const m=yo();m.apis.get(i)&&(o==null||o(),c==null||c(),m.apis.delete(i),Nn.notifyListeners(i))}}static notifyListeners(n){yo().listeners.forEach(i=>i(n))}},V(Nn,"MAX_EVENT_LOGS_PER_API",200),Nn);function se(t){const n=(a,i)=>_({type:n,props:a},(i==null?void 0:i.key)!==void 0&&{key:i.key});return n[Vh]=t,n}var h1=t=>{if(t.renderContext)throw new Error("Resource updated during render");if(t.isNeverMounted)throw new Error("Resource updated before mount");t.isMounted&&t.scheduleRerender()};function p1(t){const n=mo(),a=n.currentIndex++;if(!n.isFirstRender&&a>=n.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!n.cells[a]){const o={type:"state",value:typeof t=="function"?t():t,set:c=>{const d=o.value,h=typeof c=="function"?c(d):c;Object.is(d,h)||(o.value=h,h1(n))}};n.cells[a]=o}const i=n.cells[a];if(i.type!=="state")throw new Error("Hook order changed between renders");return i}function Un(t){const n=p1(t);return[n.value,n.set]}function m1(){const t=mo(),n=t.currentIndex++;if(!t.isFirstRender&&n>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[n]){const i={type:"effect",mounted:!1};t.cells[n]=i}if(t.cells[n].type!=="effect")throw new Error("Hook order changed between renders");return n}function je(t,n){const a=mo(),i=m1();a.renderContext.commitTasks.push({effect:t,deps:n,cellIndex:i})}function ka(t){const[n]=Un(()=>({current:t}));return n}var g1=(t,n)=>{if(t.length!==n.length)return!1;for(let a=0;a<t.length;a++)if(!Object.is(t[a],n[a]))return!1;return!0},Jt=(t,n)=>{const a=ka();return a.current||(a.current={value:t(),deps:n}),g1(a.current.deps,n)||(a.current.value=t(),a.current.deps=n),a.current.value};function os(t,n){const[a,i]=Un({}),u=Jt(()=>us(t.type,()=>i({})),[t.type]),o=n?Jt(()=>t.props,n):t.props,c=Jt(()=>ji(u,o),[u,o,a]);return je(()=>()=>Ta(u),[u]),je(()=>{Ea(u,c)},[u,c]),c.state}function zn(t){return qh(t.type,t.props)}function Fh(t){const n=new Set;t.forEach((d,h)=>{if(d.key===void 0)throw new Error(`tapResources: All resource elements must have a key. Element at index ${h} is missing a key.`);if(n.has(d.key))throw new Error(`tapResources: Duplicate key "${d.key}" found. All keys must be unique.`);n.add(d.key)});const[a,i]=Un({}),u=Jt(()=>new Map(t.map(d=>[d.key,d])),[t]),[o]=Un(()=>new Map),c=Jt(()=>{const d=new Map,h=new Set;return u.forEach((m,g)=>{h.add(g);let y=o.get(g);(!y||y.resource!==m.type)&&(y&&Ta(y),y=us(m.type,()=>i({})),o.set(g,y));const v=ji(y,m.props);d.set(g,v)}),o.forEach((m,g)=>{h.has(g)||(Ta(m),o.delete(g))}),d},[u,a]);return je(()=>{c.forEach((d,h)=>{const m=o.get(h);m&&Ea(m,d)})},[c,o]),je(()=>()=>{o.forEach(d=>{Ta(d)}),o.clear()},[o]),Jt(()=>t.map(d=>{var h;return(h=c.get(d.key))==null?void 0:h.state}),[t,c])}var bo=[],vo=!1;function y1(){vo=!1;const t=bo;bo=[];for(const n of t)try{n()}catch(a){console.error("Error in scheduled task:",a)}}function b1(t){bo.push(t),vo||(vo=!0,queueMicrotask(y1))}var v1=(ta=class{constructor(n){V(this,"_isDirty",!1);V(this,"_hasScheduledTask",!1);V(this,"_isFlushing",!1);this._task=n}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,b1(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let n=0;try{for(;this._isDirty;){if(n++,n>ta.MAX_FLUSH_DEPTH)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");this._isDirty=!1,this._task()}}finally{this._isFlushing=!1}}},V(ta,"MAX_FLUSH_DEPTH",50),ta),x1=se(({element:t,onUpdateInput:n,onFlushSync:a,onDispose:i})=>{const[u,o]=Un(t.props),c=zn({type:t.type,props:u}),d=ka(new Set).current,h=ka(c);return je(()=>{c!==h.current&&(h.current=c,d.forEach(g=>g()))}),Jt(()=>({getState:()=>h.current,subscribe:g=>(d.add(g),()=>d.delete(g)),updateInput:g=>{n(),o(()=>g)},flushSync:a,dispose:i}),[])}),S1=(t,n=!1)=>{let a=!n;const i={element:t,onUpdateInput:()=>{a||(a=!0,Ea(o,c))},onFlushSync:()=>{u.flushSync()},onDispose:()=>Ta(o)},u=new v1(()=>{c=ji(o,i),a&&Ea(o,c)}),o=us(x1,()=>u.markDirty());let c=ji(o,i);return a&&Ea(o,c),c.state},Li=Symbol("tap.Context"),Gh=t=>({[Li]:t}),Ph=(t,n,a)=>{const i=t[Li];t[Li]=n;try{return a()}finally{t[Li]=i}},Xh=t=>t[Li];const Qh=t=>{let n;const a=new Set,i=(m,g)=>{const y=typeof m=="function"?m(n):m;if(!Object.is(y,n)){const v=n;n=(g!=null?g:typeof y!="object"||y===null)?y:Object.assign({},n,y),a.forEach(x=>x(n,v))}},u=()=>n,d={setState:i,getState:u,getInitialState:()=>h,subscribe:m=>(a.add(m),()=>a.delete(m))},h=n=t(i,u,d);return d},w1=(t=>t?Qh(t):Qh),_1=t=>t;function T1(t,n=_1){const a=kn.useSyncExternalStore(t.subscribe,kn.useCallback(()=>n(t.getState()),[t,n]),kn.useCallback(()=>n(t.getInitialState()),[t,n]));return kn.useDebugValue(a),a}const Zh=t=>{const n=w1(t),a=i=>T1(n,i);return Object.assign(a,n),a},Ra=(t=>t?Zh(t):Zh);function Kh(t,n){if(typeof t=="function")return t(n);t!=null&&(t.current=n)}function Jh(...t){return n=>{let a=!1;const i=t.map(u=>{const o=Kh(u,n);return!a&&typeof o=="function"&&(a=!0),o});if(a)return()=>{for(let u=0;u<i.length;u++){const o=i[u];typeof o=="function"?o():Kh(t[u],null)}}}}function cs(...t){return M.useCallback(Jh(...t),t)}var $h=se(t=>{const n=Jt(()=>S1(t,!0),[t.type]);return je(()=>{n.updateInput(t.props)}),n}),E1=class{constructor(t){this.getApi=t}get(t,n){return this.getApi()[n]}ownKeys(){return Object.keys(this.getApi())}has(t,n){return n in this.getApi()}getOwnPropertyDescriptor(t,n){return Object.getOwnPropertyDescriptor(this.getApi(),n)}set(){return!1}defineProperty(){return!1}deleteProperty(){return!1}},On=(t,n)=>{const a=ka(t);je(()=>{a.current=t});const i=Jt(()=>new Proxy({},new E1(()=>a.current)),[]),u=n==null?void 0:n.key,o=t.getState();return Jt(()=>({key:u,state:o,api:i}),[o,u])},Ma=se(t=>{const n=ka(t.get);return je(()=>{n.current=t.get}),Jt(()=>Oe({source:t.source,query:t.query,get:()=>n.current()}),[t.source,JSON.stringify(t.query)])}),C1=se(t=>{const n=os(t.scopeElement);return Jt(()=>[t.fieldName,n],[t.fieldName,n])}),A1=se(t=>{const d=t,{on:n,subscribe:a,flushSync:i}=d,u=gt(d,["on","subscribe","flushSync"]),o=ka({on:n,subscribe:a,flushSync:i});je(()=>{o.current={on:n,subscribe:a,flushSync:i}});const c=Fh(Object.entries(u).map(([h,m])=>C1({fieldName:h,scopeElement:m},{key:h})));return Jt(()=>{const h=Object.fromEntries(c),{on:m,subscribe:g,flushSync:y}=o.current;return m&&(h.on=(v,x)=>m(v,x)),g&&(h.subscribe=v=>g(v)),y&&(h.flushSync=()=>y()),h},[...c])}),Wh=Gh(null),k1=(t,n)=>Ph(Wh,t,n),tp=()=>{const t=Xh(Wh);if(!t)throw new Error("Model context is not available in this context");return t},R1=se(({toolkit:t})=>{const[n,a]=Un(()=>({tools:{}})),i=tp();je(()=>{if(!t)return;const o=[];for(const[h,m]of Object.entries(t))m.render&&o.push(u(h,m.render));const c=Object.entries(t).reduce((h,[m,g])=>{const x=g,{render:y}=x,v=gt(x,["render"]);return h[m]=v,h},{}),d={getModelContext:()=>({tools:c})};return o.push(i.register(d)),()=>{o.forEach(h=>h())}},[t,i]);const u=(o,c)=>(a(d=>{var h;return G(_({},d),{tools:G(_({},d.tools),{[o]:[...(h=d.tools[o])!=null?h:[],c]})})}),()=>{a(d=>{var h,m;return G(_({},d),{tools:G(_({},d.tools),{[o]:(m=(h=d.tools[o])==null?void 0:h.filter(g=>g!==c))!=null?m:[]})})})});return On({getState:()=>n,setToolUI:u})}),M1=se(()=>Jt(()=>{const n=new Map;return{on:(a,i)=>{n.has(a)||n.set(a,new Set);const u=n.get(a);return u.add(i),()=>{u.delete(i),u.size===0&&n.delete(a)}},emit:(a,i)=>{const u=n.get(a),o=n.get("*");!u&&!o||queueMicrotask(()=>{if(u)for(const c of u)c(i);if(o)for(const c of o)c({event:a,payload:i})})}}},[])),ep=Gh(null),z1=(t,n)=>Ph(ep,t,n),xo=()=>{const t=Xh(ep);if(!t)throw new Error("Events context is not available");return t},O1=se(()=>{const[t]=Un(()=>({})),n=new io;return On({getState:()=>t,getModelContext:()=>n.getModelContext(),subscribe:a=>n.subscribe(a),register:a=>n.registerModelContextProvider(a)})}),D1=se(({threads:t,modelContext:n,tools:a})=>{const i=zn(M1()),{threads:u,tools:o,modelContext:c}=z1(i,()=>{const h=os(n!=null?n:O1(),[n]);return k1(h.api,()=>({modelContext:h,tools:os(a!=null?a:R1({}),[a]),threads:os(t,[t])}))}),d=Jt(()=>({threads:u.state,tools:o.state,modelContext:c.state}),[u.state,o.state,c.state]);return On({getState:()=>d,threads:u.api,tools:o.api,modelContext:c.api,on:i.on})}),N1=t=>{const n=()=>t.getState().api.threads.item("main");return{threads:Oe({source:"root",query:{},get:()=>t.getState().api.threads}),tools:Oe({source:"root",query:{},get:()=>t.getState().api.tools}),modelContext:Oe({source:"root",query:{},get:()=>t.getState().api.modelContext}),thread:Oe({source:"threads",query:{type:"main"},get:()=>t.getState().api.threads.thread("main")}),threadListItem:Oe({source:"threads",query:{type:"main"},get:()=>n()}),composer:Oe({source:"thread",query:{},get:()=>t.getState().api.threads.thread("main").composer}),on(a,i){const{event:u,scope:o}=Ca(a);if(o==="*")return t.getState().api.on(u,i);if(Qr("thread",o)||Qr("thread-list-item",o)||Qr("composer",o))return t.getState().api.on(u,c=>{c.threadId===n().getState().id&&i(c)});throw new Error(`Event scope is not available in this component: ${o}`)},subscribe:t.subscribe,flushSync:t.flushSync}},I1=t=>{const n=fs(),a=go($h(D1(t))),i=M.useMemo(()=>N1(a),[a]);return M.useMemo(()=>rp(n,i),[n,i])},Oe=t=>{const n=t.get;return n.source=t.source,n.query=t.query,n},yr=()=>()=>{},np=M.createContext({threads:Oe({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:Oe({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:Oe({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:Oe({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:Oe({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:Oe({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:Oe({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:Oe({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:Oe({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:yr,flushSync:yr,on:t=>{const{scope:n}=Ca(t);throw new Error(`Event scope is not available in this component: ${n}`)}}),fs=()=>M.useContext(np),Bi=t=>{const n=fs(),a=go(A1(t));return M.useMemo(()=>rp(n,a),[n,a])},j1=t=>I1(t);function de(t){return t?j1(t):fs()}var L1=(t,n)=>t===yr?n:n===yr?t:(...a)=>{t(...a),n(...a)},B1=(t,n)=>t===yr?n:n===yr?t:(...a)=>{const i=t(...a),u=n(...a);return()=>{i(),u()}},rp=(t,n)=>{const a=n.subscribe,i=n.flushSync;return G(_(_({},t),n),{subscribe:B1(t.subscribe,a!=null?a:yr),flushSync:L1(t.flushSync,i!=null?i:yr)})},za=({api:t,children:n,devToolsVisible:a=!0})=>(M.useEffect(()=>{if(!(!a||!t.subscribe))return d1.register(t)},[t,a]),E.jsx(np.Provider,{value:t,children:n})),ap=(my=class{constructor(t){ki(this,mn);Ri(this,mn,t)}get threads(){return hn(this,mn).threads().getState()}get tools(){return hn(this,mn).tools().getState()}get threadListItem(){return hn(this,mn).threadListItem().getState()}get thread(){return hn(this,mn).thread().getState()}get composer(){return hn(this,mn).composer().getState()}get message(){return hn(this,mn).message().getState()}get part(){return hn(this,mn).part().getState()}get attachment(){return hn(this,mn).attachment().getState()}},mn=new WeakMap,my),ne=t=>{const n=de(),a=M.useMemo(()=>new ap(n),[n]),i=M.useSyncExternalStore(n.subscribe,()=>t(a),()=>t(a));if(M.useDebugValue(i),i instanceof ap)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return i},U1=(t,n)=>{const a=de(),i=M.useRef(n);M.useEffect(()=>{i.current=n});const{scope:u,event:o}=Ca(t);M.useEffect(()=>a.on({scope:u,event:o},c=>i.current(c)),[a,u,o])};function H1(t,n){function a(i){const u=M.useContext(t);if(!(i!=null&&i.optional)&&!u)throw new Error(`This component must be used within ${n}.`);return u}return a}function ip(t,n){function a(u){const o=t(u);return o?o[n]:null}function i(u){let o=!1,c;typeof u=="function"?c=u:u&&typeof u=="object"&&(o=!!u.optional,c=u.selector);const d=a({optional:o});return d?c?d(c):d():null}return{[n]:i,[`${n}Store`]:a}}var lp=M.createContext(null),q1=H1(lp,"ThreadPrimitive.Viewport"),{useThreadViewport:ds,useThreadViewportStore:So}=ip(q1,"useThreadViewport"),V1=t=>{var a;const n=t;n.__isBound||((a=n.__internal_bindMethods)==null||a.call(n),n.__isBound=!0)};function Y1(t,n=F1){V1(t);const a=M.useSyncExternalStore(t.subscribe,()=>n(t.getState()),()=>n(t.getState()));return M.useDebugValue(a),a}var F1=t=>t;function sp(t){function n(a){let i=!1,u;typeof a=="function"?u=a:a&&(i=!!a.optional,u=a.selector);const o=t({optional:i});return o?Y1(o,u):null}return n}function up(t){const n=de(),a=ne(()=>{var i,u,o;return n.thread.source&&(o=(u=(i=n.thread()).__internal_getRuntime)==null?void 0:u.call(i))!=null?o:null});if(!a&&!(t!=null&&t.optional))throw new Error("ThreadRuntime is not available");return a}var G1=sp(up);function P1(t){const n=de(),a=ne(()=>{var i,u,o;return n.threadListItem.source&&(o=(u=(i=n.threadListItem()).__internal_getRuntime)==null?void 0:u.call(i))!=null?o:null});if(!a&&!(t!=null&&t.optional))throw new Error("ThreadListItemRuntime is not available");return a}var X1=sp(P1),Zr=t=>{const[,n]=Un(t.getState);return je(()=>(n(t.getState()),t.subscribe(()=>{n(t.getState())})),[t]),t.getState()},Q1=se(({runtime:t})=>{const n=Zr(t),a=xo();return je(()=>{const i=[],u=["switched-to","switched-away"];for(const o of u){const c=t.unstable_on(o,()=>{a.emit(`thread-list-item.${o}`,{threadId:t.getState().id})});i.push(c)}return()=>{for(const o of i)o()}},[t,a]),On({getState:()=>n,switchTo:t.switchTo,rename:t.rename,archive:t.archive,unarchive:t.unarchive,delete:t.delete,generateTitle:t.generateTitle,initialize:t.initialize,detach:t.detach,__internal_getRuntime:()=>t},{key:n.id})}),Ui=t=>{const n=Fh(t);return{state:n.map(a=>a.state),api:a=>{var u,o;const i="index"in a?(u=n[a.index])==null?void 0:u.api:(o=n.find(c=>c.key===a.key))==null?void 0:o.api;if(!i)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(a)}`);return i}}},op=se(({runtime:t})=>{const n=Zr(t);return On({getState:()=>n,remove:t.remove,__internal_getRuntime:()=>t},{key:n.id})}),Z1=se(({runtime:t,index:n})=>{const a=Jt(()=>t.getAttachmentByIndex(n),[t,n]);return zn(op({runtime:a}))}),cp=se(({threadIdRef:t,messageIdRef:n,runtime:a})=>{var d;const i=Zr(a),u=xo();je(()=>{const h=[],m=["send","attachment-add"];for(const g of m){const y=a.unstable_on(g,()=>{u.emit(`composer.${g}`,_({threadId:t.current},n&&{messageId:n.current}))});h.push(y)}return()=>{for(const g of h)g()}},[a,u,t,n]);const o=Ui(i.attachments.map((h,m)=>Z1({runtime:a,index:m},{key:m}))),c=Jt(()=>{var h;return{text:i.text,role:i.role,attachments:o.state,runConfig:i.runConfig,isEditing:i.isEditing,canCancel:i.canCancel,attachmentAccept:i.attachmentAccept,isEmpty:i.isEmpty,type:(h=i.type)!=null?h:"thread"}},[i,o.state]);return On({getState:()=>c,setText:a.setText,setRole:a.setRole,setRunConfig:a.setRunConfig,addAttachment:a.addAttachment,reset:a.reset,clearAttachments:a.clearAttachments,send:a.send,cancel:a.cancel,beginEdit:(d=a.beginEdit)!=null?d:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:h=>"id"in h?o.api({key:h.id}):o.api(h),__internal_getRuntime:()=>a})}),K1=se(({runtime:t})=>{const n=Zr(t);return On({getState:()=>n,addToolResult:i=>t.addToolResult(i),resumeToolCall:i=>t.resumeToolCall(i),__internal_getRuntime:()=>t},{key:n.type==="tool-call"?`toolCallId-${n.toolCallId}`:void 0})}),J1=se(({runtime:t,index:n})=>{const a=Jt(()=>t.getAttachmentByIndex(n),[t,n]);return zn(op({runtime:a}))}),$1=se(({runtime:t,index:n})=>{const a=Jt(()=>t.getMessagePartByIndex(n),[t,n]);return zn(K1({runtime:a}))}),W1=se(({runtime:t,threadIdRef:n})=>{var v,x;const a=Zr(t),[i,u]=Un(!1),[o,c]=Un(!1),d=Jt(()=>({get current(){return t.getState().id}}),[t]),h=zn(cp({runtime:t.composer,threadIdRef:n,messageIdRef:d})),m=Ui(a.content.map((w,R)=>$1({runtime:t,index:R},{key:R}))),g=Ui((x=(v=a.attachments)==null?void 0:v.map((w,R)=>J1({runtime:t,index:R},{key:R})))!=null?x:[]),y=Jt(()=>G(_({},a),{parts:m.state,composer:h.state,isCopied:i,isHovering:o}),[a,m.state,h.state,i,o]);return On({getState:()=>y,composer:h.api,reload:w=>t.reload(w),speak:()=>t.speak(),stopSpeaking:()=>t.stopSpeaking(),submitFeedback:w=>t.submitFeedback(w),switchToBranch:w=>t.switchToBranch(w),getCopyText:()=>t.unstable_getCopyText(),part:w=>"index"in w?m.api({index:w.index}):m.api({key:`toolCallId-${w.toolCallId}`}),attachment:w=>"id"in w?g.api({key:w.id}):g.api(w),setIsCopied:u,setIsHovering:c,__internal_getRuntime:()=>t},{key:a.id})}),tw=se(({runtime:t,id:n,threadIdRef:a})=>{const i=Jt(()=>t.getMessageById(n),[t,n]);return zn(W1({runtime:i,threadIdRef:a}))}),ew=se(({runtime:t})=>{const n=Zr(t),a=xo();je(()=>{const d=[],h=["run-start","run-end","initialize","model-context-update"];for(const m of h){const g=t.unstable_on(m,()=>{var v;const y=((v=t.getState())==null?void 0:v.threadId)||"unknown";a.emit(`thread.${m}`,{threadId:y})});d.push(g)}return()=>{for(const m of d)m()}},[t]);const i=Jt(()=>({get current(){return t.getState().threadId}}),[t]),u=zn(cp({runtime:t.composer,threadIdRef:i})),o=Ui(n.messages.map(d=>tw({runtime:t,id:d.id,threadIdRef:i},{key:d.id}))),c=Jt(()=>({isDisabled:n.isDisabled,isLoading:n.isLoading,isRunning:n.isRunning,capabilities:n.capabilities,state:n.state,suggestions:n.suggestions,extras:n.extras,speech:n.speech,composer:u.state,messages:o.state}),[n,o,u.state]);return On({getState:()=>c,composer:u.api,append:t.append,startRun:t.startRun,unstable_resumeRun:t.unstable_resumeRun,cancelRun:t.cancelRun,getModelContext:t.getModelContext,export:t.export,import:t.import,reset:t.reset,stopSpeaking:t.stopSpeaking,startVoice:()=>$(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>$(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:d=>"id"in d?o.api({key:d.id}):o.api(d),__internal_getRuntime:()=>t})}),nw=se(({runtime:t,id:n})=>{const a=Jt(()=>t.getItemById(n),[t,n]);return zn(Q1({runtime:a}))}),rw=se(({runtime:t,__internal_assistantRuntime:n})=>{const a=Zr(t),i=zn(ew({runtime:t.main})),u=Ui(Object.keys(a.threadItems).map(c=>nw({runtime:t,id:c},{key:c}))),o=Jt(()=>{var c;return{mainThreadId:a.mainThreadId,newThreadId:(c=a.newThread)!=null?c:null,isLoading:a.isLoading,threadIds:a.threads,archivedThreadIds:a.archivedThreads,threadItems:u.state,main:i.state}},[a,u.state,i.state]);return On({getState:()=>o,thread:()=>i.api,item:c=>{if(c==="main")return u.api({key:o.mainThreadId});if("id"in c)return u.api({key:c.id});const{index:d,archived:h=!1}=c,m=h?o.archivedThreadIds[d]:o.threadIds[d];return u.api({key:m})},switchToThread:c=>{t.switchToThread(c)},switchToNewThread:()=>{t.switchToNewThread()},__internal_getAssistantRuntime:()=>n})}),aw=se(t=>{const n=tp();return je(()=>t.registerModelContextProvider(n),[t,n]),zn(rw({runtime:t.threads,__internal_assistantRuntime:t}))}),wo=t=>{const n=new Map,a=()=>{let i=0;for(const u of n.values())i+=u;t(i)};return{register:()=>{const i=Symbol();return n.set(i,0),{setHeight:u=>{n.get(i)!==u&&(n.set(i,u),a())},unregister:()=>{n.delete(i),a()}}}}},iw=(t={})=>{const n=new Set,a=wo(c=>{o.setState({height:G(_({},o.getState().height),{viewport:c})})}),i=wo(c=>{o.setState({height:G(_({},o.getState().height),{inset:c})})}),u=wo(c=>{o.setState({height:G(_({},o.getState().height),{userMessage:c})})}),o=Ra(()=>{var c;return{isAtBottom:!0,scrollToBottom:({behavior:d="auto"}={})=>{for(const h of n)h({behavior:d})},onScrollToBottom:d=>(n.add(d),()=>{n.delete(d)}),turnAnchor:(c=t.turnAnchor)!=null?c:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:a.register,registerContentInset:i.register,registerUserMessageHeight:u.register}});return o},Hi=t=>t,lw=t=>{const n=So({optional:!0}),[a]=M.useState(()=>iw(t));return M.useEffect(()=>n==null?void 0:n.getState().onScrollToBottom(()=>{a.getState().scrollToBottom()}),[n,a]),M.useEffect(()=>{if(n)return a.subscribe(i=>{n.getState().isAtBottom!==i.isAtBottom&&Hi(n).setState({isAtBottom:i.isAtBottom})})},[a,n]),M.useEffect(()=>{var o;const i={turnAnchor:(o=t.turnAnchor)!=null?o:"bottom"};a.getState().turnAnchor!==i.turnAnchor&&Hi(a).setState(i)},[a,t.turnAnchor]),a},fp=({children:t,options:n={}})=>{const a=lw(n),[i]=M.useState(()=>({useThreadViewport:a}));return E.jsx(lp.Provider,{value:i,children:t})},sw=t=>{var n;return(n=t._core)==null?void 0:n.RenderComponent},uw=({children:t,runtime:n})=>{const a=de({threads:aw(n)}),i=sw(n);return E.jsxs(za,{api:a,children:[i&&E.jsx(i,{}),E.jsx(fp,{children:t})]})},dp=M.memo(uw),ow=({index:t,archived:n,children:a})=>{const i=de(),u=Bi({threadListItem:Ma({source:"threads",query:{type:"index",index:t,archived:n},get:()=>i.threads().item({index:t,archived:n})}),on(o,c){const d=()=>i.threads().item({index:t,archived:n}),{event:h,scope:m}=Ca(o);return Qr("thread-list-item",m)?i.on({scope:"*",event:h},g=>{g.threadId===d().getState().id&&c(g)}):i.on(o,c)}});return E.jsx(za,{api:u,children:a})},cw=({id:t,children:n})=>{const a=de(),i=Bi({threadListItem:Ma({source:"threads",query:{type:"id",id:t},get:()=>a.threads().item({id:t})}),on(u,o){const c=()=>a.threads().item({id:t}),{event:d,scope:h}=Ca(u);return Qr("thread-list-item",h)?a.on({scope:"*",event:d},m=>{m.threadId===c().getState().id&&o(m)}):a.on(u,o)}});return E.jsx(za,{api:i,children:n})},fw=({index:t,children:n})=>{const a=de(),i=Bi({message:Ma({source:"thread",query:{type:"index",index:t},get:()=>a.thread().message({index:t})}),composer:Ma({source:"message",query:{},get:()=>a.thread().message({index:t}).composer}),on(u,o){const c=()=>a.thread().message({index:t}),{event:d,scope:h}=Ca(u);return!Qr("composer",h)&&!Qr("message",h)?a.on(u,o):a.on({scope:"thread",event:d},m=>{m.messageId===c().getState().id&&o(m)})}});return E.jsx(za,{api:i,children:n})},dw=({index:t,children:n})=>{const a=de(),i=Bi({part:Ma({source:"message",query:{type:"index",index:t},get:()=>a.message().part({index:t})})});return E.jsx(za,{api:i,children:n})},hw=se(({text:t,isRunning:n})=>{const a=Jt(()=>({type:"text",text:t,status:n?{type:"running"}:{type:"complete"}}),[t,n]);return On({getState:()=>a,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),pw=({text:t,isRunning:n=!1,children:a})=>{const i=go($h(hw({text:t,isRunning:n}))),u=Bi({part:Ma({source:"root",query:{},get:()=>i.getState().api}),subscribe:i.subscribe,flushSync:i.flushSync});return E.jsx(za,{api:u,children:a})},hp=(t,n)=>{var a,i;return n===void 0?((a=t.status)==null?void 0:a.type)==="requires-action"&&t.status.reason==="tool-calls"&&t.content.every(u=>u.type!=="tool-call"||!!u.result):((i=t.status)==null?void 0:i.type)==="requires-action"&&t.status.reason==="tool-calls"&&t.content.every(u=>u.type!=="tool-call"||!!u.result||!n.includes(u.toolName))},_o=class extends Error{constructor(n,a){super(a);V(this,"name","AbortError");V(this,"detach");this.detach=n}},mw=class extends a1{constructor(n,a){super(n);V(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});V(this,"abortController",null);V(this,"isDisabled",!1);V(this,"_isLoading",!1);V(this,"_suggestions",[]);V(this,"_suggestionsController",null);V(this,"_options");V(this,"_lastRunConfig",{});V(this,"_loadPromise");this.__internal_setOptions(a)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(n){var c,d,h;if(this._options===n)return;this._options=n;let a=!1;const i=((c=n.adapters)==null?void 0:c.speech)!==void 0;this.capabilities.speech!==i&&(this.capabilities.speech=i,a=!0);const u=((d=n.adapters)==null?void 0:d.attachments)!==void 0;this.capabilities.attachments!==u&&(this.capabilities.attachments=u,a=!0);const o=((h=n.adapters)==null?void 0:h.feedback)!==void 0;this.capabilities.feedback!==o&&(this.capabilities.feedback=o,a=!0),a&&this._notifySubscribers()}__internal_load(){var a,i;if(this._loadPromise)return this._loadPromise;const n=(i=(a=this.adapters.history)==null?void 0:a.load())!=null?i:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=n.then(u=>{var c,d;if(!u)return;this.repository.import(u),this._notifySubscribers();const o=(d=(c=this.adapters.history)==null?void 0:c.resume)==null?void 0:d.bind(this.adapters.history);u.unstable_resume&&o&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},o)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(n){return $(this,null,function*(){var u,o,c;this.ensureInitialized();const a=Di(n,Pr(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(n.parentId,a),(u=this._options.adapters.history)==null||u.append(_({parentId:n.parentId,message:a},n.runConfig!==void 0&&{runConfig:n.runConfig})),((o=n.startRun)!=null?o:n.role==="user")?yield this.startRun({parentId:a.id,sourceId:n.sourceId,runConfig:(c=n.runConfig)!=null?c:{}}):(this.repository.resetHead(a.id),this._notifySubscribers())})}resumeRun(i){var u=i,{stream:n}=u,a=gt(u,["stream"]);if(!n)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(a,n)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(u,o){return $(this,arguments,function*({parentId:n,runConfig:a},i){var m,g,y;this.ensureInitialized();let d={id:Pr(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("run-start");try{this._suggestions=[],(m=this._suggestionsController)==null||m.abort(),this._suggestionsController=null,this._notifySubscribers();do d=yield this.performRoundtrip(n,d,a,i),i=void 0;while(hp(d,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const h=this._suggestionsController.signal;if(this.adapters.suggestion&&((g=d.status)==null?void 0:g.type)!=="requires-action"){const N=(y=this.adapters.suggestion)==null?void 0:y.generate({messages:this.messages});if(Symbol.asyncIterator in N)try{for(var v=xa(N),x,w,R;x=!(w=yield v.next()).done;x=!1){const z=w.value;if(h.aborted)break;this._suggestions=z,this._notifySubscribers()}}catch(w){R=[w]}finally{try{x&&(w=v.return)&&(yield w.call(v))}finally{if(R)throw R[0]}}else{const z=yield N;if(h.aborted)return;this._suggestions=z,this._notifySubscribers()}}})}performRoundtrip(n,a,i,u){return $(this,null,function*(){var w,R,N,z,Y,I,nt,it,L,et;const o=n?this.repository.getMessages(n):[];(w=this.abortController)==null||w.abort(),this.abortController=new AbortController;const c=a.content,d=(R=a.metadata)==null?void 0:R.unstable_annotations,h=(N=a.metadata)==null?void 0:N.unstable_data,m=(z=a.metadata)==null?void 0:z.steps,g=(Y=a.metadata)==null?void 0:Y.custom,y=J=>{var Tt,C,k,P,T,st;const bt=(Tt=J.metadata)==null?void 0:Tt.steps,ut=bt?[...m!=null?m:[],...bt]:void 0,rt=(C=J.metadata)==null?void 0:C.unstable_annotations,H=(k=J.metadata)==null?void 0:k.unstable_data,tt=rt?[...d!=null?d:[],...rt]:void 0,ct=H?[...h!=null?h:[],...H]:void 0;a=_(G(_(_({},a),J.content?{content:[...c,...(P=J.content)!=null?P:[]]}:void 0),{status:(T=J.status)!=null?T:a.status}),J.metadata?{metadata:_(_(_(_(_(_({},a.metadata),J.metadata.unstable_state?{unstable_state:J.metadata.unstable_state}:void 0),tt?{unstable_annotations:tt}:void 0),ct?{unstable_data:ct}:void 0),ut?{steps:ut}:void 0),(st=J.metadata)!=null&&st.custom?{custom:_(_({},g!=null?g:{}),J.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(n,a),this._notifySubscribers()},v=(I=this._options.maxSteps)!=null?I:2;if(((L=(it=(nt=a.metadata)==null?void 0:nt.steps)==null?void 0:it.length)!=null?L:0)>=v)return y({status:{type:"incomplete",reason:"tool-calls"}}),a;y({status:{type:"running"}}),this.repository.resetHead(a.id),this._notifySubscribers();try{this._lastRunConfig=i!=null?i:{};const J=this.getModelContext();u=u!=null?u:this.adapters.chatModel.run.bind(this.adapters.chatModel);const bt=this.abortController.signal,ut=u({messages:o,runConfig:this._lastRunConfig,abortSignal:bt,context:J,config:J,unstable_assistantMessageId:a.id,unstable_getMessage(){return a}});if(Symbol.asyncIterator in ut)try{for(var W=xa(ut),ot,ft,j;ot=!(ft=yield W.next()).done;ot=!1){const rt=ft.value;if(bt.aborted){y({status:{type:"incomplete",reason:"cancelled"}});break}y(rt)}}catch(ft){j=[ft]}finally{try{ot&&(ft=W.return)&&(yield ft.call(W))}finally{if(j)throw j[0]}}else y(yield ut);a.status.type==="running"&&y({status:{type:"complete",reason:"unknown"}})}catch(J){if(J instanceof _o)y({status:{type:"incomplete",reason:"cancelled"}});else throw y({status:{type:"incomplete",reason:"error",error:J instanceof Error?J.message:`[${typeof J}] ${new String(J).toString()}`}}),J}finally{this.abortController=null,(a.status.type==="complete"||a.status.type==="incomplete")&&(yield(et=this._options.adapters.history)==null?void 0:et.append({parentId:n,message:a,runConfig:this._lastRunConfig}))}return a})}detach(){var a;const n=new _o(!0);(a=this.abortController)==null||a.abort(n),this.abortController=null}cancelRun(){var a;const n=new _o(!1);(a=this.abortController)==null||a.abort(n),this.abortController=null}addToolResult({messageId:n,toolCallId:a,result:i,isError:u,artifact:o}){const c=this.repository.getMessage(n),{parentId:d}=c;let{message:h}=c;if(h.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let m=!1,g=!1;const y=h.content.map(v=>v.type!=="tool-call"||v.toolCallId!==a?v:(g=!0,v.result||(m=!0),G(_({},v),{result:i,artifact:o,isError:u})));if(!g)throw new Error("Tried to add tool result to non-existing tool call");h=G(_({},h),{content:y}),this.repository.addOrUpdateMessage(d,h),m&&hp(h,this._options.unstable_humanToolNames)&&this.performRoundtrip(d,h,this._lastRunConfig)}resumeToolCall(n){throw new Error("Local runtime does not support resuming tool calls.")}},pp=Object.freeze([]),To="__DEFAULT_ID__",gw=Object.freeze({[To]:{id:To,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),yw=class extends zi{constructor(n){super();V(this,"_mainThread");this._mainThread=n()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw pp}get archivedThreadIds(){throw pp}get mainThreadId(){return To}get threadData(){return gw}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getLoadThreadsPromise(){throw new Error("Method not implemented.")}getItemById(n){if(n===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw new Error("Method not implemented")}switchToThread(){return $(this,null,function*(){throw new Error("Method not implemented.")})}switchToNewThread(){throw new Error("Method not implemented.")}rename(){throw new Error("Method not implemented.")}archive(){throw new Error("Method not implemented.")}detach(){throw new Error("Method not implemented.")}unarchive(){throw new Error("Method not implemented.")}delete(){throw new Error("Method not implemented.")}initialize(n){return Promise.resolve({remoteId:n,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}},bw=class extends lo{constructor(n,a){super();V(this,"threads");V(this,"Provider");V(this,"_options");this._options=n,this.threads=new yw(()=>new mw(this._contextProvider,this._options)),a&&this.threads.getMainThreadRuntimeCore().import(fo.fromArray(a))}},mp=t=>{try{const a=t.split(".")[1];if(!a)throw new Error("Invalid JWT format");let i=a.replace(/-/g,"+").replace(/_/g,"/");for(;i.length%4!==0;)i+="=";const u=atob(i),c=JSON.parse(u).exp;if(!c||typeof c!="number")throw new Error('JWT does not contain a valid "exp" field');return c*1e3}catch(n){throw new Error("Unable to determine the token expiry: "+n)}},gp=(gy=class{constructor(t){V(this,"strategy","jwt");V(this,"cachedToken",null);V(this,"tokenExpiry",null);ki(this,tl);Ri(this,tl,t)}getAuthHeaders(){return $(this,null,function*(){const t=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-t>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const n=yield hn(this,tl).call(this);return n?(this.cachedToken=n,this.tokenExpiry=mp(n),{Authorization:`Bearer ${n}`}):!1})}readAuthHeaders(t){const n=t.get("Authorization");if(!n)return;const[a,i]=n.split(" ");if(a!=="Bearer"||!i)throw new Error("Invalid auth header received");this.cachedToken=i,this.tokenExpiry=mp(i)}},tl=new WeakMap,gy),vw=(yy=class{constructor(t,n,a){V(this,"strategy","api-key");ki(this,el);ki(this,nl);ki(this,rl);Ri(this,el,t),Ri(this,nl,n),Ri(this,rl,a)}getAuthHeaders(){return $(this,null,function*(){return{Authorization:`Bearer ${hn(this,el)}`,"Aui-User-Id":hn(this,nl),"Aui-Workspace-Id":hn(this,rl)}})}readAuthHeaders(){}},el=new WeakMap,nl=new WeakMap,rl=new WeakMap,yy),hs="aui:refresh_token",xw=class{constructor(t){V(this,"strategy","anon");V(this,"baseUrl");V(this,"jwtStrategy");this.baseUrl=t,this.jwtStrategy=new gp(()=>$(this,null,function*(){const n=Date.now(),a=localStorage.getItem(hs),i=a?JSON.parse(a):void 0;if(i)if(new Date(i.expires_at).getTime()-n>30*1e3){const m=yield fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:i.token})});if(m.ok){const g=yield m.json(),{access_token:y,refresh_token:v}=g;return v&&localStorage.setItem(hs,JSON.stringify(v)),y}}else localStorage.removeItem(hs);const u=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!u.ok)return null;const o=yield u.json(),{access_token:c,refresh_token:d}=o;return!c||!d?null:(localStorage.setItem(hs,JSON.stringify(d)),c)}))}getAuthHeaders(){return $(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(t){this.jwtStrategy.readAuthHeaders(t)}},Sw=class extends Error{constructor(t){super(t),this.name="APIError"}},ww=class{constructor(t){V(this,"_auth");V(this,"_baseUrl");if("authToken"in t)this._baseUrl=t.baseUrl,this._auth=new gp(t.authToken);else if("apiKey"in t)this._baseUrl="https://backend.assistant-api.com",this._auth=new vw(t.apiKey,t.userId,t.workspaceId);else if("anonymous"in t)this._baseUrl=t.baseUrl,this._auth=new xw(t.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return $(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(a){return $(this,arguments,function*(t,n={}){var h;const i=yield this._auth.getAuthHeaders();if(!i)throw new Error("Authorization failed");const u=G(_(_({},i),n.headers),{"Content-Type":"application/json"}),o=new URLSearchParams;if(n.query)for(const[m,g]of Object.entries(n.query))g!==!1&&(g===!0?o.set(m,"true"):o.set(m,g.toString()));const c=new URL(`${this._baseUrl}/v1${t}`);c.search=o.toString();const d=yield fetch(c,{method:(h=n.method)!=null?h:"GET",headers:u,body:n.body?JSON.stringify(n.body):null});if(this._auth.readAuthHeaders(d.headers),!d.ok){const m=yield d.text();try{const g=JSON.parse(m);throw new Sw(g.message)}catch(g){throw new Error(`Request failed with status ${d.status}, ${m}`)}}return d})}makeRequest(a){return $(this,arguments,function*(t,n={}){return(yield this.makeRawRequest(t,n)).json()})}},_w=class{constructor(t){this.cloud=t}create(){return $(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},Tw=class{constructor(t){this.cloud=t}__internal_getAssistantOptions(t){return{api:this.cloud._baseUrl+"/v1/runs/stream",headers:()=>$(this,null,function*(){const n=yield this.cloud._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");return G(_({},n),{Accept:"text/plain"})}),body:{assistant_id:t,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(t){return $(this,null,function*(){const n=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:t});return oo.fromResponse(n,new N0)})}},Ew=class{constructor(t){this.cloud=t}list(t,n){return $(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}/messages`,{query:n})})}create(t,n){return $(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:n})})}},Cw=class{constructor(t){V(this,"messages");this.cloud=t,this.messages=new Ew(t)}list(t){return $(this,null,function*(){return this.cloud.makeRequest("/threads",{query:t})})}get(t){return $(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`)})}create(t){return $(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:t})})}update(t,n){return $(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`,{method:"PUT",body:n})})}delete(t){return $(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`,{method:"DELETE"})})}},Aw=class{constructor(t){this.cloud=t}pdfToImages(t){return $(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:t})})}generatePresignedUploadUrl(t){return $(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:t})})}},kw=class{constructor(t){V(this,"threads");V(this,"auth");V(this,"runs");V(this,"files");const n=new ww(t);this.threads=new Cw(n),this.auth={tokens:new _w(n)},this.runs=new Tw(n),this.files=new Aw(n)}};function Eo(t,n=0){return n>100?!1:t===null||typeof t=="string"||typeof t=="boolean"?!0:typeof t=="number"?!Number.isNaN(t)&&Number.isFinite(t):Array.isArray(t)?t.every(a=>Eo(a,n+1)):typeof t=="object"?Object.entries(t).every(([a,i])=>typeof a=="string"&&Eo(i,n+1)):!1}var Rw=t=>{var n;return _({role:t.role,content:t.content.map(a=>{const i=a.type;switch(i){case"text":return{type:"text",text:a.text};case"reasoning":return{type:"reasoning",text:a.text};case"source":return _({type:"source",sourceType:a.sourceType,id:a.id,url:a.url},a.title?{title:a.title}:void 0);case"tool-call":return Eo(a.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(a)}`),_(_(_({type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName},JSON.stringify(a.args)===a.argsText?{args:a.args}:{argsText:a.argsText}),a.result?{result:a.result}:{}),a.isError?{isError:!0}:{});default:{const u=i;throw new Error(`Message part type not supported by aui/v0: ${u}`)}}}),metadata:t.metadata},t.status?{status:((n=t.status)==null?void 0:n.type)==="running"?{type:"incomplete",reason:"cancelled"}:t.status}:void 0)},Mw=t=>{const n=t.content,a=Di(_({id:t.id,createdAt:t.created_at},n),t.id,{type:"complete",reason:"unknown"});return{parentId:t.parent_id,message:a}},Co=new WeakMap,zw=class{constructor(t,n){this.parent=t,this.formatAdapter=n}append(t){return $(this,null,function*(){const n=this.formatAdapter.encode(t),a=this.formatAdapter.getId(t.message);return this.parent._appendWithFormat(t.parentId,a,this.formatAdapter.format,n)})}load(){return $(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,t=>this.formatAdapter.decode(t))})}},Ow=class{constructor(t,n){this.cloudRef=t,this.store=n}get _getIdForLocalId(){return Co.has(this.store.threadListItem())||Co.set(this.store.threadListItem(),{}),Co.get(this.store.threadListItem())}withFormat(t){return new zw(this,t)}append(a){return $(this,arguments,function*({parentId:t,message:n}){var o;const{remoteId:i}=yield this.store.threadListItem().initialize(),u=this.cloudRef.current.threads.messages.create(i,{parent_id:t?(o=yield this._getIdForLocalId[t])!=null?o:t:null,format:"aui/v0",content:Rw(n)}).then(({message_id:c})=>(this._getIdForLocalId[n.id]=c,c));return this._getIdForLocalId[n.id]=u,u.then(()=>{})})}load(){return $(this,null,function*(){const t=this.store.threadListItem().getState().remoteId;if(!t)return{messages:[]};const{messages:n}=yield this.cloudRef.current.threads.messages.list(t,{format:"aui/v0"});return{messages:n.filter(i=>i.format==="aui/v0").map(Mw).reverse()}})}_appendWithFormat(t,n,a,i){return $(this,null,function*(){var c;const{remoteId:u}=yield this.store.threadListItem().initialize(),o=this.cloudRef.current.threads.messages.create(u,{parent_id:t?(c=yield this._getIdForLocalId[t])!=null?c:t:null,format:a,content:i}).then(({message_id:d})=>(this._getIdForLocalId[n]=d,d));return this._getIdForLocalId[n]=o,o.then(()=>{})})}_loadWithFormat(t,n){return $(this,null,function*(){const a=this.store.threadListItem().getState().remoteId;if(!a)return{messages:[]};const{messages:i}=yield this.cloudRef.current.threads.messages.list(a,{format:t});return{messages:i.filter(u=>u.format===t).map(u=>n({id:u.id,parent_id:u.parent_id,format:u.format,content:u.content})).reverse()}})}},Dw=t=>{const n=de(),[a]=M.useState(()=>new Ow(t,n));return a},yp=typeof process!="undefined"&&((by=process==null?void 0:process.env)==null?void 0:by.NEXT_PUBLIC_ASSISTANT_BASE_URL),Ao=yp?new kw({baseUrl:yp,anonymous:!0}):void 0,Nw=t=>{var u;const n=M.useRef(t);M.useEffect(()=>{n.current=t},[t]);const a=M.useCallback(function({children:c}){var y;const d=Dw({get current(){var v;return(v=n.current.cloud)!=null?v:Ao}}),h=(y=n.current.cloud)!=null?y:Ao,m=M.useMemo(()=>new e1(h),[h]),g=M.useMemo(()=>({history:d,attachments:m}),[d,m]);return E.jsx(Hh,{adapters:g,children:c})},[]),i=(u=t.cloud)!=null?u:Ao;return i?{list:()=>$(null,null,function*(){const{threads:o}=yield i.threads.list();return{threads:o.map(c=>{var d;return{status:c.is_archived?"archived":"regular",remoteId:c.id,title:c.title,externalId:(d=c.external_id)!=null?d:void 0}})}}),initialize:()=>$(null,null,function*(){var m,g;const c=yield(g=(m=t.create)==null?void 0:m.call(t))!=null?g:Promise.resolve(),d=c?c.externalId:void 0,{thread_id:h}=yield i.threads.create({last_message_at:new Date,external_id:d});return{externalId:d,remoteId:h}}),rename:(o,c)=>$(null,null,function*(){return i.threads.update(o,{title:c})}),archive:o=>$(null,null,function*(){return i.threads.update(o,{is_archived:!0})}),unarchive:o=>$(null,null,function*(){return i.threads.update(o,{is_archived:!1})}),delete:o=>$(null,null,function*(){var c;return yield(c=t.delete)==null?void 0:c.call(t,o),i.threads.delete(o)}),generateTitle:(o,c)=>$(null,null,function*(){return i.runs.stream({thread_id:o,assistant_id:"system/thread_title",messages:c})}),fetch:o=>$(null,null,function*(){var d;const c=yield i.threads.get(o);return{status:c.is_archived?"archived":"regular",remoteId:c.id,title:c.title,externalId:(d=c.external_id)!=null?d:void 0}}),unstable_Provider:a}:new s1},Iw=(t,i)=>{var u=i,{initialMessages:n}=u,a=gt(u,["initialMessages"]);var m;const g=(m=n1())!=null?m:{},{modelContext:o}=g,c=gt(g,["modelContext"]),d=M.useMemo(()=>G(_({},a),{adapters:G(_(_({},c),a.adapters),{chatModel:t})}),[t,a,c]),[h]=M.useState(()=>new bw(d,n));return M.useEffect(()=>()=>{h.threads.getMainThreadRuntimeCore().detach()},[h]),M.useEffect(()=>{h.threads.getMainThreadRuntimeCore().__internal_setOptions(d),h.threads.getMainThreadRuntimeCore().__internal_load()},[h,d]),M.useEffect(()=>{if(o)return h.registerModelContextProvider(o)},[o,h]),M.useMemo(()=>new ko(h),[h])},bp=(t,i={})=>{var u=i,{cloud:n}=u,a=gt(u,["cloud"]);const o=Nw({cloud:n});return _p({runtimeHook:function(){return Iw(t,a)},adapter:o,allowNesting:!0})},ko=class{constructor(t){V(this,"threads");V(this,"_thread");this._core=t,this.threads=new W0(t.threads),this._thread=this.threads.main,this.__internal_bindMethods()}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(fo.fromArray(t!=null?t:[]))}},jw=t=>{const d=t,{cloud:n,initialMessages:a,maxSteps:i,adapters:u,unstable_humanToolNames:o}=d,c=gt(d,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:n,initialMessages:a,maxSteps:i,adapters:u,unstable_humanToolNames:o},otherOptions:c}};function Kr(t){const n=M.useRef(t);return M.useEffect(()=>{n.current=t}),M.useMemo(()=>(...a)=>{var i;return(i=n.current)==null?void 0:i.call(n,...a)},[])}var vp=M.createContext(null),Lw=t=>({useSmoothStatus:Ra(()=>t)}),Bw=({children:t})=>{const n=xp({optional:!0}),a=de(),[i]=M.useState(()=>Lw(a.part().getState().status));return n?t:E.jsx(vp.Provider,{value:i,children:t})},Uw=t=>{const n=M.forwardRef((a,i)=>E.jsx(Bw,{children:E.jsx(t,G(_({},a),{ref:i}))}));return n.displayName=t.displayName,n};function xp(t){const n=M.useContext(vp);if(!(t!=null&&t.optional)&&!n)throw new Error("This component must be used within a SmoothContextProvider.");return n}var{useSmoothStatus:Hw,useSmoothStatusStore:qw}=ip(xp,"useSmoothStatus"),Vw=class{constructor(t,n){V(this,"animationFrameId",null);V(this,"lastUpdateTime",Date.now());V(this,"targetText","");V(this,"animate",()=>{const t=Date.now();let a=t-this.lastUpdateTime;const i=this.targetText.length-this.currentText.length,u=Math.min(5,250/i);let o=0;for(;a>=u&&o<i;)o++,a-=u;o!==i?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,o!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+o),this.lastUpdateTime=t-a,this.setText(this.currentText))});this.currentText=t,this.setText=n}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}},Ro=Object.freeze({type:"running"}),Sp=(t,n=!1)=>{const{text:a}=t,i=ne(({message:g})=>g.id),u=M.useRef(i),[o,c]=M.useState(a),d=qw({optional:!0}),h=Kr(g=>{if(c(g),d){const y=o!==g||t.status.type==="running"?Ro:t.status;Hi(d).setState(y,!0)}});M.useEffect(()=>{if(d){const g=n&&(o!==a||t.status.type==="running")?Ro:t.status;Hi(d).setState(g,!0)}},[d,n,a,o,t.status]);const[m]=M.useState(new Vw(a,h));return M.useEffect(()=>{if(!n){m.stop();return}if(u.current!==i||!a.startsWith(m.targetText)){u.current=i,h(a),m.currentText=a,m.targetText=a,m.stop();return}m.targetText=a,m.start()},[h,m,i,n,a]),M.useEffect(()=>()=>{m.stop()},[m]),M.useMemo(()=>n?{type:"text",text:o,status:a===o?t.status:Ro}:t,[n,o,t,a])};const Yw=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:ko,BaseAssistantRuntimeCore:lo,CompositeContextProvider:io,DefaultThreadComposerRuntimeCore:fh,MessageRepository:Eh,ThreadRuntimeImpl:Uh,fromThreadMessageLike:Di,generateId:Pr,getAutoStatus:hh,splitLocalRuntimeOptions:jw,useSmooth:Sp,useSmoothStatus:Hw,useToolInvocations:l1,withSmoothContextProvider:Uw},Symbol.toStringTag,{value:"Module"}));var Fw=class extends zi{constructor(n){super();V(this,"useRuntimeHook");V(this,"instances",new Map);V(this,"useAliveThreadsKeysChanged",Ra(()=>({})));V(this,"_InnerActiveThreadProvider",({threadId:n})=>{const{useRuntime:a}=this.useRuntimeHook(),i=a(),u=i.thread.__internal_threadBinding,o=M.useCallback(()=>{const h=this.instances.get(n);if(!h)throw new Error("Thread not found. This is a bug in assistant-ui.");h.runtime=u.getState(),this._notifySubscribers()},[n,u]),c=M.useRef(!1);c.current||o(),M.useEffect(()=>(c.current=!0,o(),u.outerSubscribe(o)),[u,o]);const d=de();return M.useEffect(()=>i.threads.main.unstable_on("initialize",()=>{if(d.threadListItem().getState().status==="new"){d.threadListItem().initialize();const m=i.thread.unstable_on("run-end",()=>{m(),d.threadListItem().generateTitle()})}}),[i,d]),null});V(this,"_OuterActiveThreadProvider",M.memo(({threadId:n,provider:a})=>E.jsx(cw,{id:n,children:E.jsx(a,{children:E.jsx(this._InnerActiveThreadProvider,{threadId:n})})})));V(this,"__internal_RenderThreadRuntimes",({provider:n})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(a=>E.jsx(this._OuterActiveThreadProvider,{threadId:a,provider:n},a))));this.useRuntimeHook=Ra(()=>({useRuntime:n}))}startThreadRuntime(n){return this.instances.has(n)||(this.instances.set(n,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((a,i)=>{const u=()=>{const c=this.instances.get(n);if(!c)o(),i(new Error("Thread was deleted before runtime was started"));else if(c.runtime)o(),a(c.runtime);else return},o=this.subscribe(u);u()})}getThreadRuntimeCore(n){const a=this.instances.get(n);if(a)return a.runtime}stopThreadRuntime(n){this.instances.delete(n),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(n){this.useRuntimeHook.getState().useRuntime!==n&&this.useRuntimeHook.setState({useRuntime:n},!0)}},he=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),Gw={getMessageById(){},getBranches(){return[]},switchToBranch(){throw he},append(){throw he},startRun(){throw he},resumeRun(){throw he},cancelRun(){throw he},addToolResult(){throw he},resumeToolCall(){throw he},speak(){throw he},stopSpeaking(){throw he},submitFeedback(){throw he},getModelContext(){return{}},unstable_loadExternalState(){throw he},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return $(this,null,function*(){throw he})},removeAttachment(){return $(this,null,function*(){throw he})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw he},role:"user",setRole(){throw he},runConfig:{},setRunConfig(){throw he},reset(){return $(this,null,function*(){})},clearAttachments(){return $(this,null,function*(){})},send(){throw he},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw he},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw he},export(){return{messages:[]}},reset(){throw he},unstable_on(){return()=>{}}},wp=(t,n,a)=>a.reduce((i,u)=>{var o;return(o=u==null?void 0:u(i,n))!=null?o:i},t),Pw=class extends zi{constructor(n){super();V(this,"_pendingTransforms",[]);V(this,"_baseValue");V(this,"_cachedValue");this._baseValue=n,this._cachedValue=n}_updateState(){this._cachedValue=this._pendingTransforms.reduce((n,a)=>wp(n,a.task,[a.loading,a.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(n){this._baseValue=n,this._updateState()}optimisticUpdate(n){return $(this,null,function*(){const a=n.execute(),i=G(_({},n),{task:a});try{this._pendingTransforms.push(i),this._updateState();const u=yield a;return this._baseValue=wp(this._baseValue,u,[n.optimistic,n.then]),u}finally{const u=this._pendingTransforms.indexOf(i);u>-1&&this._pendingTransforms.splice(u,1),this._updateState()}})}};function SO(t){return t}var ps=(t,n)=>{const a=t.threadIdMap[n];if(a!==void 0)return t.threadData[a]},ms=(t,n,a)=>{const i=ps(t,n);if(!i)return t;const{id:u,remoteId:o,status:c}=i;if(c===a)return t;const d=_({},t);switch(c){case"new":d.newThreadId=void 0;break;case"regular":d.threadIds=d.threadIds.filter(h=>h!==u);break;case"archived":d.archivedThreadIds=d.archivedThreadIds.filter(h=>h!==u);break;default:{const h=c;throw new Error(`Unsupported state: ${h}`)}}switch(a){case"regular":d.threadIds=[u,...d.threadIds];break;case"archived":d.archivedThreadIds=[u,...d.archivedThreadIds];break;case"deleted":d.threadData=Object.fromEntries(Object.entries(d.threadData).filter(([h])=>h!==u)),d.threadIdMap=Object.fromEntries(Object.entries(d.threadIdMap).filter(([h])=>h!==u&&h!==o));break;default:{const h=a;throw new Error(`Unsupported state: ${h}`)}}return a!=="deleted"&&(d.threadData=G(_({},d.threadData),{[u]:G(_({},i),{status:a})})),d},Xw=class extends zi{constructor(n,a){super();V(this,"_options");V(this,"_hookManager");V(this,"_loadThreadsPromise");V(this,"_mainThreadId");V(this,"_state",new Pw({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));V(this,"useProvider");V(this,"initialize",n=>$(this,null,function*(){if(this._state.value.newThreadId!==n){const a=this.getItemById(n);if(!a)throw new Error("Thread not found");if(a.status==="new")throw new Error("Unexpected new state");return a.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(n),optimistic:a=>ms(a,n,"regular"),loading:(a,i)=>{const u=n;return G(_({},a),{threadData:G(_({},a.threadData),{[u]:G(_({},a.threadData[u]),{initializeTask:i})})})},then:(a,{remoteId:i,externalId:u})=>{const o=ps(a,n);if(!o)return a;const c=n;return G(_({},a),{threadIdMap:G(_({},a.threadIdMap),{[i]:c}),threadData:G(_({},a.threadData),{[c]:G(_({},o),{initializeTask:Promise.resolve({remoteId:i,externalId:u}),remoteId:i,externalId:u})})})}})}));V(this,"generateTitle",n=>$(this,null,function*(){var h;const a=this.getItemById(n);if(!a)throw new Error("Thread not found");if(a.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:i}=yield a.initializeTask,u=this._hookManager.getThreadRuntimeCore(a.id);if(!u)return;const o=u.messages,c=yield this._options.adapter.generateTitle(i,o),d=I0.fromAssistantStream(c);try{for(var m=xa(d),g,y,v;g=!(y=yield m.next()).done;g=!1){const x=y.value;const w=(h=x.parts.filter(N=>N.type==="text")[0])==null?void 0:h.text,R=this._state.baseValue;this._state.update(G(_({},R),{threadData:G(_({},R.threadData),{[a.id]:G(_({},a),{title:w})})}))}}catch(y){v=[y]}finally{try{g&&(y=m.return)&&(yield y.call(m))}finally{if(v)throw v[0]}}}));V(this,"useBoundIds",Ra(()=>[]));V(this,"__internal_RenderComponent",()=>{const n=M.useId();M.useEffect(()=>(this.useBoundIds.setState(o=>[...o,n],!0),()=>{this.useBoundIds.setState(o=>o.filter(c=>c!==n),!0)}),[n]);const a=this.useBoundIds(),{Provider:i}=this.useProvider(),u={modelContext:this.contextProvider};return(a.length===0||a[0]===n)&&E.jsx(Hh,{adapters:u,children:E.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:i})})});this.contextProvider=a,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new Fw(n.runtimeHook),this.useProvider=Ra(()=>{var i;return{Provider:(i=n.adapter.unstable_Provider)!=null?i:M.Fragment}}),this.__internal_setOptions(n),this.switchToNewThread()}get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:n=>G(_({},n),{isLoading:!0}),then:(n,a)=>{const i=[],u=[],o={},c={};for(const d of a.threads){switch(d.status){case"regular":i.push(d.remoteId);break;case"archived":u.push(d.remoteId);break;default:{const m=d.status;throw new Error(`Unsupported state: ${m}`)}}const h=d.remoteId;o[d.remoteId]=h,c[h]={id:d.remoteId,remoteId:d.remoteId,externalId:d.externalId,status:d.status,title:d.title,initializeTask:Promise.resolve({remoteId:d.remoteId,externalId:d.externalId})}}return G(_({},n),{threadIds:i,archivedThreadIds:u,threadIdMap:_(_({},n.threadIdMap),o),threadData:_(_({},n.threadData),c)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(n){var i;if(this._options===n)return;this._options=n;const a=(i=n.adapter.unstable_Provider)!=null?i:M.Fragment;a!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:a},!0),this._hookManager.setRuntimeHook(n.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const n=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return n||Gw}getThreadRuntimeCore(n){const a=this.getItemById(n);if(!a)throw new Error("Thread not found");const i=this._hookManager.getThreadRuntimeCore(a.id);if(!i)throw new Error("Thread not found");return i}getItemById(n){return ps(this._state.value,n)}switchToThread(n){return $(this,null,function*(){let a=this.getItemById(n);if(!a){const u=yield this._options.adapter.fetch(n),o=this._state.value,c=u.remoteId,d=G(_({},o.threadData),{[c]:{id:c,initializeTask:Promise.resolve({remoteId:u.remoteId,externalId:u.externalId}),remoteId:u.remoteId,externalId:u.externalId,status:u.status,title:u.title}}),h=G(_({},o.threadIdMap),{[u.remoteId]:c}),m=u.status==="regular"?[...o.threadIds,u.remoteId]:o.threadIds,g=u.status==="archived"?[...o.archivedThreadIds,u.remoteId]:o.archivedThreadIds;this._state.update(G(_({},o),{threadIds:m,archivedThreadIds:g,threadIdMap:h,threadData:d})),a=this.getItemById(n)}if(!a)throw new Error("Thread not found");if(this._mainThreadId===a.id)return;const i=this._hookManager.startThreadRuntime(a.id);this.mainThreadId!==void 0?yield i:i.then(()=>this._notifySubscribers()),a.status==="archived"&&(yield this.unarchive(a.id)),this._mainThreadId=a.id,this._notifySubscribers()})}switchToNewThread(){return $(this,null,function*(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)yield this._state.waitForUpdate();const n=this._state.value;let a=this._state.value.newThreadId;if(a===void 0){do a=`__LOCALID_${Pr()}`;while(n.threadIdMap[a]);const i=a;this._state.update(G(_({},n),{newThreadId:a,threadIdMap:G(_({},n.threadIdMap),{[a]:i}),threadData:G(_({},n.threadData),{[i]:{status:"new",id:a,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(a)})}rename(n,a){const i=this.getItemById(n);if(!i)throw new Error("Thread not found");if(i.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>$(this,null,function*(){const{remoteId:u}=yield i.initializeTask;return this._options.adapter.rename(u,a)}),optimistic:u=>{const o=ps(u,n);return o?G(_({},u),{threadData:G(_({},u.threadData),{[o.id]:G(_({},o),{title:a})})}):u}})}_ensureThreadIsNotMain(n){return $(this,null,function*(){if(n===this.newThreadId)throw new Error("Cannot ensure new thread is not main");n===this._mainThreadId&&(yield this.switchToNewThread())})}archive(n){return $(this,null,function*(){const a=this.getItemById(n);if(!a)throw new Error("Thread not found");if(a.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>$(this,null,function*(){yield this._ensureThreadIsNotMain(a.id);const{remoteId:i}=yield a.initializeTask;return this._options.adapter.archive(i)}),optimistic:i=>ms(i,a.id,"archived")})})}unarchive(n){const a=this.getItemById(n);if(!a)throw new Error("Thread not found");if(a.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>$(this,null,function*(){try{const{remoteId:i}=yield a.initializeTask;return yield this._options.adapter.unarchive(i)}catch(i){throw yield this._ensureThreadIsNotMain(a.id),i}}),optimistic:i=>ms(i,a.id,"regular")})}delete(n){return $(this,null,function*(){const a=this.getItemById(n);if(!a)throw new Error("Thread not found");if(a.status!=="regular"&&a.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>$(this,null,function*(){yield this._ensureThreadIsNotMain(a.id);const{remoteId:i}=yield a.initializeTask;return yield this._options.adapter.delete(i)}),optimistic:i=>ms(i,a.id,"deleted")})})}detach(n){return $(this,null,function*(){const a=this.getItemById(n);if(!a)throw new Error("Thread not found");if(a.status!=="regular"&&a.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(a.id),this._hookManager.stopThreadRuntime(a.id)})}},Qw=class extends lo{constructor(n){super();V(this,"threads");this.threads=new Xw(n,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Zw=t=>{const[n]=M.useState(()=>new Qw(t));return M.useEffect(()=>{n.threads.__internal_setOptions(t),n.threads.__internal_load()},[n,t]),M.useMemo(()=>new ko(n),[n])},_p=t=>{if(fs().threadListItem.source!==null){if(!t.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return t.runtimeHook()}return Zw(t)},Kw=Symbol.for("react.lazy"),gs=wS[" use ".trim().toString()];function Jw(t){return typeof t=="object"&&t!==null&&"then"in t}function Tp(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===Kw&&"_payload"in t&&Jw(t._payload)}function Ep(t){const n=$w(t),a=M.forwardRef((i,u)=>{let m=i,{children:o}=m,c=gt(m,["children"]);Tp(o)&&typeof gs=="function"&&(o=gs(o._payload));const d=M.Children.toArray(o),h=d.find(t_);if(h){const g=h.props.children,y=d.map(v=>v===h?M.Children.count(g)>1?M.Children.only(null):M.isValidElement(g)?g.props.children:null:v);return E.jsx(n,G(_({},c),{ref:u,children:M.isValidElement(g)?M.cloneElement(g,void 0,y):null}))}return E.jsx(n,G(_({},c),{ref:u,children:o}))});return a.displayName=`${t}.Slot`,a}var Cp=Ep("Slot");function $w(t){const n=M.forwardRef((a,i)=>{let c=a,{children:u}=c,o=gt(c,["children"]);if(Tp(u)&&typeof gs=="function"&&(u=gs(u._payload)),M.isValidElement(u)){const d=n_(u),h=e_(o,u.props);return u.type!==M.Fragment&&(h.ref=i?Jh(i,d):d),M.cloneElement(u,h)}return M.Children.count(u)>1?M.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var Ww=Symbol("radix.slottable");function t_(t){return M.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Ww}function e_(t,n){const a=_({},n);for(const i in n){const u=t[i],o=n[i];/^on[A-Z]/.test(i)?u&&o?a[i]=(...d)=>{const h=o(...d);return u(...d),h}:u&&(a[i]=u):i==="style"?a[i]=_(_({},u),o):i==="className"&&(a[i]=[u,o].filter(Boolean).join(" "))}return _(_({},t),a)}function n_(t){var i,u;let n=(i=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:i.get,a=n&&"isReactWarning"in n&&n.isReactWarning;return a?t.ref:(n=(u=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:u.get,a=n&&"isReactWarning"in n&&n.isReactWarning,a?t.props.ref:t.props.ref||t.ref)}var r_=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Xn=r_.reduce((t,n)=>{const a=Ep(`Primitive.${n}`),i=M.forwardRef((u,o)=>{const m=u,{asChild:c}=m,d=gt(m,["asChild"]),h=c?a:n;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(h,G(_({},d),{ref:o}))});return i.displayName=`Primitive.${n}`,G(_({},t),{[n]:i})},{});function Oa(t,n,{checkForDefaultPrevented:a=!0}={}){return function(u){if(t==null||t(u),a===!1||!u.defaultPrevented)return n==null?void 0:n(u)}}var Mo=(t,n,a=[])=>{const i=M.forwardRef((u,o)=>{var m;const c={},d={};Object.keys(u).forEach(g=>{a.includes(g)?c[g]=u[g]:d[g]=u[g]});const h=(m=n(c))!=null?m:void 0;return E.jsx(Xn.button,G(_({type:"button"},d),{ref:o,disabled:d.disabled||!h,onClick:Oa(d.onClick,h)}))});return i.displayName=t,i};function a_(t,n=globalThis==null?void 0:globalThis.document){const a=Kr(t);M.useEffect(()=>{const i=u=>{u.key==="Escape"&&a(u)};return n.addEventListener("keydown",i,{capture:!0}),()=>n.removeEventListener("keydown",i,{capture:!0})},[a,n])}var qi=t=>{const n=M.useRef(void 0);return M.useCallback(i=>{n.current&&n.current(),i&&(n.current=t(i))},[t])},Ap=(t,n)=>{const a=M.useCallback(i=>{if(!t)return;const u=t(),o=()=>{const d=n?n(i):i.offsetHeight;u.setHeight(d)},c=new ResizeObserver(o);return c.observe(i),o(),()=>{c.disconnect(),u.unregister()}},[t,n]);return qi(a)},kp=M.createContext(!1),Rp=(t,n)=>{const a=t.match(/^([\d.]+)(em|px|rem)$/);if(!a)return 0;const i=parseFloat(a[1]),u=a[2];if(u==="px")return i;if(u==="em"){const o=parseFloat(getComputedStyle(n).fontSize)||16;return i*o}if(u==="rem"){const o=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return i*o}return 0},Mp=({children:t,fillClampThreshold:n="10em",fillClampOffset:a="6em"})=>{const i=ne(({message:h})=>h.isLast),u=So({optional:!0}),o=M.useContext(kp),c=M.useCallback(h=>{if(!u||o)return;const m=()=>{const g=u.getState();if(g.turnAnchor==="top"&&i){const{viewport:y,inset:v,userMessage:x}=g.height,w=Rp(n,h),R=Rp(a,h),N=x<=w?x:R,z=Math.max(0,y-v-N);h.style.minHeight=`${z}px`,h.style.flexShrink="0",h.style.transition="min-height 0s"}else h.style.minHeight="",h.style.flexShrink="",h.style.transition=""};return m(),u.subscribe(m)},[u,i,o,n,a]),d=qi(c);return E.jsx(kp.Provider,{value:!0,children:E.jsx(Cp,{ref:d,children:t})})};Mp.displayName="ThreadPrimitive.ViewportSlack";var i_=()=>{const t=de(),n=ne(()=>t.message()),a=M.useCallback(i=>{const u=()=>{n.setIsHovering(!0)},o=()=>{n.setIsHovering(!1)};return i.addEventListener("mouseenter",u),i.addEventListener("mouseleave",o),i.matches(":hover")&&n.setIsHovering(!0),()=>{i.removeEventListener("mouseenter",u),i.removeEventListener("mouseleave",o),n.setIsHovering(!1)}},[n]);return qi(a)},l_=()=>{const t=ds(u=>u.turnAnchor),n=ds(u=>u.registerUserMessageHeight),a=ne(({thread:u,message:o})=>{var c;return t==="top"&&o.role==="user"&&o.index===u.messages.length-2&&((c=u.messages.at(-1))==null?void 0:c.role)==="assistant"}),i=M.useCallback(u=>u.offsetHeight,[]);return Ap(a?n:null,i)},zo=M.forwardRef((t,n)=>{const a=i_(),i=l_(),u=cs(n,a,i);return E.jsx(Mp,{children:E.jsx(Xn.div,G(_({},t),{ref:u}))})});zo.displayName="MessagePrimitive.Root";var zp=()=>ne(({part:n})=>{if(n.type!=="text"&&n.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return n}),Op=M.forwardRef((u,i)=>{var o=u,{smooth:t=!0,component:n="span"}=o,a=gt(o,["smooth","component"]);const{text:c,status:d}=Sp(zp(),t);return E.jsx(n,G(_({"data-status":d.type},a),{ref:i,children:c}))});Op.displayName="MessagePartPrimitive.Text";var s_=()=>ne(({part:n})=>{if(n.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return n}),Dp=M.forwardRef((t,n)=>{const{image:a}=s_();return E.jsx(Xn.img,G(_({src:a},t),{ref:n}))});Dp.displayName="MessagePartPrimitive.Image";var Np=({children:t})=>ne(({part:a})=>a.status.type==="running")?t:null;Np.displayName="MessagePartPrimitive.InProgress";const Ip=t=>Symbol.iterator in t,jp=t=>"entries"in t,Lp=(t,n)=>{const a=t instanceof Map?t:new Map(t.entries()),i=n instanceof Map?n:new Map(n.entries());if(a.size!==i.size)return!1;for(const[u,o]of a)if(!i.has(u)||!Object.is(o,i.get(u)))return!1;return!0},u_=(t,n)=>{const a=t[Symbol.iterator](),i=n[Symbol.iterator]();let u=a.next(),o=i.next();for(;!u.done&&!o.done;){if(!Object.is(u.value,o.value))return!1;u=a.next(),o=i.next()}return!!u.done&&!!o.done};function o_(t,n){return Object.is(t,n)?!0:typeof t!="object"||t===null||typeof n!="object"||n===null||Object.getPrototypeOf(t)!==Object.getPrototypeOf(n)?!1:Ip(t)&&Ip(n)?jp(t)&&jp(n)?Lp(t,n):u_(t,n):Lp({entries:()=>Object.entries(t)},{entries:()=>Object.entries(n)})}function c_(t){const n=kn.useRef(void 0);return a=>{const i=t(a);return o_(n.current,i)?n.current:n.current=i}}var Bp=t=>{let n=-1;return{startGroup:a=>{n===-1&&(n=a)},endGroup:(a,i)=>{n!==-1&&(i.push({type:t,startIndex:n,endIndex:a}),n=-1)},finalize:(a,i)=>{n!==-1&&i.push({type:t,startIndex:n,endIndex:a})}}},f_=t=>{const n=[],a=Bp("toolGroup"),i=Bp("reasoningGroup");for(let u=0;u<t.length;u++){const o=t[u];o==="tool-call"?(i.endGroup(u-1,n),a.startGroup(u)):o==="reasoning"?(a.endGroup(u-1,n),i.startGroup(u)):(a.endGroup(u-1,n),i.endGroup(u-1,n),n.push({type:"single",index:u}))}return a.finalize(t.length-1,n),i.finalize(t.length-1,n),n},d_=()=>{const t=ne(c_(n=>n.message.parts.map(a=>a.type)));return M.useMemo(()=>t.length===0?[]:f_(t),[t])},h_=a=>{var i=a,{Fallback:t}=i,n=gt(i,["Fallback"]);const u=ne(({tools:o})=>{var d,h;const c=(d=o.tools[n.toolName])!=null?d:t;return Array.isArray(c)?(h=c[0])!=null?h:t:c});return u?E.jsx(u,_({},n)):null},Qn={Text:()=>E.jsxs("p",{style:{whiteSpace:"pre-line"},children:[E.jsx(Op,{}),E.jsx(Np,{children:E.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>E.jsx(Dp,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:t})=>t,ReasoningGroup:({children:t})=>t},p_=({components:{Text:t=Qn.Text,Reasoning:n=Qn.Reasoning,Image:a=Qn.Image,Source:i=Qn.Source,File:u=Qn.File,Unstable_Audio:o=Qn.Unstable_Audio,tools:c={}}={}})=>{var g,y,v;const d=de(),h=ne(({part:x})=>x),m=h.type;if(m==="tool-call"){const x=d.part().addToolResult,w=d.part().resumeToolCall;if("Override"in c)return E.jsx(c.Override,G(_({},h),{addResult:x,resume:w}));const R=(y=(g=c.by_name)==null?void 0:g[h.toolName])!=null?y:c.Fallback;return E.jsx(h_,G(_({},h),{Fallback:R,addResult:x,resume:w}))}if(((v=h.status)==null?void 0:v.type)==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(m){case"text":return E.jsx(t,_({},h));case"reasoning":return E.jsx(n,_({},h));case"source":return E.jsx(i,_({},h));case"image":return E.jsx(a,_({},h));case"file":return E.jsx(u,_({},h));case"audio":return E.jsx(o,_({},h));case"data":return null;default:const x=m;throw new Error(`Unknown message part type: ${x}`)}},ys=M.memo(({index:t,components:n})=>E.jsx(dw,{index:t,children:E.jsx(p_,{components:n})}),(t,n)=>{var a,i,u,o,c,d,h,m,g,y,v,x,w,R,N,z,Y,I;return t.index===n.index&&((a=t.components)==null?void 0:a.Text)===((i=n.components)==null?void 0:i.Text)&&((u=t.components)==null?void 0:u.Reasoning)===((o=n.components)==null?void 0:o.Reasoning)&&((c=t.components)==null?void 0:c.Source)===((d=n.components)==null?void 0:d.Source)&&((h=t.components)==null?void 0:h.Image)===((m=n.components)==null?void 0:m.Image)&&((g=t.components)==null?void 0:g.File)===((y=n.components)==null?void 0:y.File)&&((v=t.components)==null?void 0:v.Unstable_Audio)===((x=n.components)==null?void 0:x.Unstable_Audio)&&((w=t.components)==null?void 0:w.tools)===((R=n.components)==null?void 0:R.tools)&&((N=t.components)==null?void 0:N.ToolGroup)===((z=n.components)==null?void 0:z.ToolGroup)&&((Y=t.components)==null?void 0:Y.ReasoningGroup)===((I=n.components)==null?void 0:I.ReasoningGroup)});ys.displayName="MessagePrimitive.PartByIndex";var m_=({status:t,component:n})=>E.jsx(pw,{text:"",isRunning:t.type==="running",children:E.jsx(n,{type:"text",text:"",status:t})}),g_=Object.freeze({type:"complete"}),y_=({components:t})=>{var a;const n=ne(i=>{var u;return(u=i.message.status)!=null?u:g_});return t!=null&&t.Empty?E.jsx(t.Empty,{status:n}):E.jsx(m_,{status:n,component:(a=t==null?void 0:t.Text)!=null?a:Qn.Text})},b_=M.memo(y_,(t,n)=>{var a,i,u,o;return((a=t.components)==null?void 0:a.Empty)===((i=n.components)==null?void 0:i.Empty)&&((u=t.components)==null?void 0:u.Text)===((o=n.components)==null?void 0:o.Text)}),Oo=({components:t})=>{const n=ne(({message:u})=>u.parts.length),a=d_(),i=M.useMemo(()=>n===0?E.jsx(b_,{components:t}):a.map(u=>{var o,c;if(u.type==="single")return E.jsx(ys,{index:u.index,components:t},u.index);if(u.type==="toolGroup"){const d=(o=t.ToolGroup)!=null?o:Qn.ToolGroup;return E.jsx(d,{startIndex:u.startIndex,endIndex:u.endIndex,children:Array.from({length:u.endIndex-u.startIndex+1},(h,m)=>E.jsx(ys,{index:u.startIndex+m,components:t},m))},`tool-${u.startIndex}`)}else{const d=(c=t.ReasoningGroup)!=null?c:Qn.ReasoningGroup;return E.jsx(d,{startIndex:u.startIndex,endIndex:u.endIndex,children:Array.from({length:u.endIndex-u.startIndex+1},(h,m)=>E.jsx(ys,{index:u.startIndex+m,components:t},m))},`reasoning-${u.startIndex}`)}}),[a,t,n]);return E.jsx(E.Fragment,{children:i})};Oo.displayName="MessagePrimitive.Parts";var Up=()=>{const t=de(),n=ne(i=>i.thread.isRunning||!i.composer.isEditing||i.composer.isEmpty),a=M.useCallback(()=>{t.composer().send()},[t]);return n?null:a},v_=Mo("ComposerPrimitive.Send",Up),Hp=M.forwardRef((i,a)=>{var u=i,{onSubmit:t}=u,n=gt(u,["onSubmit"]);const o=Up(),c=d=>{d.preventDefault(),o&&o()};return E.jsx(Xn.form,G(_({},n),{ref:a,onSubmit:Oa(t,c)}))});Hp.displayName="ComposerPrimitive.Root";function Do(){return Do=Object.assign?Object.assign.bind():function(t){for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var i in a)({}).hasOwnProperty.call(a,i)&&(t[i]=a[i])}return t},Do.apply(null,arguments)}function x_(t,n){if(t==null)return{};var a={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(n.indexOf(i)!==-1)continue;a[i]=t[i]}return a}var S_=M.useLayoutEffect,w_=function(n){var a=kn.useRef(n);return S_(function(){a.current=n}),a},qp=function(n,a){if(typeof n=="function"){n(a);return}n.current=a},__=function(n,a){var i=kn.useRef();return kn.useCallback(function(u){n.current=u,i.current&&qp(i.current,null),i.current=a,a&&qp(a,u)},[a])},Vp={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},T_=function(n){Object.keys(Vp).forEach(function(a){n.style.setProperty(a,Vp[a],"important")})},Yp=T_,Le=null,Fp=function(n,a){var i=n.scrollHeight;return a.sizingStyle.boxSizing==="border-box"?i+a.borderSize:i-a.paddingSize};function E_(t,n,a,i){a===void 0&&(a=1),i===void 0&&(i=1/0),Le||(Le=document.createElement("textarea"),Le.setAttribute("tabindex","-1"),Le.setAttribute("aria-hidden","true"),Yp(Le)),Le.parentNode===null&&document.body.appendChild(Le);var u=t.paddingSize,o=t.borderSize,c=t.sizingStyle,d=c.boxSizing;Object.keys(c).forEach(function(v){var x=v;Le.style[x]=c[x]}),Yp(Le),Le.value=n;var h=Fp(Le,t);Le.value=n,h=Fp(Le,t),Le.value="x";var m=Le.scrollHeight-u,g=m*a;d==="border-box"&&(g=g+u+o),h=Math.max(g,h);var y=m*i;return d==="border-box"&&(y=y+u+o),h=Math.min(y,h),[h,m]}var Gp=function(){},C_=function(n,a){return n.reduce(function(i,u){return i[u]=a[u],i},{})},A_=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],k_=!!document.documentElement.currentStyle,R_=function(n){var a=window.getComputedStyle(n);if(a===null)return null;var i=C_(A_,a),u=i.boxSizing;if(u==="")return null;k_&&u==="border-box"&&(i.width=parseFloat(i.width)+parseFloat(i.borderRightWidth)+parseFloat(i.borderLeftWidth)+parseFloat(i.paddingRight)+parseFloat(i.paddingLeft)+"px");var o=parseFloat(i.paddingBottom)+parseFloat(i.paddingTop),c=parseFloat(i.borderBottomWidth)+parseFloat(i.borderTopWidth);return{sizingStyle:i,paddingSize:o,borderSize:c}},M_=R_;function No(t,n,a){var i=w_(a);M.useLayoutEffect(function(){var u=function(c){return i.current(c)};if(t)return t.addEventListener(n,u),function(){return t.removeEventListener(n,u)}},[])}var z_=function(n,a){No(document.body,"reset",function(i){n.current.form===i.target&&a(i)})},O_=function(n){No(window,"resize",n)},D_=function(n){No(document.fonts,"loadingdone",n)},N_=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],I_=function(n,a){var i=n.cacheMeasurements,u=n.maxRows,o=n.minRows,c=n.onChange,d=c===void 0?Gp:c,h=n.onHeightChange,m=h===void 0?Gp:h,g=x_(n,N_),y=g.value!==void 0,v=M.useRef(null),x=__(v,a),w=M.useRef(0),R=M.useRef(),N=function(){var I=v.current,nt=i&&R.current?R.current:M_(I);if(nt){R.current=nt;var it=E_(nt,I.value||I.placeholder||"x",o,u),L=it[0],W=it[1];w.current!==L&&(w.current=L,I.style.setProperty("height",L+"px","important"),m(L,{rowHeight:W}))}},z=function(I){y||N(),d(I)};return M.useLayoutEffect(N),z_(v,function(){if(!y){var Y=v.current.value;requestAnimationFrame(function(){var I=v.current;I&&Y!==I.value&&N()})}}),O_(N),D_(N),M.createElement("textarea",Do({},g,{onChange:z,ref:x}))},j_=M.forwardRef(I_),Pp=t=>{const n=Kr(t),a=ds(i=>i.onScrollToBottom);M.useEffect(()=>a(n),[a,n])},Xp=M.forwardRef((w,x)=>{var R=w,{autoFocus:t=!1,asChild:n,disabled:a,onChange:i,onKeyDown:u,onPaste:o,submitOnEnter:c=!0,cancelOnEscape:d=!0,unstable_focusOnRunStart:h=!0,unstable_focusOnScrollToBottom:m=!0,unstable_focusOnThreadSwitched:g=!0,addAttachmentOnPaste:y=!0}=R,v=gt(R,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const N=de(),z=ne(({composer:j})=>j.isEditing?j.text:""),Y=n?Cp:j_,I=ne(({thread:j})=>j.isDisabled)||a,nt=M.useRef(null),it=cs(x,nt);a_(j=>{if(!d)return;const et=N.composer();et.getState().canCancel&&(et.cancel(),j.preventDefault())});const L=j=>{var et,J;I||!c||j.nativeEvent.isComposing||j.key==="Enter"&&j.shiftKey===!1&&(N.thread().getState().isRunning||(j.preventDefault(),(J=(et=nt.current)==null?void 0:et.closest("form"))==null||J.requestSubmit()))},W=j=>$(null,null,function*(){var bt;if(!y)return;const et=N.thread().getState().capabilities,J=Array.from(((bt=j.clipboardData)==null?void 0:bt.files)||[]);if(et.attachments&&J.length>0)try{j.preventDefault(),yield Promise.all(J.map(ut=>N.composer().addAttachment(ut)))}catch(ut){console.error("Error adding attachment:",ut)}}),ot=t&&!I,ft=M.useCallback(()=>{const j=nt.current;!j||!ot||(j.focus({preventScroll:!0}),j.setSelectionRange(j.value.length,j.value.length))},[ot]);return M.useEffect(()=>ft(),[ft]),Pp(()=>{N.composer().getState().type==="thread"&&m&&ft()}),M.useEffect(()=>{if(!(N.composer().getState().type!=="thread"||!h))return N.on("thread.run-start",ft)},[h,ft,N]),M.useEffect(()=>{if(!(N.composer().getState().type!=="thread"||!g))return N.on("thread-list-item.switched-to",ft)},[g,ft,N]),E.jsx(Y,G(_({name:"input",value:z},v),{ref:it,disabled:I,onChange:Oa(i,j=>{N.composer().getState().isEditing&&(N.composer().setText(j.target.value),N.flushSync())}),onKeyDown:Oa(u,L),onPaste:Oa(o,W)}))});Xp.displayName="ComposerPrimitive.Input";var Qp=M.forwardRef((t,n)=>E.jsx(Xn.div,G(_({},t),{ref:n})));Qp.displayName="ThreadPrimitive.Root";var Zp=({children:t})=>ne(({thread:a})=>a.messages.length===0&&!a.isLoading)?t:null;Zp.displayName="ThreadPrimitive.Empty";var L_=t=>ne(({thread:n})=>{const a=n.messages.length===0&&!n.isLoading;return!(t.empty===!0&&!a||t.empty===!1&&a||t.running===!0&&!n.isRunning||t.running===!1&&n.isRunning||t.disabled===!0&&!n.isDisabled||t.disabled===!1&&n.isDisabled)}),Kp=a=>{var i=a,{children:t}=i,n=gt(i,["children"]);return L_(n)?t:null};Kp.displayName="ThreadPrimitive.If";var B_=t=>{const n=Kr(t),a=M.useCallback(i=>{const u=new ResizeObserver(()=>{n()}),o=new MutationObserver(()=>{n()});return u.observe(i),o.observe(i,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{u.disconnect(),o.disconnect()}},[n]);return qi(a)},U_=({autoScroll:t})=>{const n=M.useRef(null),a=So();t===void 0&&(t=a.getState().turnAnchor!=="top");const i=M.useRef(0),u=M.useRef(null),o=M.useCallback(g=>{const y=n.current;y&&(u.current=g,y.scrollTo({top:y.scrollHeight,behavior:g}))},[]),c=()=>{const g=n.current;if(!g)return;const y=a.getState().isAtBottom,v=Math.abs(g.scrollHeight-g.scrollTop-g.clientHeight)<1||g.scrollHeight<=g.clientHeight;!v&&i.current<g.scrollTop||(v&&(u.current=null),v!==y&&Hi(a).setState({isAtBottom:v})),i.current=g.scrollTop},d=B_(()=>{const g=u.current;g?o(g):t&&a.getState().isAtBottom&&o("instant"),c()}),h=qi(g=>(g.addEventListener("scroll",c),()=>{g.removeEventListener("scroll",c)}));return Pp(({behavior:g})=>{o(g)}),U1("thread.run-start",()=>{u.current="auto",requestAnimationFrame(()=>{o("auto")})}),cs(d,h,n)},H_=()=>{const t=ds(a=>a.registerViewport),n=M.useCallback(a=>a.clientHeight-parseFloat(getComputedStyle(a).paddingTop),[]);return Ap(t,n)},Jp=M.forwardRef((u,i)=>{var o=u,{autoScroll:t,children:n}=o,a=gt(o,["autoScroll","children"]);const c=U_({autoScroll:t}),d=H_(),h=cs(i,c,d);return E.jsx(Xn.div,G(_({},a),{ref:h,children:n}))});Jp.displayName="ThreadPrimitive.ViewportScrollable";var $p=M.forwardRef((i,a)=>{var u=i,{turnAnchor:t}=u,n=gt(u,["turnAnchor"]);return E.jsx(fp,{options:{turnAnchor:t},children:E.jsx(Jp,G(_({},n),{ref:a}))})});$p.displayName="ThreadPrimitive.Viewport";var Wp=(t,n)=>t.Message===n.Message&&t.EditComposer===n.EditComposer&&t.UserEditComposer===n.UserEditComposer&&t.AssistantEditComposer===n.AssistantEditComposer&&t.SystemEditComposer===n.SystemEditComposer&&t.UserMessage===n.UserMessage&&t.AssistantMessage===n.AssistantMessage&&t.SystemMessage===n.SystemMessage,q_=()=>null,V_=(t,n,a)=>{var i,u,o,c,d,h,m,g,y,v,x,w;switch(n){case"user":return a?(o=(u=(i=t.UserEditComposer)!=null?i:t.EditComposer)!=null?u:t.UserMessage)!=null?o:t.Message:(c=t.UserMessage)!=null?c:t.Message;case"assistant":return a?(m=(h=(d=t.AssistantEditComposer)!=null?d:t.EditComposer)!=null?h:t.AssistantMessage)!=null?m:t.Message:(g=t.AssistantMessage)!=null?g:t.Message;case"system":return a?(x=(v=(y=t.SystemEditComposer)!=null?y:t.EditComposer)!=null?v:t.SystemMessage)!=null?x:t.Message:(w=t.SystemMessage)!=null?w:q_;default:const R=n;throw new Error(`Unknown message role: ${R}`)}},Y_=({components:t})=>{const n=ne(({message:u})=>u.role),a=ne(({message:u})=>u.composer.isEditing),i=V_(t,n,a);return E.jsx(i,{})},tm=M.memo(({index:t,components:n})=>E.jsx(fw,{index:t,children:E.jsx(Y_,{components:n})}),(t,n)=>t.index===n.index&&Wp(t.components,n.components));tm.displayName="ThreadPrimitive.MessageByIndex";var em=({components:t})=>{const n=ne(({thread:i})=>i.messages.length);return M.useMemo(()=>n===0?null:Array.from({length:n},(i,u)=>E.jsx(tm,{index:u,components:t},u)),[n,t])};em.displayName="ThreadPrimitive.Messages";var F_=M.memo(em,(t,n)=>Wp(t.components,n.components)),nm=M.forwardRef((u,i)=>{var o=u,{onClick:t,disabled:n}=o,a=gt(o,["onClick","disabled"]);const c=ne(({threads:h})=>h.newThreadId===h.mainThreadId),d=de();return E.jsx(Xn.button,G(_(_({type:"button"},c?{"data-active":"true","aria-current":"true"}:null),a),{ref:i,disabled:n,onClick:Oa(t,()=>{d.threads().switchToNewThread()})}))});nm.displayName="ThreadListPrimitive.New";var rm=M.memo(({index:t,archived:n=!1,components:a})=>{const i=a.ThreadListItem;return E.jsx(ow,{index:t,archived:n,children:E.jsx(i,{})})},(t,n)=>t.index===n.index&&t.archived===n.archived&&t.components.ThreadListItem===n.components.ThreadListItem);rm.displayName="ThreadListPrimitive.ItemByIndex";var am=({archived:t=!1,components:n})=>{const a=ne(({threads:u})=>t?u.archivedThreadIds.length:u.threadIds.length);return M.useMemo(()=>Array.from({length:a},(u,o)=>E.jsx(rm,{index:o,archived:t,components:n},o)),[a,t,n])};am.displayName="ThreadListPrimitive.Items";var im=M.forwardRef((t,n)=>E.jsx(Xn.div,G(_({},t),{ref:n})));im.displayName="ThreadListPrimitive.Root";var lm=M.forwardRef((t,n)=>{const a=ne(({threads:i,threadListItem:u})=>i.mainThreadId===u.id);return E.jsx(Xn.div,G(_(_({},a?{"data-active":"true","aria-current":"true"}:null),t),{ref:n}))});lm.displayName="ThreadListItemPrimitive.Root";var G_=()=>{const t=de();return M.useCallback(()=>{t.threadListItem().delete()},[t])},P_=Mo("ThreadListItemPrimitive.Delete",G_),X_=()=>{const t=de();return M.useCallback(()=>{t.threadListItem().switchTo()},[t])},Q_=Mo("ThreadListItemPrimitive.Trigger",X_);class sm{constructor(n,a,i=!1){V(this,"baseUrl");V(this,"sessionToken",null);V(this,"isProxyMode",!1);this.baseUrl=n.replace(/\/$/,""),this.isProxyMode=i,a&&(this.sessionToken=a)}setSessionToken(n){this.sessionToken=n}getUrl(n){if(this.isProxyMode){const a=`${this.baseUrl}${n.replace("/v1","")}`;return a.startsWith("/")||a.startsWith("./"),a}return`${this.baseUrl}${n}`}createOrContinueChat(n,a){return $(this,null,function*(){const i=this.getUrl("/v1/chats"),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const c=G(_({},n),{stream:!0}),d=yield fetch(i,{method:"POST",headers:o,body:JSON.stringify(c),signal:a});if(!d.ok){const h=yield d.json().catch(()=>({}));throw new Error(h.detail||h.message||`API error: ${d.status} ${d.statusText}`)}if(!d.body)throw new Error("Response body is null");return d.body})}getChat(n){return $(this,null,function*(){const a=this.getUrl(`/v1/chats/${n}`),i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const u=yield fetch(a,{method:"GET",headers:i});if(!u.ok){const o=yield u.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${u.status} ${u.statusText}`)}return u.json()})}listChats(n){return $(this,null,function*(){const a=this.getUrl("/v1/chats"),i=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a);n!=null&&n.limit&&i.searchParams.set("limit",n.limit.toString()),n!=null&&n.cursor&&i.searchParams.set("cursor",n.cursor),n!=null&&n["expand[]"]&&n["expand[]"].forEach(c=>{i.searchParams.append("expand[]",c)});const u={"Content-Type":"application/json"};this.sessionToken&&(u.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(i.toString(),{method:"GET",headers:u});if(!o.ok){const c=yield o.json().catch(()=>({}));throw new Error(c.detail||c.message||`API error: ${o.status} ${o.statusText}`)}return o.json()})}generateIdempotencyKey(){try{if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID()}catch(i){}const n=i=>Array.from({length:i},()=>Math.floor(Math.random()*16).toString(16)).join(""),a=()=>{const i=["8","9","a","b"];return i[Math.floor(Math.random()*i.length)]};return`${n(8)}-${n(4)}-4${n(3)}-${a()}${n(3)}-${n(12)}`}updateChat(n,a){return $(this,null,function*(){const i=`/v1/chats/${n}`,u=this.getUrl(i),o=u.startsWith("/")||u.startsWith("./")?new URL(u,window.location.origin):new URL(u),d={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(d.Authorization=`Bearer ${this.sessionToken}`);const h=yield fetch(o.toString(),{method:"PATCH",headers:d,body:JSON.stringify(a)});if(!h.ok){const g=yield h.text();let y={};try{y=JSON.parse(g)}catch(v){y={detail:g}}throw new Error(y.detail||y.message||`API error: ${h.status} ${h.statusText}`)}if(h.status===204)return{};const m=yield h.text();if(!m)return{};try{return JSON.parse(m)}catch(g){return{}}})}deleteChat(n){return $(this,null,function*(){const a=`/v1/chats/${n}`,i=this.getUrl(a),u=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),c={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const d=yield fetch(u.toString(),{method:"DELETE",headers:c});if(!d.ok){const h=yield d.json().catch(()=>({}));throw new Error(h.detail||h.message||`API error: ${d.status} ${d.statusText}`)}})}listModels(n){return $(this,null,function*(){const a=this.getUrl("/v1/models"),i=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a);n!=null&&n.limit&&i.searchParams.set("limit",n.limit.toString()),n!=null&&n.cursor&&i.searchParams.set("cursor",n.cursor),n!=null&&n["expand[]"]&&n["expand[]"].forEach(c=>{i.searchParams.append("expand[]",c)});const u={"Content-Type":"application/json"};this.sessionToken&&(u.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(i.toString(),{method:"GET",headers:u});if(!o.ok){const c=yield o.json().catch(()=>({}));throw new Error(c.detail||c.message||`API error: ${o.status} ${o.statusText}`)}return o.json()})}getModel(n){return $(this,null,function*(){const a=this.getUrl(`/v1/models/${n}`),i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const u=yield fetch(a,{method:"GET",headers:i});if(!u.ok){const o=yield u.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${u.status} ${u.statusText}`)}return u.json()})}}function Z_(t,n){return Kl(this,null,function*(){const a=t.getReader(),i=new TextDecoder;let u="";try{for(;;){if(n!=null&&n.aborted){a.cancel();break}const{done:o,value:c}=yield new gr(a.read());if(o)break;u+=i.decode(c,{stream:!0});const d=u.split(`
14
14
 
15
- `);u=d.pop()||"";for(const h of d)if(h.startsWith("data: ")){const m=h.slice(6);if(m.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(m)}catch(g){}}}}finally{a.releaseLock()}})}function K_(t){return t.map(n=>{let a="";if(typeof n.content=="string")a=n.content;else if(Array.isArray(n.content)){const i=n.content.find(u=>u.type==="text");i&&typeof i=="object"&&"text"in i&&(a=i.text)}return{role:n.role,content:a}})}function J_(t,n){const{modelId:a,systemPrompt:i,ephemeral:u,onChatCreated:o,onUserMessage:c}=n;return{run(h){return Kl(this,null,function*(){const{messages:m,abortSignal:g}=h;m.length>0&&m[m.length-1].role==="user"&&(c==null||c());const v={messages:K_(m),chatId:null,systemPrompt:i,ephemeral:u,stream:!0};a&&a.trim()!==""&&(v.modelId=a);const x=yield new gr(t.createOrContinueChat(v,g));let w="",R;try{for(var N=xa(Z_(x,g)),z,Y,I;z=!(Y=yield new gr(N.next())).done;z=!1){const nt=Y.value;if(g!=null&&g.aborted)throw new Error("Request aborted");const it=nt.id;it&&!R&&(R=it,o==null||o(it));const L=nt.delta;if(L!=null&&(w+=L),nt.type==="message"||nt.content){const ot=nt.content||"";w+=ot}if(nt.message&&(w+=nt.message.content||""),nt.tool_calls,nt.finished){w&&(yield{content:[{type:"text",text:w}]});break}w&&(yield{content:[{type:"text",text:w}]})}}catch(Y){I=[Y]}finally{try{z&&(Y=N.return)&&(yield new gr(Y.call(N)))}finally{if(I)throw I[0]}}w&&(yield{content:[{type:"text",text:w}]})})}}}const um=new Map;function $_(t,n){return{list(){return $(this,null,function*(){const i=[];let o,c=0;do{const h=yield t.listChats({limit:50,cursor:o}),m=h.items||[];Array.isArray(m)&&m.length>0&&i.push(...m),o=h.nextCursor||void 0,c++}while(o&&c<50);return{threads:i.map(h=>{const m=h.id;return!m||h.deletedAt?null:{status:"regular",remoteId:m,title:h.title||"New Chat",createdAt:h.createdAt?new Date(h.createdAt):new Date,updatedAt:h.updatedAt?new Date(h.updatedAt):new Date}}).filter(h=>h!==null)}})},initialize(i){return $(this,null,function*(){return{remoteId:um.get(i)||i,externalId:void 0}})},rename(i,u){return $(this,null,function*(){yield t.updateChat(i,{title:u})})},archive(i){return $(this,null,function*(){})},unarchive(i){return $(this,null,function*(){})},delete(i){return $(this,null,function*(){yield t.deleteChat(i)})},generateTitle(i,u){return $(this,null,function*(){return new ReadableStream})},fetch(i){return $(this,null,function*(){try{const u=yield t.getChat(i);return{status:"regular",remoteId:u.id||i,title:u.title||"Chat",createdAt:u.createdAt?new Date(u.createdAt):new Date,updatedAt:u.updatedAt?new Date(u.updatedAt):new Date}}catch(u){return{status:"regular",remoteId:i,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(i,u){um.set(i,u),n==null||n(i,u)}}}function W_({children:t,baseUrl:n,sessionToken:a,isProxyMode:i=!1,mode:u="multiChat",modelId:o,onModelChange:c,ephemeral:d=!1,systemPrompt:h,initialThreadId:m,onError:g,onChatCreated:y,onUserMessage:v,onThreadIdUpdate:x,onChatsLoaded:w}){const R=M.useMemo(()=>new sm(n,a||void 0,i),[n,a,i]),[N,z]=M.useState(o||null);M.useEffect(()=>{o&&z(o)},[o]);const Y=M.useCallback(L=>{y==null||y(L)},[y]),I=M.useCallback((L,W)=>{x==null||x(L,W)},[x]),nt=M.useMemo(()=>J_(R,{modelId:N||void 0,systemPrompt:h,ephemeral:d,onChatCreated:Y,onUserMessage:v}),[R,N,h,d,Y,v]),it=bp(nt);return u==="singleChat"?E.jsx(dp,{runtime:it,children:t}):E.jsx(tT,{client:R,modelAdapter:nt,initialThreadId:m,onChatsLoaded:w,onThreadIdUpdate:I,onError:g,children:t})}function tT({client:t,modelAdapter:n,initialThreadId:a,onChatsLoaded:i,onThreadIdUpdate:u,onError:o,children:c}){const d=M.useMemo(()=>$_(t,(y,v)=>{u==null||u(y,v)}),[t,u]),h=M.useMemo(()=>G(_({},d),{list(){return $(this,null,function*(){const v=yield d.list();return i==null||i(),v})}}),[d,i]);M.useEffect(()=>{window.__cuadraThreadListAdapter=h,window.__cuadraThreadListRuntime=null},[h]);const m=M.useCallback(()=>bp(n),[n]),g=_p({adapter:h,runtimeHook:m});return M.useEffect(()=>{window.__cuadraThreadListRuntime=g},[g]),E.jsx(dp,{runtime:g,children:c})}function wO(){}function _O(){}function eT(t,n){const a={};return(t[t.length-1]===""?[...t,""]:t).join((a.padRight?" ":"")+","+(a.padLeft===!1?"":" ")).trim()}const nT=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,rT=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,aT={};function om(t,n){return(aT.jsx?rT:nT).test(t)}const iT=/[ \t\n\f\r]/g;function lT(t){return typeof t=="object"?t.type==="text"?cm(t.value):!1:cm(t)}function cm(t){return t.replace(iT,"")===""}class Vi{constructor(n,a,i){this.normal=a,this.property=n,i&&(this.space=i)}}Vi.prototype.normal={},Vi.prototype.property={},Vi.prototype.space=void 0;function fm(t,n){const a={},i={};for(const u of t)Object.assign(a,u.property),Object.assign(i,u.normal);return new Vi(a,i,n)}function Io(t){return t.toLowerCase()}class Ye{constructor(n,a){this.attribute=a,this.property=n}}Ye.prototype.attribute="",Ye.prototype.booleanish=!1,Ye.prototype.boolean=!1,Ye.prototype.commaOrSpaceSeparated=!1,Ye.prototype.commaSeparated=!1,Ye.prototype.defined=!1,Ye.prototype.mustUseProperty=!1,Ye.prototype.number=!1,Ye.prototype.overloadedBoolean=!1,Ye.prototype.property="",Ye.prototype.spaceSeparated=!1,Ye.prototype.space=void 0;let sT=0;const Rt=Jr(),pe=Jr(),jo=Jr(),at=Jr(),ee=Jr(),Da=Jr(),nn=Jr();function Jr(){return bS(2,++sT)}const Lo=Object.freeze(Object.defineProperty({__proto__:null,boolean:Rt,booleanish:pe,commaOrSpaceSeparated:nn,commaSeparated:Da,number:at,overloadedBoolean:jo,spaceSeparated:ee},Symbol.toStringTag,{value:"Module"})),Bo=Object.keys(Lo);class Uo extends Ye{constructor(n,a,i,u){let o=-1;if(super(n,a),dm(this,"space",u),typeof i=="number")for(;++o<Bo.length;){const c=Bo[o];dm(this,Bo[o],(i&Lo[c])===Lo[c])}}}Uo.prototype.defined=!0;function dm(t,n,a){a&&(t[n]=a)}function Na(t){const n={},a={};for(const[i,u]of Object.entries(t.properties)){const o=new Uo(i,t.transform(t.attributes||{},i),u,t.space);t.mustUseProperty&&t.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,a[Io(i)]=i,a[Io(o.attribute)]=i}return new Vi(n,a,t.space)}const hm=Na({properties:{ariaActiveDescendant:null,ariaAtomic:pe,ariaAutoComplete:null,ariaBusy:pe,ariaChecked:pe,ariaColCount:at,ariaColIndex:at,ariaColSpan:at,ariaControls:ee,ariaCurrent:null,ariaDescribedBy:ee,ariaDetails:null,ariaDisabled:pe,ariaDropEffect:ee,ariaErrorMessage:null,ariaExpanded:pe,ariaFlowTo:ee,ariaGrabbed:pe,ariaHasPopup:null,ariaHidden:pe,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ee,ariaLevel:at,ariaLive:null,ariaModal:pe,ariaMultiLine:pe,ariaMultiSelectable:pe,ariaOrientation:null,ariaOwns:ee,ariaPlaceholder:null,ariaPosInSet:at,ariaPressed:pe,ariaReadOnly:pe,ariaRelevant:null,ariaRequired:pe,ariaRoleDescription:ee,ariaRowCount:at,ariaRowIndex:at,ariaRowSpan:at,ariaSelected:pe,ariaSetSize:at,ariaSort:null,ariaValueMax:at,ariaValueMin:at,ariaValueNow:at,ariaValueText:null,role:null},transform(t,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function pm(t,n){return n in t?t[n]:n}function mm(t,n){return pm(t,n.toLowerCase())}const uT=Na({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Da,acceptCharset:ee,accessKey:ee,action:null,allow:null,allowFullScreen:Rt,allowPaymentRequest:Rt,allowUserMedia:Rt,alt:null,as:null,async:Rt,autoCapitalize:null,autoComplete:ee,autoFocus:Rt,autoPlay:Rt,blocking:ee,capture:null,charSet:null,checked:Rt,cite:null,className:ee,cols:at,colSpan:null,content:null,contentEditable:pe,controls:Rt,controlsList:ee,coords:at|Da,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Rt,defer:Rt,dir:null,dirName:null,disabled:Rt,download:jo,draggable:pe,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Rt,formTarget:null,headers:ee,height:at,hidden:jo,high:at,href:null,hrefLang:null,htmlFor:ee,httpEquiv:ee,id:null,imageSizes:null,imageSrcSet:null,inert:Rt,inputMode:null,integrity:null,is:null,isMap:Rt,itemId:null,itemProp:ee,itemRef:ee,itemScope:Rt,itemType:ee,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Rt,low:at,manifest:null,max:null,maxLength:at,media:null,method:null,min:null,minLength:at,multiple:Rt,muted:Rt,name:null,nonce:null,noModule:Rt,noValidate:Rt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Rt,optimum:at,pattern:null,ping:ee,placeholder:null,playsInline:Rt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Rt,referrerPolicy:null,rel:ee,required:Rt,reversed:Rt,rows:at,rowSpan:at,sandbox:ee,scope:null,scoped:Rt,seamless:Rt,selected:Rt,shadowRootClonable:Rt,shadowRootDelegatesFocus:Rt,shadowRootMode:null,shape:null,size:at,sizes:null,slot:null,span:at,spellCheck:pe,src:null,srcDoc:null,srcLang:null,srcSet:null,start:at,step:null,style:null,tabIndex:at,target:null,title:null,translate:null,type:null,typeMustMatch:Rt,useMap:null,value:pe,width:at,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ee,axis:null,background:null,bgColor:null,border:at,borderColor:null,bottomMargin:at,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Rt,declare:Rt,event:null,face:null,frame:null,frameBorder:null,hSpace:at,leftMargin:at,link:null,longDesc:null,lowSrc:null,marginHeight:at,marginWidth:at,noResize:Rt,noHref:Rt,noShade:Rt,noWrap:Rt,object:null,profile:null,prompt:null,rev:null,rightMargin:at,rules:null,scheme:null,scrolling:pe,standby:null,summary:null,text:null,topMargin:at,valueType:null,version:null,vAlign:null,vLink:null,vSpace:at,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Rt,disableRemotePlayback:Rt,prefix:null,property:null,results:at,security:null,unselectable:null},space:"html",transform:mm}),oT=Na({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:nn,accentHeight:at,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:at,amplitude:at,arabicForm:null,ascent:at,attributeName:null,attributeType:null,azimuth:at,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:at,by:null,calcMode:null,capHeight:at,className:ee,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:at,diffuseConstant:at,direction:null,display:null,dur:null,divisor:at,dominantBaseline:null,download:Rt,dx:null,dy:null,edgeMode:null,editable:null,elevation:at,enableBackground:null,end:null,event:null,exponent:at,externalResourcesRequired:null,fill:null,fillOpacity:at,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Da,g2:Da,glyphName:Da,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:at,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:at,horizOriginX:at,horizOriginY:at,id:null,ideographic:at,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:at,k:at,k1:at,k2:at,k3:at,k4:at,kernelMatrix:nn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:at,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:at,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:at,overlineThickness:at,paintOrder:null,panose1:null,path:null,pathLength:at,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ee,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:at,pointsAtY:at,pointsAtZ:at,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:nn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:nn,rev:nn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:nn,requiredFeatures:nn,requiredFonts:nn,requiredFormats:nn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:at,specularExponent:at,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:at,strikethroughThickness:at,string:null,stroke:null,strokeDashArray:nn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:at,strokeOpacity:at,strokeWidth:null,style:null,surfaceScale:at,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:nn,tabIndex:at,tableValues:null,target:null,targetX:at,targetY:at,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:nn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:at,underlineThickness:at,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:at,values:null,vAlphabetic:at,vMathematical:at,vectorEffect:null,vHanging:at,vIdeographic:at,version:null,vertAdvY:at,vertOriginX:at,vertOriginY:at,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:at,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:pm}),gm=Na({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(t,n){return"xlink:"+n.slice(5).toLowerCase()}}),ym=Na({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:mm}),bm=Na({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,n){return"xml:"+n.slice(3).toLowerCase()}}),cT={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},fT=/[A-Z]/g,vm=/-[a-z]/g,dT=/^data[-\w.:]+$/i;function hT(t,n){const a=Io(n);let i=n,u=Ye;if(a in t.normal)return t.property[t.normal[a]];if(a.length>4&&a.slice(0,4)==="data"&&dT.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(vm,mT);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!vm.test(o)){let c=o.replace(fT,pT);c.charAt(0)!=="-"&&(c="-"+c),n="data"+c}}u=Uo}return new u(i,n)}function pT(t){return"-"+t.toLowerCase()}function mT(t){return t.charAt(1).toUpperCase()}const gT=fm([hm,uT,gm,ym,bm],"html"),Ho=fm([hm,oT,gm,ym,bm],"svg");function yT(t){return t.join(" ").trim()}var Ia={},qo,xm;function bT(){if(xm)return qo;xm=1;var t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,a=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,u=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,d=/^\s+|\s+$/g,h=`
15
+ `);u=d.pop()||"";for(const h of d)if(h.startsWith("data: ")){const m=h.slice(6);if(m.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(m)}catch(g){}}}}finally{a.releaseLock()}})}function K_(t){return t.map(n=>{let a="";if(typeof n.content=="string")a=n.content;else if(Array.isArray(n.content)){const i=n.content.find(u=>u.type==="text");i&&typeof i=="object"&&"text"in i&&(a=i.text)}return{role:n.role,content:a}})}function J_(t,n){const{modelId:a,systemPrompt:i,ephemeral:u,onChatCreated:o,onUserMessage:c}=n;return{run(h){return Kl(this,null,function*(){const{messages:m,abortSignal:g}=h;c==null||c();const v={messages:K_(m),chatId:null,systemPrompt:i,ephemeral:u,stream:!0};a&&a.trim()!==""&&(v.modelId=a);const x=yield new gr(t.createOrContinueChat(v,g));let w="",R;try{for(var N=xa(Z_(x,g)),z,Y,I;z=!(Y=yield new gr(N.next())).done;z=!1){const nt=Y.value;if(g!=null&&g.aborted)throw new Error("Request aborted");const it=nt.id;it&&!R&&(R=it,o==null||o(it));const L=nt.delta;if(L!=null&&(w+=L),nt.type==="message"||nt.content){const ot=nt.content||"";w+=ot}if(nt.message&&(w+=nt.message.content||""),nt.tool_calls,nt.finished){w&&(yield{content:[{type:"text",text:w}]});break}w&&(yield{content:[{type:"text",text:w}]})}}catch(Y){I=[Y]}finally{try{z&&(Y=N.return)&&(yield new gr(Y.call(N)))}finally{if(I)throw I[0]}}w&&(yield{content:[{type:"text",text:w}]})})}}}const um=new Map;function $_(t,n){return{list(){return $(this,null,function*(){const i=[];let o,c=0;do{const h=yield t.listChats({limit:50,cursor:o}),m=h.items||[];Array.isArray(m)&&m.length>0&&i.push(...m),o=h.nextCursor||void 0,c++}while(o&&c<50);return{threads:i.map(h=>{const m=h.id;return!m||h.deletedAt?null:{status:"regular",remoteId:m,title:h.title||"New Chat",createdAt:h.createdAt?new Date(h.createdAt):new Date,updatedAt:h.updatedAt?new Date(h.updatedAt):new Date}}).filter(h=>h!==null)}})},initialize(i){return $(this,null,function*(){return{remoteId:um.get(i)||i,externalId:void 0}})},rename(i,u){return $(this,null,function*(){yield t.updateChat(i,{title:u})})},archive(i){return $(this,null,function*(){})},unarchive(i){return $(this,null,function*(){})},delete(i){return $(this,null,function*(){yield t.deleteChat(i)})},generateTitle(i,u){return $(this,null,function*(){return new ReadableStream})},fetch(i){return $(this,null,function*(){try{const u=yield t.getChat(i);return{status:"regular",remoteId:u.id||i,title:u.title||"Chat",createdAt:u.createdAt?new Date(u.createdAt):new Date,updatedAt:u.updatedAt?new Date(u.updatedAt):new Date}}catch(u){return{status:"regular",remoteId:i,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(i,u){um.set(i,u),n==null||n(i,u)}}}function W_({children:t,baseUrl:n,sessionToken:a,isProxyMode:i=!1,mode:u="multiChat",modelId:o,onModelChange:c,ephemeral:d=!1,systemPrompt:h,initialThreadId:m,onError:g,onChatCreated:y,onUserMessage:v,onThreadIdUpdate:x,onChatsLoaded:w}){const R=M.useMemo(()=>new sm(n,a||void 0,i),[n,a,i]),[N,z]=M.useState(o||null);M.useEffect(()=>{o&&z(o)},[o]);const Y=M.useCallback(L=>{y==null||y(L)},[y]),I=M.useCallback((L,W)=>{x==null||x(L,W)},[x]),nt=M.useMemo(()=>J_(R,{modelId:N||void 0,systemPrompt:h,ephemeral:d,onChatCreated:Y,onUserMessage:v}),[R,N,h,d,Y,v]),it=bp(nt);return u==="singleChat"?E.jsx(dp,{runtime:it,children:t}):E.jsx(tT,{client:R,modelAdapter:nt,initialThreadId:m,onChatsLoaded:w,onThreadIdUpdate:I,onError:g,children:t})}function tT({client:t,modelAdapter:n,initialThreadId:a,onChatsLoaded:i,onThreadIdUpdate:u,onError:o,children:c}){const d=M.useMemo(()=>$_(t,(y,v)=>{u==null||u(y,v)}),[t,u]),h=M.useMemo(()=>G(_({},d),{list(){return $(this,null,function*(){const v=yield d.list();return i==null||i(),v})}}),[d,i]);M.useEffect(()=>{window.__cuadraThreadListAdapter=h,window.__cuadraThreadListRuntime=null},[h]);const m=M.useCallback(()=>bp(n),[n]),g=_p({adapter:h,runtimeHook:m});return M.useEffect(()=>{window.__cuadraThreadListRuntime=g},[g]),E.jsx(dp,{runtime:g,children:c})}function wO(){}function _O(){}function eT(t,n){const a={};return(t[t.length-1]===""?[...t,""]:t).join((a.padRight?" ":"")+","+(a.padLeft===!1?"":" ")).trim()}const nT=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,rT=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,aT={};function om(t,n){return(aT.jsx?rT:nT).test(t)}const iT=/[ \t\n\f\r]/g;function lT(t){return typeof t=="object"?t.type==="text"?cm(t.value):!1:cm(t)}function cm(t){return t.replace(iT,"")===""}class Vi{constructor(n,a,i){this.normal=a,this.property=n,i&&(this.space=i)}}Vi.prototype.normal={},Vi.prototype.property={},Vi.prototype.space=void 0;function fm(t,n){const a={},i={};for(const u of t)Object.assign(a,u.property),Object.assign(i,u.normal);return new Vi(a,i,n)}function Io(t){return t.toLowerCase()}class Ye{constructor(n,a){this.attribute=a,this.property=n}}Ye.prototype.attribute="",Ye.prototype.booleanish=!1,Ye.prototype.boolean=!1,Ye.prototype.commaOrSpaceSeparated=!1,Ye.prototype.commaSeparated=!1,Ye.prototype.defined=!1,Ye.prototype.mustUseProperty=!1,Ye.prototype.number=!1,Ye.prototype.overloadedBoolean=!1,Ye.prototype.property="",Ye.prototype.spaceSeparated=!1,Ye.prototype.space=void 0;let sT=0;const Rt=Jr(),pe=Jr(),jo=Jr(),at=Jr(),ee=Jr(),Da=Jr(),nn=Jr();function Jr(){return bS(2,++sT)}const Lo=Object.freeze(Object.defineProperty({__proto__:null,boolean:Rt,booleanish:pe,commaOrSpaceSeparated:nn,commaSeparated:Da,number:at,overloadedBoolean:jo,spaceSeparated:ee},Symbol.toStringTag,{value:"Module"})),Bo=Object.keys(Lo);class Uo extends Ye{constructor(n,a,i,u){let o=-1;if(super(n,a),dm(this,"space",u),typeof i=="number")for(;++o<Bo.length;){const c=Bo[o];dm(this,Bo[o],(i&Lo[c])===Lo[c])}}}Uo.prototype.defined=!0;function dm(t,n,a){a&&(t[n]=a)}function Na(t){const n={},a={};for(const[i,u]of Object.entries(t.properties)){const o=new Uo(i,t.transform(t.attributes||{},i),u,t.space);t.mustUseProperty&&t.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,a[Io(i)]=i,a[Io(o.attribute)]=i}return new Vi(n,a,t.space)}const hm=Na({properties:{ariaActiveDescendant:null,ariaAtomic:pe,ariaAutoComplete:null,ariaBusy:pe,ariaChecked:pe,ariaColCount:at,ariaColIndex:at,ariaColSpan:at,ariaControls:ee,ariaCurrent:null,ariaDescribedBy:ee,ariaDetails:null,ariaDisabled:pe,ariaDropEffect:ee,ariaErrorMessage:null,ariaExpanded:pe,ariaFlowTo:ee,ariaGrabbed:pe,ariaHasPopup:null,ariaHidden:pe,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ee,ariaLevel:at,ariaLive:null,ariaModal:pe,ariaMultiLine:pe,ariaMultiSelectable:pe,ariaOrientation:null,ariaOwns:ee,ariaPlaceholder:null,ariaPosInSet:at,ariaPressed:pe,ariaReadOnly:pe,ariaRelevant:null,ariaRequired:pe,ariaRoleDescription:ee,ariaRowCount:at,ariaRowIndex:at,ariaRowSpan:at,ariaSelected:pe,ariaSetSize:at,ariaSort:null,ariaValueMax:at,ariaValueMin:at,ariaValueNow:at,ariaValueText:null,role:null},transform(t,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function pm(t,n){return n in t?t[n]:n}function mm(t,n){return pm(t,n.toLowerCase())}const uT=Na({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Da,acceptCharset:ee,accessKey:ee,action:null,allow:null,allowFullScreen:Rt,allowPaymentRequest:Rt,allowUserMedia:Rt,alt:null,as:null,async:Rt,autoCapitalize:null,autoComplete:ee,autoFocus:Rt,autoPlay:Rt,blocking:ee,capture:null,charSet:null,checked:Rt,cite:null,className:ee,cols:at,colSpan:null,content:null,contentEditable:pe,controls:Rt,controlsList:ee,coords:at|Da,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Rt,defer:Rt,dir:null,dirName:null,disabled:Rt,download:jo,draggable:pe,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Rt,formTarget:null,headers:ee,height:at,hidden:jo,high:at,href:null,hrefLang:null,htmlFor:ee,httpEquiv:ee,id:null,imageSizes:null,imageSrcSet:null,inert:Rt,inputMode:null,integrity:null,is:null,isMap:Rt,itemId:null,itemProp:ee,itemRef:ee,itemScope:Rt,itemType:ee,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Rt,low:at,manifest:null,max:null,maxLength:at,media:null,method:null,min:null,minLength:at,multiple:Rt,muted:Rt,name:null,nonce:null,noModule:Rt,noValidate:Rt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Rt,optimum:at,pattern:null,ping:ee,placeholder:null,playsInline:Rt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Rt,referrerPolicy:null,rel:ee,required:Rt,reversed:Rt,rows:at,rowSpan:at,sandbox:ee,scope:null,scoped:Rt,seamless:Rt,selected:Rt,shadowRootClonable:Rt,shadowRootDelegatesFocus:Rt,shadowRootMode:null,shape:null,size:at,sizes:null,slot:null,span:at,spellCheck:pe,src:null,srcDoc:null,srcLang:null,srcSet:null,start:at,step:null,style:null,tabIndex:at,target:null,title:null,translate:null,type:null,typeMustMatch:Rt,useMap:null,value:pe,width:at,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ee,axis:null,background:null,bgColor:null,border:at,borderColor:null,bottomMargin:at,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Rt,declare:Rt,event:null,face:null,frame:null,frameBorder:null,hSpace:at,leftMargin:at,link:null,longDesc:null,lowSrc:null,marginHeight:at,marginWidth:at,noResize:Rt,noHref:Rt,noShade:Rt,noWrap:Rt,object:null,profile:null,prompt:null,rev:null,rightMargin:at,rules:null,scheme:null,scrolling:pe,standby:null,summary:null,text:null,topMargin:at,valueType:null,version:null,vAlign:null,vLink:null,vSpace:at,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Rt,disableRemotePlayback:Rt,prefix:null,property:null,results:at,security:null,unselectable:null},space:"html",transform:mm}),oT=Na({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:nn,accentHeight:at,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:at,amplitude:at,arabicForm:null,ascent:at,attributeName:null,attributeType:null,azimuth:at,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:at,by:null,calcMode:null,capHeight:at,className:ee,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:at,diffuseConstant:at,direction:null,display:null,dur:null,divisor:at,dominantBaseline:null,download:Rt,dx:null,dy:null,edgeMode:null,editable:null,elevation:at,enableBackground:null,end:null,event:null,exponent:at,externalResourcesRequired:null,fill:null,fillOpacity:at,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Da,g2:Da,glyphName:Da,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:at,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:at,horizOriginX:at,horizOriginY:at,id:null,ideographic:at,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:at,k:at,k1:at,k2:at,k3:at,k4:at,kernelMatrix:nn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:at,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:at,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:at,overlineThickness:at,paintOrder:null,panose1:null,path:null,pathLength:at,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ee,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:at,pointsAtY:at,pointsAtZ:at,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:nn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:nn,rev:nn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:nn,requiredFeatures:nn,requiredFonts:nn,requiredFormats:nn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:at,specularExponent:at,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:at,strikethroughThickness:at,string:null,stroke:null,strokeDashArray:nn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:at,strokeOpacity:at,strokeWidth:null,style:null,surfaceScale:at,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:nn,tabIndex:at,tableValues:null,target:null,targetX:at,targetY:at,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:nn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:at,underlineThickness:at,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:at,values:null,vAlphabetic:at,vMathematical:at,vectorEffect:null,vHanging:at,vIdeographic:at,version:null,vertAdvY:at,vertOriginX:at,vertOriginY:at,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:at,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:pm}),gm=Na({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(t,n){return"xlink:"+n.slice(5).toLowerCase()}}),ym=Na({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:mm}),bm=Na({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,n){return"xml:"+n.slice(3).toLowerCase()}}),cT={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},fT=/[A-Z]/g,vm=/-[a-z]/g,dT=/^data[-\w.:]+$/i;function hT(t,n){const a=Io(n);let i=n,u=Ye;if(a in t.normal)return t.property[t.normal[a]];if(a.length>4&&a.slice(0,4)==="data"&&dT.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(vm,mT);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!vm.test(o)){let c=o.replace(fT,pT);c.charAt(0)!=="-"&&(c="-"+c),n="data"+c}}u=Uo}return new u(i,n)}function pT(t){return"-"+t.toLowerCase()}function mT(t){return t.charAt(1).toUpperCase()}const gT=fm([hm,uT,gm,ym,bm],"html"),Ho=fm([hm,oT,gm,ym,bm],"svg");function yT(t){return t.join(" ").trim()}var Ia={},qo,xm;function bT(){if(xm)return qo;xm=1;var t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,a=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,u=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,d=/^\s+|\s+$/g,h=`
16
16
  `,m="/",g="*",y="",v="comment",x="declaration";function w(N,z){if(typeof N!="string")throw new TypeError("First argument must be a string");if(!N)return[];z=z||{};var Y=1,I=1;function nt(ut){var rt=ut.match(n);rt&&(Y+=rt.length);var H=ut.lastIndexOf(h);I=~H?ut.length-H:I+ut.length}function it(){var ut={line:Y,column:I};return function(rt){return rt.position=new L(ut),ft(),rt}}function L(ut){this.start=ut,this.end={line:Y,column:I},this.source=z.source}L.prototype.content=N;function W(ut){var rt=new Error(z.source+":"+Y+":"+I+": "+ut);if(rt.reason=ut,rt.filename=z.source,rt.line=Y,rt.column=I,rt.source=N,!z.silent)throw rt}function ot(ut){var rt=ut.exec(N);if(rt){var H=rt[0];return nt(H),N=N.slice(H.length),rt}}function ft(){ot(a)}function j(ut){var rt;for(ut=ut||[];rt=et();)rt!==!1&&ut.push(rt);return ut}function et(){var ut=it();if(!(m!=N.charAt(0)||g!=N.charAt(1))){for(var rt=2;y!=N.charAt(rt)&&(g!=N.charAt(rt)||m!=N.charAt(rt+1));)++rt;if(rt+=2,y===N.charAt(rt-1))return W("End of comment missing");var H=N.slice(2,rt-2);return I+=2,nt(H),N=N.slice(rt),I+=2,ut({type:v,comment:H})}}function J(){var ut=it(),rt=ot(i);if(rt){if(et(),!ot(u))return W("property missing ':'");var H=ot(o),tt=ut({type:x,property:R(rt[0].replace(t,y)),value:H?R(H[0].replace(t,y)):y});return ot(c),tt}}function bt(){var ut=[];j(ut);for(var rt;rt=J();)rt!==!1&&(ut.push(rt),j(ut));return ut}return ft(),bt()}function R(N){return N?N.replace(d,y):y}return qo=w,qo}var Sm;function vT(){if(Sm)return Ia;Sm=1;var t=Ia&&Ia.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.default=a;const n=t(bT());function a(i,u){let o=null;if(!i||typeof i!="string")return o;const c=(0,n.default)(i),d=typeof u=="function";return c.forEach(h=>{if(h.type!=="declaration")return;const{property:m,value:g}=h;d?u(m,g,h):g&&(o=o||{},o[m]=g)}),o}return Ia}var Yi={},wm;function xT(){if(wm)return Yi;wm=1,Object.defineProperty(Yi,"__esModule",{value:!0}),Yi.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,a=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,u=/^-(ms)-/,o=function(m){return!m||a.test(m)||t.test(m)},c=function(m,g){return g.toUpperCase()},d=function(m,g){return"".concat(g,"-")},h=function(m,g){return g===void 0&&(g={}),o(m)?m:(m=m.toLowerCase(),g.reactCompat?m=m.replace(u,d):m=m.replace(i,d),m.replace(n,c))};return Yi.camelCase=h,Yi}var Fi,_m;function ST(){if(_m)return Fi;_m=1;var t=Fi&&Fi.__importDefault||function(u){return u&&u.__esModule?u:{default:u}},n=t(vT()),a=xT();function i(u,o){var c={};return!u||typeof u!="string"||(0,n.default)(u,function(d,h){d&&h&&(c[(0,a.camelCase)(d,o)]=h)}),c}return i.default=i,Fi=i,Fi}var wT=ST();const _T=Kt(wT),Tm=Em("end"),Vo=Em("start");function Em(t){return n;function n(a){const i=a&&a.position&&a.position[t]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function TT(t){const n=Vo(t),a=Tm(t);if(n&&a)return{start:n,end:a}}function Gi(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?Cm(t.position):"start"in t||"end"in t?Cm(t):"line"in t||"column"in t?Yo(t):""}function Yo(t){return Am(t&&t.line)+":"+Am(t&&t.column)}function Cm(t){return Yo(t&&t.start)+"-"+Yo(t&&t.end)}function Am(t){return t&&typeof t=="number"?t:1}class De extends Error{constructor(n,a,i){super(),typeof a=="string"&&(i=a,a=void 0);let u="",o={},c=!1;if(a&&("line"in a&&"column"in a?o={place:a}:"start"in a&&"end"in a?o={place:a}:"type"in a?o={ancestors:[a],place:a.position}:o=_({},a)),typeof n=="string"?u=n:!o.cause&&n&&(c=!0,u=n.message,o.cause=n),!o.ruleId&&!o.source&&typeof i=="string"){const h=i.indexOf(":");h===-1?o.ruleId=i:(o.source=i.slice(0,h),o.ruleId=i.slice(h+1))}if(!o.place&&o.ancestors&&o.ancestors){const h=o.ancestors[o.ancestors.length-1];h&&(o.place=h.position)}const d=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=d?d.column:void 0,this.fatal=void 0,this.file="",this.message=u,this.line=d?d.line:void 0,this.name=Gi(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}De.prototype.file="",De.prototype.name="",De.prototype.reason="",De.prototype.message="",De.prototype.stack="",De.prototype.column=void 0,De.prototype.line=void 0,De.prototype.ancestors=void 0,De.prototype.cause=void 0,De.prototype.fatal=void 0,De.prototype.place=void 0,De.prototype.ruleId=void 0,De.prototype.source=void 0;const Fo={}.hasOwnProperty,ET=new Map,CT=/[A-Z]/g,AT=new Set(["table","tbody","thead","tfoot","tr"]),kT=new Set(["td","th"]),km="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function RT(t,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const a=n.filePath||void 0;let i;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=LT(a,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=jT(a,n.jsx,n.jsxs)}const u={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:i,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:a,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?Ho:gT,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Rm(u,t,void 0);return o&&typeof o!="string"?o:u.create(t,u.Fragment,{children:o||void 0},void 0)}function Rm(t,n,a){if(n.type==="element")return MT(t,n,a);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return zT(t,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return DT(t,n,a);if(n.type==="mdxjsEsm")return OT(t,n);if(n.type==="root")return NT(t,n,a);if(n.type==="text")return IT(t,n)}function MT(t,n,a){const i=t.schema;let u=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(u=Ho,t.schema=u),t.ancestors.push(n);const o=zm(t,n.tagName,!1),c=BT(t,n);let d=Po(t,n);return AT.has(n.tagName)&&(d=d.filter(function(h){return typeof h=="string"?!lT(h):!0})),Mm(t,c,o,n),Go(c,d),t.ancestors.pop(),t.schema=i,t.create(n,o,c,a)}function zT(t,n){if(n.data&&n.data.estree&&t.evaluater){const i=n.data.estree.body[0];return i.type,t.evaluater.evaluateExpression(i.expression)}Pi(t,n.position)}function OT(t,n){if(n.data&&n.data.estree&&t.evaluater)return t.evaluater.evaluateProgram(n.data.estree);Pi(t,n.position)}function DT(t,n,a){const i=t.schema;let u=i;n.name==="svg"&&i.space==="html"&&(u=Ho,t.schema=u),t.ancestors.push(n);const o=n.name===null?t.Fragment:zm(t,n.name,!0),c=UT(t,n),d=Po(t,n);return Mm(t,c,o,n),Go(c,d),t.ancestors.pop(),t.schema=i,t.create(n,o,c,a)}function NT(t,n,a){const i={};return Go(i,Po(t,n)),t.create(n,t.Fragment,i,a)}function IT(t,n){return n.value}function Mm(t,n,a,i){typeof a!="string"&&a!==t.Fragment&&t.passNode&&(n.node=i)}function Go(t,n){if(n.length>0){const a=n.length>1?n:n[0];a&&(t.children=a)}}function jT(t,n,a){return i;function i(u,o,c,d){const m=Array.isArray(c.children)?a:n;return d?m(o,c,d):m(o,c)}}function LT(t,n){return a;function a(i,u,o,c){const d=Array.isArray(o.children),h=Vo(i);return n(u,o,c,d,{columnNumber:h?h.column-1:void 0,fileName:t,lineNumber:h?h.line:void 0},void 0)}}function BT(t,n){const a={};let i,u;for(u in n.properties)if(u!=="children"&&Fo.call(n.properties,u)){const o=HT(t,u,n.properties[u]);if(o){const[c,d]=o;t.tableCellAlignToStyle&&c==="align"&&typeof d=="string"&&kT.has(n.tagName)?i=d:a[c]=d}}if(i){const o=a.style||(a.style={});o[t.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return a}function UT(t,n){const a={};for(const i of n.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&t.evaluater){const o=i.data.estree.body[0];o.type;const c=o.expression;c.type;const d=c.properties[0];d.type,Object.assign(a,t.evaluater.evaluateExpression(d.argument))}else Pi(t,n.position);else{const u=i.name;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&t.evaluater){const d=i.value.data.estree.body[0];d.type,o=t.evaluater.evaluateExpression(d.expression)}else Pi(t,n.position);else o=i.value===null?!0:i.value;a[u]=o}return a}function Po(t,n){const a=[];let i=-1;const u=t.passKeys?new Map:ET;for(;++i<n.children.length;){const o=n.children[i];let c;if(t.passKeys){const h=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(h){const m=u.get(h)||0;c=h+"-"+m,u.set(h,m+1)}}const d=Rm(t,o,c);d!==void 0&&a.push(d)}return a}function HT(t,n,a){const i=hT(t.schema,n);if(!(a==null||typeof a=="number"&&Number.isNaN(a))){if(Array.isArray(a)&&(a=i.commaSeparated?eT(a):yT(a)),i.property==="style"){let u=typeof a=="object"?a:qT(t,String(a));return t.stylePropertyNameCase==="css"&&(u=VT(u)),["style",u]}return[t.elementAttributeNameCase==="react"&&i.space?cT[i.property]||i.property:i.attribute,a]}}function qT(t,n){try{return _T(n,{reactCompat:!0})}catch(a){if(t.ignoreInvalidStyle)return{};const i=a,u=new De("Cannot parse `style` attribute",{ancestors:t.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw u.file=t.filePath||void 0,u.url=km+"#cannot-parse-style-attribute",u}}function zm(t,n,a){let i;if(!a)i={type:"Literal",value:n};else if(n.includes(".")){const u=n.split(".");let o=-1,c;for(;++o<u.length;){const d=om(u[o])?{type:"Identifier",name:u[o]}:{type:"Literal",value:u[o]};c=c?{type:"MemberExpression",object:c,property:d,computed:!!(o&&d.type==="Literal"),optional:!1}:d}i=c}else i=om(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const u=i.value;return Fo.call(t.components,u)?t.components[u]:u}if(t.evaluater)return t.evaluater.evaluateExpression(i);Pi(t)}function Pi(t,n){const a=new De("Cannot handle MDX estrees without `createEvaluater`",{ancestors:t.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw a.file=t.filePath||void 0,a.url=km+"#cannot-handle-mdx-estrees-without-createevaluater",a}function VT(t){const n={};let a;for(a in t)Fo.call(t,a)&&(n[YT(a)]=t[a]);return n}function YT(t){let n=t.replace(CT,FT);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function FT(t){return"-"+t.toLowerCase()}const Xo={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},GT={};function Qo(t,n){const a=GT,i=typeof a.includeImageAlt=="boolean"?a.includeImageAlt:!0,u=typeof a.includeHtml=="boolean"?a.includeHtml:!0;return Om(t,i,u)}function Om(t,n,a){if(PT(t)){if("value"in t)return t.type==="html"&&!a?"":t.value;if(n&&"alt"in t&&t.alt)return t.alt;if("children"in t)return Dm(t.children,n,a)}return Array.isArray(t)?Dm(t,n,a):""}function Dm(t,n,a){const i=[];let u=-1;for(;++u<t.length;)i[u]=Om(t[u],n,a);return i.join("")}function PT(t){return!!(t&&typeof t=="object")}const Nm=document.createElement("i");function Zo(t){const n="&"+t+";";Nm.innerHTML=n;const a=Nm.textContent;return a.charCodeAt(a.length-1)===59&&t!=="semi"||a===n?!1:a}function rn(t,n,a,i){const u=t.length;let o=0,c;if(n<0?n=-n>u?0:u+n:n=n>u?u:n,a=a>0?a:0,i.length<1e4)c=Array.from(i),c.unshift(n,a),t.splice(...c);else for(a&&t.splice(n,a);o<i.length;)c=i.slice(o,o+1e4),c.unshift(n,0),t.splice(...c),o+=1e4,n+=1e4}function pn(t,n){return t.length>0?(rn(t,t.length,0,n),t):n}const Im={}.hasOwnProperty;function jm(t){const n={};let a=-1;for(;++a<t.length;)XT(n,t[a]);return n}function XT(t,n){let a;for(a in n){const u=(Im.call(t,a)?t[a]:void 0)||(t[a]={}),o=n[a];let c;if(o)for(c in o){Im.call(u,c)||(u[c]=[]);const d=o[c];QT(u[c],Array.isArray(d)?d:d?[d]:[])}}}function QT(t,n){let a=-1;const i=[];for(;++a<n.length;)(n[a].add==="after"?t:i).push(n[a]);rn(t,0,0,i)}function Lm(t,n){const a=Number.parseInt(t,n);return a<9||a===11||a>13&&a<32||a>126&&a<160||a>55295&&a<57344||a>64975&&a<65008||(a&65535)===65535||(a&65535)===65534||a>1114111?"�":String.fromCodePoint(a)}function Dn(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Be=br(/[A-Za-z]/),Ne=br(/[\dA-Za-z]/),ZT=br(/[#-'*+\--9=?A-Z^-~]/);function bs(t){return t!==null&&(t<32||t===127)}const Ko=br(/\d/),KT=br(/[\dA-Fa-f]/),JT=br(/[!-/:-@[-`{-~]/);function St(t){return t!==null&&t<-2}function $t(t){return t!==null&&(t<0||t===32)}function zt(t){return t===-2||t===-1||t===32}const vs=br(new RegExp("\\p{P}|\\p{S}","u")),$r=br(/\s/);function br(t){return n;function n(a){return a!==null&&a>-1&&t.test(String.fromCharCode(a))}}function ja(t){const n=[];let a=-1,i=0,u=0;for(;++a<t.length;){const o=t.charCodeAt(a);let c="";if(o===37&&Ne(t.charCodeAt(a+1))&&Ne(t.charCodeAt(a+2)))u=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(c=String.fromCharCode(o));else if(o>55295&&o<57344){const d=t.charCodeAt(a+1);o<56320&&d>56319&&d<57344?(c=String.fromCharCode(o,d),u=1):c="�"}else c=String.fromCharCode(o);c&&(n.push(t.slice(i,a),encodeURIComponent(c)),i=a+u+1,c=""),u&&(a+=u,u=0)}return n.join("")+t.slice(i)}function Ut(t,n,a,i){const u=i?i-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(h){return zt(h)?(t.enter(a),d(h)):n(h)}function d(h){return zt(h)&&o++<u?(t.consume(h),d):(t.exit(a),n(h))}}const $T={tokenize:WT};function WT(t){const n=t.attempt(this.parser.constructs.contentInitial,i,u);let a;return n;function i(d){if(d===null){t.consume(d);return}return t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),Ut(t,n,"linePrefix")}function u(d){return t.enter("paragraph"),o(d)}function o(d){const h=t.enter("chunkText",{contentType:"text",previous:a});return a&&(a.next=h),a=h,c(d)}function c(d){if(d===null){t.exit("chunkText"),t.exit("paragraph"),t.consume(d);return}return St(d)?(t.consume(d),t.exit("chunkText"),o):(t.consume(d),c)}}const tE={tokenize:eE},Bm={tokenize:nE};function eE(t){const n=this,a=[];let i=0,u,o,c;return d;function d(I){if(i<a.length){const nt=a[i];return n.containerState=nt[1],t.attempt(nt[0].continuation,h,m)(I)}return m(I)}function h(I){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,u&&Y();const nt=n.events.length;let it=nt,L;for(;it--;)if(n.events[it][0]==="exit"&&n.events[it][1].type==="chunkFlow"){L=n.events[it][1].end;break}z(i);let W=nt;for(;W<n.events.length;)n.events[W][1].end=_({},L),W++;return rn(n.events,it+1,0,n.events.slice(nt)),n.events.length=W,m(I)}return d(I)}function m(I){if(i===a.length){if(!u)return v(I);if(u.currentConstruct&&u.currentConstruct.concrete)return w(I);n.interrupt=!!(u.currentConstruct&&!u._gfmTableDynamicInterruptHack)}return n.containerState={},t.check(Bm,g,y)(I)}function g(I){return u&&Y(),z(i),v(I)}function y(I){return n.parser.lazy[n.now().line]=i!==a.length,c=n.now().offset,w(I)}function v(I){return n.containerState={},t.attempt(Bm,x,w)(I)}function x(I){return i++,a.push([n.currentConstruct,n.containerState]),v(I)}function w(I){if(I===null){u&&Y(),z(0),t.consume(I);return}return u=u||n.parser.flow(n.now()),t.enter("chunkFlow",{_tokenizer:u,contentType:"flow",previous:o}),R(I)}function R(I){if(I===null){N(t.exit("chunkFlow"),!0),z(0),t.consume(I);return}return St(I)?(t.consume(I),N(t.exit("chunkFlow")),i=0,n.interrupt=void 0,d):(t.consume(I),R)}function N(I,nt){const it=n.sliceStream(I);if(nt&&it.push(null),I.previous=o,o&&(o.next=I),o=I,u.defineSkip(I.start),u.write(it),n.parser.lazy[I.start.line]){let L=u.events.length;for(;L--;)if(u.events[L][1].start.offset<c&&(!u.events[L][1].end||u.events[L][1].end.offset>c))return;const W=n.events.length;let ot=W,ft,j;for(;ot--;)if(n.events[ot][0]==="exit"&&n.events[ot][1].type==="chunkFlow"){if(ft){j=n.events[ot][1].end;break}ft=!0}for(z(i),L=W;L<n.events.length;)n.events[L][1].end=_({},j),L++;rn(n.events,ot+1,0,n.events.slice(W)),n.events.length=L}}function z(I){let nt=a.length;for(;nt-- >I;){const it=a[nt];n.containerState=it[1],it[0].exit.call(n,t)}a.length=I}function Y(){u.write([null]),o=void 0,u=void 0,n.containerState._closeFlow=void 0}}function nE(t,n,a){return Ut(t,t.attempt(this.parser.constructs.document,n,a),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function La(t){if(t===null||$t(t)||$r(t))return 1;if(vs(t))return 2}function xs(t,n,a){const i=[];let u=-1;for(;++u<t.length;){const o=t[u].resolveAll;o&&!i.includes(o)&&(n=o(n,a),i.push(o))}return n}const Jo={name:"attention",resolveAll:rE,tokenize:aE};function rE(t,n){let a=-1,i,u,o,c,d,h,m,g;for(;++a<t.length;)if(t[a][0]==="enter"&&t[a][1].type==="attentionSequence"&&t[a][1]._close){for(i=a;i--;)if(t[i][0]==="exit"&&t[i][1].type==="attentionSequence"&&t[i][1]._open&&n.sliceSerialize(t[i][1]).charCodeAt(0)===n.sliceSerialize(t[a][1]).charCodeAt(0)){if((t[i][1]._close||t[a][1]._open)&&(t[a][1].end.offset-t[a][1].start.offset)%3&&!((t[i][1].end.offset-t[i][1].start.offset+t[a][1].end.offset-t[a][1].start.offset)%3))continue;h=t[i][1].end.offset-t[i][1].start.offset>1&&t[a][1].end.offset-t[a][1].start.offset>1?2:1;const y=_({},t[i][1].end),v=_({},t[a][1].start);Um(y,-h),Um(v,h),c={type:h>1?"strongSequence":"emphasisSequence",start:y,end:_({},t[i][1].end)},d={type:h>1?"strongSequence":"emphasisSequence",start:_({},t[a][1].start),end:v},o={type:h>1?"strongText":"emphasisText",start:_({},t[i][1].end),end:_({},t[a][1].start)},u={type:h>1?"strong":"emphasis",start:_({},c.start),end:_({},d.end)},t[i][1].end=_({},c.start),t[a][1].start=_({},d.end),m=[],t[i][1].end.offset-t[i][1].start.offset&&(m=pn(m,[["enter",t[i][1],n],["exit",t[i][1],n]])),m=pn(m,[["enter",u,n],["enter",c,n],["exit",c,n],["enter",o,n]]),m=pn(m,xs(n.parser.constructs.insideSpan.null,t.slice(i+1,a),n)),m=pn(m,[["exit",o,n],["enter",d,n],["exit",d,n],["exit",u,n]]),t[a][1].end.offset-t[a][1].start.offset?(g=2,m=pn(m,[["enter",t[a][1],n],["exit",t[a][1],n]])):g=0,rn(t,i-1,a-i+3,m),a=i+m.length-g-2;break}}for(a=-1;++a<t.length;)t[a][1].type==="attentionSequence"&&(t[a][1].type="data");return t}function aE(t,n){const a=this.parser.constructs.attentionMarkers.null,i=this.previous,u=La(i);let o;return c;function c(h){return o=h,t.enter("attentionSequence"),d(h)}function d(h){if(h===o)return t.consume(h),d;const m=t.exit("attentionSequence"),g=La(h),y=!g||g===2&&u||a.includes(h),v=!u||u===2&&g||a.includes(i);return m._open=!!(o===42?y:y&&(u||!v)),m._close=!!(o===42?v:v&&(g||!y)),n(h)}}function Um(t,n){t.column+=n,t.offset+=n,t._bufferIndex+=n}const iE={name:"autolink",tokenize:lE};function lE(t,n,a){let i=0;return u;function u(x){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(x),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),o}function o(x){return Be(x)?(t.consume(x),c):x===64?a(x):m(x)}function c(x){return x===43||x===45||x===46||Ne(x)?(i=1,d(x)):m(x)}function d(x){return x===58?(t.consume(x),i=0,h):(x===43||x===45||x===46||Ne(x))&&i++<32?(t.consume(x),d):(i=0,m(x))}function h(x){return x===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(x),t.exit("autolinkMarker"),t.exit("autolink"),n):x===null||x===32||x===60||bs(x)?a(x):(t.consume(x),h)}function m(x){return x===64?(t.consume(x),g):ZT(x)?(t.consume(x),m):a(x)}function g(x){return Ne(x)?y(x):a(x)}function y(x){return x===46?(t.consume(x),i=0,g):x===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(x),t.exit("autolinkMarker"),t.exit("autolink"),n):v(x)}function v(x){if((x===45||Ne(x))&&i++<63){const w=x===45?v:y;return t.consume(x),w}return a(x)}}const Xi={partial:!0,tokenize:sE};function sE(t,n,a){return i;function i(o){return zt(o)?Ut(t,u,"linePrefix")(o):u(o)}function u(o){return o===null||St(o)?n(o):a(o)}}const Hm={continuation:{tokenize:oE},exit:cE,name:"blockQuote",tokenize:uE};function uE(t,n,a){const i=this;return u;function u(c){if(c===62){const d=i.containerState;return d.open||(t.enter("blockQuote",{_container:!0}),d.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(c),t.exit("blockQuoteMarker"),o}return a(c)}function o(c){return zt(c)?(t.enter("blockQuotePrefixWhitespace"),t.consume(c),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),n):(t.exit("blockQuotePrefix"),n(c))}}function oE(t,n,a){const i=this;return u;function u(c){return zt(c)?Ut(t,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c):o(c)}function o(c){return t.attempt(Hm,n,a)(c)}}function cE(t){t.exit("blockQuote")}const qm={name:"characterEscape",tokenize:fE};function fE(t,n,a){return i;function i(o){return t.enter("characterEscape"),t.enter("escapeMarker"),t.consume(o),t.exit("escapeMarker"),u}function u(o){return JT(o)?(t.enter("characterEscapeValue"),t.consume(o),t.exit("characterEscapeValue"),t.exit("characterEscape"),n):a(o)}}const Vm={name:"characterReference",tokenize:dE};function dE(t,n,a){const i=this;let u=0,o,c;return d;function d(y){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(y),t.exit("characterReferenceMarker"),h}function h(y){return y===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(y),t.exit("characterReferenceMarkerNumeric"),m):(t.enter("characterReferenceValue"),o=31,c=Ne,g(y))}function m(y){return y===88||y===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(y),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),o=6,c=KT,g):(t.enter("characterReferenceValue"),o=7,c=Ko,g(y))}function g(y){if(y===59&&u){const v=t.exit("characterReferenceValue");return c===Ne&&!Zo(i.sliceSerialize(v))?a(y):(t.enter("characterReferenceMarker"),t.consume(y),t.exit("characterReferenceMarker"),t.exit("characterReference"),n)}return c(y)&&u++<o?(t.consume(y),g):a(y)}}const Ym={partial:!0,tokenize:pE},Fm={concrete:!0,name:"codeFenced",tokenize:hE};function hE(t,n,a){const i=this,u={partial:!0,tokenize:it};let o=0,c=0,d;return h;function h(L){return m(L)}function m(L){const W=i.events[i.events.length-1];return o=W&&W[1].type==="linePrefix"?W[2].sliceSerialize(W[1],!0).length:0,d=L,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),g(L)}function g(L){return L===d?(c++,t.consume(L),g):c<3?a(L):(t.exit("codeFencedFenceSequence"),zt(L)?Ut(t,y,"whitespace")(L):y(L))}function y(L){return L===null||St(L)?(t.exit("codeFencedFence"),i.interrupt?n(L):t.check(Ym,R,nt)(L)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),v(L))}function v(L){return L===null||St(L)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),y(L)):zt(L)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Ut(t,x,"whitespace")(L)):L===96&&L===d?a(L):(t.consume(L),v)}function x(L){return L===null||St(L)?y(L):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),w(L))}function w(L){return L===null||St(L)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),y(L)):L===96&&L===d?a(L):(t.consume(L),w)}function R(L){return t.attempt(u,nt,N)(L)}function N(L){return t.enter("lineEnding"),t.consume(L),t.exit("lineEnding"),z}function z(L){return o>0&&zt(L)?Ut(t,Y,"linePrefix",o+1)(L):Y(L)}function Y(L){return L===null||St(L)?t.check(Ym,R,nt)(L):(t.enter("codeFlowValue"),I(L))}function I(L){return L===null||St(L)?(t.exit("codeFlowValue"),Y(L)):(t.consume(L),I)}function nt(L){return t.exit("codeFenced"),n(L)}function it(L,W,ot){let ft=0;return j;function j(rt){return L.enter("lineEnding"),L.consume(rt),L.exit("lineEnding"),et}function et(rt){return L.enter("codeFencedFence"),zt(rt)?Ut(L,J,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(rt):J(rt)}function J(rt){return rt===d?(L.enter("codeFencedFenceSequence"),bt(rt)):ot(rt)}function bt(rt){return rt===d?(ft++,L.consume(rt),bt):ft>=c?(L.exit("codeFencedFenceSequence"),zt(rt)?Ut(L,ut,"whitespace")(rt):ut(rt)):ot(rt)}function ut(rt){return rt===null||St(rt)?(L.exit("codeFencedFence"),W(rt)):ot(rt)}}}function pE(t,n,a){const i=this;return u;function u(c){return c===null?a(c):(t.enter("lineEnding"),t.consume(c),t.exit("lineEnding"),o)}function o(c){return i.parser.lazy[i.now().line]?a(c):n(c)}}const $o={name:"codeIndented",tokenize:gE},mE={partial:!0,tokenize:yE};function gE(t,n,a){const i=this;return u;function u(m){return t.enter("codeIndented"),Ut(t,o,"linePrefix",5)(m)}function o(m){const g=i.events[i.events.length-1];return g&&g[1].type==="linePrefix"&&g[2].sliceSerialize(g[1],!0).length>=4?c(m):a(m)}function c(m){return m===null?h(m):St(m)?t.attempt(mE,c,h)(m):(t.enter("codeFlowValue"),d(m))}function d(m){return m===null||St(m)?(t.exit("codeFlowValue"),c(m)):(t.consume(m),d)}function h(m){return t.exit("codeIndented"),n(m)}}function yE(t,n,a){const i=this;return u;function u(c){return i.parser.lazy[i.now().line]?a(c):St(c)?(t.enter("lineEnding"),t.consume(c),t.exit("lineEnding"),u):Ut(t,o,"linePrefix",5)(c)}function o(c){const d=i.events[i.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?n(c):St(c)?u(c):a(c)}}const bE={name:"codeText",previous:xE,resolve:vE,tokenize:SE};function vE(t){let n=t.length-4,a=3,i,u;if((t[a][1].type==="lineEnding"||t[a][1].type==="space")&&(t[n][1].type==="lineEnding"||t[n][1].type==="space")){for(i=a;++i<n;)if(t[i][1].type==="codeTextData"){t[a][1].type="codeTextPadding",t[n][1].type="codeTextPadding",a+=2,n-=2;break}}for(i=a-1,n++;++i<=n;)u===void 0?i!==n&&t[i][1].type!=="lineEnding"&&(u=i):(i===n||t[i][1].type==="lineEnding")&&(t[u][1].type="codeTextData",i!==u+2&&(t[u][1].end=t[i-1][1].end,t.splice(u+2,i-u-2),n-=i-u-2,i=u+2),u=void 0);return t}function xE(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function SE(t,n,a){let i=0,u,o;return c;function c(y){return t.enter("codeText"),t.enter("codeTextSequence"),d(y)}function d(y){return y===96?(t.consume(y),i++,d):(t.exit("codeTextSequence"),h(y))}function h(y){return y===null?a(y):y===32?(t.enter("space"),t.consume(y),t.exit("space"),h):y===96?(o=t.enter("codeTextSequence"),u=0,g(y)):St(y)?(t.enter("lineEnding"),t.consume(y),t.exit("lineEnding"),h):(t.enter("codeTextData"),m(y))}function m(y){return y===null||y===32||y===96||St(y)?(t.exit("codeTextData"),h(y)):(t.consume(y),m)}function g(y){return y===96?(t.consume(y),u++,g):u===i?(t.exit("codeTextSequence"),t.exit("codeText"),n(y)):(o.type="codeTextData",m(y))}}class wE{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,a){const i=a==null?Number.POSITIVE_INFINITY:a;return i<this.left.length?this.left.slice(n,i):n>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(n,a,i){const u=a||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-u,Number.POSITIVE_INFINITY);return i&&Qi(this.left,i),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),Qi(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Qi(this.right,n.reverse())}setCursor(n){if(!(n===this.left.length||n>this.left.length&&this.right.length===0||n<0&&this.left.length===0))if(n<this.left.length){const a=this.left.splice(n,Number.POSITIVE_INFINITY);Qi(this.right,a.reverse())}else{const a=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Qi(this.left,a.reverse())}}}function Qi(t,n){let a=0;if(n.length<1e4)t.push(...n);else for(;a<n.length;)t.push(...n.slice(a,a+1e4)),a+=1e4}function Gm(t){const n={};let a=-1,i,u,o,c,d,h,m;const g=new wE(t);for(;++a<g.length;){for(;a in n;)a=n[a];if(i=g.get(a),a&&i[1].type==="chunkFlow"&&g.get(a-1)[1].type==="listItemPrefix"&&(h=i[1]._tokenizer.events,o=0,o<h.length&&h[o][1].type==="lineEndingBlank"&&(o+=2),o<h.length&&h[o][1].type==="content"))for(;++o<h.length&&h[o][1].type!=="content";)h[o][1].type==="chunkText"&&(h[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(n,_E(g,a)),a=n[a],m=!0);else if(i[1]._container){for(o=a,u=void 0;o--;)if(c=g.get(o),c[1].type==="lineEnding"||c[1].type==="lineEndingBlank")c[0]==="enter"&&(u&&(g.get(u)[1].type="lineEndingBlank"),c[1].type="lineEnding",u=o);else if(!(c[1].type==="linePrefix"||c[1].type==="listItemIndent"))break;u&&(i[1].end=_({},g.get(u)[1].start),d=g.slice(u,a),d.unshift(i),g.splice(u,a-u+1,d))}}return rn(t,0,Number.POSITIVE_INFINITY,g.slice(0)),!m}function _E(t,n){const a=t.get(n)[1],i=t.get(n)[2];let u=n-1;const o=[];let c=a._tokenizer;c||(c=i.parser[a.contentType](a.start),a._contentTypeTextTrailing&&(c._contentTypeTextTrailing=!0));const d=c.events,h=[],m={};let g,y,v=-1,x=a,w=0,R=0;const N=[R];for(;x;){for(;t.get(++u)[1]!==x;);o.push(u),x._tokenizer||(g=i.sliceStream(x),x.next||g.push(null),y&&c.defineSkip(x.start),x._isInFirstContentOfListItem&&(c._gfmTasklistFirstContentOfListItem=!0),c.write(g),x._isInFirstContentOfListItem&&(c._gfmTasklistFirstContentOfListItem=void 0)),y=x,x=x.next}for(x=a;++v<d.length;)d[v][0]==="exit"&&d[v-1][0]==="enter"&&d[v][1].type===d[v-1][1].type&&d[v][1].start.line!==d[v][1].end.line&&(R=v+1,N.push(R),x._tokenizer=void 0,x.previous=void 0,x=x.next);for(c.events=[],x?(x._tokenizer=void 0,x.previous=void 0):N.pop(),v=N.length;v--;){const z=d.slice(N[v],N[v+1]),Y=o.pop();h.push([Y,Y+z.length-1]),t.splice(Y,2,z)}for(h.reverse(),v=-1;++v<h.length;)m[w+h[v][0]]=w+h[v][1],w+=h[v][1]-h[v][0]-1;return m}const TE={resolve:CE,tokenize:AE},EE={partial:!0,tokenize:kE};function CE(t){return Gm(t),t}function AE(t,n){let a;return i;function i(d){return t.enter("content"),a=t.enter("chunkContent",{contentType:"content"}),u(d)}function u(d){return d===null?o(d):St(d)?t.check(EE,c,o)(d):(t.consume(d),u)}function o(d){return t.exit("chunkContent"),t.exit("content"),n(d)}function c(d){return t.consume(d),t.exit("chunkContent"),a.next=t.enter("chunkContent",{contentType:"content",previous:a}),a=a.next,u}}function kE(t,n,a){const i=this;return u;function u(c){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(c),t.exit("lineEnding"),Ut(t,o,"linePrefix")}function o(c){if(c===null||St(c))return a(c);const d=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?n(c):t.interrupt(i.parser.constructs.flow,a,n)(c)}}function Pm(t,n,a,i,u,o,c,d,h){const m=h||Number.POSITIVE_INFINITY;let g=0;return y;function y(z){return z===60?(t.enter(i),t.enter(u),t.enter(o),t.consume(z),t.exit(o),v):z===null||z===32||z===41||bs(z)?a(z):(t.enter(i),t.enter(c),t.enter(d),t.enter("chunkString",{contentType:"string"}),R(z))}function v(z){return z===62?(t.enter(o),t.consume(z),t.exit(o),t.exit(u),t.exit(i),n):(t.enter(d),t.enter("chunkString",{contentType:"string"}),x(z))}function x(z){return z===62?(t.exit("chunkString"),t.exit(d),v(z)):z===null||z===60||St(z)?a(z):(t.consume(z),z===92?w:x)}function w(z){return z===60||z===62||z===92?(t.consume(z),x):x(z)}function R(z){return!g&&(z===null||z===41||$t(z))?(t.exit("chunkString"),t.exit(d),t.exit(c),t.exit(i),n(z)):g<m&&z===40?(t.consume(z),g++,R):z===41?(t.consume(z),g--,R):z===null||z===32||z===40||bs(z)?a(z):(t.consume(z),z===92?N:R)}function N(z){return z===40||z===41||z===92?(t.consume(z),R):R(z)}}function Xm(t,n,a,i,u,o){const c=this;let d=0,h;return m;function m(x){return t.enter(i),t.enter(u),t.consume(x),t.exit(u),t.enter(o),g}function g(x){return d>999||x===null||x===91||x===93&&!h||x===94&&!d&&"_hiddenFootnoteSupport"in c.parser.constructs?a(x):x===93?(t.exit(o),t.enter(u),t.consume(x),t.exit(u),t.exit(i),n):St(x)?(t.enter("lineEnding"),t.consume(x),t.exit("lineEnding"),g):(t.enter("chunkString",{contentType:"string"}),y(x))}function y(x){return x===null||x===91||x===93||St(x)||d++>999?(t.exit("chunkString"),g(x)):(t.consume(x),h||(h=!zt(x)),x===92?v:y)}function v(x){return x===91||x===92||x===93?(t.consume(x),d++,y):y(x)}}function Qm(t,n,a,i,u,o){let c;return d;function d(v){return v===34||v===39||v===40?(t.enter(i),t.enter(u),t.consume(v),t.exit(u),c=v===40?41:v,h):a(v)}function h(v){return v===c?(t.enter(u),t.consume(v),t.exit(u),t.exit(i),n):(t.enter(o),m(v))}function m(v){return v===c?(t.exit(o),h(c)):v===null?a(v):St(v)?(t.enter("lineEnding"),t.consume(v),t.exit("lineEnding"),Ut(t,m,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),g(v))}function g(v){return v===c||v===null||St(v)?(t.exit("chunkString"),m(v)):(t.consume(v),v===92?y:g)}function y(v){return v===c||v===92?(t.consume(v),g):g(v)}}function Zi(t,n){let a;return i;function i(u){return St(u)?(t.enter("lineEnding"),t.consume(u),t.exit("lineEnding"),a=!0,i):zt(u)?Ut(t,i,a?"linePrefix":"lineSuffix")(u):n(u)}}const RE={name:"definition",tokenize:zE},ME={partial:!0,tokenize:OE};function zE(t,n,a){const i=this;let u;return o;function o(x){return t.enter("definition"),c(x)}function c(x){return Xm.call(i,t,d,a,"definitionLabel","definitionLabelMarker","definitionLabelString")(x)}function d(x){return u=Dn(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),x===58?(t.enter("definitionMarker"),t.consume(x),t.exit("definitionMarker"),h):a(x)}function h(x){return $t(x)?Zi(t,m)(x):m(x)}function m(x){return Pm(t,g,a,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(x)}function g(x){return t.attempt(ME,y,y)(x)}function y(x){return zt(x)?Ut(t,v,"whitespace")(x):v(x)}function v(x){return x===null||St(x)?(t.exit("definition"),i.parser.defined.push(u),n(x)):a(x)}}function OE(t,n,a){return i;function i(d){return $t(d)?Zi(t,u)(d):a(d)}function u(d){return Qm(t,o,a,"definitionTitle","definitionTitleMarker","definitionTitleString")(d)}function o(d){return zt(d)?Ut(t,c,"whitespace")(d):c(d)}function c(d){return d===null||St(d)?n(d):a(d)}}const DE={name:"hardBreakEscape",tokenize:NE};function NE(t,n,a){return i;function i(o){return t.enter("hardBreakEscape"),t.consume(o),u}function u(o){return St(o)?(t.exit("hardBreakEscape"),n(o)):a(o)}}const IE={name:"headingAtx",resolve:jE,tokenize:LE};function jE(t,n){let a=t.length-2,i=3,u,o;return t[i][1].type==="whitespace"&&(i+=2),a-2>i&&t[a][1].type==="whitespace"&&(a-=2),t[a][1].type==="atxHeadingSequence"&&(i===a-1||a-4>i&&t[a-2][1].type==="whitespace")&&(a-=i+1===a?2:4),a>i&&(u={type:"atxHeadingText",start:t[i][1].start,end:t[a][1].end},o={type:"chunkText",start:t[i][1].start,end:t[a][1].end,contentType:"text"},rn(t,i,a-i+1,[["enter",u,n],["enter",o,n],["exit",o,n],["exit",u,n]])),t}function LE(t,n,a){let i=0;return u;function u(g){return t.enter("atxHeading"),o(g)}function o(g){return t.enter("atxHeadingSequence"),c(g)}function c(g){return g===35&&i++<6?(t.consume(g),c):g===null||$t(g)?(t.exit("atxHeadingSequence"),d(g)):a(g)}function d(g){return g===35?(t.enter("atxHeadingSequence"),h(g)):g===null||St(g)?(t.exit("atxHeading"),n(g)):zt(g)?Ut(t,d,"whitespace")(g):(t.enter("atxHeadingText"),m(g))}function h(g){return g===35?(t.consume(g),h):(t.exit("atxHeadingSequence"),d(g))}function m(g){return g===null||g===35||$t(g)?(t.exit("atxHeadingText"),d(g)):(t.consume(g),m)}}const BE=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Zm=["pre","script","style","textarea"],UE={concrete:!0,name:"htmlFlow",resolveTo:VE,tokenize:YE},HE={partial:!0,tokenize:GE},qE={partial:!0,tokenize:FE};function VE(t){let n=t.length;for(;n--&&!(t[n][0]==="enter"&&t[n][1].type==="htmlFlow"););return n>1&&t[n-2][1].type==="linePrefix"&&(t[n][1].start=t[n-2][1].start,t[n+1][1].start=t[n-2][1].start,t.splice(n-2,2)),t}function YE(t,n,a){const i=this;let u,o,c,d,h;return m;function m(T){return g(T)}function g(T){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(T),y}function y(T){return T===33?(t.consume(T),v):T===47?(t.consume(T),o=!0,R):T===63?(t.consume(T),u=3,i.interrupt?n:C):Be(T)?(t.consume(T),c=String.fromCharCode(T),N):a(T)}function v(T){return T===45?(t.consume(T),u=2,x):T===91?(t.consume(T),u=5,d=0,w):Be(T)?(t.consume(T),u=4,i.interrupt?n:C):a(T)}function x(T){return T===45?(t.consume(T),i.interrupt?n:C):a(T)}function w(T){const st="CDATA[";return T===st.charCodeAt(d++)?(t.consume(T),d===st.length?i.interrupt?n:J:w):a(T)}function R(T){return Be(T)?(t.consume(T),c=String.fromCharCode(T),N):a(T)}function N(T){if(T===null||T===47||T===62||$t(T)){const st=T===47,vt=c.toLowerCase();return!st&&!o&&Zm.includes(vt)?(u=1,i.interrupt?n(T):J(T)):BE.includes(c.toLowerCase())?(u=6,st?(t.consume(T),z):i.interrupt?n(T):J(T)):(u=7,i.interrupt&&!i.parser.lazy[i.now().line]?a(T):o?Y(T):I(T))}return T===45||Ne(T)?(t.consume(T),c+=String.fromCharCode(T),N):a(T)}function z(T){return T===62?(t.consume(T),i.interrupt?n:J):a(T)}function Y(T){return zt(T)?(t.consume(T),Y):j(T)}function I(T){return T===47?(t.consume(T),j):T===58||T===95||Be(T)?(t.consume(T),nt):zt(T)?(t.consume(T),I):j(T)}function nt(T){return T===45||T===46||T===58||T===95||Ne(T)?(t.consume(T),nt):it(T)}function it(T){return T===61?(t.consume(T),L):zt(T)?(t.consume(T),it):I(T)}function L(T){return T===null||T===60||T===61||T===62||T===96?a(T):T===34||T===39?(t.consume(T),h=T,W):zt(T)?(t.consume(T),L):ot(T)}function W(T){return T===h?(t.consume(T),h=null,ft):T===null||St(T)?a(T):(t.consume(T),W)}function ot(T){return T===null||T===34||T===39||T===47||T===60||T===61||T===62||T===96||$t(T)?it(T):(t.consume(T),ot)}function ft(T){return T===47||T===62||zt(T)?I(T):a(T)}function j(T){return T===62?(t.consume(T),et):a(T)}function et(T){return T===null||St(T)?J(T):zt(T)?(t.consume(T),et):a(T)}function J(T){return T===45&&u===2?(t.consume(T),H):T===60&&u===1?(t.consume(T),tt):T===62&&u===4?(t.consume(T),k):T===63&&u===3?(t.consume(T),C):T===93&&u===5?(t.consume(T),Tt):St(T)&&(u===6||u===7)?(t.exit("htmlFlowData"),t.check(HE,P,bt)(T)):T===null||St(T)?(t.exit("htmlFlowData"),bt(T)):(t.consume(T),J)}function bt(T){return t.check(qE,ut,P)(T)}function ut(T){return t.enter("lineEnding"),t.consume(T),t.exit("lineEnding"),rt}function rt(T){return T===null||St(T)?bt(T):(t.enter("htmlFlowData"),J(T))}function H(T){return T===45?(t.consume(T),C):J(T)}function tt(T){return T===47?(t.consume(T),c="",ct):J(T)}function ct(T){if(T===62){const st=c.toLowerCase();return Zm.includes(st)?(t.consume(T),k):J(T)}return Be(T)&&c.length<8?(t.consume(T),c+=String.fromCharCode(T),ct):J(T)}function Tt(T){return T===93?(t.consume(T),C):J(T)}function C(T){return T===62?(t.consume(T),k):T===45&&u===2?(t.consume(T),C):J(T)}function k(T){return T===null||St(T)?(t.exit("htmlFlowData"),P(T)):(t.consume(T),k)}function P(T){return t.exit("htmlFlow"),n(T)}}function FE(t,n,a){const i=this;return u;function u(c){return St(c)?(t.enter("lineEnding"),t.consume(c),t.exit("lineEnding"),o):a(c)}function o(c){return i.parser.lazy[i.now().line]?a(c):n(c)}}function GE(t,n,a){return i;function i(u){return t.enter("lineEnding"),t.consume(u),t.exit("lineEnding"),t.attempt(Xi,n,a)}}const PE={name:"htmlText",tokenize:XE};function XE(t,n,a){const i=this;let u,o,c;return d;function d(C){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(C),h}function h(C){return C===33?(t.consume(C),m):C===47?(t.consume(C),it):C===63?(t.consume(C),I):Be(C)?(t.consume(C),ot):a(C)}function m(C){return C===45?(t.consume(C),g):C===91?(t.consume(C),o=0,w):Be(C)?(t.consume(C),Y):a(C)}function g(C){return C===45?(t.consume(C),x):a(C)}function y(C){return C===null?a(C):C===45?(t.consume(C),v):St(C)?(c=y,tt(C)):(t.consume(C),y)}function v(C){return C===45?(t.consume(C),x):y(C)}function x(C){return C===62?H(C):C===45?v(C):y(C)}function w(C){const k="CDATA[";return C===k.charCodeAt(o++)?(t.consume(C),o===k.length?R:w):a(C)}function R(C){return C===null?a(C):C===93?(t.consume(C),N):St(C)?(c=R,tt(C)):(t.consume(C),R)}function N(C){return C===93?(t.consume(C),z):R(C)}function z(C){return C===62?H(C):C===93?(t.consume(C),z):R(C)}function Y(C){return C===null||C===62?H(C):St(C)?(c=Y,tt(C)):(t.consume(C),Y)}function I(C){return C===null?a(C):C===63?(t.consume(C),nt):St(C)?(c=I,tt(C)):(t.consume(C),I)}function nt(C){return C===62?H(C):I(C)}function it(C){return Be(C)?(t.consume(C),L):a(C)}function L(C){return C===45||Ne(C)?(t.consume(C),L):W(C)}function W(C){return St(C)?(c=W,tt(C)):zt(C)?(t.consume(C),W):H(C)}function ot(C){return C===45||Ne(C)?(t.consume(C),ot):C===47||C===62||$t(C)?ft(C):a(C)}function ft(C){return C===47?(t.consume(C),H):C===58||C===95||Be(C)?(t.consume(C),j):St(C)?(c=ft,tt(C)):zt(C)?(t.consume(C),ft):H(C)}function j(C){return C===45||C===46||C===58||C===95||Ne(C)?(t.consume(C),j):et(C)}function et(C){return C===61?(t.consume(C),J):St(C)?(c=et,tt(C)):zt(C)?(t.consume(C),et):ft(C)}function J(C){return C===null||C===60||C===61||C===62||C===96?a(C):C===34||C===39?(t.consume(C),u=C,bt):St(C)?(c=J,tt(C)):zt(C)?(t.consume(C),J):(t.consume(C),ut)}function bt(C){return C===u?(t.consume(C),u=void 0,rt):C===null?a(C):St(C)?(c=bt,tt(C)):(t.consume(C),bt)}function ut(C){return C===null||C===34||C===39||C===60||C===61||C===96?a(C):C===47||C===62||$t(C)?ft(C):(t.consume(C),ut)}function rt(C){return C===47||C===62||$t(C)?ft(C):a(C)}function H(C){return C===62?(t.consume(C),t.exit("htmlTextData"),t.exit("htmlText"),n):a(C)}function tt(C){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(C),t.exit("lineEnding"),ct}function ct(C){return zt(C)?Ut(t,Tt,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):Tt(C)}function Tt(C){return t.enter("htmlTextData"),c(C)}}const Wo={name:"labelEnd",resolveAll:JE,resolveTo:$E,tokenize:WE},QE={tokenize:tC},ZE={tokenize:eC},KE={tokenize:nC};function JE(t){let n=-1;const a=[];for(;++n<t.length;){const i=t[n][1];if(a.push(t[n]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const u=i.type==="labelImage"?4:2;i.type="data",n+=u}}return t.length!==a.length&&rn(t,0,t.length,a),t}function $E(t,n){let a=t.length,i=0,u,o,c,d;for(;a--;)if(u=t[a][1],o){if(u.type==="link"||u.type==="labelLink"&&u._inactive)break;t[a][0]==="enter"&&u.type==="labelLink"&&(u._inactive=!0)}else if(c){if(t[a][0]==="enter"&&(u.type==="labelImage"||u.type==="labelLink")&&!u._balanced&&(o=a,u.type!=="labelLink")){i=2;break}}else u.type==="labelEnd"&&(c=a);const h={type:t[o][1].type==="labelLink"?"link":"image",start:_({},t[o][1].start),end:_({},t[t.length-1][1].end)},m={type:"label",start:_({},t[o][1].start),end:_({},t[c][1].end)},g={type:"labelText",start:_({},t[o+i+2][1].end),end:_({},t[c-2][1].start)};return d=[["enter",h,n],["enter",m,n]],d=pn(d,t.slice(o+1,o+i+3)),d=pn(d,[["enter",g,n]]),d=pn(d,xs(n.parser.constructs.insideSpan.null,t.slice(o+i+4,c-3),n)),d=pn(d,[["exit",g,n],t[c-2],t[c-1],["exit",m,n]]),d=pn(d,t.slice(c+1)),d=pn(d,[["exit",h,n]]),rn(t,o,t.length,d),t}function WE(t,n,a){const i=this;let u=i.events.length,o,c;for(;u--;)if((i.events[u][1].type==="labelImage"||i.events[u][1].type==="labelLink")&&!i.events[u][1]._balanced){o=i.events[u][1];break}return d;function d(v){return o?o._inactive?y(v):(c=i.parser.defined.includes(Dn(i.sliceSerialize({start:o.end,end:i.now()}))),t.enter("labelEnd"),t.enter("labelMarker"),t.consume(v),t.exit("labelMarker"),t.exit("labelEnd"),h):a(v)}function h(v){return v===40?t.attempt(QE,g,c?g:y)(v):v===91?t.attempt(ZE,g,c?m:y)(v):c?g(v):y(v)}function m(v){return t.attempt(KE,g,y)(v)}function g(v){return n(v)}function y(v){return o._balanced=!0,a(v)}}function tC(t,n,a){return i;function i(y){return t.enter("resource"),t.enter("resourceMarker"),t.consume(y),t.exit("resourceMarker"),u}function u(y){return $t(y)?Zi(t,o)(y):o(y)}function o(y){return y===41?g(y):Pm(t,c,d,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(y)}function c(y){return $t(y)?Zi(t,h)(y):g(y)}function d(y){return a(y)}function h(y){return y===34||y===39||y===40?Qm(t,m,a,"resourceTitle","resourceTitleMarker","resourceTitleString")(y):g(y)}function m(y){return $t(y)?Zi(t,g)(y):g(y)}function g(y){return y===41?(t.enter("resourceMarker"),t.consume(y),t.exit("resourceMarker"),t.exit("resource"),n):a(y)}}function eC(t,n,a){const i=this;return u;function u(d){return Xm.call(i,t,o,c,"reference","referenceMarker","referenceString")(d)}function o(d){return i.parser.defined.includes(Dn(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(d):a(d)}function c(d){return a(d)}}function nC(t,n,a){return i;function i(o){return t.enter("reference"),t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),u}function u(o){return o===93?(t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),t.exit("reference"),n):a(o)}}const rC={name:"labelStartImage",resolveAll:Wo.resolveAll,tokenize:aC};function aC(t,n,a){const i=this;return u;function u(d){return t.enter("labelImage"),t.enter("labelImageMarker"),t.consume(d),t.exit("labelImageMarker"),o}function o(d){return d===91?(t.enter("labelMarker"),t.consume(d),t.exit("labelMarker"),t.exit("labelImage"),c):a(d)}function c(d){return d===94&&"_hiddenFootnoteSupport"in i.parser.constructs?a(d):n(d)}}const iC={name:"labelStartLink",resolveAll:Wo.resolveAll,tokenize:lC};function lC(t,n,a){const i=this;return u;function u(c){return t.enter("labelLink"),t.enter("labelMarker"),t.consume(c),t.exit("labelMarker"),t.exit("labelLink"),o}function o(c){return c===94&&"_hiddenFootnoteSupport"in i.parser.constructs?a(c):n(c)}}const tc={name:"lineEnding",tokenize:sC};function sC(t,n){return a;function a(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),Ut(t,n,"linePrefix")}}const Ss={name:"thematicBreak",tokenize:uC};function uC(t,n,a){let i=0,u;return o;function o(m){return t.enter("thematicBreak"),c(m)}function c(m){return u=m,d(m)}function d(m){return m===u?(t.enter("thematicBreakSequence"),h(m)):i>=3&&(m===null||St(m))?(t.exit("thematicBreak"),n(m)):a(m)}function h(m){return m===u?(t.consume(m),i++,h):(t.exit("thematicBreakSequence"),zt(m)?Ut(t,d,"whitespace")(m):d(m))}}const Fe={continuation:{tokenize:dC},exit:pC,name:"list",tokenize:fC},oC={partial:!0,tokenize:mC},cC={partial:!0,tokenize:hC};function fC(t,n,a){const i=this,u=i.events[i.events.length-1];let o=u&&u[1].type==="linePrefix"?u[2].sliceSerialize(u[1],!0).length:0,c=0;return d;function d(x){const w=i.containerState.type||(x===42||x===43||x===45?"listUnordered":"listOrdered");if(w==="listUnordered"?!i.containerState.marker||x===i.containerState.marker:Ko(x)){if(i.containerState.type||(i.containerState.type=w,t.enter(w,{_container:!0})),w==="listUnordered")return t.enter("listItemPrefix"),x===42||x===45?t.check(Ss,a,m)(x):m(x);if(!i.interrupt||x===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),h(x)}return a(x)}function h(x){return Ko(x)&&++c<10?(t.consume(x),h):(!i.interrupt||c<2)&&(i.containerState.marker?x===i.containerState.marker:x===41||x===46)?(t.exit("listItemValue"),m(x)):a(x)}function m(x){return t.enter("listItemMarker"),t.consume(x),t.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||x,t.check(Xi,i.interrupt?a:g,t.attempt(oC,v,y))}function g(x){return i.containerState.initialBlankLine=!0,o++,v(x)}function y(x){return zt(x)?(t.enter("listItemPrefixWhitespace"),t.consume(x),t.exit("listItemPrefixWhitespace"),v):a(x)}function v(x){return i.containerState.size=o+i.sliceSerialize(t.exit("listItemPrefix"),!0).length,n(x)}}function dC(t,n,a){const i=this;return i.containerState._closeFlow=void 0,t.check(Xi,u,o);function u(d){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Ut(t,n,"listItemIndent",i.containerState.size+1)(d)}function o(d){return i.containerState.furtherBlankLines||!zt(d)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,c(d)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,t.attempt(cC,n,c)(d))}function c(d){return i.containerState._closeFlow=!0,i.interrupt=void 0,Ut(t,t.attempt(Fe,n,a),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(d)}}function hC(t,n,a){const i=this;return Ut(t,u,"listItemIndent",i.containerState.size+1);function u(o){const c=i.events[i.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===i.containerState.size?n(o):a(o)}}function pC(t){t.exit(this.containerState.type)}function mC(t,n,a){const i=this;return Ut(t,u,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function u(o){const c=i.events[i.events.length-1];return!zt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?n(o):a(o)}}const Km={name:"setextUnderline",resolveTo:gC,tokenize:yC};function gC(t,n){let a=t.length,i,u,o;for(;a--;)if(t[a][0]==="enter"){if(t[a][1].type==="content"){i=a;break}t[a][1].type==="paragraph"&&(u=a)}else t[a][1].type==="content"&&t.splice(a,1),!o&&t[a][1].type==="definition"&&(o=a);const c={type:"setextHeading",start:_({},t[i][1].start),end:_({},t[t.length-1][1].end)};return t[u][1].type="setextHeadingText",o?(t.splice(u,0,["enter",c,n]),t.splice(o+1,0,["exit",t[i][1],n]),t[i][1].end=_({},t[o][1].end)):t[i][1]=c,t.push(["exit",c,n]),t}function yC(t,n,a){const i=this;let u;return o;function o(m){let g=i.events.length,y;for(;g--;)if(i.events[g][1].type!=="lineEnding"&&i.events[g][1].type!=="linePrefix"&&i.events[g][1].type!=="content"){y=i.events[g][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||y)?(t.enter("setextHeadingLine"),u=m,c(m)):a(m)}function c(m){return t.enter("setextHeadingLineSequence"),d(m)}function d(m){return m===u?(t.consume(m),d):(t.exit("setextHeadingLineSequence"),zt(m)?Ut(t,h,"lineSuffix")(m):h(m))}function h(m){return m===null||St(m)?(t.exit("setextHeadingLine"),n(m)):a(m)}}const bC={tokenize:vC};function vC(t){const n=this,a=t.attempt(Xi,i,t.attempt(this.parser.constructs.flowInitial,u,Ut(t,t.attempt(this.parser.constructs.flow,u,t.attempt(TE,u)),"linePrefix")));return a;function i(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),n.currentConstruct=void 0,a}function u(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),n.currentConstruct=void 0,a}}const xC={resolveAll:$m()},SC=Jm("string"),wC=Jm("text");function Jm(t){return{resolveAll:$m(t==="text"?_C:void 0),tokenize:n};function n(a){const i=this,u=this.parser.constructs[t],o=a.attempt(u,c,d);return c;function c(g){return m(g)?o(g):d(g)}function d(g){if(g===null){a.consume(g);return}return a.enter("data"),a.consume(g),h}function h(g){return m(g)?(a.exit("data"),o(g)):(a.consume(g),h)}function m(g){if(g===null)return!0;const y=u[g];let v=-1;if(y)for(;++v<y.length;){const x=y[v];if(!x.previous||x.previous.call(i,i.previous))return!0}return!1}}}function $m(t){return n;function n(a,i){let u=-1,o;for(;++u<=a.length;)o===void 0?a[u]&&a[u][1].type==="data"&&(o=u,u++):(!a[u]||a[u][1].type!=="data")&&(u!==o+2&&(a[o][1].end=a[u-1][1].end,a.splice(o+2,u-o-2),u=o+2),o=void 0);return t?t(a,i):a}}function _C(t,n){let a=0;for(;++a<=t.length;)if((a===t.length||t[a][1].type==="lineEnding")&&t[a-1][1].type==="data"){const i=t[a-1][1],u=n.sliceStream(i);let o=u.length,c=-1,d=0,h;for(;o--;){const m=u[o];if(typeof m=="string"){for(c=m.length;m.charCodeAt(c-1)===32;)d++,c--;if(c)break;c=-1}else if(m===-2)h=!0,d++;else if(m!==-1){o++;break}}if(n._contentTypeTextTrailing&&a===t.length&&(d=0),d){const m={type:a===t.length||h||d<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?c:i.start._bufferIndex+c,_index:i.start._index+o,line:i.end.line,column:i.end.column-d,offset:i.end.offset-d},end:_({},i.end)};i.end=_({},m.start),i.start.offset===i.end.offset?Object.assign(i,m):(t.splice(a,0,["enter",m,n],["exit",m,n]),a+=2)}a++}return t}const TC=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:RE},disable:{null:[]},document:{42:Fe,43:Fe,45:Fe,48:Fe,49:Fe,50:Fe,51:Fe,52:Fe,53:Fe,54:Fe,55:Fe,56:Fe,57:Fe,62:Hm},flow:{35:IE,42:Ss,45:[Km,Ss],60:UE,61:Km,95:Ss,96:Fm,126:Fm},flowInitial:{[-2]:$o,[-1]:$o,32:$o},insideSpan:{null:[Jo,xC]},string:{38:Vm,92:qm},text:{[-5]:tc,[-4]:tc,[-3]:tc,33:rC,38:Vm,42:Jo,60:[iE,PE],91:iC,92:[DE,qm],93:Wo,95:Jo,96:bE}},Symbol.toStringTag,{value:"Module"}));function EC(t,n,a){let i={_bufferIndex:-1,_index:0,line:a&&a.line||1,column:a&&a.column||1,offset:a&&a.offset||0};const u={},o=[];let c=[],d=[];const h={attempt:W(it),check:W(L),consume:Y,enter:I,exit:nt,interrupt:W(L,{interrupt:!0})},m={code:null,containerState:{},defineSkip:R,events:[],now:w,parser:t,previous:null,sliceSerialize:v,sliceStream:x,write:y};let g=n.tokenize.call(m,h);return n.resolveAll&&o.push(n),m;function y(et){return c=pn(c,et),N(),c[c.length-1]!==null?[]:(ot(n,0),m.events=xs(o,m.events,m),m.events)}function v(et,J){return AC(x(et),J)}function x(et){return CC(c,et)}function w(){const{_bufferIndex:et,_index:J,line:bt,column:ut,offset:rt}=i;return{_bufferIndex:et,_index:J,line:bt,column:ut,offset:rt}}function R(et){u[et.line]=et.column,j()}function N(){let et;for(;i._index<c.length;){const J=c[i._index];if(typeof J=="string")for(et=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===et&&i._bufferIndex<J.length;)z(J.charCodeAt(i._bufferIndex));else z(J)}}function z(et){g=g(et)}function Y(et){St(et)?(i.line++,i.column=1,i.offset+=et===-3?2:1,j()):et!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===c[i._index].length&&(i._bufferIndex=-1,i._index++)),m.previous=et}function I(et,J){const bt=J||{};return bt.type=et,bt.start=w(),m.events.push(["enter",bt,m]),d.push(bt),bt}function nt(et){const J=d.pop();return J.end=w(),m.events.push(["exit",J,m]),J}function it(et,J){ot(et,J.from)}function L(et,J){J.restore()}function W(et,J){return bt;function bt(ut,rt,H){let tt,ct,Tt,C;return Array.isArray(ut)?P(ut):"tokenize"in ut?P([ut]):k(ut);function k(mt){return Ot;function Ot(_t){const Ht=_t!==null&&mt[_t],re=_t!==null&&mt.null,gn=[...Array.isArray(Ht)?Ht:Ht?[Ht]:[],...Array.isArray(re)?re:re?[re]:[]];return P(gn)(_t)}}function P(mt){return tt=mt,ct=0,mt.length===0?H:T(mt[ct])}function T(mt){return Ot;function Ot(_t){return C=ft(),Tt=mt,mt.partial||(m.currentConstruct=mt),mt.name&&m.parser.constructs.disable.null.includes(mt.name)?vt():mt.tokenize.call(J?Object.assign(Object.create(m),J):m,h,st,vt)(_t)}}function st(mt){return et(Tt,C),rt}function vt(mt){return C.restore(),++ct<tt.length?T(tt[ct]):H}}}function ot(et,J){et.resolveAll&&!o.includes(et)&&o.push(et),et.resolve&&rn(m.events,J,m.events.length-J,et.resolve(m.events.slice(J),m)),et.resolveTo&&(m.events=et.resolveTo(m.events,m))}function ft(){const et=w(),J=m.previous,bt=m.currentConstruct,ut=m.events.length,rt=Array.from(d);return{from:ut,restore:H};function H(){i=et,m.previous=J,m.currentConstruct=bt,m.events.length=ut,d=rt,j()}}function j(){i.line in u&&i.column<2&&(i.column=u[i.line],i.offset+=u[i.line]-1)}}function CC(t,n){const a=n.start._index,i=n.start._bufferIndex,u=n.end._index,o=n.end._bufferIndex;let c;if(a===u)c=[t[a].slice(i,o)];else{if(c=t.slice(a,u),i>-1){const d=c[0];typeof d=="string"?c[0]=d.slice(i):c.shift()}o>0&&c.push(t[u].slice(0,o))}return c}function AC(t,n){let a=-1;const i=[];let u;for(;++a<t.length;){const o=t[a];let c;if(typeof o=="string")c=o;else switch(o){case-5:{c="\r";break}case-4:{c=`
17
17
  `;break}case-3:{c=`\r
18
18
  `;break}case-2:{c=n?" ":" ";break}case-1:{if(!n&&u)continue;c=" ";break}default:c=String.fromCharCode(o)}u=o===-2,i.push(c)}return i.join("")}function kC(t){const i={constructs:jm([TC,...(t||{}).extensions||[]]),content:u($T),defined:[],document:u(tE),flow:u(bC),lazy:{},string:u(SC),text:u(wC)};return i;function u(o){return c;function c(d){return EC(i,o,d)}}}function RC(t){for(;!Gm(t););return t}const Wm=/[\0\t\n\r]/g;function MC(){let t=1,n="",a=!0,i;return u;function u(o,c,d){const h=[];let m,g,y,v,x;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(c||void 0).decode(o)),y=0,n="",a&&(o.charCodeAt(0)===65279&&y++,a=void 0);y<o.length;){if(Wm.lastIndex=y,m=Wm.exec(o),v=m&&m.index!==void 0?m.index:o.length,x=o.charCodeAt(v),!m){n=o.slice(y);break}if(x===10&&y===v&&i)h.push(-3),i=void 0;else switch(i&&(h.push(-5),i=void 0),y<v&&(h.push(o.slice(y,v)),t+=v-y),x){case 0:{h.push(65533),t++;break}case 9:{for(g=Math.ceil(t/4)*4,h.push(-2);t++<g;)h.push(-1);break}case 10:{h.push(-4),t=1;break}default:i=!0,t=1}y=v+1}return d&&(i&&h.push(-5),n&&h.push(n),h.push(null)),h}}const zC=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function OC(t){return t.replace(zC,DC)}function DC(t,n,a){if(n)return n;if(a.charCodeAt(0)===35){const u=a.charCodeAt(1),o=u===120||u===88;return Lm(a.slice(o?2:1),o?16:10)}return Zo(a)||t}const tg={}.hasOwnProperty;function NC(t,n,a){return typeof n!="string"&&(a=n,n=void 0),IC(a)(RC(kC(a).document().write(MC()(t,n,!0))))}function IC(t){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Va),autolinkProtocol:ft,autolinkEmail:ft,atxHeading:o(Ha),blockQuote:o(re),characterEscape:ft,characterReference:ft,codeFenced:o(gn),codeFencedFenceInfo:c,codeFencedFenceMeta:c,codeIndented:o(gn,c),codeText:o(xr,c),codeTextData:ft,data:ft,codeFlowValue:ft,definition:o(ea),definitionDestinationString:c,definitionLabelString:c,definitionTitleString:c,emphasis:o(Kn),hardBreakEscape:o(qa),hardBreakTrailing:o(qa),htmlFlow:o(Ds,c),htmlFlowData:ft,htmlText:o(Ds,c),htmlTextData:ft,image:o(Ns),label:c,link:o(Va),listItem:o(al),listItemValue:v,listOrdered:o(Ya,y),listUnordered:o(Ya),paragraph:o(Dc),reference:T,referenceString:c,resourceDestinationString:c,resourceTitleString:c,setextHeading:o(Ha),strong:o(Nc),thematicBreak:o(Ic)},exit:{atxHeading:h(),atxHeadingSequence:it,autolink:h(),autolinkEmail:Ht,autolinkProtocol:_t,blockQuote:h(),characterEscapeValue:j,characterReferenceMarkerHexadecimal:vt,characterReferenceMarkerNumeric:vt,characterReferenceValue:mt,characterReference:Ot,codeFenced:h(N),codeFencedFence:R,codeFencedFenceInfo:x,codeFencedFenceMeta:w,codeFlowValue:j,codeIndented:h(z),codeText:h(rt),codeTextData:j,data:j,definition:h(),definitionDestinationString:nt,definitionLabelString:Y,definitionTitleString:I,emphasis:h(),hardBreakEscape:h(J),hardBreakTrailing:h(J),htmlFlow:h(bt),htmlFlowData:j,htmlText:h(ut),htmlTextData:j,image:h(tt),label:Tt,labelText:ct,lineEnding:et,link:h(H),listItem:h(),listOrdered:h(),listUnordered:h(),paragraph:h(),referenceString:st,resourceDestinationString:C,resourceTitleString:k,resource:P,setextHeading:h(ot),setextHeadingLineSequence:W,setextHeadingText:L,strong:h(),thematicBreak:h()}};eg(n,(t||{}).mdastExtensions||[]);const a={};return i;function i(Q){let lt={type:"root",children:[]};const Et={stack:[lt],tokenStack:[],config:n,enter:d,exit:m,buffer:c,resume:g,data:a},Dt=[];let Ft=-1;for(;++Ft<Q.length;)if(Q[Ft][1].type==="listOrdered"||Q[Ft][1].type==="listUnordered")if(Q[Ft][0]==="enter")Dt.push(Ft);else{const an=Dt.pop();Ft=u(Q,an,Ft)}for(Ft=-1;++Ft<Q.length;){const an=n[Q[Ft][0]];tg.call(an,Q[Ft][1].type)&&an[Q[Ft][1].type].call(Object.assign({sliceSerialize:Q[Ft][2].sliceSerialize},Et),Q[Ft][1])}if(Et.tokenStack.length>0){const an=Et.tokenStack[Et.tokenStack.length-1];(an[1]||ng).call(Et,void 0,an[0])}for(lt.position={start:vr(Q.length>0?Q[0][1].start:{line:1,column:1,offset:0}),end:vr(Q.length>0?Q[Q.length-2][1].end:{line:1,column:1,offset:0})},Ft=-1;++Ft<n.transforms.length;)lt=n.transforms[Ft](lt)||lt;return lt}function u(Q,lt,Et){let Dt=lt-1,Ft=-1,an=!1,Jn,qe,Se,Ge;for(;++Dt<=Et;){const Wt=Q[Dt];switch(Wt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Wt[0]==="enter"?Ft++:Ft--,Ge=void 0;break}case"lineEndingBlank":{Wt[0]==="enter"&&(Jn&&!Ge&&!Ft&&!Se&&(Se=Dt),Ge=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Ge=void 0}if(!Ft&&Wt[0]==="enter"&&Wt[1].type==="listItemPrefix"||Ft===-1&&Wt[0]==="exit"&&(Wt[1].type==="listUnordered"||Wt[1].type==="listOrdered")){if(Jn){let Sr=Dt;for(qe=void 0;Sr--;){const In=Q[Sr];if(In[1].type==="lineEnding"||In[1].type==="lineEndingBlank"){if(In[0]==="exit")continue;qe&&(Q[qe][1].type="lineEndingBlank",an=!0),In[1].type="lineEnding",qe=Sr}else if(!(In[1].type==="linePrefix"||In[1].type==="blockQuotePrefix"||In[1].type==="blockQuotePrefixWhitespace"||In[1].type==="blockQuoteMarker"||In[1].type==="listItemIndent"))break}Se&&(!qe||Se<qe)&&(Jn._spread=!0),Jn.end=Object.assign({},qe?Q[qe][1].start:Wt[1].end),Q.splice(qe||Dt,0,["exit",Jn,Wt[2]]),Dt++,Et++}if(Wt[1].type==="listItemPrefix"){const Sr={type:"listItem",_spread:!1,start:Object.assign({},Wt[1].start),end:void 0};Jn=Sr,Q.splice(Dt,0,["enter",Sr,Wt[2]]),Dt++,Et++,Se=void 0,Ge=!0}}}return Q[lt][1]._spread=an,Et}function o(Q,lt){return Et;function Et(Dt){d.call(this,Q(Dt),Dt),lt&&lt.call(this,Dt)}}function c(){this.stack.push({type:"fragment",children:[]})}function d(Q,lt,Et){this.stack[this.stack.length-1].children.push(Q),this.stack.push(Q),this.tokenStack.push([lt,Et||void 0]),Q.position={start:vr(lt.start),end:void 0}}function h(Q){return lt;function lt(Et){Q&&Q.call(this,Et),m.call(this,Et)}}function m(Q,lt){const Et=this.stack.pop(),Dt=this.tokenStack.pop();if(Dt)Dt[0].type!==Q.type&&(lt?lt.call(this,Q,Dt[0]):(Dt[1]||ng).call(this,Q,Dt[0]));else throw new Error("Cannot close `"+Q.type+"` ("+Gi({start:Q.start,end:Q.end})+"): it’s not open");Et.position.end=vr(Q.end)}function g(){return Qo(this.stack.pop())}function y(){this.data.expectingFirstListItemValue=!0}function v(Q){if(this.data.expectingFirstListItemValue){const lt=this.stack[this.stack.length-2];lt.start=Number.parseInt(this.sliceSerialize(Q),10),this.data.expectingFirstListItemValue=void 0}}function x(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.lang=Q}function w(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.meta=Q}function R(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function N(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.value=Q.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function z(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.value=Q.replace(/(\r?\n|\r)$/g,"")}function Y(Q){const lt=this.resume(),Et=this.stack[this.stack.length-1];Et.label=lt,Et.identifier=Dn(this.sliceSerialize(Q)).toLowerCase()}function I(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.title=Q}function nt(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.url=Q}function it(Q){const lt=this.stack[this.stack.length-1];if(!lt.depth){const Et=this.sliceSerialize(Q).length;lt.depth=Et}}function L(){this.data.setextHeadingSlurpLineEnding=!0}function W(Q){const lt=this.stack[this.stack.length-1];lt.depth=this.sliceSerialize(Q).codePointAt(0)===61?1:2}function ot(){this.data.setextHeadingSlurpLineEnding=void 0}function ft(Q){const Et=this.stack[this.stack.length-1].children;let Dt=Et[Et.length-1];(!Dt||Dt.type!=="text")&&(Dt=He(),Dt.position={start:vr(Q.start),end:void 0},Et.push(Dt)),this.stack.push(Dt)}function j(Q){const lt=this.stack.pop();lt.value+=this.sliceSerialize(Q),lt.position.end=vr(Q.end)}function et(Q){const lt=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Et=lt.children[lt.children.length-1];Et.position.end=vr(Q.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(lt.type)&&(ft.call(this,Q),j.call(this,Q))}function J(){this.data.atHardBreak=!0}function bt(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.value=Q}function ut(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.value=Q}function rt(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.value=Q}function H(){const Q=this.stack[this.stack.length-1];if(this.data.inReference){const lt=this.data.referenceType||"shortcut";Q.type+="Reference",Q.referenceType=lt,delete Q.url,delete Q.title}else delete Q.identifier,delete Q.label;this.data.referenceType=void 0}function tt(){const Q=this.stack[this.stack.length-1];if(this.data.inReference){const lt=this.data.referenceType||"shortcut";Q.type+="Reference",Q.referenceType=lt,delete Q.url,delete Q.title}else delete Q.identifier,delete Q.label;this.data.referenceType=void 0}function ct(Q){const lt=this.sliceSerialize(Q),Et=this.stack[this.stack.length-2];Et.label=OC(lt),Et.identifier=Dn(lt).toLowerCase()}function Tt(){const Q=this.stack[this.stack.length-1],lt=this.resume(),Et=this.stack[this.stack.length-1];if(this.data.inReference=!0,Et.type==="link"){const Dt=Q.children;Et.children=Dt}else Et.alt=lt}function C(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.url=Q}function k(){const Q=this.resume(),lt=this.stack[this.stack.length-1];lt.title=Q}function P(){this.data.inReference=void 0}function T(){this.data.referenceType="collapsed"}function st(Q){const lt=this.resume(),Et=this.stack[this.stack.length-1];Et.label=lt,Et.identifier=Dn(this.sliceSerialize(Q)).toLowerCase(),this.data.referenceType="full"}function vt(Q){this.data.characterReferenceType=Q.type}function mt(Q){const lt=this.sliceSerialize(Q),Et=this.data.characterReferenceType;let Dt;Et?(Dt=Lm(lt,Et==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Dt=Zo(lt);const Ft=this.stack[this.stack.length-1];Ft.value+=Dt}function Ot(Q){const lt=this.stack.pop();lt.position.end=vr(Q.end)}function _t(Q){j.call(this,Q);const lt=this.stack[this.stack.length-1];lt.url=this.sliceSerialize(Q)}function Ht(Q){j.call(this,Q);const lt=this.stack[this.stack.length-1];lt.url="mailto:"+this.sliceSerialize(Q)}function re(){return{type:"blockquote",children:[]}}function gn(){return{type:"code",lang:null,meta:null,value:""}}function xr(){return{type:"inlineCode",value:""}}function ea(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Kn(){return{type:"emphasis",children:[]}}function Ha(){return{type:"heading",depth:0,children:[]}}function qa(){return{type:"break"}}function Ds(){return{type:"html",value:""}}function Ns(){return{type:"image",title:null,url:"",alt:null}}function Va(){return{type:"link",title:null,url:"",children:[]}}function Ya(Q){return{type:"list",ordered:Q.type==="listOrdered",start:null,spread:Q._spread,children:[]}}function al(Q){return{type:"listItem",spread:Q._spread,checked:null,children:[]}}function Dc(){return{type:"paragraph",children:[]}}function Nc(){return{type:"strong",children:[]}}function He(){return{type:"text",value:""}}function Ic(){return{type:"thematicBreak"}}}function vr(t){return{line:t.line,column:t.column,offset:t.offset}}function eg(t,n){let a=-1;for(;++a<n.length;){const i=n[a];Array.isArray(i)?eg(t,i):jC(t,i)}}function jC(t,n){let a;for(a in n)if(tg.call(n,a))switch(a){case"canContainEols":{const i=n[a];i&&t[a].push(...i);break}case"transforms":{const i=n[a];i&&t[a].push(...i);break}case"enter":case"exit":{const i=n[a];i&&Object.assign(t[a],i);break}}}function ng(t,n){throw t?new Error("Cannot close `"+t.type+"` ("+Gi({start:t.start,end:t.end})+"): a different token (`"+n.type+"`, "+Gi({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Gi({start:n.start,end:n.end})+") is still open")}function LC(t){const n=this;n.parser=a;function a(i){return NC(i,G(_(_({},n.data("settings")),t),{extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]}))}}function BC(t,n){const a={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(n),!0)};return t.patch(n,a),t.applyData(n,a)}function UC(t,n){const a={type:"element",tagName:"br",properties:{},children:[]};return t.patch(n,a),[t.applyData(n,a),{type:"text",value:`