@cuadra-ai/uikit 0.4.21 → 0.4.22
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.
- package/dist/index.cjs +9 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +65 -65
- package/dist/index.mjs.map +1 -1
- package/dist/widget/cuadra-uikit.umd.js +1 -1
- package/dist/widget/cuadra-uikit.umd.js.map +1 -1
- package/package.json +1 -1
|
@@ -4,7 +4,7 @@ ${r.system}`:n.system=r.system),r.tools)for(const[i,a]of Object.entries(r.tools)
|
|
|
4
4
|
|
|
5
5
|
`);class pa{constructor(t){_(this,"_core");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)}}class ma extends pa{constructor(n,r){super(n);_(this,"_composerApi");this._composerApi=r}remove(){const n=this._composerApi.getState();if(!n)throw new Error("Composer is not available");return n.removeAttachment(this.getState().id)}}class Td extends ma{get source(){return"thread-composer"}}class Id extends ma{get source(){return"edit-composer"}}class vd extends pa{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}}class ga extends Hn{constructor(n){super();_(this,"config");this.config=n}getState(){return this.config.binding.getState()}outerSubscribe(n){return this.config.binding.subscribe(n)}_connect(){const n=()=>{this.notifySubscribers()};let r=this.config.binding.getState(),s=r==null?void 0:r.unstable_on(this.config.event,n);const i=()=>{var l;const o=this.config.binding.getState();o!==r&&(r=o,s==null||s(),s=(l=this.config.binding.getState())==null?void 0:l.unstable_on(this.config.event,n))},a=this.outerSubscribe(i);return()=>{a==null||a(),s==null||s()}}}const ya=Object.freeze([]),ba=Object.freeze({}),Ed=e=>{var t,n,r,s,i,a,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(n=e==null?void 0:e.canCancel)!=null?n:!1,isEmpty:(r=e==null?void 0:e.isEmpty)!=null?r:!0,attachments:(s=e==null?void 0:e.attachments)!=null?s:ya,text:(i=e==null?void 0:e.text)!=null?i:"",role:(a=e==null?void 0:e.role)!=null?a:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:ba,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",dictation:e==null?void 0:e.dictation,quote:e==null?void 0:e.quote,value:(u=e==null?void 0:e.text)!=null?u:""})},Ad=e=>{var t,n,r,s,i,a,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(n=e==null?void 0:e.canCancel)!=null?n:!1,isEmpty:(r=e==null?void 0:e.isEmpty)!=null?r:!0,text:(s=e==null?void 0:e.text)!=null?s:"",role:(i=e==null?void 0:e.role)!=null?i:"user",attachments:(a=e==null?void 0:e.attachments)!=null?a:ya,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:ba,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",dictation:e==null?void 0:e.dictation,quote:e==null?void 0:e.quote,value:(u=e==null?void 0:e.text)!=null?u:""})};class xa{constructor(t){_(this,"_core");_(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.startDictation=this.startDictation.bind(this),this.stopDictation=this.stopDictation.bind(this),this.setQuote=this.setQuote.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(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)}startDictation(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.startDictation()}stopDictation(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.stopDictation()}setQuote(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setQuote(t)}subscribe(t){return this._core.subscribe(t)}unstable_on(t,n){let r=this._eventSubscriptionSubjects.get(t);return r||(r=new ga({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,r)),r.subscribe(n)}}class Pd extends xa{constructor(n){const r=new Wr({path:n.path,getState:()=>Ed(n.getState()),subscribe:s=>n.subscribe(s)});super({path:n.path,getState:()=>n.getState(),subscribe:s=>r.subscribe(s)});_(this,"_getState");this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(n){return new Td(new Ge({path:E(m({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:n},ref:`${this.path.ref}.attachments[${n}]`}),getState:()=>{const s=this.getState().attachments[n];return s?E(m({},s),{source:"thread-composer"}):Je},subscribe:r=>this._core.subscribe(r)}),this._core)}}class Md extends xa{constructor(n,r){const s=new Wr({path:n.path,getState:()=>Ad(n.getState()),subscribe:i=>n.subscribe(i)});super({path:n.path,getState:()=>n.getState(),subscribe:i=>s.subscribe(i)});_(this,"_beginEdit");_(this,"_getState");this._beginEdit=r,this._getState=s.getState.bind(s),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 Id(new Ge({path:E(m({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:n},ref:`${this.path.ref}.attachments[${n}]`}),getState:()=>{const s=this.getState().attachments[n];return s?E(m({},s),{source:"edit-composer"}):Je},subscribe:r=>this._core.subscribe(r)}),this._core)}}class nn{constructor(t=null){_(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((n,r)=>nn.apply(n,r),this._state)}static apply(t,n){const r=n.type;switch(r){case"set":return nn.updatePath(t,n.path,()=>n.value);case"append-text":return nn.updatePath(t,n.path,s=>{if(typeof s!="string")throw new Error(`Expected string at path [${n.path.join(", ")}]`);return s+n.value});default:{const s=r;throw new Error(`Invalid operation type: ${s}`)}}}static updatePath(t,n,r){if(n.length===0)return r(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${n.join(", ")}]`);const[s,...i]=n;if(Array.isArray(t)){const o=Number(s);if(Number.isNaN(o))throw new Error(`Expected array index at [${n.join(", ")}]`);if(o>t.length||o<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[o]=this.updatePath(l[o],i,r),l}const a=m({},t);return a[s]=this.updatePath(a[s],i,r),a}}const Nd=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),Kn=(e,t,n)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const r=t.path[0],s=n(e.parts[r]);return E(m({},e),{parts:[...e.parts.slice(0,r),s,...e.parts.slice(r+1)],get content(){return this.parts}})},Dd=(e,t)=>{const n=t.part;if(n.type==="text"||n.type==="reasoning"){const r=m({type:n.type,text:"",status:{type:"running"}},n.parentId&&{parentId:n.parentId});return E(m({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="tool-call"){const r=m({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:n.toolCallId,toolName:n.toolName,argsText:"",args:{}},n.parentId&&{parentId:n.parentId});return E(m({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="source"){const r=m(m({type:"source",sourceType:n.sourceType,id:n.id,url:n.url},n.title?{title:n.title}:void 0),n.parentId&&{parentId:n.parentId});return E(m({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="file"){const r={type:"file",mimeType:n.mimeType,data:n.data};return E(m({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${n.type}`)},Ld=(e,t)=>Kn(e,t,n=>{if(n.type!=="tool-call")throw new Error("Last is not a tool call");return n.state!=="partial-call"?n:E(m({},n),{state:"call"})}),Od=(e,t)=>Kn(e,t,n=>E(m({},n),{status:{type:"complete",reason:"unknown"}})),Fd=(e,t)=>Kn(e,t,n=>{var r;if(n.type==="text"||n.type==="reasoning")return E(m({},n),{text:n.text+t.textDelta});if(n.type==="tool-call"){const s=n.argsText+t.textDelta,i=(r=$n(s))!=null?r:n.args;return E(m({},n),{argsText:s,args:i})}else throw new Error("text-delta received but part is neither text nor tool-call")}),Bd=(e,t)=>Kn(e,t,n=>{var r;if(n.type==="tool-call")return E(m(E(m({},n),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(r=t.isError)!=null?r:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),wa=(e,t)=>{var r,s;if(((r=e.status)==null?void 0:r.type)==="incomplete"&&((s=e.status)==null?void 0:s.reason)==="error")return e;const n=zd(t);return E(m({},e),{status:n})},zd=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},Rd=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),jd=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),$d=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),Ud=(e,t)=>{var s;const n=e.metadata.steps.slice(),r=n.length-1;return n.length>0&&((s=n[r])==null?void 0:s.state)==="started"?n[r]=E(m({},n[r]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):n.push({state:"finished",messageId:ca(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),E(m({},e),{metadata:E(m({},e.metadata),{steps:n})})},Hd=(e,t)=>E(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),qd=(e,t)=>{const n=new nn(e.metadata.unstable_state);return n.append(t.operations),E(m({},e),{metadata:E(m({},e.metadata),{unstable_state:n.state})})},Vd=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}};class Wd extends TransformStream{constructor({initialMessage:t,throttle:n,onError:r}={}){let s=t!=null?t:Nd(),i;const a=n?Vd(()=>{i==null||i.enqueue(s)}):()=>{i==null||i.enqueue(s)};super({start(o){i=o},transform(o){const l=o.type;switch(l){case"part-start":s=Dd(s,o);break;case"tool-call-args-text-finish":s=Ld(s,o);break;case"part-finish":s=Od(s,o);break;case"text-delta":s=Fd(s,o);break;case"result":s=Bd(s,o);break;case"message-finish":s=wa(s,o);break;case"annotations":s=Rd(s,o);break;case"data":s=jd(s,o);break;case"step-start":s=$d(s,o);break;case"step-finish":s=Ud(s,o);break;case"error":s=Hd(s,o),r==null||r(o.error);break;case"update-state":s=qd(s,o);break;default:{const u=l;throw new Error(`Unsupported chunk type: ${u}`)}}a()},flush(o){var l,u,d;if(((l=s.status)==null?void 0:l.type)==="running"){const c=(d=(u=s.parts)==null?void 0:u.some(f=>f.type==="tool-call"&&(f.state==="call"||f.state==="partial-call")&&f.result===void 0))!=null?d:!1;s=wa(s,{finishReason:c?"tool-calls":"unknown"}),o.enqueue(s)}}})}}class Kd extends la{constructor(){super(t=>{const n=new kd({transform(r,s){s.appendText(r)}});return t.pipeThrough(new TextDecoderStream).pipeThrough(n)})}}class rn{constructor(t){_(this,"readable");this.readable=t,this.readable=t}static fromAssistantStream(t){return new rn(t.pipeThrough(new Wd))}unstable_result(){return P(this,null,function*(){let t;try{for(var n=Pt(this),r,s,i;r=!(s=yield n.next()).done;r=!1){const a=s.value;t=a}}catch(s){i=[s]}finally{try{r&&(s=n.return)&&(yield s.call(n))}finally{if(i)throw i[0]}}return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}})}[Symbol.asyncIterator](){const t=this.readable.getReader();return{next(){return P(this,null,function*(){const{done:r,value:s}=yield t.read();return r?{done:!0,value:void 0}:{done:!1,value:s}})}}}tee(){const[t,n]=this.readable.tee();return[new rn(t),new rn(n)]}}const Sa=Symbol.for("aui.tool-response");class Ye{constructor(t){_(this,"artifact");_(this,"result");_(this,"isError");var n;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(n=t.isError)!=null?n:!1}get[Sa](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&Sa in t}static toResponse(t){return t instanceof Ye?t:new Ye({result:t===void 0?"<no result>":t})}}function Jd(e,t,n){try{const r=e();if(typeof r=="object"&&r!==null&&"then"in r)return r.then(t,n);t(r)}catch(r){n(r)}}function sn(e,t){let n=e;for(const r of t){if(n==null)return;n=n[r]}return n}class Gd{constructor(t,n,r){_(this,"resolve");_(this,"reject");_(this,"disposed",!1);_(this,"fieldPath");this.resolve=t,this.reject=n,this.fieldPath=r}update(t){if(!this.disposed)try{if(Lt(t,this.fieldPath)==="complete"){const n=sn(t,this.fieldPath);n!==void 0&&(this.resolve(n),this.dispose())}}catch(n){this.reject(n),this.dispose()}}dispose(){this.disposed=!0}}class ka{constructor(t,n){_(this,"controller");_(this,"disposed",!1);_(this,"fieldPath");this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=sn(t,this.fieldPath);n!==void 0&&this.controller.enqueue(n),Lt(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class _a{constructor(t,n){_(this,"controller");_(this,"disposed",!1);_(this,"fieldPath");_(this,"lastValue");this.controller=t,this.fieldPath=n}update(t){var n;if(!this.disposed)try{const r=sn(t,this.fieldPath);if(r!==void 0&&typeof r=="string"){const s=r.substring(((n=this.lastValue)==null?void 0:n.length)||0);this.lastValue=r,this.controller.enqueue(s)}Lt(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}}class Ca{constructor(t,n){_(this,"controller");_(this,"disposed",!1);_(this,"fieldPath");_(this,"processedIndexes",new Set);this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=sn(t,this.fieldPath);if(!Array.isArray(n))return;for(let r=0;r<n.length;r++)if(!this.processedIndexes.has(r)){const s=[...this.fieldPath,r];Lt(t,s)==="complete"&&(this.controller.enqueue(n[r]),this.processedIndexes.add(r))}Lt(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class Yd{constructor(t){_(this,"argTextDeltas");_(this,"handles",new Set);_(this,"args",$n(""));this.argTextDeltas=t,this.processStream()}processStream(){return P(this,null,function*(){try{let t="";const n=this.argTextDeltas.getReader();for(;;){const{value:r,done:s}=yield n.read();if(s)break;t+=r;const i=$n(t);if(i!==void 0){this.args=i;for(const a of this.handles)a.update(i)}}}catch(t){console.error("Error processing argument stream:",t);for(const n of this.handles)n.dispose()}})}get(...t){return new Promise((n,r)=>{const s=new Gd(n,r,t);if(this.args&&Lt(this.args,t)==="complete"){const i=sn(this.args,t);if(i!==void 0){n(i);return}}this.handles.add(s),s.update(this.args)})}streamValues(...t){const n=t,r=new ReadableStream({start:s=>{const i=new ka(s,n);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const s of this.handles)if(s instanceof ka){s.dispose(),this.handles.delete(s);break}}});return $r(r)}streamText(...t){const n=t,r=new ReadableStream({start:s=>{const i=new _a(s,n);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const s of this.handles)if(s instanceof _a){s.dispose(),this.handles.delete(s);break}}});return $r(r)}forEach(...t){const n=t,r=new ReadableStream({start:s=>{const i=new Ca(s,n);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const s of this.handles)if(s instanceof Ca){s.dispose(),this.handles.delete(s);break}}});return $r(r)}}class Qd{constructor(t){_(this,"promise");this.promise=t}get(){return this.promise}}class Xd{constructor(){_(this,"args");_(this,"response");_(this,"writable");_(this,"resolve");_(this,"argsText","");_(this,"result",{get:()=>P(this,null,function*(){return(yield this.response.get()).result})});const t=new TransformStream;this.writable=t.writable,this.args=new Yd(t.readable);const{promise:n,resolve:r}=Hr();this.resolve=r,this.response=new Qd(n)}appendArgsTextDelta(t){return P(this,null,function*(){const n=this.writable.getWriter();try{yield n.write(t)}catch(r){console.warn(r)}finally{n.releaseLock()}this.argsText+=t})}setResponse(t){this.resolve(t)}}class Zd extends la{constructor(t){const n=new Map,r=new Map;super(s=>{const i=new TransformStream({transform(o,l){switch((o.type!=="part-finish"||o.meta.type!=="tool-call")&&l.enqueue(o),o.type){case"part-start":if(o.part.type==="tool-call"){const d=new Xd;r.set(o.part.toolCallId,d),t.streamCall({reader:d,toolCallId:o.part.toolCallId,toolName:o.part.toolName})}break;case"text-delta":{if(o.meta.type==="tool-call"){const d=o.meta.toolCallId,c=r.get(d);if(!c)throw new Error("No controller found for tool call");c.appendArgsTextDelta(o.textDelta)}break}case"result":{if(o.meta.type!=="tool-call")break;const{toolCallId:d}=o.meta,c=r.get(d);if(!c)throw new Error("No controller found for tool call");c.setResponse(new Ye({result:o.result,artifact:o.artifact,isError:o.isError}));break}case"tool-call-args-text-finish":{if(o.meta.type!=="tool-call")break;const{toolCallId:d,toolName:c}=o.meta,f=r.get(d);if(!f)throw new Error("No controller found for tool call");let h=!1;const b=Jd(()=>{var g;let S;try{S=jr.parse(f.argsText)}catch(v){throw new Error(`Function parameter parsing failed. ${JSON.stringify(v.message)}`)}const x=t.execute({toolCallId:d,toolName:c,args:S});return x!==void 0&&(h=!0,(g=t.onExecutionStart)==null||g.call(t,d,c)),x},S=>{var g;if(h&&((g=t.onExecutionEnd)==null||g.call(t,d,c)),S===void 0)return;const x=new Ye({artifact:S.artifact,result:S.result,isError:S.isError});f.setResponse(x),l.enqueue(m({type:"result",path:o.path},x))},S=>{var g;h&&((g=t.onExecutionEnd)==null||g.call(t,d,c));const x=new Ye({result:String(S),isError:!0});f.setResponse(x),l.enqueue(m({type:"result",path:o.path},x))});b&&n.set(d,b);break}case"part-finish":{if(o.meta.type!=="tool-call")break;const{toolCallId:d}=o.meta,c=n.get(d);c?c.then(()=>{n.delete(d),r.delete(d),l.enqueue(o)}):l.enqueue(o)}}},flush(){return P(this,null,function*(){yield Promise.all(n.values())})}});return s.pipeThrough(new ua).pipeThrough(i)})}}const eh=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function th(e,t,n,r){const s=e==null?void 0:e[n.toolName];return!s||!s.execute?void 0:(a=>P(null,null,function*(){var d;if(t.aborted)return new Ye({result:"Tool execution was cancelled.",isError:!0});let o=a;if(eh(s.parameters)){let c=s.parameters["~standard"].validate(n.args);c instanceof Promise&&(c=yield c),c.issues&&(o=(d=s.experimental_onSchemaValidationError)!=null?d:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const f=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new Ye({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?f():t.addEventListener("abort",f,{once:!0})}),u=P(null,null,function*(){const c=yield o(n.args,{toolCallId:n.toolCallId,abortSignal:t,human:f=>r(n.toolCallId,f)});return Ye.toResponse(c)});return Promise.race([u,l])}))(s.execute)}function nh(e,t,n,r,s){var i,a;(a=(i=e==null?void 0:e[r.toolName])==null?void 0:i.streamCall)==null||a.call(i,n,{toolCallId:r.toolCallId,abortSignal:t,human:o=>s(r.toolCallId,o)})}function rh(e,t,n,r){const s=typeof e=="function"?e:()=>e,i=typeof t=="function"?t:()=>t;return new Zd({execute:a=>th(s(),i(),a,n),streamCall:l=>{var u=l,{reader:a}=u,o=q(u,["reader"]);return nh(s(),i(),a,o,n)},onExecutionStart:r==null?void 0:r.onExecutionStart,onExecutionEnd:r==null?void 0:r.onExecutionEnd})}class Ta{constructor(t,n,r){_(this,"contentBinding");_(this,"messageApi");_(this,"threadApi");this.contentBinding=t,this.messageApi=n,this.threadApi=r,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 r=this.messageApi.getState();if(!r)throw new Error("Message is not available");const s=n.toolName,i=n.toolCallId,a=Ye.toResponse(t);this.threadApi.getState().addToolResult({messageId:r.id,toolName:s,toolCallId:i,result:a.result,artifact:a.artifact,isError:a.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 r=n.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:t})}subscribe(t){return this.contentBinding.subscribe(t)}}class Jn extends Hn{constructor(n){super();_(this,"binding");this.binding=n}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(n){return this.binding.subscribe(n)}_connect(){const n=()=>{this.notifySubscribers()};let r=this.binding.getState(),s=r==null?void 0:r.subscribe(n);const i=()=>{var l;const o=this.binding.getState();o!==r&&(r=o,s==null||s(),s=(l=this.binding.getState())==null?void 0:l.subscribe(n),n())},a=this.outerSubscribe(i);return()=>{a==null||a(),s==null||s()}}}const Gn=Object.freeze({type:"complete"}),sh=(e,t,n)=>{if(e.role!=="assistant")return Gn;if(n.type==="tool-call")return n.result?Gn:e.status;const r=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Gn:r?e.status:Gn},Ia=(e,t)=>{const n=e.content[t];if(!n)return Je;const r=sh(e,t,n);return Object.freeze(E(m({},n),{[Vn]:n[Vn],status:r}))};class ih{constructor(t,n){_(this,"_core");_(this,"_threadBinding");_(this,"composer");_(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=t,this._threadBinding=n,this.composer=new Md(new Jn({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:r=>this._threadBinding.subscribe(r)}),()=>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(),r=n!=null?n:this._threadBinding.getState().composer,s=n!=null?n:r,{runConfig:i=s.runConfig}=t,a=this._core.getState();if(a.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.id,runConfig:i})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){var r;const t=this._core.getState();if(((r=this._threadBinding.getState().speech)==null?void 0:r.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 r=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 i=this._threadBinding.getState().getBranches(r.id);let a=n;if(t==="previous"?a=i[r.branchNumber-2]:t==="next"&&(a=i[r.branchNumber]),!a)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(a)}unstable_getCopyText(){return Wn(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 Ta(new Ge({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${t}]`,messagePartSelector:{type:"index",index:t}}),getState:()=>Ia(this.getState(),t),subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getMessagePartByToolCallId(t){return new Ta(new Ge({path:E(m({},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(),r=n.content.findIndex(s=>s.type==="tool-call"&&s.toolCallId===t);return r===-1?Je:Ia(n,r)},subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new vd(new Ge({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}}),getState:()=>{const n=this.getState().attachments,r=n==null?void 0:n[t];return r?E(m({},r),{source:"message"}):Je},subscribe:n=>this._core.subscribe(n)}))}}const ah=e=>{var t,n,r;return m({parentId:(t=e.parentId)!=null?t:null,sourceId:(n=e.sourceId)!=null?n:null,runConfig:(r=e.runConfig)!=null?r:{}},e.stream?{stream:e.stream}:{})},oh=e=>{var t,n,r;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(n=e.sourceId)!=null?n:null,runConfig:(r=e.runConfig)!=null?r:{}}},lh=(e,t)=>{var n,r,s,i,a,o,l,u,d,c,f;return typeof t=="string"?{createdAt:new Date,parentId:(r=(n=e.at(-1))==null?void 0:n.id)!=null?r:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(s=t.createdAt)!=null?s:new Date,parentId:(o=(a=t.parentId)!=null?a:(i=e.at(-1))==null?void 0:i.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(d=t.attachments)!=null?d:[],metadata:(c=t.metadata)!=null?c:{custom:{}},runConfig:(f=t.runConfig)!=null?f:{},startRun:t.startRun}},uh=(e,t)=>{const n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(n==null?void 0:n.role)!=="assistant"?!1:n.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})};class va{constructor(t,n){_(this,"_threadBinding");_(this,"composer");_(this,"_eventSubscriptionSubjects",new Map);const r=new Ge({path:t.path,getState:()=>uh(t.getState(),n.getState()),subscribe:s=>{const i=t.subscribe(s),a=n.subscribe(s);return()=>{i(),a()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>r.getState(),outerSubscribe:s=>t.outerSubscribe(s),subscribe:s=>t.subscribe(s)},this.composer=new Pd(new Jn({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:s=>this._threadBinding.subscribe(s)})),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.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(lh(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(oh(n))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(ah(t))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(t){this._threadBinding.getState().importExternalState(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(E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${t}]`,messageSelector:{type:"index",index:t}}),()=>{var s,i;const n=this._threadBinding.getState().messages,r=n[t];if(r)return{message:r,parentId:(i=(s=n[t-1])==null?void 0:s.id)!=null?i:null,index:t}})}getMessageById(t){return this._getMessageRuntime(E(m({},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 ih(new Ge({path:t,getState:()=>{var c,f;const{message:r,parentId:s,index:i}=(c=n())!=null?c:{},{messages:a,speech:o}=this._threadBinding.getState();if(!r||s===void 0||i===void 0)return Je;const u=this._threadBinding.getState().getBranches(r.id),d=r.metadata.submittedFeedback;return E(m({},r),{[Vn]:r[Vn],index:i,isLast:((f=a.at(-1))==null?void 0:f.id)===r.id,parentId:s,branchNumber:u.indexOf(r.id)+1,branchCount:u.length,speech:(o==null?void 0:o.messageId)===r.id?o:void 0,submittedFeedback:d})},subscribe:r=>this._threadBinding.subscribe(r)}),this._threadBinding)}unstable_on(t,n){let r=this._eventSubscriptionSubjects.get(t);return r||(r=new ga({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,r)),r.subscribe(n)}}const ch=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadItems}),Yn=(e,t)=>{if(t===void 0)return Je;const n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,isMain:n.id===e.mainThreadId}:Je};class Ea{constructor(t,n=va){_(this,"_core");_(this,"_runtimeFactory");_(this,"_getState");_(this,"_mainThreadListItemRuntime");_(this,"main");this._core=t,this._runtimeFactory=n;const r=new Wr({path:{},getState:()=>ch(t),subscribe:s=>t.subscribe(s)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new qn(new Ge({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Yn(this._core,this._core.mainThreadId),subscribe:s=>this._core.subscribe(s)}),this._core),this.main=new n(new Jn({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:s=>t.subscribe(s)}),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 Jn({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 qn(new Ge({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>Yn(this._core,this._core.threadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getArchivedItemByIndex(t){return new qn(new Ge({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>Yn(this._core,this._core.archivedThreadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getItemById(t){return new qn(new Ge({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>Yn(this._core,t),subscribe:n=>this._core.subscribe(n)}),this._core)}}const dh=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file";class hh{constructor(t){_(this,"cloud");_(this,"accept","*");_(this,"uploadedUrls",new Map);this.cloud=t}add(n){return Nn(this,arguments,function*({file:t}){const r=crypto.randomUUID(),s=dh(t.type);let i={id:r,type:s,name:t.name,contentType:t.type,file:t,status:{type:"running",reason:"uploading",progress:0}};yield i;try{const{signedUrl:a,publicUrl:o}=yield new Ae(this.cloud.files.generatePresignedUploadUrl({filename:t.name}));yield new Ae(fetch(a,{method:"PUT",body:t,headers:{"Content-Type":t.type},mode:"cors"})),this.uploadedUrls.set(r,o),i=E(m({},i),{status:{type:"requires-action",reason:"composer-send"}}),yield i}catch(a){i=E(m({},i),{status:{type:"incomplete",reason:"error"}}),yield i}})}remove(t){return P(this,null,function*(){this.uploadedUrls.delete(t.id)})}send(t){return P(this,null,function*(){const n=this.uploadedUrls.get(t.id);if(!n)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(t.id);let r;return t.type==="image"?r=[{type:"image",image:n,filename:t.name}]:r=[{type:"file",data:n,mimeType:t.contentType,filename:t.name}],E(m({},t),{status:{type:"complete"},content:r})})}}const Kr=y.createContext(null),Jr=({adapters:e,children:t})=>{const n=y.useContext(Kr);return p.jsx(Kr.Provider,{value:m(m({},n),e),children:t})},fh=()=>y.useContext(Kr);class ph extends Qi{constructor(n,r,{parentId:s,message:i}){var a;super();_(this,"runtime");_(this,"endEditCallback");_(this,"_nonTextParts");_(this,"_previousText");_(this,"_parentId");_(this,"_sourceId");this.runtime=n,this.endEditCallback=r,this._parentId=s,this._sourceId=i.id,this._previousText=Wn(i),this.setText(this._previousText),this.setRole(i.role),this.setAttachments((a=i.attachments)!=null?a:[]),this._nonTextParts=i.content.filter(o=>o.type!=="text"),this.setRunConfig(m({},n.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var n;return(n=this.runtime.adapters)==null?void 0:n.attachments}getDictationAdapter(){var n;return(n=this.runtime.adapters)==null?void 0:n.dictation}handleSend(n){return P(this,null,function*(){Wn(n)!==this._previousText&&this.runtime.append(E(m({},n),{content:[...n.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}}class mh{constructor(t){_(this,"_contextProvider");_(this,"_subscriptions",new Set);_(this,"_isInitialized",!1);_(this,"repository",new fa);_(this,"composer",new Xi(this));_(this,"_editComposers",new Map);_(this,"_stopSpeaking");_(this,"speech");_(this,"_eventSubscribers",new Map);this._contextProvider=t}get messages(){return this.repository.getMessages()}get state(){var n;let t;for(const r of this.messages)if(r.role==="assistant"){t=r;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 ph(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 r of n)r()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}submitFeedback({messageId:t,type:n}){var a;const r=(a=this.adapters)==null?void 0:a.feedback;if(!r)throw new Error("Feedback adapter not configured");const{message:s,parentId:i}=this.repository.getMessage(t);if(r.submit({message:s,type:n}),s.role==="assistant"){const o=E(m({},s),{metadata:E(m({},s.metadata),{submittedFeedback:{type:n}})});this.repository.addOrUpdateMessage(i,o)}this._notifySubscribers()}speak(t){var a,o;const n=(a=this.adapters)==null?void 0:a.speech;if(!n)throw new Error("Speech adapter not configured");const{message:r}=this.repository.getMessage(t);(o=this._stopSpeaking)==null||o.call(this);const s=n.speak(Wn(r)),i=s.subscribe(()=>{s.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:t,status:s.status},this._notifySubscribers()});this.speech={messageId:t,status:s.status},this._notifySubscribers(),this._stopSpeaking=()=>{s.cancel(),i(),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(Vr.fromArray(t!=null?t:[]))}unstable_on(t,n){var s,i,a;if(t==="modelContextUpdate")return(a=(i=(s=this._contextProvider).subscribe)==null?void 0:i.call(s,n))!=null?a:(()=>{});const r=this._eventSubscribers.get(t);return r?r.add(n):this._eventSubscribers.set(t,new Set([n])),()=>{this._eventSubscribers.get(t).delete(n)}}}const Gr=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function gh({state:e,getTools:t,onResult:n,setToolStatuses:r}){const s=y.useRef({}),i=y.useRef(new Map),a=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[h,b]=ha(),S=rh(t,()=>{var x,g;return(g=(x=a.current)==null?void 0:x.signal)!=null?g:new AbortController().signal},(x,g)=>new Promise((v,C)=>{const O=i.current.get(x);O&&O.reject(new Error("Human input request was superseded by a new request")),i.current.set(x,{resolve:v,reject:C}),r(F=>E(m({},F),{[x]:{type:"interrupt",payload:{type:"human",payload:g}}}))}),{onExecutionStart:x=>{o.current++,r(g=>E(m({},g),{[x]:{type:"executing"}}))},onExecutionEnd:x=>{o.current--,r(g=>{const v=m({},g);return delete v[x],v}),o.current===0&&(l.current.forEach(g=>g()),l.current=[])}});return h.pipeThrough(S).pipeThrough(new ua).pipeTo(new WritableStream({write(x){var g;if(x.type==="result"){if((g=s.current[x.meta.toolCallId])!=null&&g.hasResult)return;n(m({type:"add-tool-result",toolCallId:x.meta.toolCallId,toolName:x.meta.toolName,result:x.result,isError:x.isError},x.artifact&&{artifact:x.artifact}))}}})),b}),d=y.useRef(new Set),c=y.useRef(!0);y.useEffect(()=>{const h=b=>{b.forEach(S=>{S.content.forEach(x=>{if(x.type==="tool-call"){if(c.current)d.current.add(x.toolCallId);else{if(d.current.has(x.toolCallId))return;let g=s.current[x.toolCallId];if(g||(g={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:x.toolName,toolCallId:x.toolCallId})},s.current[x.toolCallId]=g),x.argsText!==g.argsText&&!g.argsComplete){if(!x.argsText.startsWith(g.argsText)){if(Gr(g.argsText)&&Gr(x.argsText)){g.controller.argsText.close(),s.current[x.toolCallId]={argsText:x.argsText,hasResult:g.hasResult,argsComplete:!0,controller:g.controller};return}throw new Error(`Tool call argsText can only be appended, not updated: ${x.argsText} does not start with ${g.argsText}`)}const v=x.argsText.slice(g.argsText.length);g.controller.argsText.append(v);const C=Gr(x.argsText);C&&g.controller.argsText.close(),s.current[x.toolCallId]={argsText:x.argsText,hasResult:g.hasResult,argsComplete:C,controller:g.controller}}x.result!==void 0&&!g.hasResult&&(s.current[x.toolCallId]={hasResult:!0,argsComplete:!0,argsText:g.argsText,controller:g.controller},g.controller.setResponse(new Ye({result:x.result,artifact:x.artifact,isError:x.isError})),g.controller.close())}x.messages&&h(x.messages)}})})};h(e.messages),c.current&&(c.current=!1)},[e,u]);const f=()=>(i.current.forEach(({reject:h})=>{h(new Error("Tool execution aborted"))}),i.current.clear(),a.current.abort(),a.current=new AbortController,o.current===0?Promise.resolve():new Promise(h=>{l.current.push(h)}));return{reset:()=>{f(),c.current=!0},abort:f,resume:(h,b)=>{const S=i.current.get(h);if(S)i.current.delete(h),r(x=>E(m({},x),{[h]:{type:"executing"}})),S.resolve(b);else throw new Error(`Tool call ${h} is not waiting for human input`)}}}class yh{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"))}}const Aa=(e,t)=>{var n,r;return t===void 0?((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(s=>s.type!=="tool-call"||!!s.result):((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(s=>s.type!=="tool-call"||!!s.result||!t.includes(s.toolName))};class Yr extends Error{constructor(n,r){super(r);_(this,"name","AbortError");_(this,"detach");this.detach=n}}class bh extends mh{constructor(n,r){super(n);_(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,dictation:!1,attachments:!1,feedback:!1});_(this,"abortController",null);_(this,"isDisabled",!1);_(this,"_isLoading",!1);_(this,"_suggestions",[]);_(this,"_suggestionsController",null);_(this,"_options");_(this,"_lastRunConfig",{});_(this,"_getThreadId");_(this,"_getInitializePromise");_(this,"_loadPromise");this.__internal_setOptions(r)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}__internal_setGetThreadId(n){this._getThreadId=n}__internal_setGetInitializePromise(n){this._getInitializePromise=n}get extras(){}__internal_setOptions(n){var l,u,d,c;if(this._options===n)return;this._options=n;let r=!1;const s=((l=n.adapters)==null?void 0:l.speech)!==void 0;this.capabilities.speech!==s&&(this.capabilities.speech=s,r=!0);const i=((u=n.adapters)==null?void 0:u.dictation)!==void 0;this.capabilities.dictation!==i&&(this.capabilities.dictation=i,r=!0);const a=((d=n.adapters)==null?void 0:d.attachments)!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,r=!0);const o=((c=n.adapters)==null?void 0:c.feedback)!==void 0;this.capabilities.feedback!==o&&(this.capabilities.feedback=o,r=!0),r&&this._notifySubscribers()}__internal_load(){var r,s;if(this._loadPromise)return this._loadPromise;const n=(s=(r=this.adapters.history)==null?void 0:r.load())!=null?s:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=n.then(i=>{var o,l;if(!i)return;this.repository.import(i),i.messages.length>0&&this.ensureInitialized(),this._notifySubscribers();const a=(l=(o=this.adapters.history)==null?void 0:o.resume)==null?void 0:l.bind(this.adapters.history);i.unstable_resume&&a&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},a)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(n){return P(this,null,function*(){var a,o,l,u;this.ensureInitialized();const r=(a=this._getInitializePromise)==null?void 0:a.call(this);r&&(yield r);const s=tn(n,kt(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(n.parentId,s),(o=this._options.adapters.history)==null||o.append(m({parentId:n.parentId,message:s},n.runConfig!==void 0&&{runConfig:n.runConfig})),((l=n.startRun)!=null?l:n.role==="user")?yield this.startRun({parentId:s.id,sourceId:n.sourceId,runConfig:(u=n.runConfig)!=null?u:{}}):(this.repository.resetHead(s.id),this._notifySubscribers())})}resumeRun(s){var i=s,{stream:n}=i,r=q(i,["stream"]);if(!n)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(r,n)}exportExternalState(){throw new Error("Runtime does not support exporting external states.")}importExternalState(){throw new Error("Runtime does not support importing external states.")}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(i,a){return P(this,arguments,function*({parentId:n,runConfig:r},s){var d,c,f;this.ensureInitialized();let l={id:kt(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("runStart");try{this._suggestions=[],(d=this._suggestionsController)==null||d.abort(),this._suggestionsController=null,this._notifySubscribers();do l=yield this.performRoundtrip(n,l,r,s),s=void 0;while(Aa(l,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("runEnd")}this._suggestionsController=new AbortController;const u=this._suggestionsController.signal;if(this.adapters.suggestion&&((c=l.status)==null?void 0:c.type)!=="requires-action"){const g=(f=this.adapters.suggestion)==null?void 0:f.generate({messages:this.messages});if(Symbol.asyncIterator in g)try{for(var h=Pt(g),b,S,x;b=!(S=yield h.next()).done;b=!1){const v=S.value;if(u.aborted)break;this._suggestions=v,this._notifySubscribers()}}catch(S){x=[S]}finally{try{b&&(S=h.return)&&(yield S.call(h))}finally{if(x)throw x[0]}}else{const v=yield g;if(u.aborted)return;this._suggestions=v,this._notifySubscribers()}}})}performRoundtrip(n,r,s,i){return P(this,null,function*(){var S,x,g,v,C,O,F,T,R,H,U;const a=n?this.repository.getMessages(n):[];(S=this.abortController)==null||S.abort(),this.abortController=new AbortController;const o=r.content,l=(x=r.metadata)==null?void 0:x.unstable_annotations,u=(g=r.metadata)==null?void 0:g.unstable_data,d=(v=r.metadata)==null?void 0:v.steps,c=(C=r.metadata)==null?void 0:C.custom,f=D=>{var G,ce,k,ye,Ie,pe;const N=(G=D.metadata)==null?void 0:G.steps,K=N?[...d!=null?d:[],...N]:void 0,re=(ce=D.metadata)==null?void 0:ce.unstable_annotations,V=(k=D.metadata)==null?void 0:k.unstable_data,Q=re?[...l!=null?l:[],...re]:void 0,w=V?[...u!=null?u:[],...V]:void 0;r=m(E(m(m({},r),D.content?{content:[...o,...(ye=D.content)!=null?ye:[]]}:void 0),{status:(Ie=D.status)!=null?Ie:r.status}),D.metadata?{metadata:m(m(m(m(m(m({},r.metadata),D.metadata.unstable_state?{unstable_state:D.metadata.unstable_state}:void 0),Q?{unstable_annotations:Q}:void 0),w?{unstable_data:w}:void 0),K?{steps:K}:void 0),(pe=D.metadata)!=null&&pe.custom?{custom:m(m({},c!=null?c:{}),D.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(n,r),this._notifySubscribers()},h=(O=this._options.maxSteps)!=null?O:2;if(((R=(T=(F=r.metadata)==null?void 0:F.steps)==null?void 0:T.length)!=null?R:0)>=h)return f({status:{type:"incomplete",reason:"tool-calls"}}),r;f({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=s!=null?s:{};const D=this.getModelContext();i=i!=null?i:this.adapters.chatModel.run.bind(this.adapters.chatModel);const N=this.abortController.signal,K=(H=this._getThreadId)==null?void 0:H.call(this),re=i({messages:a,runConfig:this._lastRunConfig,abortSignal:N,context:D,config:D,unstable_assistantMessageId:r.id,unstable_threadId:K,unstable_parentId:n,unstable_getMessage(){return r}});if(Symbol.asyncIterator in re)try{for(var J=Pt(re),I,B,M;I=!(B=yield J.next()).done;I=!1){const V=B.value;if(N.aborted){f({status:{type:"incomplete",reason:"cancelled"}});break}f(V)}}catch(B){M=[B]}finally{try{I&&(B=J.return)&&(yield B.call(J))}finally{if(M)throw M[0]}}else f(yield re);r.status.type==="running"&&f({status:{type:"complete",reason:"unknown"}})}catch(D){if(D instanceof Yr)f({status:{type:"incomplete",reason:"cancelled"}});else if(D instanceof Error&&D.name==="AbortError")f({status:{type:"incomplete",reason:"cancelled"}});else throw f({status:{type:"incomplete",reason:"error",error:D instanceof Error?D.message:`[${typeof D}] ${new String(D).toString()}`}}),D}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&(yield(U=this._options.adapters.history)==null?void 0:U.append({parentId:n,message:r,runConfig:this._lastRunConfig}))}return r})}detach(){var r;const n=new Yr(!0);(r=this.abortController)==null||r.abort(n),this.abortController=null}cancelRun(){var r;const n=new Yr(!1);(r=this.abortController)==null||r.abort(n),this.abortController=null}addToolResult({messageId:n,toolCallId:r,result:s,isError:i,artifact:a}){const o=this.repository.getMessage(n),{parentId:l}=o;let{message:u}=o;if(u.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let d=!1,c=!1;const f=u.content.map(h=>h.type!=="tool-call"||h.toolCallId!==r?h:(c=!0,h.result||(d=!0),E(m({},h),{result:s,artifact:a,isError:i})));if(!c)throw new Error("Tried to add tool result to non-existing tool call");u=E(m({},u),{content:f}),this.repository.addOrUpdateMessage(l,u),d&&Aa(u,this._options.unstable_humanToolNames)&&this.performRoundtrip(l,u,this._lastRunConfig)}resumeToolCall(n){throw new Error("Local runtime does not support resuming tool calls.")}}const Pa=Object.freeze([]),Qr="__DEFAULT_ID__",xh=Object.freeze({[Qr]:{id:Qr,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}});class wh extends Zt{constructor(n){super();_(this,"_mainThread");this._mainThread=n()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw Pa}get archivedThreadIds(){throw Pa}get mainThreadId(){return Qr}get threadItems(){return xh}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 P(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.")}}class Sh extends Rr{constructor(n,r){super();_(this,"threads");_(this,"Provider");_(this,"_options");this._options=n,this.threads=new wh(()=>new bh(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(Vr.fromArray(r))}}const Ma=e=>{try{const n=e.split(".")[1];if(!n)throw new Error("Invalid JWT format");let r=n.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4!==0;)r+="=";const s=atob(r),a=JSON.parse(s).exp;if(!a||typeof a!="number")throw new Error('JWT does not contain a valid "exp" field');return a*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}};class Na{constructor(t){_(this,"strategy","jwt");_(this,"cachedToken",null);_(this,"tokenExpiry",null);Pn(this,kn);Mn(this,kn,t)}getAuthHeaders(){return P(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 An(this,kn).call(this);return n?(this.cachedToken=n,this.tokenExpiry=Ma(n),{Authorization:`Bearer ${n}`}):!1})}readAuthHeaders(t){const n=t.get("Authorization");if(!n)return;const[r,s]=n.split(" ");if(r!=="Bearer"||!s)throw new Error("Invalid auth header received");this.cachedToken=s,this.tokenExpiry=Ma(s)}}kn=new WeakMap;class kh{constructor(t,n,r){_(this,"strategy","api-key");Pn(this,_n);Pn(this,Cn);Pn(this,Tn);Mn(this,_n,t),Mn(this,Cn,n),Mn(this,Tn,r)}getAuthHeaders(){return P(this,null,function*(){return{Authorization:`Bearer ${An(this,_n)}`,"Aui-User-Id":An(this,Cn),"Aui-Workspace-Id":An(this,Tn)}})}readAuthHeaders(){}}_n=new WeakMap,Cn=new WeakMap,Tn=new WeakMap;const Qn="aui:refresh_token";class _h{constructor(t){_(this,"strategy","anon");_(this,"baseUrl");_(this,"jwtStrategy");this.baseUrl=t,this.jwtStrategy=new Na(()=>P(this,null,function*(){const n=Date.now(),r=localStorage.getItem(Qn),s=r?JSON.parse(r):void 0;if(s)if(new Date(s.expires_at).getTime()-n>30*1e3){const d=yield fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:s.token})});if(d.ok){const c=yield d.json(),{access_token:f,refresh_token:h}=c;return h&&localStorage.setItem(Qn,JSON.stringify(h)),f}}else localStorage.removeItem(Qn);const i=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!i.ok)return null;const a=yield i.json(),{access_token:o,refresh_token:l}=a;return!o||!l?null:(localStorage.setItem(Qn,JSON.stringify(l)),o)}))}getAuthHeaders(){return P(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(t){this.jwtStrategy.readAuthHeaders(t)}}class Ch extends Error{constructor(t){super(t),this.name="APIError"}}class Th{constructor(t){_(this,"_auth");_(this,"_baseUrl");if("authToken"in t)this._baseUrl=t.baseUrl,this._auth=new Na(t.authToken);else if("apiKey"in t)this._baseUrl="https://backend.assistant-api.com",this._auth=new kh(t.apiKey,t.userId,t.workspaceId);else if("anonymous"in t)this._baseUrl=t.baseUrl,this._auth=new _h(t.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return P(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return P(this,arguments,function*(t,n={}){var u;const s=yield this._auth.getAuthHeaders();if(!s)throw new Error("Authorization failed");const i=E(m(m({},s),n.headers),{"Content-Type":"application/json"}),a=new URLSearchParams;if(n.query)for(const[d,c]of Object.entries(n.query))c!==!1&&(c===!0?a.set(d,"true"):a.set(d,c.toString()));const o=new URL(`${this._baseUrl}/v1${t}`);o.search=a.toString();const l=yield fetch(o,{method:(u=n.method)!=null?u:"GET",headers:i,body:n.body?JSON.stringify(n.body):null});if(this._auth.readAuthHeaders(l.headers),!l.ok){const d=yield l.text();try{const c=JSON.parse(d);throw new Ch(c.message)}catch(c){throw new Error(`Request failed with status ${l.status}, ${d}`)}}return l})}makeRequest(r){return P(this,arguments,function*(t,n={}){return(yield this.makeRawRequest(t,n)).json()})}}class Ih{constructor(t){_(this,"cloud");this.cloud=t}create(){return P(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}}class vh{constructor(t){_(this,"cloud");this.cloud=t}__internal_getAssistantOptions(t){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>P(this,null,function*(){const n=yield this.cloud._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");return E(m({},n),{Accept:"text/plain"})}),body:{assistant_id:t,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(t){return P(this,null,function*(){const n=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:t});return Ur.fromResponse(n,new Kd)})}}class Eh{constructor(t){_(this,"cloud");this.cloud=t}list(t,n){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}/messages`,{query:n})})}create(t,n){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:n})})}}class Ah{constructor(t){_(this,"cloud");_(this,"messages");this.cloud=t,this.messages=new Eh(t)}list(t){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{query:t})})}get(t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`)})}create(t){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:t})})}update(t,n){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`,{method:"PUT",body:n})})}delete(t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`,{method:"DELETE"})})}}class Ph{constructor(t){_(this,"cloud");this.cloud=t}pdfToImages(t){return P(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:t})})}generatePresignedUploadUrl(t){return P(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:t})})}}class Mh{constructor(t){_(this,"threads");_(this,"auth");_(this,"runs");_(this,"files");const n=new Th(t);this.threads=new Ah(n),this.auth={tokens:new Ih(n)},this.runs=new vh(n),this.files=new Ph(n)}}function Xr(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(n=>Xr(n,t+1)):typeof e=="object"?Object.entries(e).every(([n,r])=>typeof n=="string"&&Xr(r,t+1)):!1}const Nh=e=>{var t;return m({role:e.role,content:e.content.map(n=>{const r=n.type;switch(r){case"text":return{type:"text",text:n.text};case"reasoning":return{type:"reasoning",text:n.text};case"source":return m({type:"source",sourceType:n.sourceType,id:n.id,url:n.url},n.title?{title:n.title}:void 0);case"tool-call":return Xr(n.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(n)}`),m(m(m({type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName},JSON.stringify(n.args)===n.argsText?{args:n.args}:{argsText:n.argsText}),n.result?{result:n.result}:{}),n.isError?{isError:!0}:{});case"image":return{type:"image",image:n.image};case"file":return m({type:"file",data:n.data,mimeType:n.mimeType},n.filename?{filename:n.filename}:void 0);default:{const s=r;throw new Error(`Message part type not supported by aui/v0: ${s}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},Dh=e=>{const t=e.content,n=tn(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:n}},Zr=new WeakMap;class Lh{constructor(t,n){_(this,"parent");_(this,"formatAdapter");this.parent=t,this.formatAdapter=n}append(t){return P(this,null,function*(){const n=this.formatAdapter.encode(t),r=this.formatAdapter.getId(t.message);return this.parent._appendWithFormat(t.parentId,r,this.formatAdapter.format,n)})}load(){return P(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,t=>this.formatAdapter.decode(t))})}}class Oh{constructor(t,n){_(this,"cloudRef");_(this,"aui");this.cloudRef=t,this.aui=n}get _getIdForLocalId(){return Zr.has(this.aui.threadListItem())||Zr.set(this.aui.threadListItem(),{}),Zr.get(this.aui.threadListItem())}withFormat(t){return new Lh(this,t)}append(r){return P(this,arguments,function*({parentId:t,message:n}){var a;const{remoteId:s}=yield this.aui.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(s,{parent_id:t?(a=yield this._getIdForLocalId[t])!=null?a:t:null,format:"aui/v0",content:Nh(n)}).then(({message_id:o})=>(this._getIdForLocalId[n.id]=o,o));return this._getIdForLocalId[n.id]=i,i.then(()=>{})})}load(){return P(this,null,function*(){const t=this.aui.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(s=>s.format==="aui/v0").map(Dh).reverse()}})}_appendWithFormat(t,n,r,s){return P(this,null,function*(){var o;const{remoteId:i}=yield this.aui.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(i,{parent_id:t?(o=yield this._getIdForLocalId[t])!=null?o:t:null,format:r,content:s}).then(({message_id:l})=>(this._getIdForLocalId[n]=l,l));return this._getIdForLocalId[n]=a,a.then(()=>{})})}_loadWithFormat(t,n){return P(this,null,function*(){const r=this.aui.threadListItem().getState().remoteId;if(!r)return{messages:[]};const{messages:s}=yield this.cloudRef.current.threads.messages.list(r,{format:t});return{messages:s.filter(i=>i.format===t).map(i=>n({id:i.id,parent_id:i.parent_id,format:i.format,content:i.content})).reverse()}})}}const Fh=e=>{const t=he(),[n]=y.useState(()=>new Oh(e,t));return n},Da=typeof process!="undefined"&&((tc=process==null?void 0:process.env)==null?void 0:tc.NEXT_PUBLIC_ASSISTANT_BASE_URL),es=Da?new Mh({baseUrl:Da,anonymous:!0}):void 0,Bh=e=>{var s;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const n=y.useCallback(function({children:a}){var c;const o=Fh({get current(){var f;return(f=t.current.cloud)!=null?f:es}}),l=(c=t.current.cloud)!=null?c:es,u=y.useMemo(()=>new hh(l),[l]),d=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(Jr,{adapters:d,children:a})},[]),r=(s=e.cloud)!=null?s:es;return r?{list:()=>P(null,null,function*(){const{threads:i}=yield r.threads.list();return{threads:i.map(a=>{var o;return{status:a.is_archived?"archived":"regular",remoteId:a.id,title:a.title,externalId:(o=a.external_id)!=null?o:void 0}})}}),initialize:()=>P(null,null,function*(){var u,d;const a=yield(d=(u=e.create)==null?void 0:u.call(e))!=null?d:Promise.resolve(),o=a?a.externalId:void 0,{thread_id:l}=yield r.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(i,a)=>P(null,null,function*(){return r.threads.update(i,{title:a})}),archive:i=>P(null,null,function*(){return r.threads.update(i,{is_archived:!0})}),unarchive:i=>P(null,null,function*(){return r.threads.update(i,{is_archived:!1})}),delete:i=>P(null,null,function*(){var a;return yield(a=e.delete)==null?void 0:a.call(e,i),r.threads.delete(i)}),generateTitle:(i,a)=>P(null,null,function*(){const o=a.map(l=>E(m({},l),{content:l.content.filter(u=>u.type==="text"||u.type==="tool-call")}));return r.runs.stream({thread_id:i,assistant_id:"system/thread_title",messages:o})}),fetch:i=>P(null,null,function*(){var o;const a=yield r.threads.get(i);return{status:a.is_archived?"archived":"regular",remoteId:a.id,title:a.title,externalId:(o=a.external_id)!=null?o:void 0}}),unstable_Provider:n}:new yh},zh=(e,r)=>{var s=r,{initialMessages:t}=s,n=q(s,["initialMessages"]);var d;const c=(d=fh())!=null?d:{},{modelContext:i}=c,a=q(c,["modelContext"]),o=E(m({},n),{adapters:E(m(m({},a),n.adapters),{chatModel:e})}),[l]=y.useState(()=>new Sh(o,t)),u=y.useRef(void 0);return u.current=Z(f=>f.threadListItem.remoteId),y.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setGetThreadId(()=>u.current)},[l]),y.useEffect(()=>()=>{l.threads.getMainThreadRuntimeCore().detach()},[l]),y.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setOptions(o),l.threads.getMainThreadRuntimeCore().__internal_load()}),y.useEffect(()=>{if(i)return l.registerModelContextProvider(i)},[i,l]),y.useMemo(()=>new ts(l),[l])},La=(e,r={})=>{var s=r,{cloud:t}=s,n=q(s,["cloud"]);const i=Bh({cloud:t});return Za({runtimeHook:function(){return zh(e,n)},adapter:i,allowNesting:!0})};class ts{constructor(t){_(this,"_core");_(this,"threads");_(this,"_thread");this._core=t,this.threads=new Ea(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(Vr.fromArray(t!=null?t:[]))}}const Rh=e=>{const o=e,{cloud:t,initialMessages:n,maxSteps:r,adapters:s,unstable_humanToolNames:i}=o,a=q(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:r,adapters:s,unstable_humanToolNames:i},otherOptions:a}};function Ct(e){const t=te.useRef(e);return te.useEffect(()=>{t.current=e}),te.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}const Oa=e=>{let t;const n=new Set,r=(u,d)=>{const c=typeof u=="function"?u(t):u;if(!Object.is(c,t)){const f=t;t=(d!=null?d:typeof c!="object"||c===null)?c:Object.assign({},t,c),n.forEach(h=>h(t,f))}},s=()=>t,o={setState:r,getState:s,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u))},l=t=e(r,s,o);return o},jh=(e=>e?Oa(e):Oa),$h=e=>e;function Uh(e,t=$h){const n=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(n),n}const Fa=e=>{const t=jh(e),n=r=>Uh(t,r);return Object.assign(n,t),n},Ot=(e=>e?Fa(e):Fa);function Ba(e,t){function n(s){const i=e(s);return i?i[t]:null}function r(s){let i=!1,a;typeof s=="function"?a=s:s&&typeof s=="object"&&(i=!!s.optional,a=s.selector);const o=n({optional:i});return o?a?o(a):o():null}return{[t]:r,[`${t}Store`]:n}}const za=y.createContext(null),Hh=e=>({useSmoothStatus:Ot(()=>e)}),qh=({children:e})=>{const t=Ra({optional:!0}),n=he(),[r]=y.useState(()=>Hh(n.part().getState().status));return t?e:p.jsx(za.Provider,{value:r,children:e})},Vh=e=>{const t=y.forwardRef((n,r)=>p.jsx(qh,{children:p.jsx(e,E(m({},n),{ref:r}))}));return t.displayName=e.displayName,t};function Ra(e){const t=y.useContext(za);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}const{useSmoothStatus:Wh,useSmoothStatusStore:Kh}=Ba(Ra,"useSmoothStatus"),an=e=>e;class Jh{constructor(t,n){_(this,"currentText");_(this,"setText");_(this,"animationFrameId",null);_(this,"lastUpdateTime",Date.now());_(this,"targetText","");_(this,"animate",()=>{const t=Date.now();let r=t-this.lastUpdateTime;const s=this.targetText.length-this.currentText.length,i=Math.min(5,250/s);let a=0;for(;r>=i&&a<s;)a++,r-=i;a!==s?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,a!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+a),this.lastUpdateTime=t-r,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)}}const ns=Object.freeze({type:"running"}),ja=(e,t=!1)=>{const{text:n}=e,r=Z(d=>d.message.id),s=y.useRef(r),[i,a]=y.useState(n),o=Kh({optional:!0}),l=Ct(d=>{if(a(d),o){const c=i!==d||e.status.type==="running"?ns:e.status;an(o).setState(c,!0)}});y.useEffect(()=>{if(o){const d=t&&(i!==n||e.status.type==="running")?ns:e.status;an(o).setState(d,!0)}},[o,t,n,i,e.status]);const[u]=y.useState(new Jh(n,l));return y.useEffect(()=>{if(!t){u.stop();return}if(s.current!==r||!n.startsWith(u.targetText)){s.current=r,l(n),u.currentText=n,u.targetText=n,u.stop();return}u.targetText=n,u.start()},[l,u,r,t,n]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:i,status:n===i?e.status:ns}:e,[t,i,e,n])},Gh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:ts,BaseAssistantRuntimeCore:Rr,CompositeContextProvider:zr,DefaultThreadComposerRuntimeCore:Xi,MessageRepository:fa,ThreadRuntimeImpl:va,fromThreadMessageLike:tn,generateId:kt,getAutoStatus:ea,splitLocalRuntimeOptions:Rh,useSmooth:ja,useSmoothStatus:Wh,useToolInvocations:gh,withSmoothContextProvider:Vh},Symbol.toStringTag,{value:"Module"})),Tt=e=>{const[,t]=Ke(e.getState);return Ee(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},$a=de(({runtime:e})=>{const t=Tt(e),n=Fr();return Ee(()=>{const r=[],s=["switchedTo","switchedAway"];for(const i of s){const a=e.unstable_on(i,()=>{n(`threadListItem.${i}`,{threadId:e.getState().id})});r.push(a)}return()=>{for(const i of r)i()}},[e,n]),{state:t,methods:{getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e}}}),Ua=de(({runtime:e})=>{const t=Tt(e);return{state:t,methods:{getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e}}}),Yh=de(({runtime:e,index:t})=>{const n=ae(()=>e.getAttachmentByIndex(t),[e,t]);return tt(Ua({runtime:n}))}),Ha=de(({threadIdRef:e,messageIdRef:t,runtime:n})=>{var o;const r=Tt(n),s=Fr();Ee(()=>{const l=[],u=["send","attachmentAdd"];for(const d of u){const c=n.unstable_on(d,()=>{s(`composer.${d}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(c)}return()=>{for(const d of l)d()}},[n,s,e,t]);const i=Dt(()=>r.attachments.map((l,u)=>lt(l.id,Yh({runtime:n,index:u}))),[r.attachments,n]),a=ae(()=>{var l;return{text:r.text,role:r.role,attachments:i.state,runConfig:r.runConfig,isEditing:r.isEditing,canCancel:r.canCancel,attachmentAccept:r.attachmentAccept,isEmpty:r.isEmpty,type:(l=r.type)!=null?l:"thread",dictation:r.dictation,quote:r.quote}},[r,i.state]);return{state:a,methods:{getState:()=>a,setText:n.setText,setRole:n.setRole,setRunConfig:n.setRunConfig,addAttachment:n.addAttachment,reset:n.reset,clearAttachments:n.clearAttachments,send:n.send,cancel:n.cancel,beginEdit:(o=n.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),startDictation:n.startDictation,stopDictation:n.stopDictation,setQuote:n.setQuote,attachment:l=>"id"in l?i.get({key:l.id}):i.get(l),__internal_getRuntime:()=>n}}}),Qh=de(({runtime:e})=>{const t=Tt(e);return{state:t,methods:{getState:()=>t,addToolResult:n=>e.addToolResult(n),resumeToolCall:n=>e.resumeToolCall(n),__internal_getRuntime:()=>e}}}),Xh=de(({runtime:e,index:t})=>{const n=ae(()=>e.getAttachmentByIndex(t),[e,t]);return tt(Ua({runtime:n}))}),Zh=de(({runtime:e,index:t})=>{const n=ae(()=>e.getMessagePartByIndex(t),[e,t]);return tt(Qh({runtime:n}))}),ef=de(({runtime:e,threadIdRef:t})=>{const n=Tt(e),[r,s]=Ke(!1),[i,a]=Ke(!1),o=ae(()=>({get current(){return e.getState().id}}),[e]),l=Bn(Ha({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=Dt(()=>n.content.map((f,h)=>lt("toolCallId"in f&&f.toolCallId!=null?`toolCallId-${f.toolCallId}`:`index-${h}`,Zh({runtime:e,index:h}))),[n.content,e]),d=Dt(()=>{var f;return((f=n.attachments)!=null?f:[]).map((h,b)=>lt(h.id,Xh({runtime:e,index:b})))},[n.attachments,e]),c=ae(()=>E(m({},n),{parts:u.state,composer:l.state,isCopied:r,isHovering:i}),[n,u.state,l.state,r,i]);return{state:c,methods:{getState:()=>c,composer:l.methods,reload:f=>e.reload(f),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:f=>e.submitFeedback(f),switchToBranch:f=>e.switchToBranch(f),getCopyText:()=>e.unstable_getCopyText(),part:f=>"index"in f?u.get({index:f.index}):u.get({key:`toolCallId-${f.toolCallId}`}),attachment:f=>"id"in f?d.get({key:f.id}):d.get(f),setIsCopied:s,setIsHovering:a,__internal_getRuntime:()=>e}}}),tf=de(({runtime:e,id:t,threadIdRef:n})=>{const r=ae(()=>e.getMessageById(t),[e,t]);return tt(ef({runtime:r,threadIdRef:n}))}),nf=de(({runtime:e})=>{const t=Tt(e),n=Fr();Ee(()=>{const o=[],l=["runStart","runEnd","initialize","modelContextUpdate"];for(const u of l){const d=e.unstable_on(u,()=>{var f;const c=((f=e.getState())==null?void 0:f.threadId)||"unknown";n(`thread.${u}`,{threadId:c})});o.push(d)}return()=>{for(const u of o)u()}},[e,n]);const r=ae(()=>({get current(){return e.getState().threadId}}),[e]),s=Bn(Ha({runtime:e.composer,threadIdRef:r})),i=Dt(()=>t.messages.map(o=>lt(o.id,tf({runtime:e,id:o.id,threadIdRef:r}))),[t.messages,e,r]),a=ae(()=>({isEmpty:i.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:s.state,messages:i.state}),[t,i,s.state]);return{state:a,methods:{getState:()=>a,composer:s.methods,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:()=>P(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>P(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?i.get({key:o.id}):i.get(o),__internal_getRuntime:()=>e}}}),rf=de(({runtime:e,id:t})=>{const n=ae(()=>e.getItemById(t),[e,t]);return tt($a({runtime:n}))}),sf=de(({runtime:e,__internal_assistantRuntime:t})=>{const n=Tt(e),r=Bn(nf({runtime:e.main})),s=Dt(()=>Object.keys(n.threadItems).map(a=>lt(a,rf({runtime:e,id:a}))),[n.threadItems,e]),i=ae(()=>{var a;return{mainThreadId:n.mainThreadId,newThreadId:(a=n.newThreadId)!=null?a:null,isLoading:n.isLoading,threadIds:n.threadIds,archivedThreadIds:n.archivedThreadIds,threadItems:s.state,main:r.state}},[n,s.state,r.state]);return{state:i,methods:{getState:()=>i,thread:()=>r.methods,item:a=>{if(a==="main")return s.get({key:i.mainThreadId});if("id"in a)return s.get({key:a.id});const{index:o,archived:l=!1}=a,u=l?i.archivedThreadIds[o]:i.threadIds[o];return s.get({key:u})},switchToThread:a=>P(null,null,function*(){yield e.switchToThread(a)}),switchToNewThread:()=>P(null,null,function*(){yield e.switchToNewThread()}),__internal_getAssistantRuntime:()=>t}}}),af=1,qa=de(()=>{const[e]=Ke(()=>({version:af+1})),t=ae(()=>new zr,[]);return{state:e,methods:{getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:n=>t.subscribe(n),register:n=>t.registerModelContextProvider(n)}}});function Va(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Wa(...e){return t=>{let n=!1;const r=e.map(s=>{const i=Va(s,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let s=0;s<r.length;s++){const i=r[s];typeof i=="function"?i():Va(e[s],null)}}}}function Xn(...e){return te.useCallback(Wa(...e),e)}const Ka=de(({toolkit:e})=>{const[t,n]=Ke(()=>({tools:{}})),r=Ki(),s=vi((i,a)=>(n(o=>{var l;return E(m({},o),{tools:E(m({},o.tools),{[i]:[...(l=o.tools[i])!=null?l:[],a]})})}),()=>{n(o=>{var l,u;return E(m({},o),{tools:E(m({},o.tools),{[i]:(u=(l=o.tools[i])==null?void 0:l.filter(d=>d!==a))!=null?u:[]})})})}),[]);return Ee(()=>{if(!e)return;const i=[];for(const[l,u]of Object.entries(e))u.render&&i.push(s(l,u.render));const a=Object.entries(e).reduce((l,[u,d])=>{const h=d,{render:c}=h,f=q(h,["render"]);return l[u]=f,l},{}),o={getModelContext:()=>({tools:a})};return i.push(r.current.modelContext().register(o)),()=>{i.forEach(l=>l())}},[e,s,r]),{state:t,methods:{getState:()=>t,setToolUI:s}}});Ui(Ka,{modelContext:qa()});const of=de(e=>({state:e,methods:{getState:()=>e}})),lf=de(e=>{const[t]=Ke(()=>({suggestions:(e!=null?e:[]).map(s=>typeof s=="string"?{title:s,label:"",prompt:s}:{title:s.title,label:s.label,prompt:s.prompt})})),n=Dt(()=>t.suggestions.map((r,s)=>lt(s,of(r))),[t.suggestions]);return{state:t,methods:{getState:()=>t,suggestion:({index:r})=>n.get({index:r})}}}),Ja=de(e=>{const t=Ki();return Ee(()=>e.registerModelContextProvider(t.current.modelContext()),[e,t]),tt(sf({runtime:e.threads,__internal_assistantRuntime:e}))});Ui(Ja,{modelContext:qa(),tools:Ka({}),suggestions:lf(),threadListItem:Ve({source:"threads",query:{type:"main"},get:e=>e.threads().item("main")}),thread:Ve({source:"threads",query:{type:"main"},get:e=>e.threads().thread("main")}),composer:Ve({source:"thread",query:{},get:e=>e.threads().thread("main").composer})});const rs=e=>{const t=new Map,n=()=>{let r=0;for(const s of t.values())r+=s;e(r)};return{register:()=>{const r=Symbol();return t.set(r,0),{setHeight:s=>{t.get(r)!==s&&(t.set(r,s),n())},unregister:()=>{t.delete(r),n()}}}}},uf=(e={})=>{const t=new Set,n=rs(a=>{i.setState({height:E(m({},i.getState().height),{viewport:a})})}),r=rs(a=>{i.setState({height:E(m({},i.getState().height),{inset:a})})}),s=rs(a=>{i.setState({height:E(m({},i.getState().height),{userMessage:a})})}),i=Ot(()=>{var a;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(a=e.turnAnchor)!=null?a:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:n.register,registerContentInset:r.register,registerUserMessageHeight:s.register}});return i};function cf(e,t){function n(r){const s=y.useContext(e);if(!(r!=null&&r.optional)&&!s)throw new Error(`This component must be used within ${t}.`);return s}return n}const Ga=y.createContext(null),df=cf(Ga,"ThreadPrimitive.Viewport"),{useThreadViewport:Zn,useThreadViewportStore:ss}=Ba(df,"useThreadViewport"),hf=e=>{const t=ss({optional:!0}),[n]=y.useState(()=>uf(e));return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),y.useEffect(()=>{if(t)return n.subscribe(r=>{t.getState().isAtBottom!==r.isAtBottom&&an(t).setState({isAtBottom:r.isAtBottom})})},[n,t]),y.useEffect(()=>{var i;const r={turnAnchor:(i=e.turnAnchor)!=null?i:"bottom"};n.getState().turnAnchor!==r.turnAnchor&&an(n).setState(r)},[n,e.turnAnchor]),n},Ya=({children:e,options:t={}})=>{const n=hf(t),[r]=y.useState(()=>({useThreadViewport:n}));return p.jsx(Ga.Provider,{value:r,children:e})},ff=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},pf=({children:e,aui:t=null,runtime:n})=>{const r=he({threads:Ja(n)},{parent:t});y.useEffect(()=>{},[r]);const s=ff(n);return p.jsxs(ut,{value:r,children:[s&&p.jsx(s,{}),p.jsx(Ya,{children:e})]})},Qa=y.memo(pf),mf=({index:e,archived:t,children:n})=>{const r=he({threadListItem:Ve({source:"threads",query:{type:"index",index:e,archived:t},get:s=>s.threads().item({index:e,archived:t})})});return p.jsx(ut,{value:r,children:n})},gf=({runtime:e,children:t})=>{const n=he({threadListItem:$a({runtime:e})});return p.jsx(ut,{value:n,children:t})},yf=({index:e,children:t})=>{const n=he({message:Ve({source:"thread",query:{type:"index",index:e},get:r=>r.thread().message({index:e})}),composer:Ve({source:"message",query:{},get:r=>r.thread().message({index:e}).composer})});return p.jsx(ut,{value:n,children:t})},bf=({index:e,children:t})=>{const n=he({part:Ve({source:"message",query:{type:"index",index:e},get:r=>r.message().part({index:e})})});return p.jsx(ut,{value:n,children:t})},xf=({index:e,children:t})=>{const n=he({attachment:Ve({source:"message",query:{type:"index",index:e},get:r=>r.message().attachment({index:e})})});return p.jsx(ut,{value:n,children:t})},wf=({index:e,children:t})=>{const n=he({attachment:Ve({source:"composer",query:{type:"index",index:e},get:r=>r.composer().attachment({index:e})})});return p.jsx(ut,{value:n,children:t})},Sf=de(({text:e,isRunning:t})=>{const n=ae(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return{state:n,methods:{getState:()=>n,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}}}}),kf=({text:e,isRunning:t=!1,children:n})=>{const r=he({part:Sf({text:e,isRunning:t})});return p.jsx(ut,{value:r,children:n})};class _f extends Zt{constructor(n,r){super();_(this,"useRuntimeHook");_(this,"instances",new Map);_(this,"useAliveThreadsKeysChanged",Ot(()=>({})));_(this,"parent");_(this,"_InnerActiveThreadProvider",({threadId:n})=>{const{useRuntime:r}=this.useRuntimeHook(),s=r(),i=s.thread.__internal_threadBinding,a=y.useCallback(()=>{const d=this.instances.get(n);if(!d)throw new Error("Thread not found. This is a bug in assistant-ui.");d.runtime=i.getState(),this._notifySubscribers()},[n,i]),o=y.useRef(!1);o.current||a(),y.useEffect(()=>(o.current=!0,a(),i.outerSubscribe(a)),[i,a]);const l=he(),u=y.useRef(void 0);return y.useEffect(()=>{const d=i.getState(),c=d.__internal_setGetInitializePromise;typeof c=="function"&&c.call(d,()=>u.current)},[i]),y.useEffect(()=>s.threads.main.unstable_on("initialize",()=>{if(l.threadListItem().getState().status==="new"){u.current=l.threadListItem().initialize();const c=s.thread.unstable_on("runEnd",()=>{c(),l.threadListItem().generateTitle()})}}),[s,l]),null});_(this,"_OuterActiveThreadProvider",y.memo(({threadId:n,provider:r})=>{const s=y.useMemo(()=>new Ea(this.parent).getItemById(n),[n]);return p.jsx(gf,{runtime:s,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:n})})})}));_(this,"__internal_RenderThreadRuntimes",({provider:n})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(r=>p.jsx(this._OuterActiveThreadProvider,{threadId:r,provider:n},r))));this.parent=r,this.useRuntimeHook=Ot(()=>({useRuntime:n}))}startThreadRuntime(n){return this.instances.has(n)||(this.instances.set(n,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,s)=>{const i=()=>{const o=this.instances.get(n);if(!o)a(),s(new Error("Thread was deleted before runtime was started"));else if(o.runtime)a(),r(o.runtime);else return},a=this.subscribe(i);i()})}getThreadRuntimeCore(n){const r=this.instances.get(n);if(r)return r.runtime}stopThreadRuntime(n){this.instances.delete(n),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(n){this.useRuntimeHook.getState().useRuntime!==n&&this.useRuntimeHook.setState({useRuntime:n},!0)}}const be=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."),Cf={getMessageById(){},getBranches(){return[]},switchToBranch(){throw be},append(){throw be},startRun(){throw be},resumeRun(){throw be},cancelRun(){throw be},addToolResult(){throw be},resumeToolCall(){throw be},speak(){throw be},stopSpeaking(){throw be},submitFeedback(){throw be},getModelContext(){return{}},exportExternalState(){throw be},importExternalState(){throw be},unstable_loadExternalState(){throw be},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return P(this,null,function*(){throw be})},removeAttachment(){return P(this,null,function*(){throw be})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw be},role:"user",setRole(){throw be},runConfig:{},setRunConfig(){throw be},reset(){return P(this,null,function*(){})},clearAttachments(){return P(this,null,function*(){})},send(){throw be},cancel(){},dictation:void 0,startDictation(){throw be},stopDictation(){},quote:void 0,setQuote(){throw be},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw be},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw be},export(){return{messages:[]}},reset(){throw be},unstable_on(){return()=>{}}},Xa=(e,t,n)=>n.reduce((r,s)=>{var i;return(i=s==null?void 0:s(r,t))!=null?i:r},e);class Tf extends Zt{constructor(n){super();_(this,"_pendingTransforms",[]);_(this,"_baseValue");_(this,"_cachedValue");this._baseValue=n,this._cachedValue=n}_updateState(){this._cachedValue=this._pendingTransforms.reduce((n,r)=>Xa(n,r.task,[r.loading,r.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 P(this,null,function*(){const r=n.execute(),s=E(m({},n),{task:r});try{this._pendingTransforms.push(s),this._updateState();const i=yield r;return this._baseValue=Xa(this._baseValue,i,[n.optimistic,n.then]),i}finally{const i=this._pendingTransforms.indexOf(s);i>-1&&this._pendingTransforms.splice(i,1),this._updateState()}})}}function Ik(e){return e}const er=(e,t)=>{const n=e.threadIdMap[t];if(n!==void 0)return e.threadData[n]},tr=(e,t,n)=>{const r=er(e,t);if(!r)return e;const{id:s,remoteId:i,status:a}=r;if(a===n)return e;const o=m({},e);switch(a){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==s);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==s);break;default:{const l=a;throw new Error(`Unsupported state: ${l}`)}}switch(n){case"regular":o.threadIds=[s,...o.threadIds];break;case"archived":o.archivedThreadIds=[s,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==s)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==s&&l!==i));break;default:{const l=n;throw new Error(`Unsupported state: ${l}`)}}return n!=="deleted"&&(o.threadData=E(m({},o.threadData),{[s]:E(m({},r),{status:n})})),o};class If extends Zt{constructor(n,r){super();_(this,"contextProvider");_(this,"_options");_(this,"_hookManager");_(this,"_loadThreadsPromise");_(this,"_mainThreadId");_(this,"_state",new Tf({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));_(this,"useProvider");_(this,"initialize",n=>P(this,null,function*(){if(this._state.value.newThreadId!==n){const r=this.getItemById(n);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Unexpected new state");return r.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(n),optimistic:r=>tr(r,n,"regular"),loading:(r,s)=>{const i=n;return E(m({},r),{threadData:E(m({},r.threadData),{[i]:E(m({},r.threadData[i]),{initializeTask:s})})})},then:(r,{remoteId:s,externalId:i})=>{const a=er(r,n);if(!a)return r;const o=n;return E(m({},r),{threadIdMap:E(m({},r.threadIdMap),{[s]:o}),threadData:E(m({},r.threadData),{[o]:E(m({},a),{initializeTask:Promise.resolve({remoteId:s,externalId:i}),remoteId:s,externalId:i})})})}})}));_(this,"generateTitle",n=>P(this,null,function*(){var u;const r=this.getItemById(n);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:s}=yield r.initializeTask,i=this._hookManager.getThreadRuntimeCore(r.id);if(!i)return;const a=i.messages,o=yield this._options.adapter.generateTitle(s,a),l=rn.fromAssistantStream(o);try{for(var d=Pt(l),c,f,h;c=!(f=yield d.next()).done;c=!1){const b=f.value;const S=(u=b.parts.filter(g=>g.type==="text")[0])==null?void 0:u.text,x=this._state.baseValue;this._state.update(E(m({},x),{threadData:E(m({},x.threadData),{[r.id]:E(m({},r),{title:S})})}))}}catch(f){h=[f]}finally{try{c&&(f=d.return)&&(yield f.call(d))}finally{if(h)throw h[0]}}}));_(this,"useBoundIds",Ot(()=>[]));_(this,"__internal_RenderComponent",()=>{const n=y.useId();y.useEffect(()=>(this.useBoundIds.setState(a=>[...a,n],!0),()=>{this.useBoundIds.setState(a=>a.filter(o=>o!==n),!0)}),[n]);const r=this.useBoundIds(),{Provider:s}=this.useProvider(),i={modelContext:this.contextProvider};return(r.length===0||r[0]===n)&&p.jsx(Jr,{adapters:i,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:s})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new _f(n.runtimeHook,this),this.useProvider=Ot(()=>{var s;return{Provider:(s=n.adapter.unstable_Provider)!=null?s:y.Fragment}}),this.__internal_setOptions(n),this.switchToNewThread()}get threadItems(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:n=>E(m({},n),{isLoading:!0}),then:(n,r)=>{const s=[],i=[],a={},o={};for(const l of r.threads){switch(l.status){case"regular":s.push(l.remoteId);break;case"archived":i.push(l.remoteId);break;default:{const d=l.status;throw new Error(`Unsupported state: ${d}`)}}const u=l.remoteId;a[l.remoteId]=u,o[u]={id:l.remoteId,remoteId:l.remoteId,externalId:l.externalId,status:l.status,title:l.title,initializeTask:Promise.resolve({remoteId:l.remoteId,externalId:l.externalId})}}return E(m({},n),{threadIds:s,archivedThreadIds:i,threadIdMap:m(m({},n.threadIdMap),a),threadData:m(m({},n.threadData),o)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(n){var s;if(this._options===n)return;this._options=n;const r=(s=n.adapter.unstable_Provider)!=null?s:y.Fragment;r!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:r},!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||Cf}getThreadRuntimeCore(n){const r=this.getItemById(n);if(!r)throw new Error("Thread not found");const s=this._hookManager.getThreadRuntimeCore(r.id);if(!s)throw new Error("Thread not found");return s}getItemById(n){return er(this._state.value,n)}switchToThread(n){return P(this,null,function*(){let r=this.getItemById(n);if(!r){const i=yield this._options.adapter.fetch(n),a=this._state.value,o=i.remoteId,l=E(m({},a.threadData),{[o]:{id:o,initializeTask:Promise.resolve({remoteId:i.remoteId,externalId:i.externalId}),remoteId:i.remoteId,externalId:i.externalId,status:i.status,title:i.title}}),u=E(m({},a.threadIdMap),{[i.remoteId]:o}),d=i.status==="regular"?[...a.threadIds,i.remoteId]:a.threadIds,c=i.status==="archived"?[...a.archivedThreadIds,i.remoteId]:a.archivedThreadIds;this._state.update(E(m({},a),{threadIds:d,archivedThreadIds:c,threadIdMap:u,threadData:l})),r=this.getItemById(n)}if(!r)throw new Error("Thread not found");if(this._mainThreadId===r.id)return;const s=this._hookManager.startThreadRuntime(r.id);this.mainThreadId!==void 0?yield s:s.then(()=>this._notifySubscribers()),r.status==="archived"&&(yield this.unarchive(r.id)),this._mainThreadId=r.id,this._notifySubscribers()})}switchToNewThread(){return P(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 r=this._state.value.newThreadId;if(r===void 0){do r=`__LOCALID_${kt()}`;while(n.threadIdMap[r]);const s=r;this._state.update(E(m({},n),{newThreadId:r,threadIdMap:E(m({},n.threadIdMap),{[r]:s}),threadData:E(m({},n.threadData),{[s]:{status:"new",id:r,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(r)})}rename(n,r){const s=this.getItemById(n);if(!s)throw new Error("Thread not found");if(s.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){const{remoteId:i}=yield s.initializeTask;return this._options.adapter.rename(i,r)}),optimistic:i=>{const a=er(i,n);return a?E(m({},i),{threadData:E(m({},i.threadData),{[a.id]:E(m({},a),{title:r})})}):i}})}_ensureThreadIsNotMain(n){return P(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 P(this,null,function*(){const r=this.getItemById(n);if(!r)throw new Error("Thread not found");if(r.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:s}=yield r.initializeTask;return this._options.adapter.archive(s)}),optimistic:s=>tr(s,r.id,"archived")})})}unarchive(n){const r=this.getItemById(n);if(!r)throw new Error("Thread not found");if(r.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){try{const{remoteId:s}=yield r.initializeTask;return yield this._options.adapter.unarchive(s)}catch(s){throw yield this._ensureThreadIsNotMain(r.id),s}}),optimistic:s=>tr(s,r.id,"regular")})}delete(n){return P(this,null,function*(){const r=this.getItemById(n);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:s}=yield r.initializeTask;return yield this._options.adapter.delete(s)}),optimistic:s=>tr(s,r.id,"deleted")})})}detach(n){return P(this,null,function*(){const r=this.getItemById(n);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id)})}}class vf extends Rr{constructor(n){super();_(this,"threads");this.threads=new If(n,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}}const Ef=e=>{const[t]=y.useState(()=>new vf(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new ts(t),[t])},Za=e=>{if(he().threadListItem.source!==null){if(!e.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 e.runtimeHook()}return Ef(e)},Af=e=>{var n;const t=e;t.__isBound||((n=t.__internal_bindMethods)==null||n.call(t),t.__isBound=!0)};function Pf(e,t=Mf){Af(e);const n=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(n),n}const Mf=e=>e;function eo(e){function t(n){let r=!1,s;typeof n=="function"?s=n:n&&(r=!!n.optional,s=n.selector);const i=e({optional:r});return i?Pf(i,s):null}return t}function to(e){var r,s,i;const n=(i=(s=(r=he().threads()).__internal_getAssistantRuntime)==null?void 0:s.call(r))!=null?i:null;if(!n)throw new Error("AssistantRuntime is not available");return n}function no(e){const t=he(),n=Z(()=>{var r,s,i;return t.thread.source&&(i=(s=(r=t.thread()).__internal_getRuntime)==null?void 0:s.call(r))!=null?i:null});if(!n&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return n}const ro=eo(no);function so(e){const t=he(),n=Z(()=>{var r,s,i;return t.threadListItem.source&&(i=(s=(r=t.threadListItem()).__internal_getRuntime)==null?void 0:s.call(r))!=null?i:null});if(!n&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return n}const io=eo(so);var Nf=Symbol.for("react.lazy"),nr=te[" use ".trim().toString()];function Df(e){return typeof e=="object"&&e!==null&&"then"in e}function ao(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Nf&&"_payload"in e&&Df(e._payload)}function oo(e){const t=Lf(e),n=te.forwardRef((r,s)=>{let u=r,{children:i}=u,a=q(u,["children"]);ao(i)&&typeof nr=="function"&&(i=nr(i._payload));const o=te.Children.toArray(i),l=o.find(Ff);if(l){const d=l.props.children,c=o.map(f=>f===l?te.Children.count(d)>1?te.Children.only(null):te.isValidElement(d)?d.props.children:null:f);return p.jsx(t,E(m({},a),{ref:s,children:te.isValidElement(d)?te.cloneElement(d,void 0,c):null}))}return p.jsx(t,E(m({},a),{ref:s,children:i}))});return n.displayName=`${e}.Slot`,n}var is=oo("Slot");function Lf(e){const t=te.forwardRef((n,r)=>{let a=n,{children:s}=a,i=q(a,["children"]);if(ao(s)&&typeof nr=="function"&&(s=nr(s._payload)),te.isValidElement(s)){const o=zf(s),l=Bf(i,s.props);return s.type!==te.Fragment&&(l.ref=r?Wa(r,o):o),te.cloneElement(s,l)}return te.Children.count(s)>1?te.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Of=Symbol("radix.slottable");function Ff(e){return te.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Of}function Bf(e,t){const n=m({},t);for(const r in t){const s=e[r],i=t[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...o)=>{const l=i(...o);return s(...o),l}:s&&(n[r]=s):r==="style"?n[r]=m(m({},s),i):r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return m(m({},e),n)}function zf(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Rf=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ct=Rf.reduce((e,t)=>{const n=oo(`Primitive.${t}`),r=te.forwardRef((s,i)=>{const u=s,{asChild:a}=u,o=q(u,["asChild"]),l=a?n:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,E(m({},o),{ref:i}))});return r.displayName=`Primitive.${t}`,E(m({},e),{[t]:r})},{});function Ft(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e==null||e(s),n===!1||!s.defaultPrevented)return t==null?void 0:t(s)}}const rr=(e,t,n=[])=>{const r=y.forwardRef((s,i)=>{var u;const a={},o={};Object.keys(s).forEach(d=>{n.includes(d)?a[d]=s[d]:o[d]=s[d]});const l=(u=t(a))!=null?u:void 0;return p.jsx(ct.button,E(m({type:"button"},o),{ref:i,disabled:o.disabled||!l,onClick:Ft(o.onClick,l)}))});return r.displayName=e,r};function jf(e,t=globalThis==null?void 0:globalThis.document){const n=Ct(e);te.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}const $f=rr("AttachmentPrimitive.Remove",()=>{const e=he();return y.useCallback(()=>{e.attachment().remove()},[e])}),on=e=>{const t=y.useRef(void 0);return y.useCallback(r=>{t.current&&t.current(),r&&(t.current=e(r))},[e])},lo=(e,t)=>{const n=y.useCallback(r=>{if(!e)return;const s=e(),i=()=>{const o=t?t(r):r.offsetHeight;s.setHeight(o)},a=new ResizeObserver(i);return a.observe(r),i(),()=>{a.disconnect(),s.unregister()}},[e,t]);return on(n)},uo=y.createContext(!1),co=(e,t)=>{const n=e.match(/^([\d.]+)(em|px|rem)$/);if(!n)return 0;const r=parseFloat(n[1]),s=n[2];if(s==="px")return r;if(s==="em"){const i=parseFloat(getComputedStyle(t).fontSize)||16;return r*i}if(s==="rem"){const i=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return r*i}return 0},ho=({children:e,fillClampThreshold:t="10em",fillClampOffset:n="6em"})=>{const r=Z(l=>{var u;return l.message.isLast&&l.message.role==="assistant"&&l.message.index>=1&&((u=l.thread.messages.at(l.message.index-1))==null?void 0:u.role)==="user"}),s=ss({optional:!0}),i=y.useContext(uo),a=y.useCallback(l=>{if(!s||i)return;const u=()=>{const d=s.getState();if(d.turnAnchor==="top"&&r){const{viewport:c,inset:f,userMessage:h}=d.height,b=co(t,l),S=co(n,l),x=h<=b?h:S,g=Math.max(0,c-f-x);l.style.minHeight=`${g}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),s.subscribe(u)},[s,r,i,t,n]),o=on(a);return p.jsx(uo.Provider,{value:!0,children:p.jsx(is,{ref:o,children:e})})};ho.displayName="ThreadPrimitive.ViewportSlack";const Uf=()=>{const e=he(),t=Z(()=>e.message()),n=y.useCallback(r=>{const s=()=>{t.setIsHovering(!0)},i=()=>{t.setIsHovering(!1)};return r.addEventListener("mouseenter",s),r.addEventListener("mouseleave",i),r.matches(":hover")&&queueMicrotask(()=>t.setIsHovering(!0)),()=>{r.removeEventListener("mouseenter",s),r.removeEventListener("mouseleave",i),t.setIsHovering(!1)}},[t]);return on(n)},Hf=()=>{const e=Zn(s=>s.turnAnchor),t=Zn(s=>s.registerUserMessageHeight),n=Z(s=>{var i;return e==="top"&&s.message.role==="user"&&s.message.index===s.thread.messages.length-2&&((i=s.thread.messages.at(-1))==null?void 0:i.role)==="assistant"}),r=y.useCallback(s=>s.offsetHeight,[]);return lo(n?t:null,r)},as=y.forwardRef((e,t)=>{const n=Uf(),r=Hf(),s=Xn(t,n,r),i=Z(a=>a.message.id);return p.jsx(ho,{children:p.jsx(ct.div,E(m({},e),{ref:s,"data-message-id":i}))})});as.displayName="MessagePrimitive.Root";const qf=Object.freeze({type:"complete"}),Vf=de(({parts:e,getMessagePart:t})=>{const[n,r]=Ke(!0),s=ae(()=>{var o;const a=e[e.length-1];return(o=a==null?void 0:a.status)!=null?o:qf},[e]),i=ae(()=>({parts:e,collapsed:n,status:s}),[e,n,s]);return{state:i,methods:{getState:()=>i,setCollapsed:r,part:t}}}),Wf=({startIndex:e,endIndex:t,children:n})=>{const r=Z(a=>a.message.parts).slice(e,t+1),s=he(),i=he({chainOfThought:Vf({parts:r,getMessagePart:({index:a})=>{if(a<0||a>=r.length)throw new Error(`ChainOfThought part index ${a} is out of bounds (0..${r.length-1})`);return s.message().part({index:e+a})}})});return p.jsx(ut,{value:i,children:n})},fo=()=>Z(t=>{if(t.part.type!=="text"&&t.part.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t.part}),po=y.forwardRef((s,r)=>{var i=s,{smooth:e=!0,component:t="span"}=i,n=q(i,["smooth","component"]);const{text:a,status:o}=ja(fo(),e);return p.jsx(t,E(m({"data-status":o.type},n),{ref:r,children:a}))});po.displayName="MessagePartPrimitive.Text";const Kf=()=>Z(t=>{if(t.part.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t.part}),mo=y.forwardRef((e,t)=>{const{image:n}=Kf();return p.jsx(ct.img,E(m({src:n},e),{ref:t}))});mo.displayName="MessagePartPrimitive.Image";const go=({children:e})=>Z(n=>n.part.status.type==="running")?e:null;go.displayName="MessagePartPrimitive.InProgress";const yo=e=>Symbol.iterator in e,bo=e=>"entries"in e,xo=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[s,i]of n)if(!r.has(s)||!Object.is(i,r.get(s)))return!1;return!0},Jf=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=n.next(),i=r.next();for(;!s.done&&!i.done;){if(!Object.is(s.value,i.value))return!1;s=n.next(),i=r.next()}return!!s.done&&!!i.done};function Gf(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:yo(e)&&yo(t)?bo(e)&&bo(t)?xo(e,t):Jf(e,t):xo({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Yf(e){const t=y.useRef(void 0);return n=>{const r=e(n);return Gf(t.current,r)?t.current:t.current=r}}const os=e=>{let t=-1;return{startGroup:n=>{t===-1&&(t=n)},endGroup:(n,r)=>{t!==-1&&(r.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,r)=>{t!==-1&&r.push({type:e,startIndex:t,endIndex:n})}}},Qf=(e,t)=>{const n=[];if(t){const r=os("chainOfThoughtGroup");for(let s=0;s<e.length;s++){const i=e[s];i==="tool-call"||i==="reasoning"?r.startGroup(s):(r.endGroup(s-1,n),n.push({type:"single",index:s}))}r.finalize(e.length-1,n)}else{const r=os("toolGroup"),s=os("reasoningGroup");for(let i=0;i<e.length;i++){const a=e[i];a==="tool-call"?(s.endGroup(i-1,n),r.startGroup(i)):a==="reasoning"?(r.endGroup(i-1,n),s.startGroup(i)):(r.endGroup(i-1,n),s.endGroup(i-1,n),n.push({type:"single",index:i}))}r.finalize(e.length-1,n),s.finalize(e.length-1,n)}return n},Xf=e=>{const t=Z(Yf(n=>n.message.parts.map(r=>r.type)));return y.useMemo(()=>t.length===0?[]:Qf(t,e),[t,e])},Zf=n=>{var r=n,{Fallback:e}=r,t=q(r,["Fallback"]);const s=Z(i=>{var o,l;const a=(o=i.tools.tools[t.toolName])!=null?o:e;return Array.isArray(a)?(l=a[0])!=null?l:e:a});return s?p.jsx(s,m({},t)):null},dt={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(po,{}),p.jsx(go,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(mo,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},ep=({components:{Text:e=dt.Text,Reasoning:t=dt.Reasoning,Image:n=dt.Image,Source:r=dt.Source,File:s=dt.File,Unstable_Audio:i=dt.Unstable_Audio,tools:a={}}={}})=>{var d,c,f;const o=he(),l=Z(h=>h.part),u=l.type;if(u==="tool-call"){const h=o.part().addToolResult,b=o.part().resumeToolCall;if("Override"in a)return p.jsx(a.Override,E(m({},l),{addResult:h,resume:b}));const S=(c=(d=a.by_name)==null?void 0:d[l.toolName])!=null?c:a.Fallback;return p.jsx(Zf,E(m({},l),{Fallback:S,addResult:h,resume:b}))}if(((f=l.status)==null?void 0:f.type)==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(u){case"text":return p.jsx(e,m({},l));case"reasoning":return p.jsx(t,m({},l));case"source":return p.jsx(r,m({},l));case"image":return p.jsx(n,m({},l));case"file":return p.jsx(s,m({},l));case"audio":return p.jsx(i,m({},l));case"data":return null;default:const h=u;throw new Error(`Unknown message part type: ${h}`)}},sr=y.memo(({index:e,components:t})=>p.jsx(bf,{index:e,children:p.jsx(ep,{components:t})}),(e,t)=>{var n,r,s,i,a,o,l,u,d,c,f,h,b,S,x,g,v,C;return e.index===t.index&&((n=e.components)==null?void 0:n.Text)===((r=t.components)==null?void 0:r.Text)&&((s=e.components)==null?void 0:s.Reasoning)===((i=t.components)==null?void 0:i.Reasoning)&&((a=e.components)==null?void 0:a.Source)===((o=t.components)==null?void 0:o.Source)&&((l=e.components)==null?void 0:l.Image)===((u=t.components)==null?void 0:u.Image)&&((d=e.components)==null?void 0:d.File)===((c=t.components)==null?void 0:c.File)&&((f=e.components)==null?void 0:f.Unstable_Audio)===((h=t.components)==null?void 0:h.Unstable_Audio)&&((b=e.components)==null?void 0:b.tools)===((S=t.components)==null?void 0:S.tools)&&((x=e.components)==null?void 0:x.ToolGroup)===((g=t.components)==null?void 0:g.ToolGroup)&&((v=e.components)==null?void 0:v.ReasoningGroup)===((C=t.components)==null?void 0:C.ReasoningGroup)});sr.displayName="MessagePrimitive.PartByIndex";const tp=({status:e,component:t})=>p.jsx(kf,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),np=Object.freeze({type:"complete"}),rp=({components:e})=>{var n;const t=Z(r=>{var s;return(s=r.message.status)!=null?s:np});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(tp,{status:t,component:(n=e==null?void 0:e.Text)!=null?n:dt.Text})},wo=y.memo(rp,(e,t)=>{var n,r,s,i;return((n=e.components)==null?void 0:n.Empty)===((r=t.components)==null?void 0:r.Empty)&&((s=e.components)==null?void 0:s.Text)===((i=t.components)==null?void 0:i.Text)}),sp=({components:e,enabled:t})=>Z(r=>{if(!t||r.message.parts.length===0)return!1;const s=r.message.parts[r.message.parts.length-1];return(s==null?void 0:s.type)!=="text"&&(s==null?void 0:s.type)!=="reasoning"})?p.jsx(wo,{components:e}):null,ip=y.memo(sp,(e,t)=>{var n,r,s,i;return e.enabled===t.enabled&&((n=e.components)==null?void 0:n.Empty)===((r=t.components)==null?void 0:r.Empty)&&((s=e.components)==null?void 0:s.Text)===((i=t.components)==null?void 0:i.Text)}),ls=({components:e,unstable_showEmptyOnNonTextEnd:t=!0})=>{const n=Z(a=>a.message.parts.length),r=!!(e!=null&&e.ChainOfThought),s=Xf(r),i=y.useMemo(()=>n===0?p.jsx(wo,{components:e}):s.map(a=>{var o,l;if(a.type==="single")return p.jsx(sr,{index:a.index,components:e},a.index);if(a.type==="chainOfThoughtGroup"){const u=e==null?void 0:e.ChainOfThought;return u?p.jsx(Wf,{startIndex:a.startIndex,endIndex:a.endIndex,children:p.jsx(u,{})},`chainOfThought-${a.startIndex}`):null}else if(a.type==="toolGroup"){const u=(o=e==null?void 0:e.ToolGroup)!=null?o:dt.ToolGroup;return p.jsx(u,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(d,c)=>p.jsx(sr,{index:a.startIndex+c,components:e},c))},`tool-${a.startIndex}`)}else{const u=(l=e==null?void 0:e.ReasoningGroup)!=null?l:dt.ReasoningGroup;return p.jsx(u,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(d,c)=>p.jsx(sr,{index:a.startIndex+c,components:e},c))},`reasoning-${a.startIndex}`)}}),[s,e,n]);return p.jsxs(p.Fragment,{children:[i,p.jsx(ip,{components:e,enabled:t})]})};ls.displayName="MessagePrimitive.Parts";const ap=(e,t)=>{var r,s,i;const n=t.type;switch(n){case"image":return(r=e==null?void 0:e.Image)!=null?r:e==null?void 0:e.Attachment;case"document":return(s=e==null?void 0:e.Document)!=null?s:e==null?void 0:e.Attachment;case"file":return(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const a=n;throw new Error(`Unknown attachment type: ${a}`)}},op=({components:e})=>{const t=Z(r=>r.attachment);if(!t)return null;const n=ap(e,t);return n?p.jsx(n,{}):null},So=y.memo(({index:e,components:t})=>p.jsx(xf,{index:e,children:p.jsx(op,{components:t})}),(e,t)=>{var n,r,s,i,a,o,l,u;return e.index===t.index&&((n=e.components)==null?void 0:n.Image)===((r=t.components)==null?void 0:r.Image)&&((s=e.components)==null?void 0:s.Document)===((i=t.components)==null?void 0:i.Document)&&((a=e.components)==null?void 0:a.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});So.displayName="MessagePrimitive.AttachmentByIndex";const ko=({components:e})=>{const t=Z(r=>r.message.role!=="user"?0:r.message.attachments.length);return y.useMemo(()=>Array.from({length:t},(r,s)=>p.jsx(So,{index:s,components:e},s)),[t,e])};ko.displayName="MessagePrimitive.Attachments";const _o=()=>{const e=he(),t=Z(r=>r.thread.isRunning||!r.composer.isEditing||r.composer.isEmpty),n=y.useCallback(()=>{e.composer().send()},[e]);return t?null:n},lp=rr("ComposerPrimitive.Send",_o),Co=y.forwardRef((r,n)=>{var s=r,{onSubmit:e}=s,t=q(s,["onSubmit"]);const i=_o(),a=o=>{o.preventDefault(),i&&i()};return p.jsx(ct.form,E(m({},t),{ref:n,onSubmit:Ft(e,a)}))});Co.displayName="ComposerPrimitive.Root";function us(){return us=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},us.apply(null,arguments)}function up(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var cp=y.useLayoutEffect,dp=function(t){var n=y.useRef(t);return cp(function(){n.current=t}),n},To=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},hp=function(t,n){var r=y.useRef();return y.useCallback(function(s){t.current=s,r.current&&To(r.current,null),r.current=n,n&&To(n,s)},[n])},Io={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},fp=function(t){Object.keys(Io).forEach(function(n){t.style.setProperty(n,Io[n],"important")})},vo=fp,De=null,Eo=function(t,n){var r=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?r+n.borderSize:r-n.paddingSize};function pp(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),De||(De=document.createElement("textarea"),De.setAttribute("tabindex","-1"),De.setAttribute("aria-hidden","true"),vo(De)),De.parentNode===null&&document.body.appendChild(De);var s=e.paddingSize,i=e.borderSize,a=e.sizingStyle,o=a.boxSizing;Object.keys(a).forEach(function(f){var h=f;De.style[h]=a[h]}),vo(De),De.value=t;var l=Eo(De,e);De.value=t,l=Eo(De,e),De.value="x";var u=De.scrollHeight-s,d=u*n;o==="border-box"&&(d=d+s+i),l=Math.max(d,l);var c=u*r;return o==="border-box"&&(c=c+s+i),l=Math.min(c,l),[l,u]}var Ao=function(){},mp=function(t,n){return t.reduce(function(r,s){return r[s]=n[s],r},{})},gp=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],yp=!!document.documentElement.currentStyle,bp=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var r=mp(gp,n),s=r.boxSizing;if(s==="")return null;yp&&s==="border-box"&&(r.width=parseFloat(r.width)+parseFloat(r.borderRightWidth)+parseFloat(r.borderLeftWidth)+parseFloat(r.paddingRight)+parseFloat(r.paddingLeft)+"px");var i=parseFloat(r.paddingBottom)+parseFloat(r.paddingTop),a=parseFloat(r.borderBottomWidth)+parseFloat(r.borderTopWidth);return{sizingStyle:r,paddingSize:i,borderSize:a}},xp=bp;function cs(e,t,n){var r=dp(n);te.useLayoutEffect(function(){var s=function(a){return r.current(a)};if(e)return e.addEventListener(t,s),function(){return e.removeEventListener(t,s)}},[])}var wp=function(t,n){cs(document.body,"reset",function(r){t.current.form===r.target&&n(r)})},Sp=function(t){cs(window,"resize",t)},kp=function(t){cs(document.fonts,"loadingdone",t)},_p=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Cp=function(t,n){var r=t.cacheMeasurements,s=t.maxRows,i=t.minRows,a=t.onChange,o=a===void 0?Ao:a,l=t.onHeightChange,u=l===void 0?Ao:l,d=up(t,_p),c=d.value!==void 0,f=te.useRef(null),h=hp(f,n),b=te.useRef(0),S=te.useRef(),x=function(){var C=f.current,O=r&&S.current?S.current:xp(C);if(O){S.current=O;var F=pp(O,C.value||C.placeholder||"x",i,s),T=F[0],R=F[1];b.current!==T&&(b.current=T,C.style.setProperty("height",T+"px","important"),u(T,{rowHeight:R}))}},g=function(C){c||x(),o(C)};return te.useLayoutEffect(x),wp(f,function(){if(!c){var v=f.current.value;requestAnimationFrame(function(){var C=f.current;C&&v!==C.value&&x()})}}),Sp(x),kp(x),te.createElement("textarea",us({},d,{onChange:g,ref:h}))},Tp=te.forwardRef(Cp);const Po=e=>{const t=Ct(e),n=Zn(r=>r.onScrollToBottom);y.useEffect(()=>n(t),[n,t])},Mo=y.forwardRef((S,b)=>{var x=S,{autoFocus:e=!1,asChild:t,disabled:n,onChange:r,onKeyDown:s,onPaste:i,submitOnEnter:a,submitMode:o,cancelOnEscape:l=!0,unstable_focusOnRunStart:u=!0,unstable_focusOnScrollToBottom:d=!0,unstable_focusOnThreadSwitched:c=!0,addAttachmentOnPaste:f=!0}=x,h=q(x,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","submitMode","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const g=he(),v=o!=null?o:a===!1?"none":"enter",C=Z(M=>M.composer.isEditing?M.composer.text:""),O=t?is:Tp,F=Z(M=>{var U;return M.thread.isDisabled||((U=M.composer.dictation)==null?void 0:U.inputDisabled)})||n,T=y.useRef(null),R=Xn(b,T);jf(M=>{var D;if(!l||!((D=T.current)!=null&&D.contains(M.target)))return;const U=g.composer();U.getState().canCancel&&(U.cancel(),M.preventDefault())});const H=M=>{var U,D;if(!F&&!M.nativeEvent.isComposing&&M.key==="Enter"&&!M.shiftKey){if(g.thread().getState().isRunning)return;let K=!1;v==="ctrlEnter"?K=M.ctrlKey||M.metaKey:v==="enter"&&(K=!0),K&&(M.preventDefault(),(D=(U=T.current)==null?void 0:U.closest("form"))==null||D.requestSubmit())}},J=M=>P(null,null,function*(){var N;if(!f)return;const U=g.thread().getState().capabilities,D=Array.from(((N=M.clipboardData)==null?void 0:N.files)||[]);if(U.attachments&&D.length>0)try{M.preventDefault(),yield Promise.all(D.map(K=>g.composer().addAttachment(K)))}catch(K){console.error("Error adding attachment:",K)}}),I=e&&!F,B=y.useCallback(()=>{const M=T.current;!M||!I||(M.focus({preventScroll:!0}),M.setSelectionRange(M.value.length,M.value.length))},[I]);return y.useEffect(()=>B(),[B]),Po(()=>{g.composer().getState().type==="thread"&&d&&B()}),y.useEffect(()=>{if(!(g.composer().getState().type!=="thread"||!u))return g.on("thread.runStart",B)},[u,B,g]),y.useEffect(()=>{if(!(g.composer().getState().type!=="thread"||!c))return g.on("threadListItem.switchedTo",B)},[c,B,g]),p.jsx(O,E(m({name:"input",value:C},h),{ref:R,disabled:F,onChange:Ft(r,M=>{g.composer().getState().isEditing&&Pi(()=>{g.composer().setText(M.target.value)})}),onKeyDown:Ft(s,H),onPaste:Ft(i,J)}))});Mo.displayName="ComposerPrimitive.Input";const Ip=rr("ComposerPrimitive.AddAttachment",({multiple:e=!0}={})=>{const t=Z(s=>!s.composer.isEditing),n=he(),r=y.useCallback(()=>{const s=document.createElement("input");s.type="file",s.multiple=e,s.hidden=!0;const i=n.composer().getState().attachmentAccept;i!=="*"&&(s.accept=i),document.body.appendChild(s),s.onchange=a=>{const o=a.target.files;if(o){for(const l of o)n.composer().addAttachment(l);document.body.removeChild(s)}},s.oncancel=()=>{(!s.files||s.files.length===0)&&document.body.removeChild(s)},s.click()},[n,e]);return t?null:r},["multiple"]),vp=(e,t)=>{var r,s,i;const n=t.type;switch(n){case"image":return(r=e==null?void 0:e.Image)!=null?r:e==null?void 0:e.Attachment;case"document":return(s=e==null?void 0:e.Document)!=null?s:e==null?void 0:e.Attachment;case"file":return(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const a=n;throw new Error(`Unknown attachment type: ${a}`)}},Ep=({components:e})=>{const t=Z(r=>r.attachment);if(!t)return null;const n=vp(e,t);return n?p.jsx(n,{}):null},No=y.memo(({index:e,components:t})=>p.jsx(wf,{index:e,children:p.jsx(Ep,{components:t})}),(e,t)=>{var n,r,s,i,a,o,l,u;return e.index===t.index&&((n=e.components)==null?void 0:n.Image)===((r=t.components)==null?void 0:r.Image)&&((s=e.components)==null?void 0:s.Document)===((i=t.components)==null?void 0:i.Document)&&((a=e.components)==null?void 0:a.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});No.displayName="ComposerPrimitive.AttachmentByIndex";const Do=({components:e})=>{const t=Z(r=>r.composer.attachments.length);return y.useMemo(()=>Array.from({length:t},(r,s)=>p.jsx(No,{index:s,components:e},s)),[t,e])};Do.displayName="ComposerPrimitive.Attachments";const Lo=y.forwardRef((i,s)=>{var a=i,{disabled:e,asChild:t=!1,children:n}=a,r=q(a,["disabled","asChild","children"]);const[o,l]=y.useState(!1),u=he(),d=y.useCallback(x=>{e||(x.preventDefault(),l(!0))},[e]),c=y.useCallback(x=>{e||(x.preventDefault(),o||l(!0))},[e,o]),f=y.useCallback(x=>{if(e)return;x.preventDefault();const g=x.relatedTarget;g&&x.currentTarget.contains(g)||l(!1)},[e]),h=y.useCallback(x=>P(null,null,function*(){if(!e){x.preventDefault(),l(!1);for(const g of x.dataTransfer.files)try{yield u.composer().addAttachment(g)}catch(v){console.error("Failed to add attachment:",v)}}}),[e,u]),b={onDragEnterCapture:d,onDragOverCapture:c,onDragLeaveCapture:f,onDropCapture:h},S=t?is:"div";return p.jsx(S,E(m(m(E(m({},o?{"data-dragging":"true"}:null),{ref:s}),b),r),{children:n}))});Lo.displayName="ComposerPrimitive.AttachmentDropzone";const Oo=y.forwardRef((e,t)=>p.jsx(ct.div,E(m({},e),{ref:t})));Oo.displayName="ThreadPrimitive.Root";const Fo=({children:e})=>Z(n=>n.thread.messages.length===0&&!n.thread.isLoading)?e:null;Fo.displayName="ThreadPrimitive.Empty";const Ap=e=>{const t=Ct(e),n=y.useCallback(r=>{const s=new ResizeObserver(()=>{t()}),i=new MutationObserver(a=>{a.some(l=>l.type!=="attributes"||l.attributeName!=="style")&&t()});return s.observe(r),i.observe(r,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{s.disconnect(),i.disconnect()}},[t]);return on(n)},Pp=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{const s=y.useRef(null),i=ss();e===void 0&&(e=i.getState().turnAnchor!=="top");const a=y.useRef(0),o=y.useRef(null),l=y.useCallback(h=>{const b=s.current;b&&(o.current=h,b.scrollTo({top:b.scrollHeight,behavior:h}))},[]),u=()=>{const h=s.current;if(!h)return;const b=i.getState().isAtBottom,S=Math.abs(h.scrollHeight-h.scrollTop-h.clientHeight)<1||h.scrollHeight<=h.clientHeight;!S&&a.current<h.scrollTop||(S&&(o.current=null),(S||o.current===null)&&S!==b&&an(i).setState({isAtBottom:S})),a.current=h.scrollTop},d=Ap(()=>{const h=o.current;h?l(h):e&&i.getState().isAtBottom&&l("instant"),u()}),c=on(h=>(h.addEventListener("scroll",u),()=>{h.removeEventListener("scroll",u)}));return Po(({behavior:h})=>{l(h)}),Br("thread.runStart",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),Br("thread.initialize",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Br("threadListItem.switchedTo",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Xn(d,c,s)},Mp=()=>{const e=Zn(n=>n.registerViewport),t=y.useCallback(n=>n.clientHeight,[]);return lo(e,t)},Bo=y.forwardRef((o,a)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r,children:s}=l,i=q(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=Pp({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r}),d=Mp(),c=Xn(a,u,d);return p.jsx(ct.div,E(m({},i),{ref:c,children:s}))});Bo.displayName="ThreadPrimitive.ViewportScrollable";const zo=y.forwardRef((r,n)=>{var s=r,{turnAnchor:e}=s,t=q(s,["turnAnchor"]);return p.jsx(Ya,{options:{turnAnchor:e},children:p.jsx(Bo,E(m({},t),{ref:n}))})});zo.displayName="ThreadPrimitive.Viewport";const Ro=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,Np=()=>null,Dp=(e,t,n)=>{var r,s,i,a,o,l,u,d,c,f,h,b;switch(t){case"user":return n?(i=(s=(r=e.UserEditComposer)!=null?r:e.EditComposer)!=null?s:e.UserMessage)!=null?i:e.Message:(a=e.UserMessage)!=null?a:e.Message;case"assistant":return n?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(d=e.AssistantMessage)!=null?d:e.Message;case"system":return n?(h=(f=(c=e.SystemEditComposer)!=null?c:e.EditComposer)!=null?f:e.SystemMessage)!=null?h:e.Message:(b=e.SystemMessage)!=null?b:Np;default:const S=t;throw new Error(`Unknown message role: ${S}`)}},Lp=({components:e})=>{const t=Z(s=>s.message.role),n=Z(s=>s.message.composer.isEditing),r=Dp(e,t,n);return p.jsx(r,{})},jo=y.memo(({index:e,components:t})=>p.jsx(yf,{index:e,children:p.jsx(Lp,{components:t})}),(e,t)=>e.index===t.index&&Ro(e.components,t.components));jo.displayName="ThreadPrimitive.MessageByIndex";const $o=({components:e})=>{const t=Z(r=>r.thread.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(r,s)=>p.jsx(jo,{index:s,components:e},s)),[t,e])};$o.displayName="ThreadPrimitive.Messages";const Op=y.memo($o,(e,t)=>Ro(e.components,t.components)),ds=y.forwardRef((s,r)=>{var i=s,{onClick:e,disabled:t}=i,n=q(i,["onClick","disabled"]);const a=Z(l=>l.threads.newThreadId===l.threads.mainThreadId),o=he();return p.jsx(ct.button,E(m(m({type:"button"},a?{"data-active":"true","aria-current":"true"}:null),n),{ref:r,disabled:t,onClick:Ft(e,()=>{o.threads().switchToNewThread()})}))});ds.displayName="ThreadListPrimitive.New";const Uo=y.memo(({index:e,archived:t=!1,components:n})=>{const r=n.ThreadListItem;return p.jsx(mf,{index:e,archived:t,children:p.jsx(r,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);Uo.displayName="ThreadListPrimitive.ItemByIndex";const Ho=({archived:e=!1,components:t})=>{const n=Z(s=>e?s.threads.archivedThreadIds.length:s.threads.threadIds.length);return y.useMemo(()=>Array.from({length:n},(s,i)=>p.jsx(Uo,{index:i,archived:e,components:t},i)),[n,e,t])};Ho.displayName="ThreadListPrimitive.Items";const hs=y.forwardRef((e,t)=>p.jsx(ct.div,E(m({},e),{ref:t})));hs.displayName="ThreadListPrimitive.Root";const fs=y.forwardRef((e,t)=>{const n=Z(r=>r.threads.mainThreadId===r.threadListItem.id);return p.jsx(ct.div,E(m(m({},n?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});fs.displayName="ThreadListItemPrimitive.Root";const qo=rr("ThreadListItemPrimitive.Trigger",()=>{const e=he();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])});function Fp(){if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto!="undefined"&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}class Vo{constructor(t,n,r=!1){_(this,"baseUrl");_(this,"sessionToken",null);_(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=r,n&&(this.sessionToken=n)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const n=`${this.baseUrl}${t.replace("/v1","")}`;return n.startsWith("/")||n.startsWith("./"),n}return`${this.baseUrl}${t}`}createOrContinueChat(t,n){return P(this,null,function*(){const r=this.getUrl("/v1/chats"),i={"Content-Type":"application/json",Accept:"text/event-stream","Accept-Encoding":"identity","Cache-Control":"no-cache","X-Accel-Buffering":"no","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const a=E(m({},t),{stream:!0}),o=yield fetch(r,{method:"POST",headers:i,body:JSON.stringify(a),signal:n,cache:"no-store"});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}if(!o.body)throw new Error("Response body is null");return o.body})}getChat(t){return P(this,null,function*(){const n=this.getUrl(`/v1/chats/${t}`),r={"Content-Type":"application/json"};this.sessionToken&&(r.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(n,{method:"GET",headers:r});if(!s.ok){const i=yield s.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}listChats(t){return P(this,null,function*(){const n=this.getUrl("/v1/chats"),r=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n);t!=null&&t.limit&&r.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&r.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(a=>{r.searchParams.append("expand[]",a)});const s={"Content-Type":"application/json"};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(r.toString(),{method:"GET",headers:s});if(!i.ok){const a=yield i.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}generateIdempotencyKey(){return Fp()}updateChat(t,n){return P(this,null,function*(){const r=`/v1/chats/${t}`,s=this.getUrl(r),i=s.startsWith("/")||s.startsWith("./")?new URL(s,window.location.origin):new URL(s),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(i.toString(),{method:"PATCH",headers:o,body:JSON.stringify(n)});if(!l.ok){const d=yield l.text();let c={};try{c=JSON.parse(d)}catch(f){c={detail:d}}throw new Error(c.detail||c.message||`API error: ${l.status} ${l.statusText}`)}if(l.status===204)return{};const u=yield l.text();if(!u)return{};try{return JSON.parse(u)}catch(d){return{}}})}deleteChat(t){return P(this,null,function*(){const n=`/v1/chats/${t}`,r=this.getUrl(n),s=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r),a={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(s.toString(),{method:"DELETE",headers:a});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}})}generateChatTitle(t,n){return P(this,null,function*(){const r=`/v1/chats/${t}/title`,s=this.getUrl(r),i=s.startsWith("/")||s.startsWith("./")?new URL(s,window.location.origin):new URL(s),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(i.toString(),{method:"POST",headers:o,body:n?JSON.stringify(n):void 0});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}listModels(t){return P(this,null,function*(){const n=this.getUrl("/v1/models"),r=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n);t!=null&&t.limit&&r.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&r.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(a=>{r.searchParams.append("expand[]",a)});const s={"Content-Type":"application/json"};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(r.toString(),{method:"GET",headers:s});if(!i.ok){const a=yield i.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}getModel(t){return P(this,null,function*(){const n=this.getUrl(`/v1/models/${t}`),r={"Content-Type":"application/json"};this.sessionToken&&(r.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(n,{method:"GET",headers:r});if(!s.ok){const i=yield s.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}uploadFile(t,n,r){return P(this,null,function*(){const s=this.getUrl("/v1/files"),i=this.generateIdempotencyKey(),a=new FormData;a.append("file",t),n&&a.append("resource_type",n),r&&a.append("resource_id",r);const o={"Idempotency-Key":i};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(s,{method:"POST",headers:o,body:a});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}}function Bp(e,t){return Nn(this,null,function*(){const n=e.getReader(),r=new TextDecoder;let s="";try{for(;;){if(t!=null&&t.aborted){n.cancel();break}const{done:i,value:a}=yield new Ae(n.read());if(i)break;s+=r.decode(a,{stream:!0});const o=s.split(`
|
|
6
6
|
|
|
7
|
-
`);s=o.pop()||"";for(const l of o)if(l.startsWith("data: ")){const u=l.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch(d){}}}}finally{n.releaseLock()}})}function zp(e){return e.map(t=>{let n="";if(typeof t.content=="string")n=t.content;else if(Array.isArray(t.content)){const r=t.content.find(s=>s.type==="text");r&&typeof r=="object"&&"text"in r&&(n=r.text)}return{role:t.role,content:n}})}function Wo(e){return m(m({id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}}},e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}}),e.role==="user"&&{attachments:[]})}const Bt=new Map,ln=new Map;let Ko;function ps(e,t){const n=Bt.get(e);if(n)return n;if(t)for(const r of t){const s=ln.get(r.id);if(s)return Bt.set(e,s),s}return e}function Rp(e,t){return{list(){return P(this,null,function*(){const r=[];let i,a=0;do{const l=yield e.listChats({limit:50,cursor:i}),u=l.items||[];Array.isArray(u)&&u.length>0&&r.push(...u),i=l.nextCursor||void 0,a++}while(i&&a<50);return{threads:r.map(l=>{const u=l.id;return!u||l.deletedAt?null:{status:"regular",remoteId:u,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}})},initialize(r){return P(this,null,function*(){return{remoteId:Bt.get(r)||r,externalId:void 0}})},rename(r,s){return P(this,null,function*(){const i=ps(r);yield e.updateChat(i,{title:s})})},archive(r){return P(this,null,function*(){})},unarchive(r){return P(this,null,function*(){})},delete(r){return P(this,null,function*(){const s=ps(r);yield e.deleteChat(s)})},generateTitle(r,s){return P(this,null,function*(){var o;const i=ps(r,s);let a;try{a=(yield e.generateChatTitle(i)).title}catch(l){console.error("[generateTitle] API call failed, falling back to first message",l);const u=s.find(c=>c.role==="user"),d=(o=u==null?void 0:u.content)==null?void 0:o.filter(c=>c.type==="text").map(c=>c.text).join(" ").trim();a=d?d.length>60?d.slice(0,57)+"...":d:void 0}return da(l=>{const u=l.addTextPart();a&&u.append(a),u.close(),l.close()})})},fetch(r){return P(this,null,function*(){try{const s=yield e.getChat(r);return{status:"regular",remoteId:s.id||r,title:s.title||"Chat",createdAt:s.createdAt?new Date(s.createdAt):new Date,updatedAt:s.updatedAt?new Date(s.updatedAt):new Date}}catch(s){return{status:"regular",remoteId:r,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(r,s){Bt.set(r,s),t==null||t(r,s)},unstable_Provider:({children:r})=>{const s=io(),i=s==null?void 0:s.remoteId,a=s==null?void 0:s.isMain;y.useEffect(()=>{a&&(Ko=i)},[i,a]);const o=y.useMemo(()=>({load(){return P(this,null,function*(){if(!i)return{messages:[]};try{const d=yield e.getChat(i);if(!d.messages||d.messages.length===0)return{messages:[]};const c=d.messages.map(h=>Wo(h)),f=c.map((h,b)=>({message:h,parentId:b>0?c[b-1].id:null}));for(const h of c)ln.set(h.id,i);return{messages:f}}catch(d){return{messages:[]}}})},append(d){return P(this,null,function*(){})}}),[i,e]),l=y.useMemo(()=>({history:o}),[o]);return p.jsx(Jr,{adapters:l,children:r})}}}class jp{constructor(){_(this,"messageMetadata",new Map);_(this,"currentMessageId",null);_(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const n=this.messageMetadata.get(this.currentMessageId)||{},r=t.sources;r&&r.length>0&&(this.messageMetadata.set(this.currentMessageId,E(m({},n),{sources:r})),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(t){return this.messageMetadata.get(t)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.listeners.forEach(t=>t())}}const xt=new jp,ms=[];let ir=[];function Jo(e,t,n=50,r=800){ms.push({question:e,response:t,streamingSpeed:n,initialDelay:r})}function Go(e,t){const{modelId:n,getModelId:r,systemPrompt:s,ephemeral:i,enableReasoning:a,onChatCreated:o,onUserMessage:l,onThreadIdUpdate:u,onBeforeRequest:d,mockResponseOnBlocked:c}=t,f=()=>{var b;return(b=r?r():n)!=null?b:null};return{run(b){return Nn(this,null,function*(){var G,ce,k;const{messages:S,abortSignal:x}=b,g=b.unstable_threadId,v=ms.shift();if(v){l==null||l();const j=(G=v.initialDelay)!=null?G:800;if(j>0&&(yield new Ae(new Promise(se=>setTimeout(se,j)))),x!=null&&x.aborted)throw new Error("Request aborted");const le=v.response.split(" ");let ue="";const Se=v.streamingSpeed||50,He=`premade-${Date.now()}`;i&&(o==null||o(He));for(let se=0;se<le.length;se++){if(x!=null&&x.aborted)throw new Error("Request aborted");ue+=(se===0?"":" ")+le[se],yield{content:[{type:"text",text:ue}]},yield new Ae(new Promise(ve=>setTimeout(ve,Se+Math.random()*(Se*.5))))}yield{content:[{type:"text",text:ue}]},ir.push({role:"user",content:v.question},{role:"assistant",content:v.response});return}let C;for(const j of S){const le=ln.get(j.id);if(le){C=le;break}}l==null||l();let O=S,F=-1;for(let j=S.length-1;j>=0;j--)if(S[j].role==="assistant"){F=j;break}(C||F>=0)&&F>=0&&(O=S.slice(F+1));const T=zp(O);if(ir.length>0&&!C){const j=ir.map(le=>({role:le.role,content:le.content}));T.unshift(...j),ir=[]}const R=[];let H;for(let j=O.length-1;j>=0;j--)if(O[j].role==="user"){H=O[j];break}if(H&&"attachments"in H){const j=H.attachments;if(j&&j.length>0){for(const le of j)if(le.file)try{const ue=yield new Ae(e.uploadFile(le.file));R.push(ue.id)}catch(ue){}}}const J={messages:T,chatId:C||null,systemPrompt:s,ephemeral:i,enableReasoning:a,stream:!0},I=f();if(I&&I.trim()!==""&&(J.modelId=I),R.length>0&&(J.fileIds=R),d&&!(yield new Ae(d()))){if(c){const le=typeof c=="function"?c():c,ue=S.filter(ve=>ve.role==="user"),Se=ue.length>0?ue[ue.length-1]:void 0;let He="Message";if(Se){if(typeof Se.content=="string")He=Se.content;else if(Array.isArray(Se.content)){const ve=Se.content.find(ft=>ft.type==="text");He=(ve==null?void 0:ve.text)||"Message"}}Jo(He,le,40,400);const se=ms.shift();if(se){l==null||l();const ve=(ce=se.initialDelay)!=null?ce:400;if(ve>0&&(yield new Ae(new Promise(ot=>setTimeout(ot,ve)))),x!=null&&x.aborted)throw new Error("Request aborted");const ft=se.response.split(" ");let at="";const pt=se.streamingSpeed||40,In=`mock-${Date.now()}`;i&&(o==null||o(In));for(let ot=0;ot<ft.length;ot++){if(x!=null&&x.aborted)throw new Error("Request aborted");at+=(ot===0?"":" ")+ft[ot],yield{content:[{type:"text",text:at}]},yield new Ae(new Promise(X=>setTimeout(X,pt+Math.random()*(pt*.3))))}yield{content:[{type:"text",text:at}]};return}}throw new Error("Request blocked")}const B=yield new Ae(e.createOrContinueChat(J,x));let M="",U="",D;const N=[];let K=0,re=!1;const V=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;xt.clear(),xt.setCurrentMessage(V);const Q=()=>{N.length!==K&&(K=N.length,xt.update({sources:N.length>0?[...N]:void 0}))},w=()=>{Q();const j=[];return U&&j.push({type:"reasoning",text:U}),M&&j.push({type:"text",text:M}),j.length===0&&j.push({type:"text",text:""}),{content:j}};try{for(var ye=Pt(Bp(B,x)),Ie,pe,it;Ie=!(pe=yield new Ae(ye.next())).done;Ie=!1){const j=pe.value;if(x!=null&&x.aborted)throw new Error("Request aborted");const le=j.id||j.chatId||j.messageId;if(le&&!D){D=le;const se=g||Ko;o==null||o(le);for(const ve of S)ln.set(ve.id,le);se&&!Bt.has(se)&&Bt.set(se,le),u&&se&&u(se,le)}const ue=j.sources;if(ue&&Array.isArray(ue)&&ue.length>0)for(const se of ue)N.some(ve=>ve.sourceId===se.sourceId)||N.push({sourceId:se.sourceId,filename:se.filename||"Unknown",score:(k=se.score)!=null?k:1,chunkId:se.chunkId,datasetId:se.datasetId});const Se=j.reasoning;if(Se&&Se.length>0&&(U+=Se,yield w()),j.type)switch(j.type){case"source-document":j.sourceId&&N.push({sourceId:j.sourceId,filename:j.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":j.delta&&(U+=j.delta),(M||U)&&(yield w());continue;case"reasoning-end":(M||U)&&(yield w());continue;case"text-delta":j.delta&&(U&&!re&&!M&&(re=!0,yield new Ae(new Promise(se=>setTimeout(se,400)))),M+=j.delta),M&&(yield w());continue;case"error":throw new Error(j.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const He=j.delta;if(He!=null&&(U&&!re&&!M&&(re=!0,yield new Ae(new Promise(se=>setTimeout(se,400)))),M+=He),j.content&&(M+=j.content),j.message&&(M+=j.message.content||""),j.finished){(M||U||N.length>0)&&(yield w());break}(M||U||N.length>0)&&(yield w())}}catch(pe){it=[pe]}finally{try{Ie&&(pe=ye.return)&&(yield new Ae(pe.call(ye)))}finally{if(it)throw it[0]}}(M||U||N.length>0)&&(yield w())})}}}class un extends Error{constructor(t,n,r){super(t),this.code=n,this.file=r,this.name="AttachmentValidationError"}}const $p=["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/markdown","text/csv","application/json"],Up=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],Hp=10*1024*1024;function Yo(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}function qp(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function Vp(e,t){const r={"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/gif":[".gif"],"image/webp":[".webp"],"image/svg+xml":[".svg"],"application/pdf":[".pdf"],"text/plain":[".txt"],"text/markdown":[".md"],"text/csv":[".csv"],"application/json":[".json"]}[e];return r?r.includes(t.toLowerCase()):!0}function Wp(){return typeof crypto!="undefined"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Qo(e={}){const{validation:t={},supportsVision:n=!0,onValidationError:r,onAttachmentAdded:s,onAttachmentRemoved:i}=e,{maxFileSizeBytes:a=Hp,allowedMimeTypes:o=$p,allowedExtensions:l=Up,validateContentType:u=!0}=t,d=l.join(",");function c(h){if(h.size>a){const S=new un('File "'+h.name+'" is too large ('+Yo(h.size)+"). Maximum size is "+Yo(a)+".","FILE_TOO_LARGE",h);throw r==null||r(S),S}if(!n&&h.type.startsWith("image/")){const S=new un("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",h);throw r==null||r(S),S}const b=qp(h.name);if(b&&!l.some(S=>S.toLowerCase()===b)){const S=new un('File type "'+b+'" is not allowed. Allowed types: '+l.join(", "),"INVALID_TYPE",h);throw r==null||r(S),S}if(h.type&&!o.some(S=>{if(S.endsWith("/*")){const x=S.slice(0,-1);return h.type.startsWith(x)}return h.type===S})){const S=new un('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw r==null||r(S),S}if(u&&h.type&&b&&!Vp(h.type,b)){const S=new un('File extension "'+b+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw r==null||r(S),S}}return{accept:d,add(b){return P(this,arguments,function*({file:h}){c(h);let S="file";h.type.startsWith("image/")?S="image":(h.type.includes("pdf")||h.type.includes("document")||h.type.includes("text")||h.name.endsWith(".pdf")||h.name.endsWith(".docx")||h.name.endsWith(".txt")||h.name.endsWith(".md")||h.name.endsWith(".csv")||h.name.endsWith(".json"))&&(S="document");const x={id:Wp(),type:S,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return s==null||s(x),x})},remove(h){return P(this,null,function*(){i==null||i(h.id)})},send(h){return P(this,null,function*(){if(h.type==="image"&&h.file){const b=yield new Promise((S,x)=>{const g=new FileReader;g.onload=()=>S(g.result),g.onerror=()=>x(new Error("Failed to read file")),g.readAsDataURL(h.file)});return E(m({},h),{status:{type:"complete"},content:[{type:"image",image:b}]})}return E(m({},h),{status:{type:"complete"},content:[]})})}}}class Kp{constructor(){_(this,"current",null);_(this,"listeners",new Set);_(this,"getSnapshot",()=>this.current);_(this,"subscribe",t=>(this.listeners.add(t),()=>this.listeners.delete(t)))}push(t,n){this.current={message:t,code:n,timestamp:Date.now()},this.notify()}clear(){this.current&&(this.current=null,this.notify())}notify(){this.listeners.forEach(t=>t())}}const zt=new Kp;function Jp({children:e,baseUrl:t,sessionToken:n,isProxyMode:r=!1,mode:s="multiChat",modelId:i,onModelChange:a,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:d,onError:c,onChatCreated:f,onUserMessage:h,onThreadIdUpdate:b,onChatsLoaded:S,enableAttachments:x=!1,supportsVision:g=!0,onBeforeRequest:v,mockResponseOnBlocked:C}){const O=y.useMemo(()=>new Vo(t,n||void 0,r),[t,n,r]),[F,T]=y.useState(i||null);y.useEffect(()=>{i&&T(i)},[i]);const R=y.useCallback(I=>{f==null||f(I)},[f]),H=y.useCallback((I,B)=>{b==null||b(I,B)},[b]),J=y.useMemo(()=>Go(O,{modelId:F||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:R,onUserMessage:h,onBeforeRequest:v,mockResponseOnBlocked:C}),[O,F,l,o,u,R,h,v,C]);return s==="singleChat"?p.jsx(Gp,{client:O,initialThreadId:d,modelAdapter:J,enableAttachments:x,supportsVision:g,onChatCreated:R,children:e}):p.jsx(Qp,{client:O,modelAdapterOptions:{modelId:F||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:R,onUserMessage:h,onBeforeRequest:v,mockResponseOnBlocked:C},initialThreadId:d,onChatsLoaded:S,onThreadIdUpdate:H,onError:c,enableAttachments:x,supportsVision:g,children:e})}function Gp({client:e,initialThreadId:t,modelAdapter:n,enableAttachments:r,supportsVision:s=!0,onChatCreated:i,children:a}){const[o,l]=y.useState(void 0),[u,d]=y.useState(!!t);return y.useEffect(()=>{if(!t){d(!1);return}let c=!1;function f(){return P(this,null,function*(){try{const h=yield e.getChat(t);if(c)return;if(h.messages&&h.messages.length>0){const b=h.messages.map(S=>Wo(S));for(const S of h.messages)ln.set(S.id,h.id);l(b)}i==null||i(h.id)}catch(h){}finally{c||d(!1)}})}return f(),()=>{c=!0}},[e,t,i]),u?null:p.jsx(Yp,{modelAdapter:n,initialMessages:o,enableAttachments:r,supportsVision:s,children:a})}function Yp({modelAdapter:e,initialMessages:t,enableAttachments:n,supportsVision:r=!0,children:s}){const i=y.useMemo(()=>n?Qo({supportsVision:r,onValidationError:o=>{zt.push(o.message,o.code)}}):void 0,[n,r]),a=La(e,{initialMessages:t,adapters:m({},i&&{attachments:i})});return p.jsx(Qa,{runtime:a,children:s})}function Qp({client:e,modelAdapterOptions:t,initialThreadId:n,onChatsLoaded:r,onThreadIdUpdate:s,onError:i,enableAttachments:a,supportsVision:o,children:l}){const u=y.useMemo(()=>Rp(e,(C,O)=>{s==null||s(C,O)}),[e,s]),d=y.useCallback((C,O)=>{u.updateRemoteId&&u.updateRemoteId(C,O),s==null||s(C,O)},[u,s]),c=y.useRef(r);c.current=r;const f=y.useMemo(()=>E(m({},u),{list(){return P(this,null,function*(){var F;const O=yield u.list();return(F=c.current)==null||F.call(c),O})}}),[u]);y.useEffect(()=>{window.__cuadraThreadListAdapter=f,window.__cuadraThreadListRuntime=null},[f]);const h=y.useRef(t.modelId);h.current=t.modelId;const b=y.useMemo(()=>{const F=t,{modelId:C}=F;return q(F,["modelId"])},[t.systemPrompt,t.ephemeral,t.enableReasoning,t.onChatCreated,t.onUserMessage,t.onBeforeRequest,t.mockResponseOnBlocked]),S=y.useMemo(()=>Go(e,E(m({},b),{getModelId:()=>h.current,onThreadIdUpdate:d})),[e,b,d]),x=y.useMemo(()=>a?Qo({supportsVision:o,onValidationError:C=>{zt.push(C.message,C.code)}}):void 0,[a,o]),g=y.useCallback(()=>La(S,{adapters:m({},x&&{attachments:x})}),[S,x]),v=Za({adapter:f,runtimeHook:g});return y.useEffect(()=>{window.__cuadraThreadListRuntime=v},[v]),p.jsx(Qa,{runtime:v,children:l})}function Pk(){}function Mk(){}function Xp(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Zp=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,em=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,tm={};function Xo(e,t){return(tm.jsx?em:Zp).test(e)}const nm=/[ \t\n\f\r]/g;function rm(e){return typeof e=="object"?e.type==="text"?Zo(e.value):!1:Zo(e)}function Zo(e){return e.replace(nm,"")===""}class cn{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}cn.prototype.normal={},cn.prototype.property={},cn.prototype.space=void 0;function el(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new cn(n,r,t)}function gs(e){return e.toLowerCase()}class Be{constructor(t,n){this.attribute=n,this.property=t}}Be.prototype.attribute="",Be.prototype.booleanish=!1,Be.prototype.boolean=!1,Be.prototype.commaOrSpaceSeparated=!1,Be.prototype.commaSeparated=!1,Be.prototype.defined=!1,Be.prototype.mustUseProperty=!1,Be.prototype.number=!1,Be.prototype.overloadedBoolean=!1,Be.prototype.property="",Be.prototype.spaceSeparated=!1,Be.prototype.space=void 0;let sm=0;const ee=It(),we=It(),ys=It(),L=It(),ge=It(),Rt=It(),$e=It();function It(){return ic(2,++sm)}const bs=Object.freeze(Object.defineProperty({__proto__:null,boolean:ee,booleanish:we,commaOrSpaceSeparated:$e,commaSeparated:Rt,number:L,overloadedBoolean:ys,spaceSeparated:ge},Symbol.toStringTag,{value:"Module"})),xs=Object.keys(bs);class ws extends Be{constructor(t,n,r,s){let i=-1;if(super(t,n),tl(this,"space",s),typeof r=="number")for(;++i<xs.length;){const a=xs[i];tl(this,xs[i],(r&bs[a])===bs[a])}}}ws.prototype.defined=!0;function tl(e,t,n){n&&(e[t]=n)}function jt(e){const t={},n={};for(const[r,s]of Object.entries(e.properties)){const i=new ws(r,e.transform(e.attributes||{},r),s,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[gs(r)]=r,n[gs(i.attribute)]=r}return new cn(t,n,e.space)}const nl=jt({properties:{ariaActiveDescendant:null,ariaAtomic:we,ariaAutoComplete:null,ariaBusy:we,ariaChecked:we,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:ge,ariaCurrent:null,ariaDescribedBy:ge,ariaDetails:null,ariaDisabled:we,ariaDropEffect:ge,ariaErrorMessage:null,ariaExpanded:we,ariaFlowTo:ge,ariaGrabbed:we,ariaHasPopup:null,ariaHidden:we,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ge,ariaLevel:L,ariaLive:null,ariaModal:we,ariaMultiLine:we,ariaMultiSelectable:we,ariaOrientation:null,ariaOwns:ge,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:we,ariaReadOnly:we,ariaRelevant:null,ariaRequired:we,ariaRoleDescription:ge,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:we,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function rl(e,t){return t in e?e[t]:t}function sl(e,t){return rl(e,t.toLowerCase())}const im=jt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Rt,acceptCharset:ge,accessKey:ge,action:null,allow:null,allowFullScreen:ee,allowPaymentRequest:ee,allowUserMedia:ee,alt:null,as:null,async:ee,autoCapitalize:null,autoComplete:ge,autoFocus:ee,autoPlay:ee,blocking:ge,capture:null,charSet:null,checked:ee,cite:null,className:ge,cols:L,colSpan:null,content:null,contentEditable:we,controls:ee,controlsList:ge,coords:L|Rt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ee,defer:ee,dir:null,dirName:null,disabled:ee,download:ys,draggable:we,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ee,formTarget:null,headers:ge,height:L,hidden:ys,high:L,href:null,hrefLang:null,htmlFor:ge,httpEquiv:ge,id:null,imageSizes:null,imageSrcSet:null,inert:ee,inputMode:null,integrity:null,is:null,isMap:ee,itemId:null,itemProp:ge,itemRef:ge,itemScope:ee,itemType:ge,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ee,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:ee,muted:ee,name:null,nonce:null,noModule:ee,noValidate:ee,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:ee,optimum:L,pattern:null,ping:ge,placeholder:null,playsInline:ee,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ee,referrerPolicy:null,rel:ge,required:ee,reversed:ee,rows:L,rowSpan:L,sandbox:ge,scope:null,scoped:ee,seamless:ee,selected:ee,shadowRootClonable:ee,shadowRootDelegatesFocus:ee,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:we,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:ee,useMap:null,value:we,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ge,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ee,declare:ee,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:ee,noHref:ee,noShade:ee,noWrap:ee,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:we,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ee,disableRemotePlayback:ee,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:sl}),am=jt({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:$e,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:ge,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:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:ee,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,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:Rt,g2:Rt,glyphName:Rt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:$e,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,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:L,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:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ge,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:$e,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:$e,rev:$e,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:$e,requiredFeatures:$e,requiredFonts:$e,requiredFormats:$e,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:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:$e,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:$e,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:$e,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:rl}),il=jt({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),al=jt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:sl}),ol=jt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),om={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"},lm=/[A-Z]/g,ll=/-[a-z]/g,um=/^data[-\w.:]+$/i;function cm(e,t){const n=gs(t);let r=t,s=Be;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&um.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(ll,hm);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!ll.test(i)){let a=i.replace(lm,dm);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}s=ws}return new s(r,t)}function dm(e){return"-"+e.toLowerCase()}function hm(e){return e.charAt(1).toUpperCase()}const fm=el([nl,im,il,al,ol],"html"),Ss=el([nl,am,il,al,ol],"svg");function pm(e){return e.join(" ").trim()}var $t={},ks,ul;function mm(){if(ul)return ks;ul=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,s=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
|
|
7
|
+
`);s=o.pop()||"";for(const l of o)if(l.startsWith("data: ")){const u=l.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch(d){}}}}finally{n.releaseLock()}})}function zp(e){return e.map(t=>{let n="";if(typeof t.content=="string")n=t.content;else if(Array.isArray(t.content)){const r=t.content.find(s=>s.type==="text");r&&typeof r=="object"&&"text"in r&&(n=r.text)}return{role:t.role,content:n}})}function Wo(e){return m(m({id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}}},e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}}),e.role==="user"&&{attachments:[]})}const Bt=new Map,ln=new Map;let Ko;function ps(e,t){const n=Bt.get(e);if(n)return n;if(t)for(const r of t){const s=ln.get(r.id);if(s)return Bt.set(e,s),s}return e}function Rp(e,t){return{list(){return P(this,null,function*(){const r=[];let i,a=0;do{const l=yield e.listChats({limit:50,cursor:i}),u=l.items||[];Array.isArray(u)&&u.length>0&&r.push(...u),i=l.nextCursor||void 0,a++}while(i&&a<50);return{threads:r.map(l=>{const u=l.id;return!u||l.deletedAt?null:{status:"regular",remoteId:u,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}})},initialize(r){return P(this,null,function*(){return{remoteId:Bt.get(r)||r,externalId:void 0}})},rename(r,s){return P(this,null,function*(){const i=ps(r);yield e.updateChat(i,{title:s})})},archive(r){return P(this,null,function*(){})},unarchive(r){return P(this,null,function*(){})},delete(r){return P(this,null,function*(){const s=ps(r);yield e.deleteChat(s)})},generateTitle(r,s){return P(this,null,function*(){var o;const i=ps(r,s);let a;try{a=(yield e.generateChatTitle(i)).title}catch(l){console.error("[generateTitle] API call failed, falling back to first message",l);const u=s.find(c=>c.role==="user"),d=(o=u==null?void 0:u.content)==null?void 0:o.filter(c=>c.type==="text").map(c=>c.text).join(" ").trim();a=d?d.length>60?d.slice(0,57)+"...":d:void 0}return da(l=>{const u=l.addTextPart();a&&u.append(a),u.close(),l.close()})})},fetch(r){return P(this,null,function*(){try{const s=yield e.getChat(r);return{status:"regular",remoteId:s.id||r,title:s.title||"Chat",createdAt:s.createdAt?new Date(s.createdAt):new Date,updatedAt:s.updatedAt?new Date(s.updatedAt):new Date}}catch(s){return{status:"regular",remoteId:r,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(r,s){Bt.set(r,s),t==null||t(r,s)},unstable_Provider:({children:r})=>{const s=io(),i=s==null?void 0:s.remoteId,a=s==null?void 0:s.isMain;y.useEffect(()=>{a&&(Ko=i)},[i,a]);const o=y.useMemo(()=>({load(){return P(this,null,function*(){if(!i)return{messages:[]};try{const d=yield e.getChat(i);if(!d.messages||d.messages.length===0)return{messages:[]};const c=d.messages.map(h=>Wo(h)),f=c.map((h,b)=>({message:h,parentId:b>0?c[b-1].id:null}));for(const h of c)ln.set(h.id,i);return{messages:f}}catch(d){return{messages:[]}}})},append(d){return P(this,null,function*(){})}}),[i,e]),l=y.useMemo(()=>({history:o}),[o]);return p.jsx(Jr,{adapters:l,children:r})}}}class jp{constructor(){_(this,"messageMetadata",new Map);_(this,"currentMessageId",null);_(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const n=this.messageMetadata.get(this.currentMessageId)||{},r=t.sources;r&&r.length>0&&(this.messageMetadata.set(this.currentMessageId,E(m({},n),{sources:r})),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(t){return this.messageMetadata.get(t)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.listeners.forEach(t=>t())}}const xt=new jp,ms=[];let ir=[];function Jo(e,t,n=50,r=800){ms.push({question:e,response:t,streamingSpeed:n,initialDelay:r})}function Go(e,t){const{modelId:n,getModelId:r,systemPrompt:s,ephemeral:i,enableReasoning:a,onChatCreated:o,onUserMessage:l,onThreadIdUpdate:u,onBeforeRequest:d,mockResponseOnBlocked:c}=t,f=()=>{var b;return(b=r?r():n)!=null?b:null};return{run(b){return Nn(this,null,function*(){var G,ce,k;const{messages:S,abortSignal:x}=b,g=b.unstable_threadId,v=ms.shift();if(v){l==null||l();const j=(G=v.initialDelay)!=null?G:800;if(j>0&&(yield new Ae(new Promise(se=>setTimeout(se,j)))),x!=null&&x.aborted)throw new Error("Request aborted");const le=v.response.split(" ");let ue="";const Se=v.streamingSpeed||50,He=`premade-${Date.now()}`;i&&(o==null||o(He));for(let se=0;se<le.length;se++){if(x!=null&&x.aborted)throw new Error("Request aborted");ue+=(se===0?"":" ")+le[se],yield{content:[{type:"text",text:ue}]},yield new Ae(new Promise(ve=>setTimeout(ve,Se+Math.random()*(Se*.5))))}yield{content:[{type:"text",text:ue}]},ir.push({role:"user",content:v.question},{role:"assistant",content:v.response});return}let C;for(const j of S){const le=ln.get(j.id);if(le){C=le;break}}l==null||l();let O=S,F=-1;for(let j=S.length-1;j>=0;j--)if(S[j].role==="assistant"){F=j;break}(C||F>=0)&&F>=0&&(O=S.slice(F+1));const T=zp(O);if(ir.length>0&&!C){const j=ir.map(le=>({role:le.role,content:le.content}));T.unshift(...j),ir=[]}const R=[];let H;for(let j=O.length-1;j>=0;j--)if(O[j].role==="user"){H=O[j];break}if(H&&"attachments"in H){const j=H.attachments;if(j&&j.length>0){for(const le of j)if(le.file)try{const ue=yield new Ae(e.uploadFile(le.file));R.push(ue.id)}catch(ue){}}}const J={messages:T,chatId:C||null,systemPrompt:s,ephemeral:i,enableReasoning:a,stream:!0},I=f();if(I&&I.trim()!==""&&(J.modelId=I),R.length>0&&(J.fileIds=R),d&&!(yield new Ae(d()))){if(c){const le=typeof c=="function"?c():c,ue=S.filter(ve=>ve.role==="user"),Se=ue.length>0?ue[ue.length-1]:void 0;let He="Message";if(Se){if(typeof Se.content=="string")He=Se.content;else if(Array.isArray(Se.content)){const ve=Se.content.find(ft=>ft.type==="text");He=(ve==null?void 0:ve.text)||"Message"}}Jo(He,le,40,400);const se=ms.shift();if(se){l==null||l();const ve=(ce=se.initialDelay)!=null?ce:400;if(ve>0&&(yield new Ae(new Promise(ot=>setTimeout(ot,ve)))),x!=null&&x.aborted)throw new Error("Request aborted");const ft=se.response.split(" ");let at="";const pt=se.streamingSpeed||40,In=`mock-${Date.now()}`;i&&(o==null||o(In));for(let ot=0;ot<ft.length;ot++){if(x!=null&&x.aborted)throw new Error("Request aborted");at+=(ot===0?"":" ")+ft[ot],yield{content:[{type:"text",text:at}]},yield new Ae(new Promise(X=>setTimeout(X,pt+Math.random()*(pt*.3))))}yield{content:[{type:"text",text:at}]};return}}throw new Error("Request blocked")}const B=yield new Ae(e.createOrContinueChat(J,x));let M="",U="",D;const N=[];let K=0,re=!1;const V=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;xt.clear(),xt.setCurrentMessage(V);const Q=()=>{N.length!==K&&(K=N.length,xt.update({sources:N.length>0?[...N]:void 0}))},w=()=>{Q();const j=[];return U&&j.push({type:"reasoning",text:U}),M&&j.push({type:"text",text:M}),j.length===0&&j.push({type:"text",text:""}),{content:j}};try{for(var ye=Pt(Bp(B,x)),Ie,pe,it;Ie=!(pe=yield new Ae(ye.next())).done;Ie=!1){const j=pe.value;if(x!=null&&x.aborted)throw new Error("Request aborted");const le=j.id||j.chatId||j.messageId;if(le&&!D){D=le;const se=g||Ko;o==null||o(le);for(const ve of S)ln.set(ve.id,le);se&&!Bt.has(se)&&Bt.set(se,le),u&&se&&u(se,le)}const ue=j.sources;if(ue&&Array.isArray(ue)&&ue.length>0)for(const se of ue)N.some(ve=>ve.sourceId===se.sourceId)||N.push({sourceId:se.sourceId,filename:se.filename||"Unknown",score:(k=se.score)!=null?k:1,chunkId:se.chunkId,datasetId:se.datasetId});const Se=j.reasoning;if(Se&&Se.length>0&&(U+=Se,yield w()),j.type)switch(j.type){case"source-document":j.sourceId&&N.push({sourceId:j.sourceId,filename:j.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":j.delta&&(U+=j.delta),(M||U)&&(yield w());continue;case"reasoning-end":(M||U)&&(yield w());continue;case"text-delta":j.delta&&(U&&!re&&!M&&(re=!0,yield new Ae(new Promise(se=>setTimeout(se,400)))),M+=j.delta),M&&(yield w());continue;case"error":throw new Error(j.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const He=j.delta;if(He!=null&&(U&&!re&&!M&&(re=!0,yield new Ae(new Promise(se=>setTimeout(se,400)))),M+=He),j.content&&(M+=j.content),j.message&&(M+=j.message.content||""),j.finished){(M||U||N.length>0)&&(yield w());break}(M||U||N.length>0)&&(yield w())}}catch(pe){it=[pe]}finally{try{Ie&&(pe=ye.return)&&(yield new Ae(pe.call(ye)))}finally{if(it)throw it[0]}}(M||U||N.length>0)&&(yield w())})}}}class un extends Error{constructor(t,n,r){super(t),this.code=n,this.file=r,this.name="AttachmentValidationError"}}const $p=["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/markdown","text/csv","application/json"],Up=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],Hp=10*1024*1024;function Yo(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}function qp(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function Vp(e,t){const r={"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/gif":[".gif"],"image/webp":[".webp"],"image/svg+xml":[".svg"],"application/pdf":[".pdf"],"text/plain":[".txt"],"text/markdown":[".md"],"text/csv":[".csv"],"application/json":[".json"]}[e];return r?r.includes(t.toLowerCase()):!0}function Wp(){return typeof crypto!="undefined"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Qo(e={}){const{validation:t={},supportsVision:n=!0,onValidationError:r,onAttachmentAdded:s,onAttachmentRemoved:i}=e,{maxFileSizeBytes:a=Hp,allowedMimeTypes:o=$p,allowedExtensions:l=Up,validateContentType:u=!0}=t,d=l.join(",");function c(h){if(h.size>a){const S=new un('File "'+h.name+'" is too large ('+Yo(h.size)+"). Maximum size is "+Yo(a)+".","FILE_TOO_LARGE",h);throw r==null||r(S),S}if(!n&&h.type.startsWith("image/")){const S=new un("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",h);throw r==null||r(S),S}const b=qp(h.name);if(b&&!l.some(S=>S.toLowerCase()===b)){const S=new un('File type "'+b+'" is not allowed. Allowed types: '+l.join(", "),"INVALID_TYPE",h);throw r==null||r(S),S}if(h.type&&!o.some(S=>{if(S.endsWith("/*")){const x=S.slice(0,-1);return h.type.startsWith(x)}return h.type===S})){const S=new un('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw r==null||r(S),S}if(u&&h.type&&b&&!Vp(h.type,b)){const S=new un('File extension "'+b+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw r==null||r(S),S}}return{accept:d,add(b){return P(this,arguments,function*({file:h}){c(h);let S="file";h.type.startsWith("image/")?S="image":(h.type.includes("pdf")||h.type.includes("document")||h.type.includes("text")||h.name.endsWith(".pdf")||h.name.endsWith(".docx")||h.name.endsWith(".txt")||h.name.endsWith(".md")||h.name.endsWith(".csv")||h.name.endsWith(".json"))&&(S="document");const x={id:Wp(),type:S,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return s==null||s(x),x})},remove(h){return P(this,null,function*(){i==null||i(h.id)})},send(h){return P(this,null,function*(){if(h.type==="image"&&h.file){const b=yield new Promise((S,x)=>{const g=new FileReader;g.onload=()=>S(g.result),g.onerror=()=>x(new Error("Failed to read file")),g.readAsDataURL(h.file)});return E(m({},h),{status:{type:"complete"},content:[{type:"image",image:b}]})}return E(m({},h),{status:{type:"complete"},content:[]})})}}}class Kp{constructor(){_(this,"current",null);_(this,"listeners",new Set);_(this,"getSnapshot",()=>this.current);_(this,"subscribe",t=>(this.listeners.add(t),()=>this.listeners.delete(t)))}push(t,n){this.current={message:t,code:n,timestamp:Date.now()},this.notify()}clear(){this.current&&(this.current=null,this.notify())}notify(){this.listeners.forEach(t=>t())}}const zt=new Kp;function Jp({children:e,baseUrl:t,sessionToken:n,isProxyMode:r=!1,mode:s="multiChat",modelId:i,onModelChange:a,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:d,onError:c,onChatCreated:f,onUserMessage:h,onThreadIdUpdate:b,onChatsLoaded:S,enableAttachments:x=!1,supportsVision:g=!0,onBeforeRequest:v,mockResponseOnBlocked:C}){const O=y.useMemo(()=>new Vo(t,n||void 0,r),[t,n,r]),[F,T]=y.useState(i||null);y.useEffect(()=>{i&&T(i)},[i]);const R=y.useCallback(I=>{f==null||f(I)},[f]),H=y.useCallback((I,B)=>{b==null||b(I,B)},[b]),J=y.useMemo(()=>Go(O,{modelId:F||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:R,onUserMessage:h,onBeforeRequest:v,mockResponseOnBlocked:C}),[O,F,l,o,u,R,h,v,C]);return s==="singleChat"?p.jsx(Gp,{client:O,initialThreadId:d,modelAdapter:J,enableAttachments:x,supportsVision:g,onChatCreated:R,children:e}):p.jsx(Qp,{client:O,modelAdapterOptions:{modelId:F||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:R,onUserMessage:h,onBeforeRequest:v,mockResponseOnBlocked:C},initialThreadId:d,onChatsLoaded:S,onThreadIdUpdate:H,onError:c,enableAttachments:x,supportsVision:g,children:e})}function Gp({client:e,initialThreadId:t,modelAdapter:n,enableAttachments:r,supportsVision:s=!0,onChatCreated:i,children:a}){const[o,l]=y.useState(void 0),[u,d]=y.useState(!!t),c=y.useRef(i);return c.current=i,y.useEffect(()=>{if(!t){d(!1);return}let f=!1;function h(){return P(this,null,function*(){var b;try{const S=yield e.getChat(t);if(f)return;if(S.messages&&S.messages.length>0){const x=S.messages.map(g=>Wo(g));for(const g of S.messages)ln.set(g.id,S.id);l(x)}(b=c.current)==null||b.call(c,S.id)}catch(S){}finally{f||d(!1)}})}return h(),()=>{f=!0}},[e,t]),u?null:p.jsx(Yp,{modelAdapter:n,initialMessages:o,enableAttachments:r,supportsVision:s,children:a})}function Yp({modelAdapter:e,initialMessages:t,enableAttachments:n,supportsVision:r=!0,children:s}){const i=y.useMemo(()=>n?Qo({supportsVision:r,onValidationError:o=>{zt.push(o.message,o.code)}}):void 0,[n,r]),a=La(e,{initialMessages:t,adapters:m({},i&&{attachments:i})});return p.jsx(Qa,{runtime:a,children:s})}function Qp({client:e,modelAdapterOptions:t,initialThreadId:n,onChatsLoaded:r,onThreadIdUpdate:s,onError:i,enableAttachments:a,supportsVision:o,children:l}){const u=y.useMemo(()=>Rp(e,(C,O)=>{s==null||s(C,O)}),[e,s]),d=y.useCallback((C,O)=>{u.updateRemoteId&&u.updateRemoteId(C,O),s==null||s(C,O)},[u,s]),c=y.useRef(r);c.current=r;const f=y.useMemo(()=>E(m({},u),{list(){return P(this,null,function*(){var F;const O=yield u.list();return(F=c.current)==null||F.call(c),O})}}),[u]);y.useEffect(()=>{window.__cuadraThreadListAdapter=f,window.__cuadraThreadListRuntime=null},[f]);const h=y.useRef(t.modelId);h.current=t.modelId;const b=y.useMemo(()=>{const F=t,{modelId:C}=F;return q(F,["modelId"])},[t.systemPrompt,t.ephemeral,t.enableReasoning,t.onChatCreated,t.onUserMessage,t.onBeforeRequest,t.mockResponseOnBlocked]),S=y.useMemo(()=>Go(e,E(m({},b),{getModelId:()=>h.current,onThreadIdUpdate:d})),[e,b,d]),x=y.useMemo(()=>a?Qo({supportsVision:o,onValidationError:C=>{zt.push(C.message,C.code)}}):void 0,[a,o]),g=y.useCallback(()=>La(S,{adapters:m({},x&&{attachments:x})}),[S,x]),v=Za({adapter:f,runtimeHook:g});return y.useEffect(()=>{window.__cuadraThreadListRuntime=v},[v]),p.jsx(Qa,{runtime:v,children:l})}function Pk(){}function Mk(){}function Xp(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Zp=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,em=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,tm={};function Xo(e,t){return(tm.jsx?em:Zp).test(e)}const nm=/[ \t\n\f\r]/g;function rm(e){return typeof e=="object"?e.type==="text"?Zo(e.value):!1:Zo(e)}function Zo(e){return e.replace(nm,"")===""}class cn{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}cn.prototype.normal={},cn.prototype.property={},cn.prototype.space=void 0;function el(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new cn(n,r,t)}function gs(e){return e.toLowerCase()}class Be{constructor(t,n){this.attribute=n,this.property=t}}Be.prototype.attribute="",Be.prototype.booleanish=!1,Be.prototype.boolean=!1,Be.prototype.commaOrSpaceSeparated=!1,Be.prototype.commaSeparated=!1,Be.prototype.defined=!1,Be.prototype.mustUseProperty=!1,Be.prototype.number=!1,Be.prototype.overloadedBoolean=!1,Be.prototype.property="",Be.prototype.spaceSeparated=!1,Be.prototype.space=void 0;let sm=0;const ee=It(),we=It(),ys=It(),L=It(),ge=It(),Rt=It(),$e=It();function It(){return ic(2,++sm)}const bs=Object.freeze(Object.defineProperty({__proto__:null,boolean:ee,booleanish:we,commaOrSpaceSeparated:$e,commaSeparated:Rt,number:L,overloadedBoolean:ys,spaceSeparated:ge},Symbol.toStringTag,{value:"Module"})),xs=Object.keys(bs);class ws extends Be{constructor(t,n,r,s){let i=-1;if(super(t,n),tl(this,"space",s),typeof r=="number")for(;++i<xs.length;){const a=xs[i];tl(this,xs[i],(r&bs[a])===bs[a])}}}ws.prototype.defined=!0;function tl(e,t,n){n&&(e[t]=n)}function jt(e){const t={},n={};for(const[r,s]of Object.entries(e.properties)){const i=new ws(r,e.transform(e.attributes||{},r),s,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[gs(r)]=r,n[gs(i.attribute)]=r}return new cn(t,n,e.space)}const nl=jt({properties:{ariaActiveDescendant:null,ariaAtomic:we,ariaAutoComplete:null,ariaBusy:we,ariaChecked:we,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:ge,ariaCurrent:null,ariaDescribedBy:ge,ariaDetails:null,ariaDisabled:we,ariaDropEffect:ge,ariaErrorMessage:null,ariaExpanded:we,ariaFlowTo:ge,ariaGrabbed:we,ariaHasPopup:null,ariaHidden:we,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ge,ariaLevel:L,ariaLive:null,ariaModal:we,ariaMultiLine:we,ariaMultiSelectable:we,ariaOrientation:null,ariaOwns:ge,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:we,ariaReadOnly:we,ariaRelevant:null,ariaRequired:we,ariaRoleDescription:ge,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:we,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function rl(e,t){return t in e?e[t]:t}function sl(e,t){return rl(e,t.toLowerCase())}const im=jt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Rt,acceptCharset:ge,accessKey:ge,action:null,allow:null,allowFullScreen:ee,allowPaymentRequest:ee,allowUserMedia:ee,alt:null,as:null,async:ee,autoCapitalize:null,autoComplete:ge,autoFocus:ee,autoPlay:ee,blocking:ge,capture:null,charSet:null,checked:ee,cite:null,className:ge,cols:L,colSpan:null,content:null,contentEditable:we,controls:ee,controlsList:ge,coords:L|Rt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ee,defer:ee,dir:null,dirName:null,disabled:ee,download:ys,draggable:we,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ee,formTarget:null,headers:ge,height:L,hidden:ys,high:L,href:null,hrefLang:null,htmlFor:ge,httpEquiv:ge,id:null,imageSizes:null,imageSrcSet:null,inert:ee,inputMode:null,integrity:null,is:null,isMap:ee,itemId:null,itemProp:ge,itemRef:ge,itemScope:ee,itemType:ge,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ee,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:ee,muted:ee,name:null,nonce:null,noModule:ee,noValidate:ee,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:ee,optimum:L,pattern:null,ping:ge,placeholder:null,playsInline:ee,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ee,referrerPolicy:null,rel:ge,required:ee,reversed:ee,rows:L,rowSpan:L,sandbox:ge,scope:null,scoped:ee,seamless:ee,selected:ee,shadowRootClonable:ee,shadowRootDelegatesFocus:ee,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:we,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:ee,useMap:null,value:we,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ge,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ee,declare:ee,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:ee,noHref:ee,noShade:ee,noWrap:ee,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:we,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ee,disableRemotePlayback:ee,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:sl}),am=jt({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:$e,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:ge,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:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:ee,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,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:Rt,g2:Rt,glyphName:Rt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:$e,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,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:L,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:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ge,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:$e,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:$e,rev:$e,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:$e,requiredFeatures:$e,requiredFonts:$e,requiredFormats:$e,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:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:$e,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:$e,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:$e,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:rl}),il=jt({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),al=jt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:sl}),ol=jt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),om={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"},lm=/[A-Z]/g,ll=/-[a-z]/g,um=/^data[-\w.:]+$/i;function cm(e,t){const n=gs(t);let r=t,s=Be;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&um.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(ll,hm);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!ll.test(i)){let a=i.replace(lm,dm);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}s=ws}return new s(r,t)}function dm(e){return"-"+e.toLowerCase()}function hm(e){return e.charAt(1).toUpperCase()}const fm=el([nl,im,il,al,ol],"html"),Ss=el([nl,am,il,al,ol],"svg");function pm(e){return e.join(" ").trim()}var $t={},ks,ul;function mm(){if(ul)return ks;ul=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,s=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
|
|
8
8
|
`,u="/",d="*",c="",f="comment",h="declaration";function b(x,g){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];g=g||{};var v=1,C=1;function O(D){var N=D.match(t);N&&(v+=N.length);var K=D.lastIndexOf(l);C=~K?D.length-K:C+D.length}function F(){var D={line:v,column:C};return function(N){return N.position=new T(D),J(),N}}function T(D){this.start=D,this.end={line:v,column:C},this.source=g.source}T.prototype.content=x;function R(D){var N=new Error(g.source+":"+v+":"+C+": "+D);if(N.reason=D,N.filename=g.source,N.line=v,N.column=C,N.source=x,!g.silent)throw N}function H(D){var N=D.exec(x);if(N){var K=N[0];return O(K),x=x.slice(K.length),N}}function J(){H(n)}function I(D){var N;for(D=D||[];N=B();)N!==!1&&D.push(N);return D}function B(){var D=F();if(!(u!=x.charAt(0)||d!=x.charAt(1))){for(var N=2;c!=x.charAt(N)&&(d!=x.charAt(N)||u!=x.charAt(N+1));)++N;if(N+=2,c===x.charAt(N-1))return R("End of comment missing");var K=x.slice(2,N-2);return C+=2,O(K),x=x.slice(N),C+=2,D({type:f,comment:K})}}function M(){var D=F(),N=H(r);if(N){if(B(),!H(s))return R("property missing ':'");var K=H(i),re=D({type:h,property:S(N[0].replace(e,c)),value:K?S(K[0].replace(e,c)):c});return H(a),re}}function U(){var D=[];I(D);for(var N;N=M();)N!==!1&&(D.push(N),I(D));return D}return J(),U()}function S(x){return x?x.replace(o,c):c}return ks=b,ks}var cl;function gm(){if(cl)return $t;cl=1;var e=$t&&$t.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty($t,"__esModule",{value:!0}),$t.default=n;const t=e(mm());function n(r,s){let i=null;if(!r||typeof r!="string")return i;const a=(0,t.default)(r),o=typeof s=="function";return a.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:d}=l;o?s(u,d,l):d&&(i=i||{},i[u]=d)}),i}return $t}var dn={},dl;function ym(){if(dl)return dn;dl=1,Object.defineProperty(dn,"__esModule",{value:!0}),dn.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,s=/^-(ms)-/,i=function(u){return!u||n.test(u)||e.test(u)},a=function(u,d){return d.toUpperCase()},o=function(u,d){return"".concat(d,"-")},l=function(u,d){return d===void 0&&(d={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(s,o):u=u.replace(r,o),u.replace(t,a))};return dn.camelCase=l,dn}var hn,hl;function bm(){if(hl)return hn;hl=1;var e=hn&&hn.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},t=e(gm()),n=ym();function r(s,i){var a={};return!s||typeof s!="string"||(0,t.default)(s,function(o,l){o&&l&&(a[(0,n.camelCase)(o,i)]=l)}),a}return r.default=r,hn=r,hn}var xm=bm();const wm=Rn(xm),fl=pl("end"),_s=pl("start");function pl(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Sm(e){const t=_s(e),n=fl(e);if(t&&n)return{start:t,end:n}}function fn(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?ml(e.position):"start"in e||"end"in e?ml(e):"line"in e||"column"in e?Cs(e):""}function Cs(e){return gl(e&&e.line)+":"+gl(e&&e.column)}function ml(e){return Cs(e&&e.start)+"-"+Cs(e&&e.end)}function gl(e){return e&&typeof e=="number"?e:1}class Pe extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let s="",i={},a=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i=m({},n)),typeof t=="string"?s=t:!i.cause&&t&&(a=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const l=r.indexOf(":");l===-1?i.ruleId=r:(i.source=r.slice(0,l),i.ruleId=r.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=o?o.line:void 0,this.name=fn(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Pe.prototype.file="",Pe.prototype.name="",Pe.prototype.reason="",Pe.prototype.message="",Pe.prototype.stack="",Pe.prototype.column=void 0,Pe.prototype.line=void 0,Pe.prototype.ancestors=void 0,Pe.prototype.cause=void 0,Pe.prototype.fatal=void 0,Pe.prototype.place=void 0,Pe.prototype.ruleId=void 0,Pe.prototype.source=void 0;const Ts={}.hasOwnProperty,km=new Map,_m=/[A-Z]/g,Cm=new Set(["table","tbody","thead","tfoot","tr"]),Tm=new Set(["td","th"]),yl="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Im(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=Lm(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=Dm(n,t.jsx,t.jsxs)}const s={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Ss:fm,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=bl(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function bl(e,t,n){if(t.type==="element")return vm(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Em(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Pm(e,t,n);if(t.type==="mdxjsEsm")return Am(e,t);if(t.type==="root")return Mm(e,t,n);if(t.type==="text")return Nm(e,t)}function vm(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=Ss,e.schema=s),e.ancestors.push(t);const i=wl(e,t.tagName,!1),a=Om(e,t);let o=vs(e,t);return Cm.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!rm(l):!0})),xl(e,a,i,t),Is(a,o),e.ancestors.pop(),e.schema=r,e.create(t,i,a,n)}function Em(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}pn(e,t.position)}function Am(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);pn(e,t.position)}function Pm(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=Ss,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:wl(e,t.name,!0),a=Fm(e,t),o=vs(e,t);return xl(e,a,i,t),Is(a,o),e.ancestors.pop(),e.schema=r,e.create(t,i,a,n)}function Mm(e,t,n){const r={};return Is(r,vs(e,t)),e.create(t,e.Fragment,r,n)}function Nm(e,t){return t.value}function xl(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Is(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Dm(e,t,n){return r;function r(s,i,a,o){const u=Array.isArray(a.children)?n:t;return o?u(i,a,o):u(i,a)}}function Lm(e,t){return n;function n(r,s,i,a){const o=Array.isArray(i.children),l=_s(r);return t(s,i,a,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function Om(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&Ts.call(t.properties,s)){const i=Bm(e,s,t.properties[s]);if(i){const[a,o]=i;e.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&Tm.has(t.tagName)?r=o:n[a]=o}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function Fm(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const a=i.expression;a.type;const o=a.properties[0];o.type,Object.assign(n,e.evaluater.evaluateExpression(o.argument))}else pn(e,t.position);else{const s=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const o=r.value.data.estree.body[0];o.type,i=e.evaluater.evaluateExpression(o.expression)}else pn(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function vs(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:km;for(;++r<t.children.length;){const i=t.children[r];let a;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=s.get(l)||0;a=l+"-"+u,s.set(l,u+1)}}const o=bl(e,i,a);o!==void 0&&n.push(o)}return n}function Bm(e,t,n){const r=cm(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?Xp(n):pm(n)),r.property==="style"){let s=typeof n=="object"?n:zm(e,String(n));return e.stylePropertyNameCase==="css"&&(s=Rm(s)),["style",s]}return[e.elementAttributeNameCase==="react"&&r.space?om[r.property]||r.property:r.attribute,n]}}function zm(e,t){try{return wm(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,s=new Pe("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=yl+"#cannot-parse-style-attribute",s}}function wl(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const s=t.split(".");let i=-1,a;for(;++i<s.length;){const o=Xo(s[i])?{type:"Identifier",name:s[i]}:{type:"Literal",value:s[i]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(i&&o.type==="Literal"),optional:!1}:o}r=a}else r=Xo(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const s=r.value;return Ts.call(e.components,s)?e.components[s]:s}if(e.evaluater)return e.evaluater.evaluateExpression(r);pn(e)}function pn(e,t){const n=new Pe("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=yl+"#cannot-handle-mdx-estrees-without-createevaluater",n}function Rm(e){const t={};let n;for(n in e)Ts.call(e,n)&&(t[jm(n)]=e[n]);return t}function jm(e){let t=e.replace(_m,$m);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function $m(e){return"-"+e.toLowerCase()}const Es={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"]},Um={};function As(e,t){const n=Um,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,s=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Sl(e,r,s)}function Sl(e,t,n){if(Hm(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return kl(e.children,t,n)}return Array.isArray(e)?kl(e,t,n):""}function kl(e,t,n){const r=[];let s=-1;for(;++s<e.length;)r[s]=Sl(e[s],t,n);return r.join("")}function Hm(e){return!!(e&&typeof e=="object")}const _l=document.createElement("i");function Ps(e){const t="&"+e+";";_l.innerHTML=t;const n=_l.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function Ue(e,t,n,r){const s=e.length;let i=0,a;if(t<0?t=-t>s?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)a=Array.from(r),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);i<r.length;)a=r.slice(i,i+1e4),a.unshift(t,0),e.splice(...a),i+=1e4,t+=1e4}function We(e,t){return e.length>0?(Ue(e,e.length,0,t),e):t}const Cl={}.hasOwnProperty;function Tl(e){const t={};let n=-1;for(;++n<e.length;)qm(t,e[n]);return t}function qm(e,t){let n;for(n in t){const s=(Cl.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let a;if(i)for(a in i){Cl.call(s,a)||(s[a]=[]);const o=i[a];Vm(s[a],Array.isArray(o)?o:o?[o]:[])}}}function Vm(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);Ue(e,0,0,r)}function Il(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Qe(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Le=wt(/[A-Za-z]/),Me=wt(/[\dA-Za-z]/),Wm=wt(/[#-'*+\--9=?A-Z^-~]/);function ar(e){return e!==null&&(e<32||e===127)}const Ms=wt(/\d/),Km=wt(/[\dA-Fa-f]/),Jm=wt(/[!-/:-@[-`{-~]/);function W(e){return e!==null&&e<-2}function fe(e){return e!==null&&(e<0||e===32)}function ne(e){return e===-2||e===-1||e===32}const or=wt(new RegExp("\\p{P}|\\p{S}","u")),vt=wt(/\s/);function wt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Ut(e){const t=[];let n=-1,r=0,s=0;for(;++n<e.length;){const i=e.charCodeAt(n);let a="";if(i===37&&Me(e.charCodeAt(n+1))&&Me(e.charCodeAt(n+2)))s=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(a=String.fromCharCode(i));else if(i>55295&&i<57344){const o=e.charCodeAt(n+1);i<56320&&o>56319&&o<57344?(a=String.fromCharCode(i,o),s=1):a="�"}else a=String.fromCharCode(i);a&&(t.push(e.slice(r,n),encodeURIComponent(a)),r=n+s+1,a=""),s&&(n+=s,s=0)}return t.join("")+e.slice(r)}function oe(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return a;function a(l){return ne(l)?(e.enter(n),o(l)):t(l)}function o(l){return ne(l)&&i++<s?(e.consume(l),o):(e.exit(n),t(l))}}const Gm={tokenize:Ym};function Ym(e){const t=e.attempt(this.parser.constructs.contentInitial,r,s);let n;return t;function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),oe(e,t,"linePrefix")}function s(o){return e.enter("paragraph"),i(o)}function i(o){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,a(o)}function a(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return W(o)?(e.consume(o),e.exit("chunkText"),i):(e.consume(o),a)}}const Qm={tokenize:Xm},vl={tokenize:Zm};function Xm(e){const t=this,n=[];let r=0,s,i,a;return o;function o(C){if(r<n.length){const O=n[r];return t.containerState=O[1],e.attempt(O[0].continuation,l,u)(C)}return u(C)}function l(C){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&v();const O=t.events.length;let F=O,T;for(;F--;)if(t.events[F][0]==="exit"&&t.events[F][1].type==="chunkFlow"){T=t.events[F][1].end;break}g(r);let R=O;for(;R<t.events.length;)t.events[R][1].end=m({},T),R++;return Ue(t.events,F+1,0,t.events.slice(O)),t.events.length=R,u(C)}return o(C)}function u(C){if(r===n.length){if(!s)return f(C);if(s.currentConstruct&&s.currentConstruct.concrete)return b(C);t.interrupt=!!(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(vl,d,c)(C)}function d(C){return s&&v(),g(r),f(C)}function c(C){return t.parser.lazy[t.now().line]=r!==n.length,a=t.now().offset,b(C)}function f(C){return t.containerState={},e.attempt(vl,h,b)(C)}function h(C){return r++,n.push([t.currentConstruct,t.containerState]),f(C)}function b(C){if(C===null){s&&v(),g(0),e.consume(C);return}return s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),S(C)}function S(C){if(C===null){x(e.exit("chunkFlow"),!0),g(0),e.consume(C);return}return W(C)?(e.consume(C),x(e.exit("chunkFlow")),r=0,t.interrupt=void 0,o):(e.consume(C),S)}function x(C,O){const F=t.sliceStream(C);if(O&&F.push(null),C.previous=i,i&&(i.next=C),i=C,s.defineSkip(C.start),s.write(F),t.parser.lazy[C.start.line]){let T=s.events.length;for(;T--;)if(s.events[T][1].start.offset<a&&(!s.events[T][1].end||s.events[T][1].end.offset>a))return;const R=t.events.length;let H=R,J,I;for(;H--;)if(t.events[H][0]==="exit"&&t.events[H][1].type==="chunkFlow"){if(J){I=t.events[H][1].end;break}J=!0}for(g(r),T=R;T<t.events.length;)t.events[T][1].end=m({},I),T++;Ue(t.events,H+1,0,t.events.slice(R)),t.events.length=T}}function g(C){let O=n.length;for(;O-- >C;){const F=n[O];t.containerState=F[1],F[0].exit.call(t,e)}n.length=C}function v(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function Zm(e,t,n){return oe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ht(e){if(e===null||fe(e)||vt(e))return 1;if(or(e))return 2}function lr(e,t,n){const r=[];let s=-1;for(;++s<e.length;){const i=e[s].resolveAll;i&&!r.includes(i)&&(t=i(t,n),r.push(i))}return t}const Ns={name:"attention",resolveAll:eg,tokenize:tg};function eg(e,t){let n=-1,r,s,i,a,o,l,u,d;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;l=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const c=m({},e[r][1].end),f=m({},e[n][1].start);El(c,-l),El(f,l),a={type:l>1?"strongSequence":"emphasisSequence",start:c,end:m({},e[r][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[n][1].start),end:f},i={type:l>1?"strongText":"emphasisText",start:m({},e[r][1].end),end:m({},e[n][1].start)},s={type:l>1?"strong":"emphasis",start:m({},a.start),end:m({},o.end)},e[r][1].end=m({},a.start),e[n][1].start=m({},o.end),u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=We(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=We(u,[["enter",s,t],["enter",a,t],["exit",a,t],["enter",i,t]]),u=We(u,lr(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=We(u,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=We(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,Ue(e,r-1,n-r+3,u),n=r+u.length-d-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function tg(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,s=Ht(r);let i;return a;function a(l){return i=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===i)return e.consume(l),o;const u=e.exit("attentionSequence"),d=Ht(l),c=!d||d===2&&s||n.includes(l),f=!s||s===2&&d||n.includes(r);return u._open=!!(i===42?c:c&&(s||!f)),u._close=!!(i===42?f:f&&(d||!c)),t(l)}}function El(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const ng={name:"autolink",tokenize:rg};function rg(e,t,n){let r=0;return s;function s(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(h){return Le(h)?(e.consume(h),a):h===64?n(h):u(h)}function a(h){return h===43||h===45||h===46||Me(h)?(r=1,o(h)):u(h)}function o(h){return h===58?(e.consume(h),r=0,l):(h===43||h===45||h===46||Me(h))&&r++<32?(e.consume(h),o):(r=0,u(h))}function l(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||ar(h)?n(h):(e.consume(h),l)}function u(h){return h===64?(e.consume(h),d):Wm(h)?(e.consume(h),u):n(h)}function d(h){return Me(h)?c(h):n(h)}function c(h){return h===46?(e.consume(h),r=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):f(h)}function f(h){if((h===45||Me(h))&&r++<63){const b=h===45?f:c;return e.consume(h),b}return n(h)}}const mn={partial:!0,tokenize:sg};function sg(e,t,n){return r;function r(i){return ne(i)?oe(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||W(i)?t(i):n(i)}}const Al={continuation:{tokenize:ag},exit:og,name:"blockQuote",tokenize:ig};function ig(e,t,n){const r=this;return s;function s(a){if(a===62){const o=r.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),i}return n(a)}function i(a){return ne(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function ag(e,t,n){const r=this;return s;function s(a){return ne(a)?oe(e,i,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):i(a)}function i(a){return e.attempt(Al,t,n)(a)}}function og(e){e.exit("blockQuote")}const Pl={name:"characterEscape",tokenize:lg};function lg(e,t,n){return r;function r(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),s}function s(i){return Jm(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const Ml={name:"characterReference",tokenize:ug};function ug(e,t,n){const r=this;let s=0,i,a;return o;function o(c){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),l}function l(c){return c===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(c),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,a=Me,d(c))}function u(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,a=Km,d):(e.enter("characterReferenceValue"),i=7,a=Ms,d(c))}function d(c){if(c===59&&s){const f=e.exit("characterReferenceValue");return a===Me&&!Ps(r.sliceSerialize(f))?n(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(c)&&s++<i?(e.consume(c),d):n(c)}}const Nl={partial:!0,tokenize:dg},Dl={concrete:!0,name:"codeFenced",tokenize:cg};function cg(e,t,n){const r=this,s={partial:!0,tokenize:F};let i=0,a=0,o;return l;function l(T){return u(T)}function u(T){const R=r.events[r.events.length-1];return i=R&&R[1].type==="linePrefix"?R[2].sliceSerialize(R[1],!0).length:0,o=T,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(T)}function d(T){return T===o?(a++,e.consume(T),d):a<3?n(T):(e.exit("codeFencedFenceSequence"),ne(T)?oe(e,c,"whitespace")(T):c(T))}function c(T){return T===null||W(T)?(e.exit("codeFencedFence"),r.interrupt?t(T):e.check(Nl,S,O)(T)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(T))}function f(T){return T===null||W(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(T)):ne(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),oe(e,h,"whitespace")(T)):T===96&&T===o?n(T):(e.consume(T),f)}function h(T){return T===null||W(T)?c(T):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),b(T))}function b(T){return T===null||W(T)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(T)):T===96&&T===o?n(T):(e.consume(T),b)}function S(T){return e.attempt(s,O,x)(T)}function x(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),g}function g(T){return i>0&&ne(T)?oe(e,v,"linePrefix",i+1)(T):v(T)}function v(T){return T===null||W(T)?e.check(Nl,S,O)(T):(e.enter("codeFlowValue"),C(T))}function C(T){return T===null||W(T)?(e.exit("codeFlowValue"),v(T)):(e.consume(T),C)}function O(T){return e.exit("codeFenced"),t(T)}function F(T,R,H){let J=0;return I;function I(N){return T.enter("lineEnding"),T.consume(N),T.exit("lineEnding"),B}function B(N){return T.enter("codeFencedFence"),ne(N)?oe(T,M,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):M(N)}function M(N){return N===o?(T.enter("codeFencedFenceSequence"),U(N)):H(N)}function U(N){return N===o?(J++,T.consume(N),U):J>=a?(T.exit("codeFencedFenceSequence"),ne(N)?oe(T,D,"whitespace")(N):D(N)):H(N)}function D(N){return N===null||W(N)?(T.exit("codeFencedFence"),R(N)):H(N)}}}function dg(e,t,n){const r=this;return s;function s(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i)}function i(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}const Ds={name:"codeIndented",tokenize:fg},hg={partial:!0,tokenize:pg};function fg(e,t,n){const r=this;return s;function s(u){return e.enter("codeIndented"),oe(e,i,"linePrefix",5)(u)}function i(u){const d=r.events[r.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?l(u):W(u)?e.attempt(hg,a,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||W(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function pg(e,t,n){const r=this;return s;function s(a){return r.parser.lazy[r.now().line]?n(a):W(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s):oe(e,i,"linePrefix",5)(a)}function i(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):W(a)?s(a):n(a)}}const mg={name:"codeText",previous:yg,resolve:gg,tokenize:bg};function gg(e){let t=e.length-4,n=3,r,s;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)s===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(s=r):(r===t||e[r][1].type==="lineEnding")&&(e[s][1].type="codeTextData",r!==s+2&&(e[s][1].end=e[r-1][1].end,e.splice(s+2,r-s-2),t-=r-s-2,r=s+2),s=void 0);return e}function yg(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function bg(e,t,n){let r=0,s,i;return a;function a(c){return e.enter("codeText"),e.enter("codeTextSequence"),o(c)}function o(c){return c===96?(e.consume(c),r++,o):(e.exit("codeTextSequence"),l(c))}function l(c){return c===null?n(c):c===32?(e.enter("space"),e.consume(c),e.exit("space"),l):c===96?(i=e.enter("codeTextSequence"),s=0,d(c)):W(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(c))}function u(c){return c===null||c===32||c===96||W(c)?(e.exit("codeTextData"),l(c)):(e.consume(c),u)}function d(c){return c===96?(e.consume(c),s++,d):s===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(c)):(i.type="codeTextData",u(c))}}class xg{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const r=n==null?Number.POSITIVE_INFINITY:n;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const s=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return r&&gn(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),gn(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),gn(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);gn(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);gn(this.left,n.reverse())}}}function gn(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function Ll(e){const t={};let n=-1,r,s,i,a,o,l,u;const d=new xg(e);for(;++n<d.length;){for(;n in t;)n=t[n];if(r=d.get(n),n&&r[1].type==="chunkFlow"&&d.get(n-1)[1].type==="listItemPrefix"&&(l=r[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,wg(d,n)),n=t[n],u=!0);else if(r[1]._container){for(i=n,s=void 0;i--;)if(a=d.get(i),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(s&&(d.get(s)[1].type="lineEndingBlank"),a[1].type="lineEnding",s=i);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;s&&(r[1].end=m({},d.get(s)[1].start),o=d.slice(s,n),o.unshift(r),d.splice(s,n-s+1,o))}}return Ue(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function wg(e,t){const n=e.get(t)[1],r=e.get(t)[2];let s=t-1;const i=[];let a=n._tokenizer;a||(a=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const o=a.events,l=[],u={};let d,c,f=-1,h=n,b=0,S=0;const x=[S];for(;h;){for(;e.get(++s)[1]!==h;);i.push(s),h._tokenizer||(d=r.sliceStream(h),h.next||d.push(null),c&&a.defineSkip(h.start),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(d),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),c=h,h=h.next}for(h=n;++f<o.length;)o[f][0]==="exit"&&o[f-1][0]==="enter"&&o[f][1].type===o[f-1][1].type&&o[f][1].start.line!==o[f][1].end.line&&(S=f+1,x.push(S),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(a.events=[],h?(h._tokenizer=void 0,h.previous=void 0):x.pop(),f=x.length;f--;){const g=o.slice(x[f],x[f+1]),v=i.pop();l.push([v,v+g.length-1]),e.splice(v,2,g)}for(l.reverse(),f=-1;++f<l.length;)u[b+l[f][0]]=b+l[f][1],b+=l[f][1]-l[f][0]-1;return u}const Sg={resolve:_g,tokenize:Cg},kg={partial:!0,tokenize:Tg};function _g(e){return Ll(e),e}function Cg(e,t){let n;return r;function r(o){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),s(o)}function s(o){return o===null?i(o):W(o)?e.check(kg,a,i)(o):(e.consume(o),s)}function i(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function a(o){return e.consume(o),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}function Tg(e,t,n){const r=this;return s;function s(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),oe(e,i,"linePrefix")}function i(a){if(a===null||W(a))return n(a);const o=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):e.interrupt(r.parser.constructs.flow,n,t)(a)}}function Ol(e,t,n,r,s,i,a,o,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return c;function c(g){return g===60?(e.enter(r),e.enter(s),e.enter(i),e.consume(g),e.exit(i),f):g===null||g===32||g===41||ar(g)?n(g):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),S(g))}function f(g){return g===62?(e.enter(i),e.consume(g),e.exit(i),e.exit(s),e.exit(r),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),h(g))}function h(g){return g===62?(e.exit("chunkString"),e.exit(o),f(g)):g===null||g===60||W(g)?n(g):(e.consume(g),g===92?b:h)}function b(g){return g===60||g===62||g===92?(e.consume(g),h):h(g)}function S(g){return!d&&(g===null||g===41||fe(g))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),t(g)):d<u&&g===40?(e.consume(g),d++,S):g===41?(e.consume(g),d--,S):g===null||g===32||g===40||ar(g)?n(g):(e.consume(g),g===92?x:S)}function x(g){return g===40||g===41||g===92?(e.consume(g),S):S(g)}}function Fl(e,t,n,r,s,i){const a=this;let o=0,l;return u;function u(h){return e.enter(r),e.enter(s),e.consume(h),e.exit(s),e.enter(i),d}function d(h){return o>999||h===null||h===91||h===93&&!l||h===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?n(h):h===93?(e.exit(i),e.enter(s),e.consume(h),e.exit(s),e.exit(r),t):W(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),c(h))}function c(h){return h===null||h===91||h===93||W(h)||o++>999?(e.exit("chunkString"),d(h)):(e.consume(h),l||(l=!ne(h)),h===92?f:c)}function f(h){return h===91||h===92||h===93?(e.consume(h),o++,c):c(h)}}function Bl(e,t,n,r,s,i){let a;return o;function o(f){return f===34||f===39||f===40?(e.enter(r),e.enter(s),e.consume(f),e.exit(s),a=f===40?41:f,l):n(f)}function l(f){return f===a?(e.enter(s),e.consume(f),e.exit(s),e.exit(r),t):(e.enter(i),u(f))}function u(f){return f===a?(e.exit(i),l(a)):f===null?n(f):W(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),oe(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===a||f===null||W(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?c:d)}function c(f){return f===a||f===92?(e.consume(f),d):d(f)}}function yn(e,t){let n;return r;function r(s){return W(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):ne(s)?oe(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const Ig={name:"definition",tokenize:Eg},vg={partial:!0,tokenize:Ag};function Eg(e,t,n){const r=this;let s;return i;function i(h){return e.enter("definition"),a(h)}function a(h){return Fl.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function o(h){return s=Qe(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),l):n(h)}function l(h){return fe(h)?yn(e,u)(h):u(h)}function u(h){return Ol(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(vg,c,c)(h)}function c(h){return ne(h)?oe(e,f,"whitespace")(h):f(h)}function f(h){return h===null||W(h)?(e.exit("definition"),r.parser.defined.push(s),t(h)):n(h)}}function Ag(e,t,n){return r;function r(o){return fe(o)?yn(e,s)(o):n(o)}function s(o){return Bl(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return ne(o)?oe(e,a,"whitespace")(o):a(o)}function a(o){return o===null||W(o)?t(o):n(o)}}const Pg={name:"hardBreakEscape",tokenize:Mg};function Mg(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return W(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const Ng={name:"headingAtx",resolve:Dg,tokenize:Lg};function Dg(e,t){let n=e.length-2,r=3,s,i;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(s={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},i={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},Ue(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function Lg(e,t,n){let r=0;return s;function s(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),a(d)}function a(d){return d===35&&r++<6?(e.consume(d),a):d===null||fe(d)?(e.exit("atxHeadingSequence"),o(d)):n(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||W(d)?(e.exit("atxHeading"),t(d)):ne(d)?oe(e,o,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),o(d))}function u(d){return d===null||d===35||fe(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const Og=["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"],zl=["pre","script","style","textarea"],Fg={concrete:!0,name:"htmlFlow",resolveTo:Rg,tokenize:jg},Bg={partial:!0,tokenize:Ug},zg={partial:!0,tokenize:$g};function Rg(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function jg(e,t,n){const r=this;let s,i,a,o,l;return u;function u(k){return d(k)}function d(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),c}function c(k){return k===33?(e.consume(k),f):k===47?(e.consume(k),i=!0,S):k===63?(e.consume(k),s=3,r.interrupt?t:w):Le(k)?(e.consume(k),a=String.fromCharCode(k),x):n(k)}function f(k){return k===45?(e.consume(k),s=2,h):k===91?(e.consume(k),s=5,o=0,b):Le(k)?(e.consume(k),s=4,r.interrupt?t:w):n(k)}function h(k){return k===45?(e.consume(k),r.interrupt?t:w):n(k)}function b(k){const ye="CDATA[";return k===ye.charCodeAt(o++)?(e.consume(k),o===ye.length?r.interrupt?t:M:b):n(k)}function S(k){return Le(k)?(e.consume(k),a=String.fromCharCode(k),x):n(k)}function x(k){if(k===null||k===47||k===62||fe(k)){const ye=k===47,Ie=a.toLowerCase();return!ye&&!i&&zl.includes(Ie)?(s=1,r.interrupt?t(k):M(k)):Og.includes(a.toLowerCase())?(s=6,ye?(e.consume(k),g):r.interrupt?t(k):M(k)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(k):i?v(k):C(k))}return k===45||Me(k)?(e.consume(k),a+=String.fromCharCode(k),x):n(k)}function g(k){return k===62?(e.consume(k),r.interrupt?t:M):n(k)}function v(k){return ne(k)?(e.consume(k),v):I(k)}function C(k){return k===47?(e.consume(k),I):k===58||k===95||Le(k)?(e.consume(k),O):ne(k)?(e.consume(k),C):I(k)}function O(k){return k===45||k===46||k===58||k===95||Me(k)?(e.consume(k),O):F(k)}function F(k){return k===61?(e.consume(k),T):ne(k)?(e.consume(k),F):C(k)}function T(k){return k===null||k===60||k===61||k===62||k===96?n(k):k===34||k===39?(e.consume(k),l=k,R):ne(k)?(e.consume(k),T):H(k)}function R(k){return k===l?(e.consume(k),l=null,J):k===null||W(k)?n(k):(e.consume(k),R)}function H(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||fe(k)?F(k):(e.consume(k),H)}function J(k){return k===47||k===62||ne(k)?C(k):n(k)}function I(k){return k===62?(e.consume(k),B):n(k)}function B(k){return k===null||W(k)?M(k):ne(k)?(e.consume(k),B):n(k)}function M(k){return k===45&&s===2?(e.consume(k),K):k===60&&s===1?(e.consume(k),re):k===62&&s===4?(e.consume(k),G):k===63&&s===3?(e.consume(k),w):k===93&&s===5?(e.consume(k),Q):W(k)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(Bg,ce,U)(k)):k===null||W(k)?(e.exit("htmlFlowData"),U(k)):(e.consume(k),M)}function U(k){return e.check(zg,D,ce)(k)}function D(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),N}function N(k){return k===null||W(k)?U(k):(e.enter("htmlFlowData"),M(k))}function K(k){return k===45?(e.consume(k),w):M(k)}function re(k){return k===47?(e.consume(k),a="",V):M(k)}function V(k){if(k===62){const ye=a.toLowerCase();return zl.includes(ye)?(e.consume(k),G):M(k)}return Le(k)&&a.length<8?(e.consume(k),a+=String.fromCharCode(k),V):M(k)}function Q(k){return k===93?(e.consume(k),w):M(k)}function w(k){return k===62?(e.consume(k),G):k===45&&s===2?(e.consume(k),w):M(k)}function G(k){return k===null||W(k)?(e.exit("htmlFlowData"),ce(k)):(e.consume(k),G)}function ce(k){return e.exit("htmlFlow"),t(k)}}function $g(e,t,n){const r=this;return s;function s(a){return W(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):n(a)}function i(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}function Ug(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(mn,t,n)}}const Hg={name:"htmlText",tokenize:qg};function qg(e,t,n){const r=this;let s,i,a;return o;function o(w){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(w),l}function l(w){return w===33?(e.consume(w),u):w===47?(e.consume(w),F):w===63?(e.consume(w),C):Le(w)?(e.consume(w),H):n(w)}function u(w){return w===45?(e.consume(w),d):w===91?(e.consume(w),i=0,b):Le(w)?(e.consume(w),v):n(w)}function d(w){return w===45?(e.consume(w),h):n(w)}function c(w){return w===null?n(w):w===45?(e.consume(w),f):W(w)?(a=c,re(w)):(e.consume(w),c)}function f(w){return w===45?(e.consume(w),h):c(w)}function h(w){return w===62?K(w):w===45?f(w):c(w)}function b(w){const G="CDATA[";return w===G.charCodeAt(i++)?(e.consume(w),i===G.length?S:b):n(w)}function S(w){return w===null?n(w):w===93?(e.consume(w),x):W(w)?(a=S,re(w)):(e.consume(w),S)}function x(w){return w===93?(e.consume(w),g):S(w)}function g(w){return w===62?K(w):w===93?(e.consume(w),g):S(w)}function v(w){return w===null||w===62?K(w):W(w)?(a=v,re(w)):(e.consume(w),v)}function C(w){return w===null?n(w):w===63?(e.consume(w),O):W(w)?(a=C,re(w)):(e.consume(w),C)}function O(w){return w===62?K(w):C(w)}function F(w){return Le(w)?(e.consume(w),T):n(w)}function T(w){return w===45||Me(w)?(e.consume(w),T):R(w)}function R(w){return W(w)?(a=R,re(w)):ne(w)?(e.consume(w),R):K(w)}function H(w){return w===45||Me(w)?(e.consume(w),H):w===47||w===62||fe(w)?J(w):n(w)}function J(w){return w===47?(e.consume(w),K):w===58||w===95||Le(w)?(e.consume(w),I):W(w)?(a=J,re(w)):ne(w)?(e.consume(w),J):K(w)}function I(w){return w===45||w===46||w===58||w===95||Me(w)?(e.consume(w),I):B(w)}function B(w){return w===61?(e.consume(w),M):W(w)?(a=B,re(w)):ne(w)?(e.consume(w),B):J(w)}function M(w){return w===null||w===60||w===61||w===62||w===96?n(w):w===34||w===39?(e.consume(w),s=w,U):W(w)?(a=M,re(w)):ne(w)?(e.consume(w),M):(e.consume(w),D)}function U(w){return w===s?(e.consume(w),s=void 0,N):w===null?n(w):W(w)?(a=U,re(w)):(e.consume(w),U)}function D(w){return w===null||w===34||w===39||w===60||w===61||w===96?n(w):w===47||w===62||fe(w)?J(w):(e.consume(w),D)}function N(w){return w===47||w===62||fe(w)?J(w):n(w)}function K(w){return w===62?(e.consume(w),e.exit("htmlTextData"),e.exit("htmlText"),t):n(w)}function re(w){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),V}function V(w){return ne(w)?oe(e,Q,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(w):Q(w)}function Q(w){return e.enter("htmlTextData"),a(w)}}const Ls={name:"labelEnd",resolveAll:Jg,resolveTo:Gg,tokenize:Yg},Vg={tokenize:Qg},Wg={tokenize:Xg},Kg={tokenize:Zg};function Jg(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const s=r.type==="labelImage"?4:2;r.type="data",t+=s}}return e.length!==n.length&&Ue(e,0,e.length,n),e}function Gg(e,t){let n=e.length,r=0,s,i,a,o;for(;n--;)if(s=e[n][1],i){if(s.type==="link"||s.type==="labelLink"&&s._inactive)break;e[n][0]==="enter"&&s.type==="labelLink"&&(s._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(s.type==="labelImage"||s.type==="labelLink")&&!s._balanced&&(i=n,s.type!=="labelLink")){r=2;break}}else s.type==="labelEnd"&&(a=n);const l={type:e[i][1].type==="labelLink"?"link":"image",start:m({},e[i][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[i][1].start),end:m({},e[a][1].end)},d={type:"labelText",start:m({},e[i+r+2][1].end),end:m({},e[a-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=We(o,e.slice(i+1,i+r+3)),o=We(o,[["enter",d,t]]),o=We(o,lr(t.parser.constructs.insideSpan.null,e.slice(i+r+4,a-3),t)),o=We(o,[["exit",d,t],e[a-2],e[a-1],["exit",u,t]]),o=We(o,e.slice(a+1)),o=We(o,[["exit",l,t]]),Ue(e,i,e.length,o),e}function Yg(e,t,n){const r=this;let s=r.events.length,i,a;for(;s--;)if((r.events[s][1].type==="labelImage"||r.events[s][1].type==="labelLink")&&!r.events[s][1]._balanced){i=r.events[s][1];break}return o;function o(f){return i?i._inactive?c(f):(a=r.parser.defined.includes(Qe(r.sliceSerialize({start:i.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),l):n(f)}function l(f){return f===40?e.attempt(Vg,d,a?d:c)(f):f===91?e.attempt(Wg,d,a?u:c)(f):a?d(f):c(f)}function u(f){return e.attempt(Kg,d,c)(f)}function d(f){return t(f)}function c(f){return i._balanced=!0,n(f)}}function Qg(e,t,n){return r;function r(c){return e.enter("resource"),e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),s}function s(c){return fe(c)?yn(e,i)(c):i(c)}function i(c){return c===41?d(c):Ol(e,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function a(c){return fe(c)?yn(e,l)(c):d(c)}function o(c){return n(c)}function l(c){return c===34||c===39||c===40?Bl(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):d(c)}function u(c){return fe(c)?yn(e,d)(c):d(c)}function d(c){return c===41?(e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),e.exit("resource"),t):n(c)}}function Xg(e,t,n){const r=this;return s;function s(o){return Fl.call(r,e,i,a,"reference","referenceMarker","referenceString")(o)}function i(o){return r.parser.defined.includes(Qe(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(o):n(o)}function a(o){return n(o)}}function Zg(e,t,n){return r;function r(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),s}function s(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):n(i)}}const ey={name:"labelStartImage",resolveAll:Ls.resolveAll,tokenize:ty};function ty(e,t,n){const r=this;return s;function s(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),i}function i(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),a):n(o)}function a(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const ny={name:"labelStartLink",resolveAll:Ls.resolveAll,tokenize:ry};function ry(e,t,n){const r=this;return s;function s(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),i}function i(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}const Os={name:"lineEnding",tokenize:sy};function sy(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),oe(e,t,"linePrefix")}}const ur={name:"thematicBreak",tokenize:iy};function iy(e,t,n){let r=0,s;return i;function i(u){return e.enter("thematicBreak"),a(u)}function a(u){return s=u,o(u)}function o(u){return u===s?(e.enter("thematicBreakSequence"),l(u)):r>=3&&(u===null||W(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===s?(e.consume(u),r++,l):(e.exit("thematicBreakSequence"),ne(u)?oe(e,o,"whitespace")(u):o(u))}}const ze={continuation:{tokenize:uy},exit:dy,name:"list",tokenize:ly},ay={partial:!0,tokenize:hy},oy={partial:!0,tokenize:cy};function ly(e,t,n){const r=this,s=r.events[r.events.length-1];let i=s&&s[1].type==="linePrefix"?s[2].sliceSerialize(s[1],!0).length:0,a=0;return o;function o(h){const b=r.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(b==="listUnordered"?!r.containerState.marker||h===r.containerState.marker:Ms(h)){if(r.containerState.type||(r.containerState.type=b,e.enter(b,{_container:!0})),b==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(ur,n,u)(h):u(h);if(!r.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(h)}return n(h)}function l(h){return Ms(h)&&++a<10?(e.consume(h),l):(!r.interrupt||a<2)&&(r.containerState.marker?h===r.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):n(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||h,e.check(mn,r.interrupt?n:d,e.attempt(ay,f,c))}function d(h){return r.containerState.initialBlankLine=!0,i++,f(h)}function c(h){return ne(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),f):n(h)}function f(h){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function uy(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(mn,s,i);function s(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,oe(e,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!ne(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(oy,t,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,oe(e,e.attempt(ze,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function cy(e,t,n){const r=this;return oe(e,s,"listItemIndent",r.containerState.size+1);function s(i){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?t(i):n(i)}}function dy(e){e.exit(this.containerState.type)}function hy(e,t,n){const r=this;return oe(e,s,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const a=r.events[r.events.length-1];return!ne(i)&&a&&a[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Rl={name:"setextUnderline",resolveTo:fy,tokenize:py};function fy(e,t){let n=e.length,r,s,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(s=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const a={type:"setextHeading",start:m({},e[r][1].start),end:m({},e[e.length-1][1].end)};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",a,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end=m({},e[i][1].end)):e[r][1]=a,e.push(["exit",a,t]),e}function py(e,t,n){const r=this;let s;return i;function i(u){let d=r.events.length,c;for(;d--;)if(r.events[d][1].type!=="lineEnding"&&r.events[d][1].type!=="linePrefix"&&r.events[d][1].type!=="content"){c=r.events[d][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||c)?(e.enter("setextHeadingLine"),s=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===s?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),ne(u)?oe(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||W(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const my={tokenize:gy};function gy(e){const t=this,n=e.attempt(mn,r,e.attempt(this.parser.constructs.flowInitial,s,oe(e,e.attempt(this.parser.constructs.flow,s,e.attempt(Sg,s)),"linePrefix")));return n;function r(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function s(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const yy={resolveAll:$l()},by=jl("string"),xy=jl("text");function jl(e){return{resolveAll:$l(e==="text"?wy:void 0),tokenize:t};function t(n){const r=this,s=this.parser.constructs[e],i=n.attempt(s,a,o);return a;function a(d){return u(d)?i(d):o(d)}function o(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),l}function l(d){return u(d)?(n.exit("data"),i(d)):(n.consume(d),l)}function u(d){if(d===null)return!0;const c=s[d];let f=-1;if(c)for(;++f<c.length;){const h=c[f];if(!h.previous||h.previous.call(r,r.previous))return!0}return!1}}}function $l(e){return t;function t(n,r){let s=-1,i;for(;++s<=n.length;)i===void 0?n[s]&&n[s][1].type==="data"&&(i=s,s++):(!n[s]||n[s][1].type!=="data")&&(s!==i+2&&(n[i][1].end=n[s-1][1].end,n.splice(i+2,s-i-2),s=i+2),i=void 0);return e?e(n,r):n}}function wy(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],s=t.sliceStream(r);let i=s.length,a=-1,o=0,l;for(;i--;){const u=s[i];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(u===-2)l=!0,o++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(o=0),o){const u={type:n===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?a:r.start._bufferIndex+a,_index:r.start._index+i,line:r.end.line,column:r.end.column-o,offset:r.end.offset-o},end:m({},r.end)};r.end=m({},u.start),r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Sy=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:Ig},disable:{null:[]},document:{42:ze,43:ze,45:ze,48:ze,49:ze,50:ze,51:ze,52:ze,53:ze,54:ze,55:ze,56:ze,57:ze,62:Al},flow:{35:Ng,42:ur,45:[Rl,ur],60:Fg,61:Rl,95:ur,96:Dl,126:Dl},flowInitial:{[-2]:Ds,[-1]:Ds,32:Ds},insideSpan:{null:[Ns,yy]},string:{38:Ml,92:Pl},text:{[-5]:Os,[-4]:Os,[-3]:Os,33:ey,38:Ml,42:Ns,60:[ng,Hg],91:ny,92:[Pg,Pl],93:Ls,95:Ns,96:mg}},Symbol.toStringTag,{value:"Module"}));function ky(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const s={},i=[];let a=[],o=[];const l={attempt:R(F),check:R(T),consume:v,enter:C,exit:O,interrupt:R(T,{interrupt:!0})},u={code:null,containerState:{},defineSkip:S,events:[],now:b,parser:e,previous:null,sliceSerialize:f,sliceStream:h,write:c};let d=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function c(B){return a=We(a,B),x(),a[a.length-1]!==null?[]:(H(t,0),u.events=lr(i,u.events,u),u.events)}function f(B,M){return Cy(h(B),M)}function h(B){return _y(a,B)}function b(){const{_bufferIndex:B,_index:M,line:U,column:D,offset:N}=r;return{_bufferIndex:B,_index:M,line:U,column:D,offset:N}}function S(B){s[B.line]=B.column,I()}function x(){let B;for(;r._index<a.length;){const M=a[r._index];if(typeof M=="string")for(B=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===B&&r._bufferIndex<M.length;)g(M.charCodeAt(r._bufferIndex));else g(M)}}function g(B){d=d(B)}function v(B){W(B)?(r.line++,r.column=1,r.offset+=B===-3?2:1,I()):B!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===a[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=B}function C(B,M){const U=M||{};return U.type=B,U.start=b(),u.events.push(["enter",U,u]),o.push(U),U}function O(B){const M=o.pop();return M.end=b(),u.events.push(["exit",M,u]),M}function F(B,M){H(B,M.from)}function T(B,M){M.restore()}function R(B,M){return U;function U(D,N,K){let re,V,Q,w;return Array.isArray(D)?ce(D):"tokenize"in D?ce([D]):G(D);function G(pe){return it;function it(j){const le=j!==null&&pe[j],ue=j!==null&&pe.null,Se=[...Array.isArray(le)?le:le?[le]:[],...Array.isArray(ue)?ue:ue?[ue]:[]];return ce(Se)(j)}}function ce(pe){return re=pe,V=0,pe.length===0?K:k(pe[V])}function k(pe){return it;function it(j){return w=J(),Q=pe,pe.partial||(u.currentConstruct=pe),pe.name&&u.parser.constructs.disable.null.includes(pe.name)?Ie():pe.tokenize.call(M?Object.assign(Object.create(u),M):u,l,ye,Ie)(j)}}function ye(pe){return B(Q,w),N}function Ie(pe){return w.restore(),++V<re.length?k(re[V]):K}}}function H(B,M){B.resolveAll&&!i.includes(B)&&i.push(B),B.resolve&&Ue(u.events,M,u.events.length-M,B.resolve(u.events.slice(M),u)),B.resolveTo&&(u.events=B.resolveTo(u.events,u))}function J(){const B=b(),M=u.previous,U=u.currentConstruct,D=u.events.length,N=Array.from(o);return{from:D,restore:K};function K(){r=B,u.previous=M,u.currentConstruct=U,u.events.length=D,o=N,I()}}function I(){r.line in s&&r.column<2&&(r.column=s[r.line],r.offset+=s[r.line]-1)}}function _y(e,t){const n=t.start._index,r=t.start._bufferIndex,s=t.end._index,i=t.end._bufferIndex;let a;if(n===s)a=[e[n].slice(r,i)];else{if(a=e.slice(n,s),r>-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}i>0&&a.push(e[s].slice(0,i))}return a}function Cy(e,t){let n=-1;const r=[];let s;for(;++n<e.length;){const i=e[n];let a;if(typeof i=="string")a=i;else switch(i){case-5:{a="\r";break}case-4:{a=`
|
|
9
9
|
`;break}case-3:{a=`\r
|
|
10
10
|
`;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&s)continue;a=" ";break}default:a=String.fromCharCode(i)}s=i===-2,r.push(a)}return r.join("")}function Ty(e){const r={constructs:Tl([Sy,...(e||{}).extensions||[]]),content:s(Gm),defined:[],document:s(Qm),flow:s(my),lazy:{},string:s(by),text:s(xy)};return r;function s(i){return a;function a(o){return ky(r,i,o)}}}function Iy(e){for(;!Ll(e););return e}const Ul=/[\0\t\n\r]/g;function vy(){let e=1,t="",n=!0,r;return s;function s(i,a,o){const l=[];let u,d,c,f,h;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(a||void 0).decode(i)),c=0,t="",n&&(i.charCodeAt(0)===65279&&c++,n=void 0);c<i.length;){if(Ul.lastIndex=c,u=Ul.exec(i),f=u&&u.index!==void 0?u.index:i.length,h=i.charCodeAt(f),!u){t=i.slice(c);break}if(h===10&&c===f&&r)l.push(-3),r=void 0;else switch(r&&(l.push(-5),r=void 0),c<f&&(l.push(i.slice(c,f)),e+=f-c),h){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:r=!0,e=1}c=f+1}return o&&(r&&l.push(-5),t&&l.push(t),l.push(null)),l}}const Ey=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Ay(e){return e.replace(Ey,Py)}function Py(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const s=n.charCodeAt(1),i=s===120||s===88;return Il(n.slice(i?2:1),i?16:10)}return Ps(n)||e}const Hl={}.hasOwnProperty;function My(e,t,n){return typeof t!="string"&&(n=t,t=void 0),Ny(n)(Iy(Ty(n).document().write(vy()(e,t,!0))))}function Ny(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(ot),autolinkProtocol:J,autolinkEmail:J,atxHeading:i(ft),blockQuote:i(ue),characterEscape:J,characterReference:J,codeFenced:i(Se),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:i(Se,a),codeText:i(He,a),codeTextData:J,data:J,codeFlowValue:J,definition:i(se),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:i(ve),hardBreakEscape:i(at),hardBreakTrailing:i(at),htmlFlow:i(pt,a),htmlFlowData:J,htmlText:i(pt,a),htmlTextData:J,image:i(In),label:a,link:i(ot),listItem:i(Ce),listItemValue:f,listOrdered:i(X,c),listUnordered:i(X),paragraph:i(Xe),reference:k,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:i(ft),strong:i(kr),thematicBreak:i(tk)},exit:{atxHeading:l(),atxHeadingSequence:F,autolink:l(),autolinkEmail:le,autolinkProtocol:j,blockQuote:l(),characterEscapeValue:I,characterReferenceMarkerHexadecimal:Ie,characterReferenceMarkerNumeric:Ie,characterReferenceValue:pe,characterReference:it,codeFenced:l(x),codeFencedFence:S,codeFencedFenceInfo:h,codeFencedFenceMeta:b,codeFlowValue:I,codeIndented:l(g),codeText:l(N),codeTextData:I,data:I,definition:l(),definitionDestinationString:O,definitionLabelString:v,definitionTitleString:C,emphasis:l(),hardBreakEscape:l(M),hardBreakTrailing:l(M),htmlFlow:l(U),htmlFlowData:I,htmlText:l(D),htmlTextData:I,image:l(re),label:Q,labelText:V,lineEnding:B,link:l(K),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:ye,resourceDestinationString:w,resourceTitleString:G,resource:ce,setextHeading:l(H),setextHeadingLineSequence:R,setextHeadingText:T,strong:l(),thematicBreak:l()}};ql(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(A){let z={type:"root",children:[]};const Y={stack:[z],tokenStack:[],config:t,enter:o,exit:u,buffer:a,resume:d,data:n},ie=[];let me=-1;for(;++me<A.length;)if(A[me][1].type==="listOrdered"||A[me][1].type==="listUnordered")if(A[me][0]==="enter")ie.push(me);else{const Ze=ie.pop();me=s(A,Ze,me)}for(me=-1;++me<A.length;){const Ze=t[A[me][0]];Hl.call(Ze,A[me][1].type)&&Ze[A[me][1].type].call(Object.assign({sliceSerialize:A[me][2].sliceSerialize},Y),A[me][1])}if(Y.tokenStack.length>0){const Ze=Y.tokenStack[Y.tokenStack.length-1];(Ze[1]||Vl).call(Y,void 0,Ze[0])}for(z.position={start:St(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:St(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},me=-1;++me<t.transforms.length;)z=t.transforms[me](z)||z;return z}function s(A,z,Y){let ie=z-1,me=-1,Ze=!1,At,mt,vn,En;for(;++ie<=Y;){const qe=A[ie];switch(qe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{qe[0]==="enter"?me++:me--,En=void 0;break}case"lineEndingBlank":{qe[0]==="enter"&&(At&&!En&&!me&&!vn&&(vn=ie),En=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:En=void 0}if(!me&&qe[0]==="enter"&&qe[1].type==="listItemPrefix"||me===-1&&qe[0]==="exit"&&(qe[1].type==="listUnordered"||qe[1].type==="listOrdered")){if(At){let Wt=ie;for(mt=void 0;Wt--;){const gt=A[Wt];if(gt[1].type==="lineEnding"||gt[1].type==="lineEndingBlank"){if(gt[0]==="exit")continue;mt&&(A[mt][1].type="lineEndingBlank",Ze=!0),gt[1].type="lineEnding",mt=Wt}else if(!(gt[1].type==="linePrefix"||gt[1].type==="blockQuotePrefix"||gt[1].type==="blockQuotePrefixWhitespace"||gt[1].type==="blockQuoteMarker"||gt[1].type==="listItemIndent"))break}vn&&(!mt||vn<mt)&&(At._spread=!0),At.end=Object.assign({},mt?A[mt][1].start:qe[1].end),A.splice(mt||ie,0,["exit",At,qe[2]]),ie++,Y++}if(qe[1].type==="listItemPrefix"){const Wt={type:"listItem",_spread:!1,start:Object.assign({},qe[1].start),end:void 0};At=Wt,A.splice(ie,0,["enter",Wt,qe[2]]),ie++,Y++,vn=void 0,En=!0}}}return A[z][1]._spread=Ze,Y}function i(A,z){return Y;function Y(ie){o.call(this,A(ie),ie),z&&z.call(this,ie)}}function a(){this.stack.push({type:"fragment",children:[]})}function o(A,z,Y){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([z,Y||void 0]),A.position={start:St(z.start),end:void 0}}function l(A){return z;function z(Y){A&&A.call(this,Y),u.call(this,Y)}}function u(A,z){const Y=this.stack.pop(),ie=this.tokenStack.pop();if(ie)ie[0].type!==A.type&&(z?z.call(this,A,ie[0]):(ie[1]||Vl).call(this,A,ie[0]));else throw new Error("Cannot close `"+A.type+"` ("+fn({start:A.start,end:A.end})+"): it’s not open");Y.position.end=St(A.end)}function d(){return As(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function f(A){if(this.data.expectingFirstListItemValue){const z=this.stack[this.stack.length-2];z.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function h(){const A=this.resume(),z=this.stack[this.stack.length-1];z.lang=A}function b(){const A=this.resume(),z=this.stack[this.stack.length-1];z.meta=A}function S(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function g(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A.replace(/(\r?\n|\r)$/g,"")}function v(A){const z=this.resume(),Y=this.stack[this.stack.length-1];Y.label=z,Y.identifier=Qe(this.sliceSerialize(A)).toLowerCase()}function C(){const A=this.resume(),z=this.stack[this.stack.length-1];z.title=A}function O(){const A=this.resume(),z=this.stack[this.stack.length-1];z.url=A}function F(A){const z=this.stack[this.stack.length-1];if(!z.depth){const Y=this.sliceSerialize(A).length;z.depth=Y}}function T(){this.data.setextHeadingSlurpLineEnding=!0}function R(A){const z=this.stack[this.stack.length-1];z.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function H(){this.data.setextHeadingSlurpLineEnding=void 0}function J(A){const Y=this.stack[this.stack.length-1].children;let ie=Y[Y.length-1];(!ie||ie.type!=="text")&&(ie=ek(),ie.position={start:St(A.start),end:void 0},Y.push(ie)),this.stack.push(ie)}function I(A){const z=this.stack.pop();z.value+=this.sliceSerialize(A),z.position.end=St(A.end)}function B(A){const z=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Y=z.children[z.children.length-1];Y.position.end=St(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(z.type)&&(J.call(this,A),I.call(this,A))}function M(){this.data.atHardBreak=!0}function U(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A}function D(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A}function N(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A}function K(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const z=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=z,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function re(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const z=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=z,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function V(A){const z=this.sliceSerialize(A),Y=this.stack[this.stack.length-2];Y.label=Ay(z),Y.identifier=Qe(z).toLowerCase()}function Q(){const A=this.stack[this.stack.length-1],z=this.resume(),Y=this.stack[this.stack.length-1];if(this.data.inReference=!0,Y.type==="link"){const ie=A.children;Y.children=ie}else Y.alt=z}function w(){const A=this.resume(),z=this.stack[this.stack.length-1];z.url=A}function G(){const A=this.resume(),z=this.stack[this.stack.length-1];z.title=A}function ce(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function ye(A){const z=this.resume(),Y=this.stack[this.stack.length-1];Y.label=z,Y.identifier=Qe(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function Ie(A){this.data.characterReferenceType=A.type}function pe(A){const z=this.sliceSerialize(A),Y=this.data.characterReferenceType;let ie;Y?(ie=Il(z,Y==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ie=Ps(z);const me=this.stack[this.stack.length-1];me.value+=ie}function it(A){const z=this.stack.pop();z.position.end=St(A.end)}function j(A){I.call(this,A);const z=this.stack[this.stack.length-1];z.url=this.sliceSerialize(A)}function le(A){I.call(this,A);const z=this.stack[this.stack.length-1];z.url="mailto:"+this.sliceSerialize(A)}function ue(){return{type:"blockquote",children:[]}}function Se(){return{type:"code",lang:null,meta:null,value:""}}function He(){return{type:"inlineCode",value:""}}function se(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ve(){return{type:"emphasis",children:[]}}function ft(){return{type:"heading",depth:0,children:[]}}function at(){return{type:"break"}}function pt(){return{type:"html",value:""}}function In(){return{type:"image",title:null,url:"",alt:null}}function ot(){return{type:"link",title:null,url:"",children:[]}}function X(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function Ce(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function Xe(){return{type:"paragraph",children:[]}}function kr(){return{type:"strong",children:[]}}function ek(){return{type:"text",value:""}}function tk(){return{type:"thematicBreak"}}}function St(e){return{line:e.line,column:e.column,offset:e.offset}}function ql(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?ql(e,r):Dy(e,r)}}function Dy(e,t){let n;for(n in t)if(Hl.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function Vl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+fn({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+fn({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+fn({start:t.start,end:t.end})+") is still open")}function Ly(e){const t=this;t.parser=n;function n(r){return My(r,E(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function Oy(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function Fy(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|